Skip to main content

varve_core/
lineindex.rs

1//! The signed line index (REQ-INDEXAUTH-001) — which layers a line HAS.
2//!
3//! varve signs each layer manifest and each realm, but the LISTING of a line's
4//! layers has been the registry's raw `/tags/list`: unauthenticated. A
5//! compromised or merely stale index host can HIDE a layer and every artifact
6//! it does serve still verifies, so nothing detects it. Hiding also breaks
7//! digest-pinned resolution, because a `LayerRef::Digest` is resolved by
8//! enumerating tags and checking each candidate's payload digest.
9//!
10//! This is the Uptane insight applied to varve: rollback protection has to
11//! survive a compromised Director/registry, not merely a tampered artifact.
12//! Guix gets the equivalent property by authenticating its index git-history
13//! through signed commits.
14//!
15//! The document is deliberately the same shape as `linestatus`: a DSSE
16//! envelope under its own payload type, a monotonic per-line counter, and the
17//! same refusal on a counter regression. Two signed documents about the same
18//! line that disagree on how they are handled would be a bug generator.
19
20use std::collections::BTreeMap;
21use std::path::{Path, PathBuf};
22
23use serde::{Deserialize, Serialize};
24
25use crate::install::VerifyError;
26use crate::layer::Line;
27
28/// The authenticated payload type — a signed something-else (a layer manifest,
29/// a line-status) cannot be replayed as an index.
30pub const LINE_INDEX_PAYLOAD_TYPE: &str = "application/vnd.pulseengine.varve.line-index.v1+json";
31
32/// The artifact type under which an index travels as an OCI referrer.
33pub const LINE_INDEX_ARTIFACT_TYPE: &str = LINE_INDEX_PAYLOAD_TYPE;
34
35/// One layer the realm asserts exists on this line.
36#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
37#[serde(deny_unknown_fields)]
38pub struct IndexedLayer {
39    /// The layer id, e.g. "2026.08.2".
40    pub layer: String,
41    /// The digest of that layer's signed PAYLOAD — the same identity a pin's
42    /// `digest` names, so an index entry and a pin can be compared directly.
43    pub digest: String,
44    /// The channel the layer was published on.
45    pub channel: String,
46    /// That layer's manifest counter. The anti-rollback high-water mark is
47    /// keyed on a COUNTER, not a layer id, so the index must carry the counter
48    /// or clause 4 cannot feed the mechanism it exists to protect. (An earlier
49    /// draft returned the greatest layer id here, which type-checked and was
50    /// useless.)
51    pub counter: u64,
52}
53
54/// What the realm says a line contains.
55#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
56#[serde(deny_unknown_fields)]
57pub struct LineIndex {
58    /// The release line, e.g. "2026.08".
59    pub line: String,
60    /// Monotonic per-line document counter — a stale index must not silently
61    /// replace a newer one, exactly as for line-status.
62    pub counter: u64,
63    /// RFC 3339 issue time of this document.
64    #[serde(rename = "issued-at")]
65    pub issued_at: String,
66    /// Every layer of this line, in publication order.
67    pub layers: Vec<IndexedLayer>,
68}
69
70#[derive(Debug, thiserror::Error)]
71pub enum IndexError {
72    #[error(transparent)]
73    Verify(#[from] VerifyError),
74    #[error("line-index payload is not valid: {0}")]
75    Payload(String),
76    #[error(
77        "refusing stale line-index for {line}: presented counter {presented}, cached {cached} — \
78         a withdrawn or superseded index cannot be replayed over a newer one"
79    )]
80    Stale {
81        line: String,
82        presented: u64,
83        cached: u64,
84    },
85    #[error(
86        "the realm's signed index for {line} names layer {layer} ({digest}), which this source \
87         does not serve. A source that hides a layer is either compromised or stale; every \
88         layer it DOES serve still verifies, which is exactly why this check exists. Use a \
89         different source, or obtain a newer signed index."
90    )]
91    Omitted {
92        line: String,
93        layer: String,
94        digest: String,
95    },
96    #[error(
97        "realm '{realm}' declares that it publishes a signed line index, but none was found for \
98         {line}. Either the source is not serving it, or the realm's declaration is wrong — \
99         varve will not fall back to an unauthenticated listing for a realm that promised one."
100    )]
101    Missing { realm: String, line: String },
102    #[error("line-index document is for line {document}, not {expected}")]
103    WrongLine { document: String, expected: String },
104    #[error("io error at {path}: {source}")]
105    Io {
106        path: String,
107        #[source]
108        source: std::io::Error,
109    },
110}
111
112impl IndexError {
113    /// May another source be asked after this failure? (REQ-MIRROR-002.)
114    ///
115    /// Yes where THIS source's index is unavailable, unauthentic, malformed,
116    /// for another line, or hides a layer the signed index names: another
117    /// source may serve it properly. `Stale` also fails over: every source is
118    /// judged against the same persisted local cache, so a later one can
119    /// never pass below it, and ending the search there would only cost
120    /// availability (a primary restored from backup, a stale CDN tag). No for
121    /// local I/O. Exhaustive, no `_` arm.
122    pub fn fails_over(&self) -> bool {
123        match self {
124            IndexError::Verify(_)
125            | IndexError::Payload(_)
126            | IndexError::WrongLine { .. }
127            | IndexError::Omitted { .. }
128            | IndexError::Missing { .. }
129            | IndexError::Stale { .. } => true,
130            IndexError::Io { .. } => false,
131        }
132    }
133}
134
135impl LineIndex {
136    /// Verify an envelope against the realm's trust root and parse it.
137    pub fn verify_and_parse(
138        envelope: &[u8],
139        trust: &crate::keyroles::RealmTrust,
140    ) -> Result<Self, IndexError> {
141        let payload = trust.verify_bytes(envelope, LINE_INDEX_PAYLOAD_TYPE)?;
142        serde_json::from_slice(&payload).map_err(|e| IndexError::Payload(e.to_string()))
143    }
144
145    /// Sign an index (the producing side — CI, beside deposit).
146    pub fn sign(&self, secret_key: &[u8], key_id: &str) -> Result<String, IndexError> {
147        let signer = crate::verify::FileSigner::new_unchecked(secret_key, key_id)?;
148        self.sign_with(&signer)
149    }
150
151    /// [`LineIndex::sign`] with any [`crate::verify::RealmSigner`].
152    pub fn sign_with(&self, signer: &dyn crate::verify::RealmSigner) -> Result<String, IndexError> {
153        let payload = serde_json::to_vec_pretty(self).expect("index serializes");
154        Ok(crate::verify::dsse_sign_with(
155            &payload,
156            LINE_INDEX_PAYLOAD_TYPE,
157            signer,
158        )?)
159    }
160
161    /// The line this document is about.
162    pub fn line(&self) -> Result<Line, IndexError> {
163        self.line
164            .parse()
165            .map_err(|e: crate::layer::LayerIdError| IndexError::Payload(e.to_string()))
166    }
167
168    /// Clause 3: every layer the index names must be present in what the
169    /// source actually offers. `served` is the set of layer ids the source
170    /// enumerated. Returns the FIRST omission, named — not a boolean, because
171    /// an error a user cannot act on is not a check.
172    pub fn refuse_omission(&self, served: &[String]) -> Result<(), IndexError> {
173        for entry in &self.layers {
174            if !served.iter().any(|s| s == &entry.layer) {
175                return Err(IndexError::Omitted {
176                    line: self.line.clone(),
177                    layer: entry.layer.clone(),
178                    digest: entry.digest.clone(),
179                });
180            }
181        }
182        Ok(())
183    }
184
185    /// Clause 4: the high-water mark this index justifies, independent of what
186    /// the source chose to serve. A registry that hides the newest layer must
187    /// not thereby lower the bar a later install has to clear, which is the
188    /// whole point of authenticating the listing.
189    ///
190    /// The greatest counter the realm asserts for this line. `None` for an
191    /// empty index, which asserts nothing and must not be mistaken for a mark
192    /// of zero.
193    /// Which layers of this index are newer than `pinned`, and which entries
194    /// could not be ordered at all (REQ-LAYERDIFF-001 clause 1).
195    ///
196    /// IN THE LIB, not in the CLI that calls it, because it is a DECISION and
197    /// the mutation gate's kill criteria are `--workspace --lib`. A comparison
198    /// living in `main.rs` is one the gate cannot reach, and this particular
199    /// comparison is one I got wrong: measuring a real realm on 2026-10-01 I
200    /// ordered layer ids as STRINGS, which puts `2026.09.12` before
201    /// `2026.09.2`, and reported a staleness figure wrong by eight layers.
202    /// `LayerId` orders by `(line, patch)` numerically.
203    ///
204    /// An entry that will not parse is RETURNED, never dropped: a layer this
205    /// varve cannot order is one it cannot promise is not newer, and dropping
206    /// it would turn "I do not understand this entry" into "there is nothing
207    /// newer" — the same collapse of two different answers that makes an
208    /// unauthenticated tag listing useless for this question.
209    pub fn newer_than<'a>(
210        &'a self,
211        pinned: &crate::layer::LayerId,
212    ) -> (Vec<&'a IndexedLayer>, Vec<&'a str>) {
213        let mut newer: Vec<&IndexedLayer> = self
214            .layers
215            .iter()
216            .filter(|l| {
217                l.layer
218                    .parse::<crate::layer::LayerId>()
219                    .is_ok_and(|id| &id > pinned)
220            })
221            .collect();
222        newer.sort_by_key(|l| l.layer.parse::<crate::layer::LayerId>().ok());
223        let unparseable: Vec<&str> = self
224            .layers
225            .iter()
226            .filter(|l| l.layer.parse::<crate::layer::LayerId>().is_err())
227            .map(|l| l.layer.as_str())
228            .collect();
229        (newer, unparseable)
230    }
231
232    pub fn high_water(&self) -> Option<u64> {
233        self.layers.iter().map(|e| e.counter).max()
234    }
235
236    /// Clause 2: refuse a presented index older than one already held.
237    /// Equality is allowed — a CI re-run must stay idempotent, the same rule
238    /// `attach_envelope_to_layout` follows for line-status.
239    pub fn refuse_regression(&self, cached: Option<&LineIndex>) -> Result<(), IndexError> {
240        if let Some(prev) = cached
241            && prev.line == self.line
242            && self.counter < prev.counter
243        {
244            return Err(IndexError::Stale {
245                line: self.line.clone(),
246                presented: self.counter,
247                cached: prev.counter,
248            });
249        }
250        Ok(())
251    }
252
253    /// The index as a lookup from layer id to its signed payload digest.
254    pub fn by_layer(&self) -> BTreeMap<&str, &str> {
255        self.layers
256            .iter()
257            .map(|e| (e.layer.as_str(), e.digest.as_str()))
258            .collect()
259    }
260}
261
262/// What a consumer knows about a realm's index obligation.
263#[derive(Debug, Clone, Copy)]
264pub struct IndexPolicy<'a> {
265    /// The realm's name, for error messages.
266    pub realm: &'a str,
267    /// The realm's trust — the index verifies against this and nothing else,
268    /// under the STATUS role where the realm declares roles. The SOURCE is the
269    /// party being constrained, so it is never asked whether the index is good.
270    pub trust: &'a crate::keyroles::RealmTrust,
271    /// The realm declared `signed-index = true` (clause 5).
272    pub required: bool,
273}
274
275/// The index in `envelope` if it VERIFIES under the realm's trust and is about
276/// `line`; `None` otherwise (the failure is `check`'s to report, this only asks
277/// "what has this source proved?").
278///
279/// For a caller that must remember what an earlier source proved while a later
280/// one is asked (varve#311): a verified document is a baseline whether or not
281/// the rest of that source's attempt succeeded.
282pub fn proven_by(
283    line: &str,
284    envelope: &[u8],
285    trust: &crate::keyroles::RealmTrust,
286) -> Option<LineIndex> {
287    LineIndex::verify_and_parse(envelope, trust)
288        .ok()
289        .filter(|doc| doc.line == line)
290}
291
292/// The index with the higher counter; `a` on a tie. The baseline a later source
293/// is judged against is the higher of what is cached and what this run proved.
294pub fn higher_counter(a: Option<LineIndex>, b: Option<LineIndex>) -> Option<LineIndex> {
295    match (a, b) {
296        (Some(a), Some(b)) => Some(if b.counter > a.counter { b } else { a }),
297        (a, b) => a.or(b),
298    }
299}
300
301/// Run the whole index check for one line, returning the verified index when
302/// there is one. Separate from `install` so each clause is exercised directly:
303/// integration tests cannot kill mutants under `--workspace --lib`, and this
304/// is trust-critical code.
305///
306/// `envelope` is what the source offered (None = it offered nothing);
307/// `served` is what the source is willing to serve (None = it cannot
308/// enumerate); `cached` is the index already held, if any.
309pub fn check(
310    line: &str,
311    envelope: Option<&[u8]>,
312    served: Option<&[String]>,
313    cached: Option<&LineIndex>,
314    policy: &IndexPolicy<'_>,
315) -> Result<Option<LineIndex>, IndexError> {
316    let Some(bytes) = envelope else {
317        // Clause 5: absence is an error only where the realm promised one.
318        if policy.required {
319            return Err(IndexError::Missing {
320                realm: policy.realm.to_string(),
321                line: line.to_string(),
322            });
323        }
324        return Ok(None);
325    };
326
327    let index = LineIndex::verify_and_parse(bytes, policy.trust)?;
328    // The document must be about the line we asked about. Without this, a
329    // valid index for a QUIET line would satisfy the check for a busy one
330    // while naming none of its layers — omission detection that always passes.
331    if index.line != line {
332        return Err(IndexError::WrongLine {
333            document: index.line.clone(),
334            expected: line.to_string(),
335        });
336    }
337    index.refuse_regression(cached)?;
338    if let Some(served) = served {
339        index.refuse_omission(served)?;
340    }
341    Ok(Some(index))
342}
343
344// ─────────────────────── carriage: how an index travels ───────────────────
345//
346// A line-status rides INSIDE a layer's artifact manifest, because it is
347// evidence about the layer being fetched. An index is about the LINE and must
348// be obtainable before any layer is chosen — including when the layer a
349// consumer wants is the one being hidden — so it gets its own address:
350// one tag per line on a registry, one referrer entry per line in a layout.
351// Reading it through a layer would let a source suppress the index by
352// suppressing the layer, which is the attack.
353
354/// Annotation naming the line a carried index document covers. Distinct from
355/// `linestatus::ANN_LINE` on purpose: a layout carries both documents about
356/// the same line, and two readers keyed on one annotation name is the sort of
357/// near-miss that ends with a status being read as an index.
358pub const ANN_INDEX_LINE: &str = "eu.pulseengine.varve.index-line";
359
360/// Tag prefix under which a line's signed index is published on a registry.
361/// Deliberately not parseable as a `LayerId` (`YYYY.MM.P`), so an index tag
362/// can never be mistaken for a layer the line contains — including by
363/// `served_layers`, which would otherwise report the index itself as a layer.
364pub const LINE_INDEX_TAG_PREFIX: &str = "line-index-";
365
366/// The registry tag carrying the signed index for a line.
367pub fn index_tag(line: &str) -> String {
368    format!("{LINE_INDEX_TAG_PREFIX}{line}")
369}
370
371/// Attach a signed index envelope to an OCI image layout as a referrer,
372/// replacing any previous index for the same line. No layer blob or digest is
373/// touched: evidence is added beside the artifact, never folded into it.
374pub fn attach_to_layout(layout: &Path, line: &str, envelope: &[u8]) -> Result<(), IndexError> {
375    let io = |path: &Path, source: std::io::Error| IndexError::Io {
376        path: path.display().to_string(),
377        source,
378    };
379    let digest = crate::store::manifest_digest(envelope);
380    let hex = digest.strip_prefix("sha256:").expect("digest shape");
381    let blob_dir = layout.join("blobs").join("sha256");
382    std::fs::create_dir_all(&blob_dir).map_err(|e| io(&blob_dir, e))?;
383    let blob_path = blob_dir.join(hex);
384    std::fs::write(&blob_path, envelope).map_err(|e| io(&blob_path, e))?;
385
386    let index_path = layout.join("index.json");
387    let mut index: serde_json::Value =
388        serde_json::from_slice(&std::fs::read(&index_path).map_err(|e| io(&index_path, e))?)
389            .map_err(|e| IndexError::Payload(format!("index.json: {e}")))?;
390    let entries = index["manifests"]
391        .as_array_mut()
392        .ok_or_else(|| IndexError::Payload("index.json has no manifests array".into()))?;
393    entries.retain(|e| {
394        !(e["artifactType"] == LINE_INDEX_ARTIFACT_TYPE
395            && e["annotations"][ANN_INDEX_LINE] == *line)
396    });
397    entries.push(serde_json::json!({
398        "mediaType": "application/json",
399        "artifactType": LINE_INDEX_ARTIFACT_TYPE,
400        "digest": digest,
401        "size": envelope.len(),
402        "annotations": { ANN_INDEX_LINE: line }
403    }));
404    std::fs::write(
405        &index_path,
406        serde_json::to_vec_pretty(&index).expect("index serializes"),
407    )
408    .map_err(|e| io(&index_path, e))?;
409    Ok(())
410}
411
412/// Attach an index envelope to a layout, deriving the line from the document
413/// itself (the producing side, `varve attach-index`). Returns (line, counter).
414///
415/// The payload is read to learn the line, not trusted: the consumer re-verifies
416/// against its realm's root. Two guards mirror `attach-status`, because a
417/// producer mistake here is a consumer outage later:
418///  * a counter regression is refused, so a re-run of a CI step cannot
419///    downgrade a published layout's index — and so the same rule holds at the
420///    only place that PRODUCES the artifact, not merely where it is read;
421///  * an index for a different line than the layout's own layer is refused,
422///    rather than being left for the consumer to discover as `WrongLine`.
423pub fn attach_envelope_to_layout(
424    layout: &Path,
425    envelope: &[u8],
426) -> Result<(String, u64), IndexError> {
427    let doc = parse_unverified(envelope)?;
428    let line: Line = doc.line.parse().map_err(|e: crate::layer::LayerIdError| {
429        IndexError::Payload(format!("index line '{}': {e}", doc.line))
430    })?;
431    let line = line.to_string();
432    if let Some(existing) = read_from_layout(layout, &line)? {
433        let prev = parse_unverified(&existing)?;
434        doc.refuse_regression(Some(&prev))?;
435    }
436    if let Some(layout_line) = crate::linestatus::layout_line(layout)
437        && layout_line != line
438    {
439        return Err(IndexError::WrongLine {
440            document: line,
441            expected: layout_line,
442        });
443    }
444    attach_to_layout(layout, &line, envelope)?;
445    Ok((line, doc.counter))
446}
447
448/// Read the index envelope a layout carries for a line, if any.
449pub fn read_from_layout(layout: &Path, line: &str) -> Result<Option<Vec<u8>>, IndexError> {
450    let index_path = layout.join("index.json");
451    let bytes = match std::fs::read(&index_path) {
452        Ok(bytes) => bytes,
453        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
454        Err(source) => {
455            return Err(IndexError::Io {
456                path: index_path.display().to_string(),
457                source,
458            });
459        }
460    };
461    let index: serde_json::Value = serde_json::from_slice(&bytes)
462        .map_err(|e| IndexError::Payload(format!("index.json: {e}")))?;
463    // Both artifactType AND line must match. Matching on the type alone would
464    // hand a consumer another line's index, which `check` would then reject as
465    // `WrongLine` — a correct refusal with a misleading cause.
466    let Some(entry) = index["manifests"].as_array().and_then(|entries| {
467        entries.iter().find(|e| {
468            e["artifactType"] == LINE_INDEX_ARTIFACT_TYPE
469                && e["annotations"][ANN_INDEX_LINE] == *line
470        })
471    }) else {
472        return Ok(None);
473    };
474    let digest = entry["digest"]
475        .as_str()
476        .ok_or_else(|| IndexError::Payload("index entry has no digest".into()))?;
477    let hex = digest.strip_prefix("sha256:").unwrap_or(digest);
478    let blob_path = layout.join("blobs").join("sha256").join(hex);
479    std::fs::read(&blob_path)
480        .map(Some)
481        .map_err(|source| IndexError::Io {
482            path: blob_path.display().to_string(),
483            source,
484        })
485}
486
487/// Parse an index out of an envelope WITHOUT verifying it. Used only to read
488/// back a document this machine already accepted (the cache) or is about to
489/// publish (attach); every place the document is TRUSTED goes through
490/// `verify_and_parse`.
491pub(crate) fn parse_unverified(envelope: &[u8]) -> Result<LineIndex, IndexError> {
492    let text = std::str::from_utf8(envelope)
493        .map_err(|e| IndexError::Payload(format!("envelope is not utf-8: {e}")))?;
494    let env = wsc::dsse::DsseEnvelope::from_json(text)
495        .map_err(|e| IndexError::Payload(format!("not a DSSE envelope: {e}")))?;
496    let payload = env
497        .payload_bytes()
498        .map_err(|e| IndexError::Payload(format!("envelope payload: {e}")))?;
499    serde_json::from_slice(&payload)
500        .map_err(|e| IndexError::Payload(format!("index document: {e}")))
501}
502
503/// Per-line cache of the newest index this machine has accepted — what clause
504/// 2 compares a presented index against.
505///
506/// Local, unsigned state, exactly like `HighWaterMarks`: it is written only
507/// after an index has verified against the realm's root, and it is read back
508/// unverified. The failure it can produce is REFUSING an install, never
509/// accepting a bad one — an attacker who can already write here can delete the
510/// core instead.
511#[derive(Debug)]
512pub struct IndexCache {
513    dir: PathBuf,
514}
515
516impl IndexCache {
517    pub fn at_root(root: &Path) -> Self {
518        IndexCache {
519            dir: root.join("state").join("line-index"),
520        }
521    }
522
523    /// The index cached for a line, if one has ever been accepted.
524    pub fn load(&self, line: &str) -> Result<Option<LineIndex>, IndexError> {
525        let path = self.path(line);
526        match std::fs::read(&path) {
527            Ok(bytes) => Ok(Some(parse_unverified(&bytes)?)),
528            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
529            Err(source) => Err(IndexError::Io {
530                path: path.display().to_string(),
531                source,
532            }),
533        }
534    }
535
536    /// Record a VERIFIED envelope, refusing a counter regression — the same
537    /// rule `check` applies, held here too so a caller that skipped the check
538    /// cannot quietly lower the cached mark.
539    pub fn update(
540        &self,
541        line: &str,
542        envelope: &[u8],
543        parsed: &LineIndex,
544    ) -> Result<(), IndexError> {
545        parsed.refuse_regression(self.load(line)?.as_ref())?;
546        let io = |path: &Path, source: std::io::Error| IndexError::Io {
547            path: path.display().to_string(),
548            source,
549        };
550        std::fs::create_dir_all(&self.dir).map_err(|e| io(&self.dir, e))?;
551        let path = self.path(line);
552        std::fs::write(&path, envelope).map_err(|e| io(&path, e))?;
553        Ok(())
554    }
555
556    fn path(&self, line: &str) -> PathBuf {
557        self.dir.join(format!("{line}.dsse.json"))
558    }
559}
560
561#[cfg(test)]
562mod tests {
563    use super::*;
564    use crate::verify::generate_root_keypair;
565
566    fn index(counter: u64, layers: &[(&str, &str)]) -> LineIndex {
567        // Layer counters ascend with the layer id, as a real line's do.
568        LineIndex {
569            line: "2026.08".into(),
570            counter,
571            issued_at: "2026-08-18T00:00:00Z".into(),
572            layers: layers
573                .iter()
574                .enumerate()
575                .map(|(i, (l, d))| IndexedLayer {
576                    layer: (*l).into(),
577                    digest: (*d).into(),
578                    channel: "qualified".into(),
579                    counter: (i as u64) + 1,
580                })
581                .collect(),
582        }
583    }
584
585    // rivet: verifies REQ-INDEXAUTH-001
586    #[test]
587    fn an_index_verifies_only_against_the_realm_that_signed_it() {
588        let (sk, pk) = generate_root_keypair();
589        let (_other_sk, other_pk) = generate_root_keypair();
590        let doc = index(1, &[("2026.08.0", "sha256:aa"), ("2026.08.1", "sha256:bb")]);
591        let envelope = doc.sign(&sk, "root-1").unwrap();
592
593        assert_eq!(
594            LineIndex::verify_and_parse(
595                envelope.as_bytes(),
596                &crate::keyroles::test_support::rt(&pk)
597            )
598            .unwrap(),
599            doc
600        );
601        // Another realm's root must not accept it — an index is an assertion
602        // BY a realm, so it carries that realm's authority and no other's.
603        assert!(
604            LineIndex::verify_and_parse(
605                envelope.as_bytes(),
606                &crate::keyroles::test_support::rt(&other_pk)
607            )
608            .is_err()
609        );
610    }
611
612    // rivet: verifies REQ-MIRROR-002
613    #[test]
614    fn proven_by_answers_only_for_a_verified_index_about_the_asked_line() {
615        let (sk, pk) = generate_root_keypair();
616        let (_other_sk, other_pk) = generate_root_keypair();
617        let doc = index(4, &[("2026.08.0", "sha256:aa")]);
618        let envelope = doc.sign(&sk, "root-1").unwrap();
619        let trust = crate::keyroles::test_support::rt(&pk);
620        assert_eq!(
621            proven_by("2026.08", envelope.as_bytes(), &trust),
622            Some(doc.clone())
623        );
624        // A different line, a different realm's root, and bytes that are not
625        // an envelope prove nothing.
626        assert_eq!(proven_by("2026.09", envelope.as_bytes(), &trust), None);
627        let other = crate::keyroles::test_support::rt(&other_pk);
628        assert_eq!(proven_by("2026.08", envelope.as_bytes(), &other), None);
629        assert_eq!(proven_by("2026.08", b"not an envelope", &trust), None);
630    }
631
632    // rivet: verifies REQ-MIRROR-002
633    #[test]
634    fn the_baseline_is_the_higher_counter_and_a_tie_keeps_the_first() {
635        let lo = index(2, &[("2026.08.0", "sha256:aa")]);
636        let hi = index(5, &[("2026.08.0", "sha256:bb")]);
637        assert_eq!(
638            higher_counter(Some(lo.clone()), Some(hi.clone())),
639            Some(hi.clone())
640        );
641        assert_eq!(
642            higher_counter(Some(hi.clone()), Some(lo.clone())),
643            Some(hi.clone())
644        );
645        assert_eq!(higher_counter(Some(lo.clone()), None), Some(lo.clone()));
646        assert_eq!(higher_counter(None, Some(lo.clone())), Some(lo.clone()));
647        assert_eq!(higher_counter(None, None), None);
648        let same = index(5, &[("2026.08.0", "sha256:cc")]);
649        assert_eq!(higher_counter(Some(hi.clone()), Some(same)), Some(hi));
650    }
651
652    // rivet: verifies REQ-INDEXAUTH-001
653    #[test]
654    fn a_signed_line_status_cannot_be_replayed_as_an_index() {
655        // The payload type is the whole defence against cross-document replay.
656        // Both documents are signed by the SAME root and both are about a
657        // line, so without a distinct type a status could stand in for an
658        // index and assert that a line contains nothing.
659        let (sk, pk) = generate_root_keypair();
660        let status = crate::linestatus::LineStatus {
661            min_counter: None,
662            line: "2026.08".into(),
663            counter: 9,
664            issued_at: "2026-08-18T00:00:00Z".into(),
665            support_until: None,
666            yanked: Default::default(),
667            known_problems: Vec::new(),
668        };
669        let envelope = status.sign(&sk, "root-1").unwrap();
670        // Assert the TYPE rejected it, not the schema. Mutating the payload
671        // type constant to line-status's left an `is_err()` version of this
672        // test GREEN, because the two structs have divergent
673        // deny_unknown_fields shapes and serde refused it anyway — the test
674        // proved schema divergence while claiming to prove the type check. If
675        // the schemas ever converged, replay would open and nothing would
676        // notice.
677        match LineIndex::verify_and_parse(
678            envelope.as_bytes(),
679            &crate::keyroles::test_support::rt(&pk),
680        ) {
681            Err(IndexError::Verify(_)) => {}
682            Err(IndexError::Payload(p)) => panic!(
683                "rejected by the SCHEMA ({p}), not by the payload type — the type is the \
684                 defence against cross-document replay and must be what fails"
685            ),
686            Ok(_) => panic!("a line-status must not verify as a line-index"),
687            Err(other) => panic!("expected a payload-type rejection, got {other}"),
688        }
689
690        // The converse, so the defence is shown to be symmetric: an index
691        // must not be accepted as a status either.
692        let idx = index(1, &[("2026.08.0", "sha256:aa")]);
693        let idx_env = idx.sign(&sk, "root-1").unwrap();
694        assert!(
695            crate::linestatus::LineStatus::verify_and_parse(
696                idx_env.as_bytes(),
697                &crate::keyroles::test_support::rt(&pk)
698            )
699            .is_err(),
700            "a line-index must not verify as a line-status"
701        );
702    }
703
704    // rivet: verifies REQ-INDEXAUTH-001
705    #[test]
706    fn a_source_that_hides_a_layer_the_index_names_is_refused() {
707        // THE attack this requirement exists for. The registry serves a valid,
708        // correctly-signed 2026.08.0 and simply omits 2026.08.1 — a freshness
709        // attack in which every byte the consumer receives verifies.
710        let doc = index(1, &[("2026.08.0", "sha256:aa"), ("2026.08.1", "sha256:bb")]);
711        let err = doc
712            .refuse_omission(&["2026.08.0".to_string()])
713            .expect_err("hiding a layer must be refused");
714        match &err {
715            IndexError::Omitted { layer, digest, .. } => {
716                assert_eq!(layer, "2026.08.1");
717                assert_eq!(digest, "sha256:bb", "name the digest, so it can be sought");
718            }
719            other => panic!("expected Omitted, got {other}"),
720        }
721        // The message must be actionable, not merely correct.
722        let msg = err.to_string();
723        assert!(msg.contains("2026.08.1"), "names the hidden layer: {msg}");
724        assert!(
725            msg.contains("still verifies"),
726            "says WHY per-artifact verification did not catch this: {msg}"
727        );
728
729        // A source serving everything the index names is accepted, and extra
730        // layers are not an error: an index is a floor, not a whitelist, so a
731        // consumer holding an older index still works against a newer source.
732        assert!(
733            doc.refuse_omission(&[
734                "2026.08.0".to_string(),
735                "2026.08.1".to_string(),
736                "2026.08.2".to_string(),
737            ])
738            .is_ok()
739        );
740    }
741
742    // rivet: verifies REQ-INDEXAUTH-001
743    #[test]
744    fn the_high_water_mark_comes_from_the_index_not_from_what_was_served() {
745        // Clause 4, and the Uptane property: a registry hiding the newest
746        // layer must not lower the bar a later install has to clear.
747        let doc = index(
748            1,
749            &[
750                ("2026.08.0", "sha256:aa"),
751                ("2026.08.2", "sha256:cc"),
752                ("2026.08.1", "sha256:bb"),
753            ],
754        );
755        // The mark is a COUNTER — the units HighWaterMarks actually stores.
756        // An earlier draft returned the greatest LayerId here: it type-checked
757        // and could not feed the mechanism clause 4 exists to protect.
758        assert_eq!(
759            doc.high_water(),
760            Some(3),
761            "the greatest counter the REALM asserts, regardless of the order \
762             entries appear in the document or of what any source served"
763        );
764        // An empty index asserts nothing and must not be read as a mark of 0,
765        // which would be a mark that every layer clears.
766        assert_eq!(index(1, &[]).high_water(), None);
767    }
768
769    // rivet: verifies REQ-INDEXAUTH-001
770    #[test]
771    fn a_stale_index_cannot_replace_a_newer_one() {
772        let newer = index(7, &[("2026.08.1", "sha256:bb")]);
773        let older = index(3, &[("2026.08.0", "sha256:aa")]);
774
775        let err = older
776            .refuse_regression(Some(&newer))
777            .expect_err("a lower counter must be refused");
778        assert!(matches!(
779            err,
780            IndexError::Stale {
781                presented: 3,
782                cached: 7,
783                ..
784            }
785        ));
786        let msg = err.to_string();
787        assert!(msg.contains('3') && msg.contains('7'), "names both: {msg}");
788
789        // Equal is not a regression — CI re-runs must stay idempotent, the
790        // same rule line-status follows.
791        assert!(newer.refuse_regression(Some(&newer)).is_ok());
792        // Newer over older is the ordinary case.
793        assert!(newer.refuse_regression(Some(&older)).is_ok());
794        // Nothing cached yet is not a regression either.
795        assert!(older.refuse_regression(None).is_ok());
796    }
797
798    // rivet: verifies REQ-INDEXAUTH-001
799    #[test]
800    fn an_index_for_another_line_is_not_silently_accepted() {
801        let doc = index(1, &[("2026.08.0", "sha256:aa")]);
802        let other = LineIndex {
803            line: "2026.09".into(),
804            ..index(1, &[("2026.09.0", "sha256:zz")])
805        };
806        // A different line is not a regression — the counters are per line, so
807        // comparing them would refuse a legitimate document.
808        assert!(doc.refuse_regression(Some(&other)).is_ok());
809        assert_eq!(doc.line().unwrap().to_string(), "2026.08");
810    }
811
812    // rivet: verifies REQ-INDEXAUTH-001
813    #[test]
814    fn a_realm_that_promised_an_index_does_not_fall_back_to_an_unsigned_listing() {
815        // Clause 5, both directions. If absence were tolerated for a
816        // declaring realm, an attacker would disable the entire check by
817        // deleting one file — the check would be advisory, not a control.
818        let (_sk, pk) = generate_root_keypair();
819        let declaring = IndexPolicy {
820            realm: "acme",
821            trust: crate::keyroles::test_support::leak_rt(&pk),
822            required: true,
823        };
824        let silent = IndexPolicy {
825            required: false,
826            ..declaring
827        };
828
829        let err = check("2026.08", None, None, None, &declaring)
830            .expect_err("a declaring realm must not accept a missing index");
831        assert!(matches!(err, IndexError::Missing { .. }));
832        let msg = err.to_string();
833        assert!(msg.contains("acme"), "names the realm: {msg}");
834        assert!(
835            msg.contains("will not fall back"),
836            "says what it refused to do, not merely that something is absent: {msg}"
837        );
838
839        // A realm that never promised one keeps working — the default must not
840        // break every realm in existence.
841        assert!(
842            check("2026.08", None, None, None, &silent)
843                .unwrap()
844                .is_none()
845        );
846    }
847
848    // rivet: verifies REQ-INDEXAUTH-001
849    #[test]
850    fn an_index_for_a_different_line_cannot_satisfy_this_line() {
851        // Without this, a valid index for a QUIET line satisfies the check for
852        // a busy one while naming none of its layers — omission detection that
853        // structurally always passes, which is worse than no check because it
854        // reports success.
855        let (sk, pk) = generate_root_keypair();
856        let policy = IndexPolicy {
857            realm: "acme",
858            trust: crate::keyroles::test_support::leak_rt(&pk),
859            required: true,
860        };
861        let quiet = LineIndex {
862            line: "2026.01".into(),
863            ..index(1, &[])
864        };
865        let envelope = quiet.sign(&sk, "k").unwrap();
866        let err = check(
867            "2026.08",
868            Some(envelope.as_bytes()),
869            Some(&["2026.08.0".to_string()]),
870            None,
871            &policy,
872        )
873        .expect_err("an index for another line must not satisfy this one");
874        assert!(matches!(
875            err,
876            IndexError::WrongLine { ref document, ref expected }
877                if document == "2026.01" && expected == "2026.08"
878        ));
879    }
880
881    // rivet: verifies REQ-INDEXAUTH-001
882    #[test]
883    fn a_source_that_cannot_enumerate_is_not_treated_as_hiding_everything() {
884        // `None` (cannot enumerate — an offline archive directory) must be
885        // distinct from `Some(vec![])` (enumerates, has nothing). Collapsing
886        // them would make every air-gapped install fail with a false
887        // accusation of tampering, which is how a security control gets turned
888        // off in the field.
889        let (sk, pk) = generate_root_keypair();
890        let policy = IndexPolicy {
891            realm: "acme",
892            trust: crate::keyroles::test_support::leak_rt(&pk),
893            required: true,
894        };
895        let doc = index(1, &[("2026.08.0", "sha256:aa")]);
896        let envelope = doc.sign(&sk, "k").unwrap();
897
898        let ok = check("2026.08", Some(envelope.as_bytes()), None, None, &policy)
899            .expect("a source that cannot enumerate is not evidence of hiding");
900        assert_eq!(ok.unwrap().counter, 1);
901
902        // …but one that CAN enumerate and serves nothing is hiding everything.
903        assert!(matches!(
904            check(
905                "2026.08",
906                Some(envelope.as_bytes()),
907                Some(&[]),
908                None,
909                &policy
910            ),
911            Err(IndexError::Omitted { .. })
912        ));
913    }
914
915    // rivet: verifies REQ-INDEXAUTH-001
916    #[test]
917    fn check_refuses_a_stale_index_not_only_refuse_regression_does() {
918        // `a_stale_index_cannot_replace_a_newer_one` calls refuse_regression
919        // DIRECTLY, so deleting the call from `check` — the function install
920        // actually goes through — left the suite green. That is the exact
921        // shape four consecutive reviews have found: evidence that exercises a
922        // different function than the clause runs through. This one goes
923        // through `check`.
924        let (sk, pk) = generate_root_keypair();
925        let policy = IndexPolicy {
926            realm: "acme",
927            trust: crate::keyroles::test_support::leak_rt(&pk),
928            required: true,
929        };
930        let cached = index(7, &[("2026.08.1", "sha256:bb")]);
931        let stale = index(3, &[("2026.08.0", "sha256:aa")]);
932        let envelope = stale.sign(&sk, "k").unwrap();
933
934        let err = check(
935            "2026.08",
936            Some(envelope.as_bytes()),
937            None,
938            Some(&cached),
939            &policy,
940        )
941        .expect_err("a replayed older index must be refused by the path install uses");
942        assert!(matches!(
943            err,
944            IndexError::Stale {
945                presented: 3,
946                cached: 7,
947                ..
948            }
949        ));
950
951        // The newer one is accepted through the same path.
952        let fresher = index(8, &[("2026.08.1", "sha256:bb")]);
953        let ok = fresher.sign(&sk, "k").unwrap();
954        assert_eq!(
955            check("2026.08", Some(ok.as_bytes()), None, Some(&cached), &policy)
956                .unwrap()
957                .unwrap()
958                .counter,
959            8
960        );
961    }
962
963    /// A layout of one signed layer, the shape `deposit` writes.
964    fn layout_for(layer: &str, sk: &[u8]) -> (tempfile::TempDir, std::path::PathBuf) {
965        let tmp = tempfile::tempdir().unwrap();
966        let dest = tmp.path().join("layout");
967        let payload = crate::manifest::fixtures::manifest_with_tools(
968            layer,
969            "qualified",
970            1,
971            "2026-08-18T00:00:00Z",
972            &[],
973        );
974        let envelope = crate::verify::sign_layer_manifest(&payload, sk, "root-1").unwrap();
975        crate::archive::write_oci_layout(
976            &payload,
977            envelope.as_bytes(),
978            &[],
979            layer,
980            "qualified",
981            // A test fixture layout, not a real archive: no platform stamp.
982            None,
983            &dest,
984            false,
985        )
986        .unwrap();
987        (tmp, dest)
988    }
989
990    // rivet: verifies REQ-INDEXAUTH-001
991    #[test]
992    fn an_index_attached_to_a_layout_is_what_an_offline_install_reads_back() {
993        // Clause 1's transport half for the air-gapped path. Without it the
994        // document exists, verifies, and reaches nobody who is not on a
995        // registry — which is the transport varve exists to serve.
996        use crate::source::LayerSource;
997        let (sk, _pk) = generate_root_keypair();
998        let (_tmp, layout) = layout_for("2026.08.0", &sk);
999        let envelope = index(4, &[("2026.08.0", "sha256:aa")])
1000            .sign(&sk, "root-1")
1001            .unwrap();
1002        attach_to_layout(&layout, "2026.08", envelope.as_bytes()).unwrap();
1003
1004        let source = crate::archive::OciLayoutSource::at(&layout);
1005        assert_eq!(
1006            source.fetch_line_index("2026.08").unwrap().as_deref(),
1007            Some(envelope.as_bytes()),
1008            "the layout source must hand back the attached index verbatim"
1009        );
1010        // Another line's index is not served for this one: a reader keyed on
1011        // the artifact type alone would produce a `WrongLine` refusal whose
1012        // stated cause is wrong.
1013        assert_eq!(source.fetch_line_index("2026.09").unwrap(), None);
1014        // A layout with no index at all is `None`, not an error — whether that
1015        // is tolerable is the realm's call, not the layout's.
1016        let (_t2, bare) = layout_for("2026.08.0", &sk);
1017        assert_eq!(
1018            crate::archive::OciLayoutSource::at(&bare)
1019                .fetch_line_index("2026.08")
1020                .unwrap(),
1021            None
1022        );
1023
1024        // A layout carries BOTH documents about one line. Attaching a
1025        // line-status must not disturb the index, and the index reader must
1026        // not pick up the status: they are separate artifact types and are
1027        // kept apart by type, not by luck of ordering.
1028        let status = crate::linestatus::LineStatus {
1029            min_counter: None,
1030            line: "2026.08".into(),
1031            counter: 1,
1032            issued_at: "2026-08-18T00:00:00Z".into(),
1033            support_until: None,
1034            yanked: Default::default(),
1035            known_problems: Vec::new(),
1036        }
1037        .sign(&sk, "root-1")
1038        .unwrap();
1039        crate::linestatus::attach_to_layout(
1040            &layout,
1041            &"2026.08".parse().unwrap(),
1042            status.as_bytes(),
1043        )
1044        .unwrap();
1045        assert_eq!(
1046            source.fetch_line_index("2026.08").unwrap().as_deref(),
1047            Some(envelope.as_bytes()),
1048            "attaching a status must not displace the index"
1049        );
1050        assert_eq!(
1051            crate::linestatus::read_from_layout(&layout, &"2026.08".parse().unwrap())
1052                .unwrap()
1053                .as_deref(),
1054            Some(status.as_bytes()),
1055            "…and the index must not be handed back as the status either"
1056        );
1057
1058        // Re-attaching replaces rather than accumulating: two indexes for one
1059        // line in a layout is a document whose meaning depends on read order.
1060        let newer = index(5, &[("2026.08.0", "sha256:aa")])
1061            .sign(&sk, "root-1")
1062            .unwrap();
1063        attach_to_layout(&layout, "2026.08", newer.as_bytes()).unwrap();
1064        let json: serde_json::Value =
1065            serde_json::from_slice(&std::fs::read(layout.join("index.json")).unwrap()).unwrap();
1066        assert_eq!(
1067            json["manifests"]
1068                .as_array()
1069                .unwrap()
1070                .iter()
1071                .filter(|e| e["artifactType"] == LINE_INDEX_ARTIFACT_TYPE)
1072                .count(),
1073            1,
1074            "one index per line, replaced in place"
1075        );
1076        assert_eq!(
1077            source.fetch_line_index("2026.08").unwrap().as_deref(),
1078            Some(newer.as_bytes())
1079        );
1080    }
1081
1082    // rivet: verifies REQ-INDEXAUTH-001
1083    #[test]
1084    fn a_producer_cannot_downgrade_or_misfile_a_published_index() {
1085        // Clause 2 at the PRODUCING end. `attach-status` learned this the hard
1086        // way: the one place that creates the artifact was the one place the
1087        // monotonicity rule was missing, so a re-run of a CI step silently
1088        // shipped a superseded document that fresh consumers then cached.
1089        let (sk, _pk) = generate_root_keypair();
1090        let (_tmp, layout) = layout_for("2026.08.0", &sk);
1091        let newer = index(7, &[("2026.08.0", "sha256:aa")])
1092            .sign(&sk, "root-1")
1093            .unwrap();
1094        let (line, counter) = attach_envelope_to_layout(&layout, newer.as_bytes()).unwrap();
1095        assert_eq!((line.as_str(), counter), ("2026.08", 7));
1096
1097        let older = index(3, &[("2026.08.0", "sha256:aa")])
1098            .sign(&sk, "root-1")
1099            .unwrap();
1100        let err = attach_envelope_to_layout(&layout, older.as_bytes())
1101            .expect_err("a producer must not publish an index older than the layout's");
1102        assert!(
1103            matches!(
1104                err,
1105                IndexError::Stale {
1106                    presented: 3,
1107                    cached: 7,
1108                    ..
1109                }
1110            ),
1111            "got: {err}"
1112        );
1113        // The newer one is still what the layout serves.
1114        assert_eq!(
1115            read_from_layout(&layout, "2026.08").unwrap().as_deref(),
1116            Some(newer.as_bytes())
1117        );
1118
1119        // An index for another line than the layout's own layer is refused
1120        // here rather than left for the consumer to hit as `WrongLine`.
1121        let foreign = LineIndex {
1122            line: "2099.01".into(),
1123            ..index(1, &[])
1124        }
1125        .sign(&sk, "root-1")
1126        .unwrap();
1127        let err = attach_envelope_to_layout(&layout, foreign.as_bytes())
1128            .expect_err("a 2099.01 index does not belong on a 2026.08 layout");
1129        assert!(
1130            matches!(err, IndexError::WrongLine { ref document, ref expected }
1131                if document == "2099.01" && expected == "2026.08"),
1132            "got: {err}"
1133        );
1134        // …and a document whose `line` is not a line at all never gets signed
1135        // onto a layout: it would verify forever and match nothing.
1136        let nonsense = LineIndex {
1137            line: "twenty-twenty-six".into(),
1138            ..index(1, &[])
1139        }
1140        .sign(&sk, "root-1")
1141        .unwrap();
1142        assert!(attach_envelope_to_layout(&layout, nonsense.as_bytes()).is_err());
1143    }
1144
1145    // rivet: verifies REQ-INDEXAUTH-001
1146    #[test]
1147    fn the_cache_is_what_gives_clause_two_something_to_compare_against() {
1148        // `refuse_regression` needs a HELD document, and nothing held one:
1149        // every test supplied the "cached" index by hand, so the rule could
1150        // never fire on a real machine. This is that store.
1151        let tmp = tempfile::tempdir().unwrap();
1152        let cache = IndexCache::at_root(tmp.path());
1153        assert_eq!(
1154            cache.load("2026.08").unwrap(),
1155            None,
1156            "nothing accepted yet is None, not an empty index — an empty index \
1157             asserts that the line contains nothing"
1158        );
1159
1160        let (sk, _pk) = generate_root_keypair();
1161        let seven = index(7, &[("2026.08.1", "sha256:bb")]);
1162        cache
1163            .update("2026.08", seven.sign(&sk, "k").unwrap().as_bytes(), &seven)
1164            .unwrap();
1165        assert_eq!(cache.load("2026.08").unwrap().unwrap().counter, 7);
1166
1167        // A replayed older document cannot lower the mark, even by a caller
1168        // that skipped `check`.
1169        let three = index(3, &[("2026.08.0", "sha256:aa")]);
1170        let err = cache
1171            .update("2026.08", three.sign(&sk, "k").unwrap().as_bytes(), &three)
1172            .expect_err("the cache must not accept a regression");
1173        assert!(matches!(err, IndexError::Stale { .. }), "got: {err}");
1174        assert_eq!(cache.load("2026.08").unwrap().unwrap().counter, 7);
1175
1176        // Equal is idempotent; newer advances; another line is independent,
1177        // because the counters are per line.
1178        cache
1179            .update("2026.08", seven.sign(&sk, "k").unwrap().as_bytes(), &seven)
1180            .unwrap();
1181        let eight = index(8, &[("2026.08.1", "sha256:bb")]);
1182        cache
1183            .update("2026.08", eight.sign(&sk, "k").unwrap().as_bytes(), &eight)
1184            .unwrap();
1185        assert_eq!(cache.load("2026.08").unwrap().unwrap().counter, 8);
1186        let other = LineIndex {
1187            line: "2026.09".into(),
1188            ..index(1, &[])
1189        };
1190        cache
1191            .update("2026.09", other.sign(&sk, "k").unwrap().as_bytes(), &other)
1192            .expect("a low counter on a DIFFERENT line is not a regression");
1193        assert_eq!(cache.load("2026.08").unwrap().unwrap().counter, 8);
1194    }
1195
1196    // rivet: verifies REQ-INDEXAUTH-001
1197    #[test]
1198    fn the_index_tag_cannot_be_mistaken_for_a_layer_of_the_line() {
1199        // `served_layers` filters a registry's tags by parsing them as layer
1200        // ids. If the tag carrying the index parsed as one, the index would
1201        // appear in the line's own listing — and, worse, an index naming a tag
1202        // shaped like its own would be self-satisfying.
1203        assert_eq!(index_tag("2026.08"), "line-index-2026.08");
1204        assert!(
1205            index_tag("2026.08")
1206                .parse::<crate::layer::LayerId>()
1207                .is_err()
1208        );
1209        assert!(index_tag("2026.08").starts_with(LINE_INDEX_TAG_PREFIX));
1210    }
1211
1212    // rivet: verifies REQ-INDEXAUTH-001
1213    #[test]
1214    fn the_source_never_gets_to_vouch_for_its_own_index() {
1215        // The source is the party this document exists to constrain, so an
1216        // index it signs with its own key must be worthless.
1217        let (_realm_sk, realm_pk) = generate_root_keypair();
1218        let (impostor_sk, _impostor_pk) = generate_root_keypair();
1219        let policy = IndexPolicy {
1220            realm: "acme",
1221            trust: crate::keyroles::test_support::leak_rt(&realm_pk),
1222            required: true,
1223        };
1224        let forged = index(99, &[("2026.08.0", "sha256:aa")])
1225            .sign(&impostor_sk, "not-the-realm")
1226            .unwrap();
1227        assert!(matches!(
1228            check("2026.08", Some(forged.as_bytes()), None, None, &policy),
1229            Err(IndexError::Verify(_))
1230        ));
1231    }
1232}
1233
1234#[cfg(test)]
1235mod newer_than_tests {
1236    use super::{IndexedLayer, LineIndex};
1237    use crate::layer::LayerId;
1238    fn pinned_index(layers: &[(&str, &str)]) -> LineIndex {
1239        LineIndex {
1240            line: "2026.09".into(),
1241            counter: 7,
1242            issued_at: "2026-10-01T00:00:00Z".into(),
1243            layers: layers
1244                .iter()
1245                .map(|(layer, channel)| IndexedLayer {
1246                    layer: (*layer).to_string(),
1247                    digest: format!("sha256:{layer}"),
1248                    channel: (*channel).to_string(),
1249                    counter: 1,
1250                })
1251                .collect(),
1252        }
1253    }
1254
1255    /// The ordering is NUMERIC, and this is the case that proves it.
1256    ///
1257    /// `2026.09.2` is OLDER than the pinned `2026.09.12`, and a string compare
1258    /// says the opposite because '1' < '2'. I made exactly this mistake on
1259    /// 2026-10-01 while measuring how stale a real realm was and reported a
1260    /// figure wrong by eight layers. If this test ever passes with a
1261    /// lexicographic comparison, it is measuring nothing.
1262    // rivet: verifies REQ-LAYERDIFF-001
1263    #[test]
1264    fn newer_means_numerically_newer_not_alphabetically() {
1265        let pinned: LayerId = "2026.09.12".parse().unwrap();
1266        let idx = pinned_index(&[
1267            ("2026.09.2", "rolling"),
1268            ("2026.09.9", "rolling"),
1269            ("2026.09.12", "rolling"),
1270            ("2026.09.13", "rolling"),
1271            ("2026.10.1", "rolling"),
1272        ]);
1273        let (newer, unparseable) = idx.newer_than(&pinned);
1274        let got: Vec<&str> = newer.iter().map(|l| l.layer.as_str()).collect();
1275        assert_eq!(
1276            got,
1277            vec!["2026.09.13", "2026.10.1"],
1278            "2026.09.2 and 2026.09.9 are OLDER than 2026.09.12; a string \
1279             compare would have reported them as newer"
1280        );
1281        assert!(unparseable.is_empty());
1282    }
1283
1284    /// The pin being the newest is a real answer, not an empty one.
1285    // rivet: verifies REQ-LAYERDIFF-001
1286    #[test]
1287    fn nothing_newer_is_reported_as_nothing_newer() {
1288        let pinned: LayerId = "2026.10.1".parse().unwrap();
1289        let idx = pinned_index(&[("2026.09.20", "rolling"), ("2026.10.1", "rolling")]);
1290        let (newer, unparseable) = idx.newer_than(&pinned);
1291        assert!(newer.is_empty(), "{newer:?}");
1292        assert!(unparseable.is_empty());
1293    }
1294
1295    /// An entry this varve cannot order is RETURNED, not dropped.
1296    ///
1297    /// Dropping it would turn "I do not understand this" into "there is
1298    /// nothing newer", which is the same collapse of two different answers
1299    /// that makes a tag listing unusable for this question.
1300    // rivet: verifies REQ-LAYERDIFF-001
1301    #[test]
1302    fn an_entry_that_cannot_be_ordered_is_not_silently_dropped() {
1303        let pinned: LayerId = "2026.09.12".parse().unwrap();
1304        let idx = pinned_index(&[("2026.09.13", "rolling"), ("next", "rolling")]);
1305        let (newer, unparseable) = idx.newer_than(&pinned);
1306        assert_eq!(
1307            newer.iter().map(|l| l.layer.as_str()).collect::<Vec<_>>(),
1308            vec!["2026.09.13"]
1309        );
1310        assert_eq!(unparseable, vec!["next"], "the unorderable entry vanished");
1311    }
1312}
1313
1314#[cfg(test)]
1315mod failover_class_tests {
1316    use super::*;
1317
1318    // rivet: verifies REQ-MIRROR-002
1319    #[test]
1320    fn a_sources_bad_index_fails_over_but_a_verified_regression_or_local_io_does_not() {
1321        assert!(IndexError::Payload("x".into()).fails_over());
1322        assert!(
1323            IndexError::WrongLine {
1324                document: "a".into(),
1325                expected: "b".into()
1326            }
1327            .fails_over()
1328        );
1329        assert!(
1330            IndexError::Omitted {
1331                line: "l".into(),
1332                layer: "x".into(),
1333                digest: "d".into()
1334            }
1335            .fails_over()
1336        );
1337        assert!(
1338            IndexError::Missing {
1339                realm: "r".into(),
1340                line: "l".into()
1341            }
1342            .fails_over()
1343        );
1344        assert!(
1345            IndexError::Stale {
1346                line: "l".into(),
1347                presented: 1,
1348                cached: 2
1349            }
1350            .fails_over()
1351        );
1352        assert!(
1353            !IndexError::Io {
1354                path: "p".into(),
1355                source: std::io::Error::other("x")
1356            }
1357            .fails_over()
1358        );
1359    }
1360}