Skip to main content

varve_core/
rollback.rs

1//! Anti-rollback and staleness verdicts (REQ-ROLLBACK-001, DD-005).
2//!
3//! The SUIT/Uptane discipline: the client persists, per release line, the
4//! highest release counter it has ever accepted — the high-water mark — and
5//! hard-rejects any layer below it. Counters are scoped *per line*, so a
6//! consumer frozen on 2026.07 keeps rollback protection inside that line
7//! without ever being pressured toward 2026.08.
8//!
9//! Time is an input, never sampled here: staleness verdicts are pure
10//! functions of (issued-at, now, threshold), so they are testable and the
11//! trusted base stays free of clock-reading policy.
12
13use std::collections::BTreeMap;
14use std::path::{Path, PathBuf};
15
16use crate::layer::Line;
17use crate::manifest::LayerManifest;
18
19/// Outcome of the anti-rollback check for one manifest.
20#[derive(Debug, Clone, PartialEq, Eq)]
21pub enum RollbackVerdict {
22    /// Counter at or above the recorded mark (or first contact): acceptable.
23    Accept,
24    /// Counter strictly below the recorded high-water mark: rejected.
25    Rollback {
26        line: String,
27        presented: u64,
28        high_water: u64,
29    },
30    /// FIRST CONTACT, below the line's signed floor: rejected
31    /// (REQ-FIRSTCONTACT-001).
32    ///
33    /// A client with no mark for a line used to accept any counter, because
34    /// there was nothing to compare against. That is the one moment when
35    /// anti-rollback — the property this tool exists for — protects nobody,
36    /// and it is exactly the moment an attacker chooses: a brand-new checkout,
37    /// a fresh CI runner, a new machine. Every one of those is a first
38    /// contact, so "first contact is rare" is false in precisely the
39    /// environments varve is built for.
40    ///
41    /// The realm states a floor in its signed line-status, so a consumer with
42    /// no history still has one.
43    BelowFloor {
44        line: String,
45        presented: u64,
46        floor: u64,
47    },
48}
49
50/// Persisted high-water marks, one per release line, stored under the varve
51/// root (NOT inside the core — the core holds evidence, this is client state).
52#[derive(Debug)]
53pub struct HighWaterMarks {
54    path: PathBuf,
55    marks: BTreeMap<String, u64>,
56    /// Documents a source VERIFIED during this run (varve#311). Memory only,
57    /// never written: see [`Self::carry_index`].
58    carried: Carried,
59}
60
61#[derive(Debug, Default)]
62struct Carried {
63    index: BTreeMap<String, crate::lineindex::LineIndex>,
64    status: BTreeMap<String, crate::linestatus::LineStatus>,
65}
66
67#[derive(Debug, thiserror::Error)]
68pub enum RollbackError {
69    // The io source is NOT repeated in the message: anyhow's `{err:#}` chain
70    // already appends every source, and including it here printed the cause
71    // twice (varve#60).
72    #[error("io error at {path}")]
73    Io {
74        path: String,
75        #[source]
76        source: std::io::Error,
77    },
78    #[error(
79        "{path}: high-water-mark state is corrupt: {reason} — refusing to guess; repair or remove the file"
80    )]
81    Corrupt { path: String, reason: String },
82}
83
84impl HighWaterMarks {
85    /// Load the marks stored under `root` (missing file = first contact).
86    pub fn load(root: &Path) -> Result<Self, RollbackError> {
87        let path = root.join("state").join("high-water-marks.json");
88        let marks = match std::fs::read(&path) {
89            Ok(bytes) => serde_json::from_slice(&bytes).map_err(|e| RollbackError::Corrupt {
90                path: path.display().to_string(),
91                reason: e.to_string(),
92            })?,
93            Err(e) if e.kind() == std::io::ErrorKind::NotFound => BTreeMap::new(),
94            Err(source) => {
95                return Err(RollbackError::Io {
96                    path: path.display().to_string(),
97                    source,
98                });
99            }
100        };
101        Ok(HighWaterMarks {
102            path,
103            marks,
104            carried: Carried::default(),
105        })
106    }
107
108    /// Remember a line index that VERIFIED against the realm's root during this
109    /// run, so a later source in the same operation is judged against it even
110    /// when the source that proved it failed over before its attempt finished
111    /// (varve#311: a later source must never pass against a lower bar than an
112    /// earlier one proved).
113    ///
114    /// In memory only. Nothing is persisted here: persisting is the install's
115    /// own step 7, and a run that ends in a refusal must not leave a raised
116    /// state behind (the cache that decides `has_local_history` is untouched).
117    /// The caller passes only a document that passed signature verification;
118    /// the highest counter is kept.
119    pub fn carry_index(&mut self, doc: crate::lineindex::LineIndex) {
120        let keep = self
121            .carried
122            .index
123            .get(&doc.line)
124            .is_none_or(|have| doc.counter > have.counter);
125        if keep {
126            self.carried.index.insert(doc.line.clone(), doc);
127        }
128    }
129
130    /// The highest verified index carried for `line` this run, if any.
131    pub fn carried_index(&self, line: &str) -> Option<crate::lineindex::LineIndex> {
132        self.carried.index.get(line).cloned()
133    }
134
135    /// As [`Self::carry_index`], for a verified line-status.
136    pub fn carry_status(&mut self, doc: crate::linestatus::LineStatus) {
137        let keep = self
138            .carried
139            .status
140            .get(&doc.line)
141            .is_none_or(|have| doc.counter > have.counter);
142        if keep {
143            self.carried.status.insert(doc.line.clone(), doc);
144        }
145    }
146
147    /// The highest verified line-status carried for `line` this run, if any.
148    pub fn carried_status(&self, line: &str) -> Option<crate::linestatus::LineStatus> {
149        self.carried.status.get(line).cloned()
150    }
151
152    /// The recorded mark for a line, if any.
153    pub fn mark(&self, line: &Line) -> Option<u64> {
154        self.marks.get(&line.to_string()).copied()
155    }
156
157    /// Check a manifest against the marks. `Accept` does NOT advance the
158    /// mark — call [`Self::advance`] after the layer is fully verified and
159    /// laid down, so a failed install cannot burn the mark.
160    pub fn check(&self, manifest: &LayerManifest) -> RollbackVerdict {
161        self.check_with_floor(manifest, None)
162    }
163
164    /// The check, with the realm's signed per-line floor when one is known
165    /// (REQ-FIRSTCONTACT-001).
166    ///
167    /// `floor` must come from a line-status document that has ALREADY been
168    /// verified against the realm's trust root. An unverified floor would be
169    /// an attacker-chosen number, and a floor of zero from a forged document
170    /// is worse than no floor at all — it looks like protection.
171    ///
172    /// The local mark still wins where it is higher: a consumer who has
173    /// accepted counter 9 must not be walked back to a realm-stated floor of
174    /// 3. The floor raises the bottom for someone who has no history; it never
175    /// lowers it for someone who does.
176    pub fn check_with_floor(
177        &self,
178        manifest: &LayerManifest,
179        floor: Option<u64>,
180    ) -> RollbackVerdict {
181        let line = manifest.layer.line().to_string();
182        match self.marks.get(&line) {
183            Some(&high_water) if manifest.counter < high_water => RollbackVerdict::Rollback {
184                line,
185                presented: manifest.counter,
186                high_water,
187            },
188            // A recorded mark at or above the presented counter is the
189            // consumer's own history and is authoritative; the floor has
190            // nothing to add.
191            Some(_) => RollbackVerdict::Accept,
192            None => match floor {
193                Some(floor) if manifest.counter < floor => RollbackVerdict::BelowFloor {
194                    line,
195                    presented: manifest.counter,
196                    floor,
197                },
198                _ => RollbackVerdict::Accept,
199            },
200        }
201    }
202
203    /// Record acceptance of a manifest: raise the line's mark to the
204    /// manifest's counter (never lowers) and persist.
205    pub fn advance(&mut self, manifest: &LayerManifest) -> Result<(), RollbackError> {
206        let line = manifest.layer.line().to_string();
207        let mark = self.marks.entry(line).or_insert(0);
208        *mark = (*mark).max(manifest.counter);
209        self.persist()
210    }
211
212    fn persist(&self) -> Result<(), RollbackError> {
213        let io = |path: &Path, source: std::io::Error| RollbackError::Io {
214            path: path.display().to_string(),
215            source,
216        };
217        let dir = self.path.parent().expect("state file has a parent");
218        std::fs::create_dir_all(dir).map_err(|e| io(dir, e))?;
219        let bytes = serde_json::to_vec_pretty(&self.marks).expect("marks serialize");
220        std::fs::write(&self.path, bytes).map_err(|e| io(&self.path, e))?;
221        Ok(())
222    }
223}
224
225/// Staleness verdict: how old is the layer's issued-at relative to `now`?
226/// Both are RFC 3339 strings; `threshold_days` is policy supplied by the
227/// caller. Returns `Some(age_days)` when the layer is older than the
228/// threshold — a warning, never a rejection: a frozen consumer's layer aging
229/// is expected, staying silently ignorant of it is not.
230pub fn staleness_warning(issued_at: &str, now: &str, threshold_days: u32) -> Option<i64> {
231    let age = epoch_days(now)? - epoch_days(issued_at)?;
232    (age > i64::from(threshold_days)).then_some(age)
233}
234
235/// Days since the civil epoch for the date part of an RFC 3339 timestamp.
236/// Day resolution is deliberate: staleness policy is measured in days, so
237/// sub-day precision would only manufacture spurious boundary cases.
238// Public so the manifest parser can reject a malformed issued-at at parse
239// time (F2, 2026-08-08 audit) — the producer and the staleness verdict must
240// agree on what a valid date is, so there is one function.
241pub fn epoch_days(rfc3339: &str) -> Option<i64> {
242    // Accept "YYYY-MM-DD", optionally followed by "T…" (the time part is not
243    // used at day resolution). The date must be exactly 10 chars with dashes
244    // at positions 4 and 7 — each guard independently reachable.
245    let date = rfc3339.split_once('T').map_or(rfc3339, |(d, _)| d);
246    let b = date.as_bytes();
247    if date.len() != 10 || b[4] != b'-' || b[7] != b'-' {
248        return None;
249    }
250    let y: i64 = date[0..4].parse().ok()?;
251    let m: i64 = date[5..7].parse().ok()?;
252    let d: i64 = date[8..10].parse().ok()?;
253    if !(1..=12).contains(&m) {
254        return None;
255    }
256    // Real days-per-month incl. the Gregorian leap rule — Feb 31 is not a
257    // date (the old 1..=31 check let impossible days through).
258    let leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
259    let dim = [
260        31,
261        if leap { 29 } else { 28 },
262        31,
263        30,
264        31,
265        30,
266        31,
267        31,
268        30,
269        31,
270        30,
271        31,
272    ];
273    if d < 1 || d > dim[(m - 1) as usize] {
274        return None;
275    }
276    // Howard Hinnant's days_from_civil.
277    let y = y - i64::from(m <= 2);
278    let era = if y >= 0 { y } else { y - 399 } / 400;
279    let yoe = y - era * 400;
280    let mp = (m + 9) % 12;
281    let doy = (153 * mp + 2) / 5 + d - 1;
282    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
283    Some(era * 146_097 + doe - 719_468)
284}
285
286#[cfg(test)]
287mod tests {
288    fn idx(line: &str, counter: u64, digest: &str) -> crate::lineindex::LineIndex {
289        crate::lineindex::LineIndex {
290            line: line.into(),
291            counter,
292            issued_at: "2026-08-18T00:00:00Z".into(),
293            layers: vec![crate::lineindex::IndexedLayer {
294                layer: format!("{line}.0"),
295                digest: digest.into(),
296                channel: "rolling".into(),
297                counter: 1,
298            }],
299        }
300    }
301
302    fn status(line: &str, counter: u64, min: Option<u64>) -> crate::linestatus::LineStatus {
303        crate::linestatus::LineStatus {
304            line: line.into(),
305            counter,
306            issued_at: "2026-08-18T00:00:00Z".into(),
307            support_until: None,
308            min_counter: min,
309            yanked: Default::default(),
310            known_problems: Vec::new(),
311        }
312    }
313
314    // rivet: verifies REQ-MIRROR-002
315    #[test]
316    fn carried_documents_keep_the_highest_counter_per_line_and_never_touch_disk() {
317        let tmp = tempfile::tempdir().unwrap();
318        let mut marks = HighWaterMarks::load(tmp.path()).unwrap();
319        assert!(marks.carried_index("2026.08").is_none());
320        assert!(marks.carried_status("2026.08").is_none());
321
322        marks.carry_index(idx("2026.08", 5, "sha256:aa"));
323        // Lower, and an equal one with other content, do not displace it.
324        marks.carry_index(idx("2026.08", 2, "sha256:bb"));
325        marks.carry_index(idx("2026.08", 5, "sha256:cc"));
326        assert_eq!(
327            marks.carried_index("2026.08"),
328            Some(idx("2026.08", 5, "sha256:aa"))
329        );
330        marks.carry_index(idx("2026.08", 7, "sha256:dd"));
331        assert_eq!(marks.carried_index("2026.08").unwrap().counter, 7);
332        // Per line.
333        assert!(marks.carried_index("2026.09").is_none());
334
335        marks.carry_status(status("2026.08", 3, Some(5)));
336        marks.carry_status(status("2026.08", 2, None));
337        assert_eq!(
338            marks.carried_status("2026.08"),
339            Some(status("2026.08", 3, Some(5)))
340        );
341        // An equal counter does not displace the first (a tie keeps it).
342        marks.carry_status(status("2026.08", 3, Some(9)));
343        assert_eq!(
344            marks.carried_status("2026.08"),
345            Some(status("2026.08", 3, Some(5)))
346        );
347        marks.carry_status(status("2026.08", 4, Some(6)));
348        assert_eq!(
349            marks.carried_status("2026.08").unwrap().min_counter,
350            Some(6)
351        );
352        assert!(marks.carried_status("2026.09").is_none());
353
354        // In memory only: a reload sees nothing, and no file was written.
355        assert!(
356            HighWaterMarks::load(tmp.path())
357                .unwrap()
358                .carried_index("2026.08")
359                .is_none()
360        );
361        assert!(!tmp.path().join("state").exists());
362    }
363
364    // rivet: verifies REQ-PROOF-001
365    #[test]
366    fn the_leap_rule_holds_at_the_year_the_solver_found() {
367        // cargo-mutants left three survivors here on 2026-08-08, all
368        // "replace || with && in epoch_days" — the Gregorian leap predicate.
369        // proptest never sampled a year that distinguishes the mutant. ordeal
370        // did: y = 8192 (divisible by 4, not by 100, not by 400), so it is a
371        // leap year under the correct rule and NOT under the mutant. That
372        // makes 8192-02-29 the date the mutant must get wrong.
373        // See proofs/epoch-days-leap-mutant-is-distinguishable.smt2.
374        assert!(
375            epoch_days("8192-02-29").is_some(),
376            "8192 is a leap year: 8192-02-29 must be a real date"
377        );
378        // The neighbouring non-leap cases the same predicate must reject.
379        assert!(
380            epoch_days("8100-02-29").is_none(),
381            "8100 %% 100 == 0, %% 400 != 0"
382        );
383        assert!(epoch_days("8000-02-29").is_some(), "8000 %% 400 == 0");
384        assert!(
385            epoch_days("8193-02-29").is_none(),
386            "8193 is not divisible by 4"
387        );
388    }
389    use super::*;
390    use crate::manifest::{LayerManifest, fixtures};
391
392    fn manifest(layer: &str, counter: u64) -> LayerManifest {
393        LayerManifest::parse(&fixtures::manifest(
394            layer,
395            "qualified",
396            counter,
397            "2026-07-31T09:14:00Z",
398        ))
399        .unwrap()
400    }
401
402    // rivet: verifies REQ-ROLLBACK-001
403    #[test]
404    fn first_contact_accepts_and_advance_records_the_mark() {
405        let tmp = tempfile::tempdir().unwrap();
406        let mut hwm = HighWaterMarks::load(tmp.path()).unwrap();
407        let m = manifest("2026.07.0", 3);
408        assert_eq!(hwm.check(&m), RollbackVerdict::Accept);
409        assert_eq!(hwm.mark(m.layer.line()), None, "check must not advance");
410        hwm.advance(&m).unwrap();
411        assert_eq!(hwm.mark(m.layer.line()), Some(3));
412    }
413
414    /// `advance` never lowers a mark — and it says so in its doc, which
415    /// nothing tested until varve#210.
416    ///
417    /// An infra report measuring a 12-runner fleet found marks of 4 written
418    /// on 09-23 sitting beside marks of 3 written on 09-30, and reasonably
419    /// read that as something rewriting the mark downward. It is not: the
420    /// real cause is state LOSS and re-seeding, because a missing file loads
421    /// as first contact. But the claim being untested is how that reading
422    /// stayed plausible, and "repair the mark" is exactly the fix somebody
423    /// reaches for next. A lowered mark silently re-accepts every layer the
424    /// consumer has already moved past.
425    // rivet: verifies REQ-ROLLBACK-001
426    #[test]
427    fn advance_never_lowers_a_mark_however_it_is_called() {
428        let tmp = tempfile::tempdir().unwrap();
429        let mut hwm = HighWaterMarks::load(tmp.path()).unwrap();
430        hwm.advance(&manifest("2026.07.3", 9)).unwrap();
431        assert_eq!(hwm.mark(manifest("2026.07.0", 1).layer.line()), Some(9));
432
433        // Every counter below the mark, including zero, leaves it alone.
434        for lower in [8, 4, 1, 0] {
435            hwm.advance(&manifest("2026.07.0", lower)).unwrap();
436            assert_eq!(
437                hwm.mark(manifest("2026.07.0", 1).layer.line()),
438                Some(9),
439                "advancing with counter {lower} lowered the mark"
440            );
441        }
442        // Equal is a no-op; higher still raises.
443        hwm.advance(&manifest("2026.07.3", 9)).unwrap();
444        assert_eq!(hwm.mark(manifest("2026.07.0", 1).layer.line()), Some(9));
445        hwm.advance(&manifest("2026.07.4", 10)).unwrap();
446        assert_eq!(hwm.mark(manifest("2026.07.0", 1).layer.line()), Some(10));
447
448        // And it survives a reload, because the refusal an operator meets is
449        // served from the file and not from this process's memory.
450        let reloaded = HighWaterMarks::load(tmp.path()).unwrap();
451        assert_eq!(
452            reloaded.mark(manifest("2026.07.0", 1).layer.line()),
453            Some(10),
454            "the mark did not persist at its highest value"
455        );
456    }
457
458    // rivet: verifies REQ-ROLLBACK-001
459    #[test]
460    fn a_counter_below_the_mark_is_rejected() {
461        let tmp = tempfile::tempdir().unwrap();
462        let mut hwm = HighWaterMarks::load(tmp.path()).unwrap();
463        hwm.advance(&manifest("2026.07.1", 4)).unwrap();
464        let verdict = hwm.check(&manifest("2026.07.0", 3));
465        assert_eq!(
466            verdict,
467            RollbackVerdict::Rollback {
468                line: "2026.07".into(),
469                presented: 3,
470                high_water: 4
471            }
472        );
473    }
474
475    // rivet: verifies REQ-ROLLBACK-001
476    #[test]
477    fn an_equal_counter_reinstalls_cleanly() {
478        let tmp = tempfile::tempdir().unwrap();
479        let mut hwm = HighWaterMarks::load(tmp.path()).unwrap();
480        hwm.advance(&manifest("2026.07.0", 3)).unwrap();
481        assert_eq!(
482            hwm.check(&manifest("2026.07.0", 3)),
483            RollbackVerdict::Accept
484        );
485    }
486
487    // rivet: verifies REQ-ROLLBACK-001
488    #[test]
489    fn counters_are_scoped_per_line() {
490        let tmp = tempfile::tempdir().unwrap();
491        let mut hwm = HighWaterMarks::load(tmp.path()).unwrap();
492        hwm.advance(&manifest("2026.08.0", 9)).unwrap();
493        // The August line's mark must not embargo the July line: wohl stays
494        // frozen on July without being pressured forward.
495        assert_eq!(
496            hwm.check(&manifest("2026.07.0", 1)),
497            RollbackVerdict::Accept
498        );
499    }
500
501    // rivet: verifies REQ-ROLLBACK-001
502    #[test]
503    fn marks_survive_a_new_session() {
504        let tmp = tempfile::tempdir().unwrap();
505        {
506            let mut hwm = HighWaterMarks::load(tmp.path()).unwrap();
507            hwm.advance(&manifest("2026.07.1", 5)).unwrap();
508        }
509        let hwm = HighWaterMarks::load(tmp.path()).unwrap();
510        assert_eq!(
511            hwm.check(&manifest("2026.07.0", 2)),
512            RollbackVerdict::Rollback {
513                line: "2026.07".into(),
514                presented: 2,
515                high_water: 5
516            }
517        );
518    }
519
520    // rivet: verifies REQ-ROLLBACK-001
521    #[test]
522    fn advance_never_lowers_a_mark() {
523        let tmp = tempfile::tempdir().unwrap();
524        let mut hwm = HighWaterMarks::load(tmp.path()).unwrap();
525        hwm.advance(&manifest("2026.07.1", 5)).unwrap();
526        hwm.advance(&manifest("2026.07.0", 2)).unwrap();
527        assert_eq!(hwm.mark(manifest("2026.07.0", 2).layer.line()), Some(5));
528    }
529
530    // rivet: verifies REQ-ROLLBACK-001
531    #[test]
532    fn corrupt_state_is_an_error_not_a_reset() {
533        let tmp = tempfile::tempdir().unwrap();
534        let state_dir = tmp.path().join("state");
535        std::fs::create_dir_all(&state_dir).unwrap();
536        std::fs::write(state_dir.join("high-water-marks.json"), b"{ nope").unwrap();
537        // A silent reset would reopen the rollback window; refuse instead.
538        assert!(matches!(
539            HighWaterMarks::load(tmp.path()),
540            Err(RollbackError::Corrupt { .. })
541        ));
542    }
543
544    // rivet: verifies REQ-ROLLBACK-001
545    #[test]
546    fn epoch_day_arithmetic_matches_the_civil_calendar() {
547        // ABSOLUTE anchors (differences would let constant-offset mutants
548        // cancel), computed independently: epoch, leap days, century rules,
549        // and year 0000 — the one reachable negative-era branch. Kills the
550        // arithmetic mutants in the Hinnant algorithm.
551        for (ts, days) in [
552            ("1970-01-01T00:00:00Z", 0i64),
553            ("1970-01-02T00:00:00Z", 1),
554            ("1969-12-31T00:00:00Z", -1),
555            ("2000-02-29T00:00:00Z", 11016),
556            ("2026-08-07T00:00:00Z", 20672),
557            ("2026-03-01T00:00:00Z", 20513),
558            ("2024-02-29T00:00:00Z", 19782),
559            ("2100-01-01T00:00:00Z", 47482),
560            ("1900-03-01T00:00:00Z", -25508),
561            ("2026-12-31T00:00:00Z", 20818),
562            ("0000-03-01T00:00:00Z", -719468),
563            ("0000-01-01T00:00:00Z", -719528),
564            ("0000-02-29T00:00:00Z", -719469),
565        ] {
566            assert_eq!(epoch_days(ts), Some(days), "epoch_days({ts})");
567        }
568        // Out-of-range calendar fields are None, not a number.
569        for bad in [
570            "2026-13-01T00:00:00Z",
571            "2026-00-01T00:00:00Z",
572            "2026-01-32T00:00:00Z",
573            "2026-01-00T00:00:00Z",
574        ] {
575            assert_eq!(epoch_days(bad), None, "{bad}");
576        }
577    }
578
579    // rivet: verifies REQ-ROLLBACK-001
580    #[test]
581    fn epoch_days_enforces_the_exact_yyyy_mm_dd_t_shape() {
582        // A bare 10-char date (no time) is valid; anything after must be 'T'.
583        assert_eq!(epoch_days("2026-08-07"), Some(20672));
584        assert_eq!(epoch_days("2026-08-07 00:00:00Z"), None, "space, not T");
585        assert_eq!(epoch_days("2026-08-07X"), None, "non-T separator");
586        // Field widths are exact; extra dash-fields rejected.
587        for bad in [
588            "2026-08-7T00:00:00Z",  // date part only 9 chars -> len != 10
589            "2026X08-07T00:00:00Z", // dash-at-4 missing
590            "2026-08X07T00:00:00Z", // dash-at-7 missing
591            "202608-07T00:00:00Z",  // shifted, both dashes wrong
592        ] {
593            assert_eq!(epoch_days(bad), None, "{bad}");
594        }
595    }
596
597    // rivet: verifies REQ-ROLLBACK-001
598    #[test]
599    fn epoch_days_applies_the_full_gregorian_leap_rule() {
600        // Feb 29 valid only on real leap years — exercises %4, %100, %400
601        // independently so no single leap-condition mutant survives.
602        assert!(epoch_days("2024-02-29T00:00:00Z").is_some(), "2024 %4 leap");
603        assert_eq!(epoch_days("2023-02-29T00:00:00Z"), None, "2023 non-leap");
604        assert_eq!(
605            epoch_days("1900-02-29T00:00:00Z"),
606            None,
607            "1900 %100 non-leap"
608        );
609        assert!(
610            epoch_days("2000-02-29T00:00:00Z").is_some(),
611            "2000 %400 leap"
612        );
613        // And Feb 28 is always valid, Feb 30 never.
614        assert!(epoch_days("2023-02-28T00:00:00Z").is_some());
615        assert_eq!(epoch_days("2024-02-30T00:00:00Z"), None);
616        // 30-day month boundary.
617        assert!(epoch_days("2026-04-30T00:00:00Z").is_some());
618        assert_eq!(epoch_days("2026-04-31T00:00:00Z"), None, "April has 30");
619    }
620
621    // rivet: verifies REQ-ROLLBACK-001
622    #[test]
623    fn staleness_threshold_boundary_is_strictly_greater_than() {
624        // Exactly at the threshold: quiet. One past: warn.
625        assert_eq!(
626            staleness_warning("2026-07-01T00:00:00Z", "2026-07-31T00:00:00Z", 30),
627            None
628        );
629        assert_eq!(
630            staleness_warning("2026-07-01T00:00:00Z", "2026-08-01T00:00:00Z", 30),
631            Some(31)
632        );
633    }
634
635    // rivet: verifies REQ-ROLLBACK-001
636    #[test]
637    fn an_unreadable_state_file_is_an_io_error_not_first_contact() {
638        // A directory where the state file should be: reading errors with
639        // something other than NotFound — must surface, never silently
640        // reset the marks (that would reopen the rollback window).
641        let tmp = tempfile::tempdir().unwrap();
642        std::fs::create_dir_all(tmp.path().join("state/high-water-marks.json")).unwrap();
643        assert!(matches!(
644            HighWaterMarks::load(tmp.path()),
645            Err(RollbackError::Io { .. })
646        ));
647    }
648
649    // rivet: verifies REQ-ROLLBACK-001
650    #[test]
651    fn staleness_is_a_pure_function_of_issued_at_now_and_threshold() {
652        // 100 days old, threshold 90: warn with the age.
653        assert_eq!(
654            staleness_warning("2026-04-01T00:00:00Z", "2026-07-10T00:00:00Z", 90),
655            Some(100)
656        );
657        // 10 days old, threshold 90: quiet.
658        assert_eq!(
659            staleness_warning("2026-06-30T00:00:00Z", "2026-07-10T00:00:00Z", 90),
660            None
661        );
662        // Unparseable issued-at: warn conservatively? No — the manifest
663        // parser already rejected it; here both inputs are trusted RFC 3339.
664        // Clock skew (issued-at in the future) is quiet, not negative-aged.
665        assert_eq!(
666            staleness_warning("2026-08-01T00:00:00Z", "2026-07-10T00:00:00Z", 90),
667            None
668        );
669    }
670}
671
672#[cfg(test)]
673mod first_contact_tests {
674    use super::*;
675
676    use crate::manifest::{LayerManifest, fixtures};
677
678    fn manifest(layer: &str, counter: u64) -> LayerManifest {
679        LayerManifest::parse(&fixtures::manifest(
680            layer,
681            "qualified",
682            counter,
683            "2026-07-31T09:14:00Z",
684        ))
685        .unwrap()
686    }
687
688    /// A fresh client, no marks file, nothing recorded — the state every new
689    /// machine starts in.
690    fn fresh() -> (tempfile::TempDir, HighWaterMarks) {
691        let tmp = tempfile::tempdir().unwrap();
692        let hwm = HighWaterMarks::load(tmp.path()).unwrap();
693        (tmp, hwm)
694    }
695
696    fn with_mark(line: &str, counter: u64) -> (tempfile::TempDir, HighWaterMarks) {
697        let tmp = tempfile::tempdir().unwrap();
698        let mut hwm = HighWaterMarks::load(tmp.path()).unwrap();
699        hwm.advance(&manifest(&format!("{line}.{counter}"), counter))
700            .unwrap();
701        (tmp, hwm)
702    }
703
704    /// The hole this closes. A consumer with no history accepted ANY counter,
705    /// because there was nothing to compare against — the one moment the
706    /// anti-rollback property protects nobody, and the moment an attacker
707    /// picks. A fresh checkout, a new CI runner, a new machine: every one is a
708    /// first contact, so "first contact is rare" is false in exactly the
709    /// environments varve is built for.
710    // rivet: verifies REQ-FIRSTCONTACT-001
711    #[test]
712    fn a_first_contact_below_the_signed_floor_is_refused() {
713        let (_t, hwm) = fresh();
714        // No mark for this line at all.
715        assert_eq!(
716            hwm.check(&manifest("2026.07.2", 2)),
717            RollbackVerdict::Accept
718        );
719        // With a realm-stated floor, the same layer is refused.
720        match hwm.check_with_floor(&manifest("2026.07.2", 2), Some(5)) {
721            RollbackVerdict::BelowFloor {
722                line,
723                presented,
724                floor,
725            } => {
726                assert_eq!(line, "2026.07");
727                assert_eq!(presented, 2);
728                assert_eq!(floor, 5);
729            }
730            other => panic!("expected BelowFloor, got {other:?}"),
731        }
732    }
733
734    // rivet: verifies REQ-FIRSTCONTACT-001
735    #[test]
736    fn a_first_contact_at_or_above_the_floor_is_accepted() {
737        let (_t, hwm) = fresh();
738        assert_eq!(
739            hwm.check_with_floor(&manifest("2026.07.5", 5), Some(5)),
740            RollbackVerdict::Accept
741        );
742        assert_eq!(
743            hwm.check_with_floor(&manifest("2026.07.9", 9), Some(5)),
744            RollbackVerdict::Accept
745        );
746    }
747
748    /// The floor raises the bottom for someone with no history. It must never
749    /// LOWER it for someone who has one: a consumer who has accepted counter 9
750    /// cannot be walked back to a realm-stated floor of 3.
751    // rivet: verifies REQ-FIRSTCONTACT-001
752    #[test]
753    fn a_floor_below_a_recorded_mark_does_not_reopen_the_window() {
754        let (_t, hwm) = with_mark("2026.07", 9);
755        match hwm.check_with_floor(&manifest("2026.07.3", 3), Some(3)) {
756            RollbackVerdict::Rollback { high_water, .. } => assert_eq!(high_water, 9),
757            other => panic!("the local mark must still win: {other:?}"),
758        }
759    }
760
761    /// A line with no stated floor behaves exactly as before, so a realm that
762    /// has not adopted this keeps working.
763    // rivet: verifies REQ-FIRSTCONTACT-001
764    #[test]
765    fn a_line_with_no_stated_floor_is_unchanged() {
766        let (_t, hwm) = fresh();
767        assert_eq!(
768            hwm.check_with_floor(&manifest("2026.07.0", 0), None),
769            RollbackVerdict::Accept
770        );
771        assert_eq!(
772            hwm.check(&manifest("2026.07.0", 0)),
773            hwm.check_with_floor(&manifest("2026.07.0", 0), None)
774        );
775    }
776
777    /// A floor of zero is not protection, and must not read as if it were —
778    /// it accepts everything, which is what an attacker would choose if they
779    /// could pick the number. (They cannot: the floor is only read from a
780    /// line-status already verified against the realm root.)
781    // rivet: verifies REQ-FIRSTCONTACT-001
782    #[test]
783    fn a_floor_of_zero_accepts_everything_exactly_as_no_floor_does() {
784        let (_t, hwm) = fresh();
785        assert_eq!(
786            hwm.check_with_floor(&manifest("2026.07.0", 0), Some(0)),
787            RollbackVerdict::Accept
788        );
789    }
790
791    /// The floor is per LINE. A floor learned for one line must not silently
792    /// govern another — lines advance independently.
793    // rivet: verifies REQ-FIRSTCONTACT-001
794    #[test]
795    fn the_floor_applies_to_the_line_it_was_stated_for() {
796        let (_t, hwm) = with_mark("2026.07", 9);
797        // A different line has no mark, so the floor governs it.
798        match hwm.check_with_floor(&manifest("2026.08.1", 1), Some(4)) {
799            RollbackVerdict::BelowFloor { line, .. } => assert_eq!(line, "2026.08"),
800            other => panic!("{other:?}"),
801        }
802    }
803}