1use std::collections::BTreeMap;
21use std::path::{Path, PathBuf};
22
23use serde::{Deserialize, Serialize};
24
25use crate::install::VerifyError;
26use crate::layer::Line;
27
28pub const LINE_INDEX_PAYLOAD_TYPE: &str = "application/vnd.pulseengine.varve.line-index.v1+json";
31
32pub const LINE_INDEX_ARTIFACT_TYPE: &str = LINE_INDEX_PAYLOAD_TYPE;
34
35#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
37#[serde(deny_unknown_fields)]
38pub struct IndexedLayer {
39 pub layer: String,
41 pub digest: String,
44 pub channel: String,
46 pub counter: u64,
52}
53
54#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
56#[serde(deny_unknown_fields)]
57pub struct LineIndex {
58 pub line: String,
60 pub counter: u64,
63 #[serde(rename = "issued-at")]
65 pub issued_at: String,
66 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 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 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 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 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 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 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 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 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 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#[derive(Debug, Clone, Copy)]
264pub struct IndexPolicy<'a> {
265 pub realm: &'a str,
267 pub trust: &'a crate::keyroles::RealmTrust,
271 pub required: bool,
273}
274
275pub 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
292pub 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
301pub 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 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 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
344pub const ANN_INDEX_LINE: &str = "eu.pulseengine.varve.index-line";
359
360pub const LINE_INDEX_TAG_PREFIX: &str = "line-index-";
365
366pub fn index_tag(line: &str) -> String {
368 format!("{LINE_INDEX_TAG_PREFIX}{line}")
369}
370
371pub 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
412pub 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
448pub 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 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
487pub(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#[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 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 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 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 #[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 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 #[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 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 #[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 #[test]
654 fn a_signed_line_status_cannot_be_replayed_as_an_index() {
655 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 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 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 #[test]
706 fn a_source_that_hides_a_layer_the_index_names_is_refused() {
707 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 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 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 #[test]
744 fn the_high_water_mark_comes_from_the_index_not_from_what_was_served() {
745 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 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 assert_eq!(index(1, &[]).high_water(), None);
767 }
768
769 #[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 assert!(newer.refuse_regression(Some(&newer)).is_ok());
792 assert!(newer.refuse_regression(Some(&older)).is_ok());
794 assert!(older.refuse_regression(None).is_ok());
796 }
797
798 #[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 assert!(doc.refuse_regression(Some(&other)).is_ok());
809 assert_eq!(doc.line().unwrap().to_string(), "2026.08");
810 }
811
812 #[test]
814 fn a_realm_that_promised_an_index_does_not_fall_back_to_an_unsigned_listing() {
815 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 assert!(
842 check("2026.08", None, None, None, &silent)
843 .unwrap()
844 .is_none()
845 );
846 }
847
848 #[test]
850 fn an_index_for_a_different_line_cannot_satisfy_this_line() {
851 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 #[test]
883 fn a_source_that_cannot_enumerate_is_not_treated_as_hiding_everything() {
884 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 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 #[test]
917 fn check_refuses_a_stale_index_not_only_refuse_regression_does() {
918 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 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 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 None,
983 &dest,
984 false,
985 )
986 .unwrap();
987 (tmp, dest)
988 }
989
990 #[test]
992 fn an_index_attached_to_a_layout_is_what_an_offline_install_reads_back() {
993 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 assert_eq!(source.fetch_line_index("2026.09").unwrap(), None);
1014 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 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 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 #[test]
1084 fn a_producer_cannot_downgrade_or_misfile_a_published_index() {
1085 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 assert_eq!(
1115 read_from_layout(&layout, "2026.08").unwrap().as_deref(),
1116 Some(newer.as_bytes())
1117 );
1118
1119 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 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 #[test]
1147 fn the_cache_is_what_gives_clause_two_something_to_compare_against() {
1148 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 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 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 #[test]
1198 fn the_index_tag_cannot_be_mistaken_for_a_layer_of_the_line() {
1199 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 #[test]
1214 fn the_source_never_gets_to_vouch_for_its_own_index() {
1215 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 #[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 #[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 #[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 #[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}