Skip to main content

vault_core/
config_history.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright the UnENVerse contributors.
3//! Phase 35 — the config time machine (ADR-0141).
4//!
5//! Config lives in git and its secrets live elsewhere, and the two drift: the
6//! copy in git is redacted, so it is not the file that runs, and the file that
7//! runs is versioned by nobody. The vault is the one place that holds both, so
8//! it keeps a snapshot of every rendered config whenever that config changes.
9//!
10//! # Two copies of each snapshot, on purpose
11//!
12//! `content` is the file exactly as it would be deployed, secrets included.
13//! `masked` is the same render with every resolved secret replaced by its
14//! fingerprint, which is what `unv project export` already prints to a
15//! terminal. Every default view (list, show, diff, the app) reads `masked`, so
16//! "this key changed" is visible without the key ever being read; `content`
17//! is reached only with `--reveal`/`--out` or the app's Reveal. Masking the
18//! stored text afterwards would not work: a rotated-away secret is no longer in
19//! the vault, so nothing would know to mask it in an old snapshot.
20//!
21//! # Tamper evidence and retention
22//!
23//! Each stream (project and exporter) is a hash chain: `chain = sha256(prev ‖
24//! project ‖ exporter ‖ sha(content) ‖ sha(masked) ‖ at)`. Old secrets living
25//! forever is a liability, so history is pruned by policy (`keep` newest and
26//! everything younger than `days`), and pruning a prefix would normally break
27//! the chain. A **checkpoint** row records the chain value at the pruned
28//! boundary so the remainder still verifies, and the prune also appends a row
29//! to the vault's own audit chain naming that value; [`verify`] requires the two
30//! to agree, so forging a checkpoint means forging the audit chain too.
31
32use crate::textdiff;
33use rusqlite::{params, Connection, OptionalExtension};
34use serde::Serialize;
35use sha2::{Digest, Sha256};
36
37pub const DEFAULT_KEEP: i64 = 50;
38pub const DEFAULT_DAYS: i64 = 90;
39/// A snapshot larger than this is not stored. A rendered config is kilobytes;
40/// anything bigger is a file this feature was not built for.
41pub const MAX_BYTES: usize = 2 * 1024 * 1024;
42
43pub fn init_schema(conn: &Connection) -> Result<(), String> {
44    conn.execute_batch(
45        "CREATE TABLE IF NOT EXISTS config_snapshots (
46             seq          INTEGER PRIMARY KEY AUTOINCREMENT,
47             project      TEXT NOT NULL,
48             project_name TEXT NOT NULL,
49             exporter     TEXT NOT NULL,
50             at           TEXT NOT NULL,
51             sha256       TEXT NOT NULL,
52             bytes        INTEGER NOT NULL,
53             content      TEXT NOT NULL,
54             masked       TEXT NOT NULL,
55             exposed      TEXT NOT NULL DEFAULT '[]',
56             cause        TEXT NOT NULL,
57             actor        TEXT,
58             chain        TEXT NOT NULL
59         );
60         CREATE INDEX IF NOT EXISTS config_snapshots_stream
61             ON config_snapshots(project, exporter, seq);
62         CREATE INDEX IF NOT EXISTS config_snapshots_sha ON config_snapshots(sha256);
63         CREATE TABLE IF NOT EXISTS config_checkpoints (
64             id                 INTEGER PRIMARY KEY AUTOINCREMENT,
65             project            TEXT NOT NULL,
66             exporter           TEXT NOT NULL,
67             pruned_through_seq INTEGER NOT NULL,
68             chain_at           TEXT NOT NULL,
69             pruned_count       INTEGER NOT NULL,
70             at                 TEXT NOT NULL
71         );",
72    )
73    .map_err(|e| e.to_string())?;
74    // A history created before blast radius (Phase 36) lacks the column. The
75    // migration checks the schema first; an unexpected ALTER failure is never
76    // hidden as a harmless duplicate-column outcome.
77    crate::migrate_schema::add_column_if_missing(
78        conn,
79        "config_snapshots",
80        "exposed",
81        "TEXT NOT NULL DEFAULT '[]'",
82    )?;
83    // R20: a snapshot whose content was purged by `entry forget` keeps its hash and chain link.
84    crate::migrate_schema::add_column_if_missing(
85        conn,
86        "config_snapshots",
87        "forgotten",
88        "INTEGER NOT NULL DEFAULT 0",
89    )?;
90    Ok(())
91}
92
93fn sha(s: &str) -> String {
94    hex::encode(Sha256::digest(s.as_bytes()))
95}
96
97fn chain_of(
98    prev: &str,
99    project: &str,
100    exporter: &str,
101    content: &str,
102    masked: &str,
103    exposed: &str,
104    at: &str,
105) -> String {
106    chain_of_sha(prev, project, exporter, &sha(content), masked, exposed, at)
107}
108
109/// [`chain_of`] from the content's hash, which is all a forgotten snapshot still has.
110fn chain_of_sha(
111    prev: &str,
112    project: &str,
113    exporter: &str,
114    content_sha: &str,
115    masked: &str,
116    exposed: &str,
117    at: &str,
118) -> String {
119    // `exposed` is derived data, but it is what blast radius is answered from, so
120    // editing it to hide an entry must break the chain like editing the text does.
121    sha(&format!(
122        "envv-history-v2|{prev}|{project}|{exporter}|{}|{}|{}|{at}",
123        content_sha,
124        sha(masked),
125        sha(exposed)
126    ))
127}
128
129// ── Policy ────────────────────────────────────────────────────────────────────
130
131#[derive(Debug, Clone, Copy, PartialEq, Serialize)]
132pub struct Policy {
133    pub enabled: bool,
134    pub keep: i64,
135    pub days: i64,
136}
137
138fn meta_get(conn: &Connection, key: &str) -> Option<String> {
139    conn.query_row("SELECT value FROM vault_meta WHERE key = ?1", [key], |r| {
140        r.get(0)
141    })
142    .optional()
143    .ok()
144    .flatten()
145}
146
147fn meta_set(conn: &Connection, key: &str, value: &str) -> Result<(), String> {
148    conn.execute(
149        "INSERT OR REPLACE INTO vault_meta (key, value) VALUES (?1, ?2)",
150        params![key, value],
151    )
152    .map(|_| ())
153    .map_err(|e| e.to_string())
154}
155
156pub fn policy(conn: &Connection) -> Policy {
157    let num = |k: &str, d: i64| {
158        meta_get(conn, k)
159            .and_then(|v| v.parse::<i64>().ok())
160            .filter(|n| *n >= 0)
161            .unwrap_or(d)
162    };
163    Policy {
164        enabled: meta_get(conn, "history_enabled").as_deref() != Some("0"),
165        keep: num("history_keep", DEFAULT_KEEP),
166        days: num("history_days", DEFAULT_DAYS),
167    }
168}
169
170pub fn set_policy(
171    conn: &Connection,
172    enabled: Option<bool>,
173    keep: Option<i64>,
174    days: Option<i64>,
175) -> Result<Policy, String> {
176    if let Some(k) = keep {
177        if !(1..=100_000).contains(&k) {
178            return Err(
179                "keep must be between 1 and 100000 (a stream always keeps its newest snapshot)"
180                    .into(),
181            );
182        }
183        meta_set(conn, "history_keep", &k.to_string())?;
184    }
185    if let Some(d) = days {
186        if !(0..=36_500).contains(&d) {
187            return Err("days must be between 0 and 36500".into());
188        }
189        meta_set(conn, "history_days", &d.to_string())?;
190    }
191    if let Some(e) = enabled {
192        meta_set(conn, "history_enabled", if e { "1" } else { "0" })?;
193    }
194    Ok(policy(conn))
195}
196
197// ── Recording ─────────────────────────────────────────────────────────────────
198
199/// One rendered stream: which project and which exporter produced the text.
200pub struct Stream<'a> {
201    pub project: &'a str,
202    pub project_name: &'a str,
203    pub exporter: &'a str,
204}
205
206#[derive(Debug, Clone, Serialize, PartialEq)]
207pub struct SnapMeta {
208    pub seq: i64,
209    pub project: String,
210    pub project_name: String,
211    pub exporter: String,
212    pub at: String,
213    pub sha256: String,
214    pub bytes: i64,
215    pub cause: String,
216    pub actor: Option<String>,
217}
218
219const META_COLS: &str = "seq, project, project_name, exporter, at, sha256, bytes, cause, actor";
220
221fn meta_row(r: &rusqlite::Row) -> rusqlite::Result<SnapMeta> {
222    Ok(SnapMeta {
223        seq: r.get(0)?,
224        project: r.get(1)?,
225        project_name: r.get(2)?,
226        exporter: r.get(3)?,
227        at: r.get(4)?,
228        sha256: r.get(5)?,
229        bytes: r.get(6)?,
230        cause: r.get(7)?,
231        actor: r.get(8)?,
232    })
233}
234
235/// Records a snapshot when `content` differs from the stream's latest. Returns
236/// the new sequence number, or `None` when nothing changed (or history is off).
237pub fn record(
238    conn: &Connection,
239    s: &Stream,
240    content: &str,
241    masked: &str,
242    exposed: &str,
243    cause: &str,
244    actor: Option<&str>,
245) -> Result<Option<i64>, String> {
246    if !policy(conn).enabled {
247        return Ok(None);
248    }
249    if content.len() > MAX_BYTES {
250        return Err(format!(
251            "{} {} renders to {} bytes; history keeps files up to {} bytes",
252            s.project_name,
253            s.exporter,
254            content.len(),
255            MAX_BYTES
256        ));
257    }
258    // IMMEDIATE: two writers (a save's background snapshot and a push's) must not
259    // both read the same tail and each extend it, or the chain forks and the
260    // stream can never verify again.
261    let tx = rusqlite::Transaction::new_unchecked(conn, rusqlite::TransactionBehavior::Immediate)
262        .map_err(|e| e.to_string())?;
263    let last: Option<(String, String)> = tx
264        .query_row(
265            "SELECT sha256, chain FROM config_snapshots WHERE project = ?1 AND exporter = ?2 \
266             ORDER BY seq DESC LIMIT 1",
267            params![s.project, s.exporter],
268            |r| Ok((r.get(0)?, r.get(1)?)),
269        )
270        .optional()
271        .map_err(|e| e.to_string())?;
272    let new_sha = sha(content);
273    if last.as_ref().is_some_and(|(h, _)| *h == new_sha) {
274        return Ok(None);
275    }
276    // After a prune the newest row may be the only link back to a checkpoint;
277    // either way the previous chain value is the latest row's, or genesis.
278    let prev = last.map_or_else(|| genesis_for(&tx, s.project, s.exporter), |(_, c)| c);
279    let at = crate::iso_now();
280    let chain = chain_of(&prev, s.project, s.exporter, content, masked, exposed, &at);
281    tx.execute(
282        "INSERT INTO config_snapshots \
283         (project, project_name, exporter, at, sha256, bytes, content, masked, exposed, cause, actor, chain) \
284         VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,?12)",
285        params![
286            s.project,
287            s.project_name,
288            s.exporter,
289            at,
290            new_sha,
291            content.len() as i64,
292            content,
293            masked,
294            exposed,
295            cause,
296            actor,
297            chain
298        ],
299    )
300    .map_err(|e| e.to_string())?;
301    let seq = tx.last_insert_rowid();
302    tx.commit().map_err(|e| e.to_string())?;
303    Ok(Some(seq))
304}
305
306/// The chain value a stream's first remaining snapshot extends: the newest
307/// checkpoint's, or genesis when nothing was ever pruned.
308fn genesis_for(conn: &Connection, project: &str, exporter: &str) -> String {
309    conn.query_row(
310        "SELECT chain_at FROM config_checkpoints WHERE project = ?1 AND exporter = ?2 \
311         ORDER BY pruned_through_seq DESC LIMIT 1",
312        params![project, exporter],
313        |r| r.get(0),
314    )
315    .optional()
316    .ok()
317    .flatten()
318    .unwrap_or_else(|| "genesis".to_string())
319}
320
321// ── Reading ───────────────────────────────────────────────────────────────────
322
323pub fn list(
324    conn: &Connection,
325    project: Option<&str>,
326    exporter: Option<&str>,
327    since: Option<&str>,
328    limit: i64,
329) -> Result<Vec<SnapMeta>, String> {
330    let mut stmt = conn
331        .prepare(&format!(
332            "SELECT {META_COLS} FROM config_snapshots \
333             WHERE (?1 IS NULL OR project = ?1 OR project_name = ?1) \
334               AND (?2 IS NULL OR exporter = ?2) AND (?3 IS NULL OR at >= ?3) \
335             ORDER BY seq DESC LIMIT ?4"
336        ))
337        .map_err(|e| e.to_string())?;
338    let rows = stmt
339        .query_map(
340            params![project, exporter, since, limit.clamp(1, 10_000)],
341            meta_row,
342        )
343        .map_err(|e| e.to_string())?;
344    rows.collect::<Result<Vec<_>, _>>()
345        .map_err(|e| e.to_string())
346}
347
348pub struct Snapshot {
349    pub meta: SnapMeta,
350    pub content: String,
351    pub masked: String,
352    /// JSON array of the vault secrets whose exact value appears in `content`.
353    pub exposed: String,
354}
355
356pub fn get(conn: &Connection, seq: i64) -> Result<Option<Snapshot>, String> {
357    let gone: Option<i64> = conn
358        .query_row(
359            "SELECT forgotten FROM config_snapshots WHERE seq = ?1",
360            [seq],
361            |r| r.get(0),
362        )
363        .optional()
364        .map_err(|e| e.to_string())?;
365    if gone == Some(1) {
366        return Err(format!(
367            "The content of snapshot #{seq} was forgotten (unv entry forget); only its hash remains"
368        ));
369    }
370    conn.query_row(
371        &format!(
372            "SELECT {META_COLS}, content, masked, exposed FROM config_snapshots WHERE seq = ?1"
373        ),
374        [seq],
375        |r| {
376            Ok(Snapshot {
377                meta: meta_row(r)?,
378                content: r.get(9)?,
379                masked: r.get(10)?,
380                exposed: r.get(11)?,
381            })
382        },
383    )
384    .optional()
385    .map_err(|e| e.to_string())
386}
387
388/// Snapshots whose content has this hash, newest first. This is how a hub says
389/// "the file on that host is the one rendered on 3 October".
390pub fn find_by_sha(conn: &Connection, sha256: &str, limit: i64) -> Result<Vec<SnapMeta>, String> {
391    let mut stmt = conn
392        .prepare(&format!(
393            "SELECT {META_COLS} FROM config_snapshots WHERE sha256 = ?1 ORDER BY seq DESC LIMIT ?2"
394        ))
395        .map_err(|e| e.to_string())?;
396    let rows = stmt
397        .query_map(params![sha256, limit.clamp(1, 100)], meta_row)
398        .map_err(|e| e.to_string())?;
399    rows.collect::<Result<Vec<_>, _>>()
400        .map_err(|e| e.to_string())
401}
402
403/// What the files with this hash contained: the union over every snapshot that
404/// recorded it (the same text can be recorded again after a revert), or `None`
405/// when no snapshot has it, so a caller can tell "nothing exposed" from "unknown".
406pub fn exposed_by_sha(
407    conn: &Connection,
408    sha256: &str,
409) -> Result<Option<Vec<crate::blast::Exposed>>, String> {
410    let mut stmt = conn
411        .prepare("SELECT exposed FROM config_snapshots WHERE sha256 = ?1")
412        .map_err(|e| e.to_string())?;
413    let rows: Vec<String> = stmt
414        .query_map([sha256], |r| r.get(0))
415        .map_err(|e| e.to_string())?
416        .collect::<Result<_, _>>()
417        .map_err(|e| e.to_string())?;
418    if rows.is_empty() {
419        return Ok(None);
420    }
421    let mut all: Vec<crate::blast::Exposed> = Vec::new();
422    for json in rows {
423        let list: Vec<crate::blast::Exposed> =
424            serde_json::from_str(&json).map_err(|e| e.to_string())?;
425        for e in list {
426            if !all.contains(&e) {
427                all.push(e);
428            }
429        }
430    }
431    Ok(Some(all))
432}
433
434/// The newest snapshot of a stream.
435pub fn latest(
436    conn: &Connection,
437    project: &str,
438    exporter: &str,
439) -> Result<Option<Snapshot>, String> {
440    let seq: Option<i64> = conn
441        .query_row(
442            "SELECT seq FROM config_snapshots WHERE project = ?1 AND exporter = ?2 \
443             ORDER BY seq DESC LIMIT 1",
444            params![project, exporter],
445            |r| r.get(0),
446        )
447        .optional()
448        .map_err(|e| e.to_string())?;
449    match seq {
450        Some(s) => get(conn, s),
451        None => Ok(None),
452    }
453}
454
455/// A unified diff between two snapshots of the same stream. `masked` picks the
456/// fingerprinted text (the default everywhere) or the real one.
457pub fn diff(
458    conn: &Connection,
459    a: i64,
460    b: i64,
461    masked: bool,
462    context: usize,
463) -> Result<String, String> {
464    let sa = get(conn, a)?.ok_or_else(|| format!("No snapshot #{a}"))?;
465    let sb = get(conn, b)?.ok_or_else(|| format!("No snapshot #{b}"))?;
466    if (&sa.meta.project, &sa.meta.exporter) != (&sb.meta.project, &sb.meta.exporter) {
467        return Err(
468            "Those snapshots belong to different configs; compare two of one stream".into(),
469        );
470    }
471    let pick = |s: &Snapshot| {
472        if masked {
473            s.masked.clone()
474        } else {
475            s.content.clone()
476        }
477    };
478    Ok(textdiff::unified(
479        &format!("#{a} {}", sa.meta.at),
480        &format!("#{b} {}", sb.meta.at),
481        &pick(&sa),
482        &pick(&sb),
483        context,
484    ))
485}
486
487/// Picks the two snapshots a diff should compare. With `from`/`to` unset, the two
488/// newest of the stream named by `project` (and `exporter`, which is required
489/// when the project has more than one stream, such as Compose and its `.env`).
490pub fn resolve_pair(
491    conn: &Connection,
492    project: Option<&str>,
493    exporter: Option<&str>,
494    from: Option<i64>,
495    to: Option<i64>,
496) -> Result<(i64, i64), String> {
497    if let (Some(a), Some(b)) = (from, to) {
498        return Ok((a, b));
499    }
500    let project = project.ok_or("Name a project, or give both --from and --to")?;
501    let rows = list(conn, Some(project), exporter, None, 1000)?;
502    let mut exporters: Vec<&str> = rows.iter().map(|m| m.exporter.as_str()).collect();
503    exporters.sort_unstable();
504    exporters.dedup();
505    if exporters.len() > 1 {
506        return Err(format!(
507            "'{project}' has several configs ({}); say which with --exporter",
508            exporters.join(", ")
509        ));
510    }
511    // `rows` is newest first.
512    let newest = rows
513        .first()
514        .ok_or_else(|| format!("No snapshots of '{project}' yet"))?;
515    let b = to.unwrap_or(newest.seq);
516    let a = match from {
517        Some(a) => a,
518        None => rows
519            .iter()
520            .find(|m| m.seq < b)
521            .map(|m| m.seq)
522            .ok_or_else(|| {
523                format!("'{project}' has only one snapshot, so there is nothing to compare")
524            })?,
525    };
526    Ok((a, b))
527}
528
529// ── Retention ─────────────────────────────────────────────────────────────────
530
531#[derive(Debug, Serialize, PartialEq)]
532pub struct PruneReport {
533    pub would_delete: i64,
534    pub deleted: i64,
535    pub streams_touched: i64,
536    pub bytes_freed: i64,
537}
538
539/// Deletes, per stream, every snapshot that is both beyond the newest `keep` and
540/// older than `days` days, leaving a checkpoint so the rest still verifies.
541/// `dry_run` counts without touching anything.
542pub fn prune(
543    conn: &Connection,
544    keep: i64,
545    days: i64,
546    dry_run: bool,
547    actor: Option<&str>,
548) -> Result<PruneReport, String> {
549    let cutoff = cutoff_iso(days)?;
550    let streams: Vec<(String, String)> = {
551        let mut st = conn
552            .prepare("SELECT DISTINCT project, exporter FROM config_snapshots")
553            .map_err(|e| e.to_string())?;
554        let rows = st
555            .query_map([], |r| Ok((r.get(0)?, r.get(1)?)))
556            .map_err(|e| e.to_string())?;
557        rows.collect::<Result<_, _>>().map_err(|e| e.to_string())?
558    };
559    let mut rep = PruneReport {
560        would_delete: 0,
561        deleted: 0,
562        streams_touched: 0,
563        bytes_freed: 0,
564    };
565    // IMMEDIATE: two writers (a save's background snapshot and a push's) must not
566    // both read the same tail and each extend it, or the chain forks and the
567    // stream can never verify again.
568    let tx = rusqlite::Transaction::new_unchecked(conn, rusqlite::TransactionBehavior::Immediate)
569        .map_err(|e| e.to_string())?;
570    for (project, exporter) in streams {
571        // Rows to delete: older than the cutoff AND not among the newest `keep`.
572        // `keep >= 1` is enforced by the policy, so a stream never empties.
573        let doomed: Vec<(i64, String, i64)> = {
574            let mut st = tx
575                .prepare(
576                    "SELECT seq, chain, bytes, at FROM config_snapshots \
577                     WHERE project = ?1 AND exporter = ?2 ORDER BY seq ASC",
578                )
579                .map_err(|e| e.to_string())?;
580            let rows = st
581                .query_map(params![project, exporter], |r| {
582                    Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get::<_, String>(3)?))
583                })
584                .map_err(|e| e.to_string())?;
585            let all: Vec<(i64, String, i64, String)> =
586                rows.collect::<Result<_, _>>().map_err(|e| e.to_string())?;
587            // The newest `keep` rows stay whatever their timestamps say.
588            let keep_from = all.len().saturating_sub(keep.max(1) as usize);
589            // Only a PREFIX can be pruned (a checkpoint stands in for everything up to
590            // a seq), so stop at the first row that is recent or inside the kept window.
591            // A clock that stepped back can leave a recent row between two old ones.
592            all.into_iter()
593                .enumerate()
594                .take_while(|(i, r)| *i < keep_from && r.3.as_str() < cutoff.as_str())
595                .map(|(_, r)| (r.0, r.1, r.2))
596                .collect()
597        };
598        let Some((last_seq, last_chain, _)) = doomed.last().cloned() else {
599            continue;
600        };
601        rep.would_delete += doomed.len() as i64;
602        rep.bytes_freed += doomed.iter().map(|d| d.2).sum::<i64>();
603        rep.streams_touched += 1;
604        if dry_run {
605            continue;
606        }
607        tx.execute(
608            "DELETE FROM config_snapshots WHERE project = ?1 AND exporter = ?2 AND seq <= ?3",
609            params![project, exporter, last_seq],
610        )
611        .map_err(|e| e.to_string())?;
612        let at = crate::iso_now();
613        tx.execute(
614            "INSERT INTO config_checkpoints \
615             (project, exporter, pruned_through_seq, chain_at, pruned_count, at) \
616             VALUES (?1,?2,?3,?4,?5,?6)",
617            params![
618                project,
619                exporter,
620                last_seq,
621                last_chain,
622                doomed.len() as i64,
623                at
624            ],
625        )
626        .map_err(|e| e.to_string())?;
627        rep.deleted += doomed.len() as i64;
628        // The audit chain is the other half of the attestation: verify() demands a
629        // row naming this chain value for every checkpoint.
630        crate::record_event(
631            &tx,
632            "config.prune",
633            &project,
634            Some(
635                &serde_json::json!({
636                    "exporter": exporter, "through_seq": last_seq,
637                    "chain_at": last_chain, "count": doomed.len()
638                })
639                .to_string(),
640            ),
641            actor,
642        )?;
643    }
644    tx.commit().map_err(|e| e.to_string())?;
645    Ok(rep)
646}
647
648fn cutoff_iso(days: i64) -> Result<String, String> {
649    let now = time::OffsetDateTime::now_utc();
650    let then = now
651        .checked_sub(time::Duration::days(days))
652        .ok_or("days is out of range")?;
653    Ok(format!(
654        "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}Z",
655        then.year(),
656        u8::from(then.month()),
657        then.day(),
658        then.hour(),
659        then.minute(),
660        then.second()
661    ))
662}
663
664// ── Verification ──────────────────────────────────────────────────────────────
665
666#[derive(Debug, Serialize, PartialEq)]
667pub struct VerifyReport {
668    pub streams: i64,
669    pub snapshots: i64,
670    pub checkpoints: i64,
671    pub problems: Vec<String>,
672}
673
674/// Recomputes every hash and every chain, and checks each checkpoint against the
675/// audit chain.
676pub fn verify(conn: &Connection) -> Result<VerifyReport, String> {
677    let mut rep = VerifyReport {
678        streams: 0,
679        snapshots: 0,
680        checkpoints: 0,
681        problems: vec![],
682    };
683    let streams: Vec<(String, String)> = {
684        let mut st = conn
685            .prepare(
686                "SELECT project, exporter FROM config_snapshots \
687                 UNION SELECT project, exporter FROM config_checkpoints",
688            )
689            .map_err(|e| e.to_string())?;
690        let rows = st
691            .query_map([], |r| Ok((r.get(0)?, r.get(1)?)))
692            .map_err(|e| e.to_string())?;
693        rows.collect::<Result<_, _>>().map_err(|e| e.to_string())?
694    };
695    let audit: Vec<String> = {
696        let mut st = conn
697            .prepare("SELECT COALESCE(details,'') FROM vault_audit WHERE action = 'config.prune'")
698            .map_err(|e| e.to_string())?;
699        let rows = st.query_map([], |r| r.get(0)).map_err(|e| e.to_string())?;
700        rows.collect::<Result<_, _>>().map_err(|e| e.to_string())?
701    };
702    for (project, exporter) in streams {
703        rep.streams += 1;
704        let label = format!("{project}/{exporter}");
705        let cps: Vec<(i64, String)> = {
706            let mut st = conn
707                .prepare(
708                    "SELECT pruned_through_seq, chain_at FROM config_checkpoints \
709                     WHERE project = ?1 AND exporter = ?2 ORDER BY pruned_through_seq ASC",
710                )
711                .map_err(|e| e.to_string())?;
712            let rows = st
713                .query_map(params![project, exporter], |r| Ok((r.get(0)?, r.get(1)?)))
714                .map_err(|e| e.to_string())?;
715            rows.collect::<Result<_, _>>().map_err(|e| e.to_string())?
716        };
717        for (through, chain_at) in &cps {
718            rep.checkpoints += 1;
719            if !audit.iter().any(|d| d.contains(chain_at.as_str())) {
720                rep.problems.push(format!(
721                    "{label}: checkpoint through #{through} has no matching row in the audit chain"
722                ));
723            }
724        }
725        let mut prev = cps
726            .last()
727            .map_or_else(|| "genesis".to_string(), |c| c.1.clone());
728        let mut st = conn
729            .prepare(
730                "SELECT seq, at, content, masked, sha256, bytes, chain, exposed, forgotten FROM config_snapshots \
731                 WHERE project = ?1 AND exporter = ?2 ORDER BY seq ASC",
732            )
733            .map_err(|e| e.to_string())?;
734        let rows = st
735            .query_map(params![project, exporter], |r| {
736                Ok((
737                    r.get::<_, i64>(0)?,
738                    r.get::<_, String>(1)?,
739                    r.get::<_, String>(2)?,
740                    r.get::<_, String>(3)?,
741                    r.get::<_, String>(4)?,
742                    r.get::<_, i64>(5)?,
743                    r.get::<_, String>(6)?,
744                    r.get::<_, String>(7)?,
745                    r.get::<_, i64>(8)? == 1,
746                ))
747            })
748            .map_err(|e| e.to_string())?;
749        for row in rows {
750            let (seq, at, content, masked, stored_sha, bytes, chain, exposed, forgotten) =
751                row.map_err(|e| e.to_string())?;
752            rep.snapshots += 1;
753            // A forgotten snapshot has no content left to hash; the stored hash stands in for it,
754            // and an edit to that hash still breaks the chain below.
755            if forgotten {
756                if !content.is_empty() {
757                    rep.problems.push(format!(
758                        "{label}: #{seq} is marked forgotten but still holds content"
759                    ));
760                }
761            } else if sha(&content) != stored_sha || content.len() as i64 != bytes {
762                rep.problems
763                    .push(format!("{label}: #{seq} content does not match its hash"));
764            }
765            let want = chain_of_sha(
766                &prev,
767                &project,
768                &exporter,
769                &stored_sha,
770                &masked,
771                &exposed,
772                &at,
773            );
774            if want != chain {
775                rep.problems
776                    .push(format!("{label}: #{seq} breaks the chain"));
777            }
778            prev = chain;
779        }
780    }
781    Ok(rep)
782}
783
784#[derive(Debug, Serialize)]
785pub struct Stats {
786    pub snapshots: i64,
787    pub streams: i64,
788    pub bytes: i64,
789    pub oldest: Option<String>,
790}
791
792pub fn stats(conn: &Connection) -> Result<Stats, String> {
793    conn.query_row(
794        "SELECT COUNT(*), COUNT(DISTINCT project || '/' || exporter), COALESCE(SUM(bytes),0), MIN(at) \
795         FROM config_snapshots",
796        [],
797        |r| {
798            Ok(Stats {
799                snapshots: r.get(0)?,
800                streams: r.get(1)?,
801                bytes: r.get(2)?,
802                oldest: r.get(3)?,
803            })
804        },
805    )
806    .map_err(|e| e.to_string())
807}
808
809#[cfg(test)]
810mod tests {
811    use super::*;
812
813    fn db() -> Connection {
814        let c = Connection::open_in_memory().unwrap();
815        crate::init_schema(&c).unwrap();
816        c
817    }
818
819    const S: Stream = Stream {
820        project: "p1",
821        project_name: "edge",
822        exporter: "nginx",
823    };
824
825    fn rec(c: &Connection, body: &str) -> Option<i64> {
826        record(c, &S, body, &masked_of(body), "[]", "save", Some("owner")).unwrap()
827    }
828
829    /// Stands in for the fingerprinted render: derived from the body but not
830    /// containing it, as a real masked render does not contain the secret.
831    fn masked_of(body: &str) -> String {
832        format!("m:{}", &sha(body)[..8])
833    }
834
835    /// Rewrites `at` so a snapshot looks older, keeping the chain valid the way
836    /// a real older snapshot would be: recompute from the start of the stream.
837    fn age(c: &Connection, seq: i64, at: &str) {
838        c.execute(
839            "UPDATE config_snapshots SET at = ?1 WHERE seq = ?2",
840            params![at, seq],
841        )
842        .unwrap();
843        rechain(c);
844    }
845
846    fn rechain(c: &Connection) {
847        let rows: Vec<(i64, String, String, String, String)> = {
848            let mut st = c
849                .prepare(
850                    "SELECT seq, at, content, masked, exposed FROM config_snapshots ORDER BY seq",
851                )
852                .unwrap();
853            st.query_map([], |r| {
854                Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?))
855            })
856            .unwrap()
857            .map(Result::unwrap)
858            .collect()
859        };
860        let mut prev = genesis_for(c, "p1", "nginx");
861        for (seq, at, content, masked, exposed) in rows {
862            prev = chain_of(&prev, "p1", "nginx", &content, &masked, &exposed, &at);
863            c.execute(
864                "UPDATE config_snapshots SET chain = ?1 WHERE seq = ?2",
865                params![prev, seq],
866            )
867            .unwrap();
868        }
869    }
870
871    #[test]
872    fn concurrent_writers_never_fork_the_chain() {
873        // A counter beside the process id, not the clock: two tests starting within one clock tick
874        // (macOS has a coarse one) shared a directory and failed with "database is locked".
875        let n = {
876            use std::sync::atomic::{AtomicU64, Ordering};
877            static SEQ: AtomicU64 = AtomicU64::new(0);
878            format!(
879                "{}-{}",
880                std::process::id(),
881                SEQ.fetch_add(1, Ordering::SeqCst)
882            )
883        };
884        let path = std::env::temp_dir().join(format!("unv-hist-conc-{n}.db"));
885        {
886            let c = Connection::open(&path).unwrap();
887            crate::init_schema(&c).unwrap();
888        }
889        let handles: Vec<_> = (0..4)
890            .map(|t| {
891                let path = path.clone();
892                std::thread::spawn(move || {
893                    let c = Connection::open(&path).unwrap();
894                    // Windows file locking serialises these writers for longer than
895                    // rusqlite's default 5 s wait ("database is locked" in CI). The
896                    // test is about the chain, not about how long a writer queues.
897                    c.busy_timeout(std::time::Duration::from_secs(120)).unwrap();
898                    for i in 0..25 {
899                        let body = format!("thread {t} version {i}");
900                        record(&c, &S, &body, &masked_of(&body), "[]", "save", None).unwrap();
901                    }
902                })
903            })
904            .collect();
905        for h in handles {
906            h.join().unwrap();
907        }
908        let c = Connection::open(&path).unwrap();
909        let v = verify(&c).unwrap();
910        assert_eq!(v.snapshots, 100);
911        assert!(v.problems.is_empty(), "{:?}", v.problems);
912    }
913
914    #[test]
915    fn a_change_is_recorded_and_an_identical_render_is_not() {
916        let c = db();
917        assert!(rec(&c, "a").is_some());
918        assert!(rec(&c, "a").is_none());
919        assert!(rec(&c, "b").is_some());
920        assert_eq!(list(&c, Some("edge"), None, None, 10).unwrap().len(), 2);
921    }
922
923    #[test]
924    fn going_back_to_an_earlier_text_is_a_new_snapshot() {
925        let c = db();
926        rec(&c, "a");
927        rec(&c, "b");
928        assert!(rec(&c, "a").is_some(), "reverting a change is a change");
929    }
930
931    #[test]
932    fn a_stream_is_per_project_and_exporter() {
933        let c = db();
934        rec(&c, "a");
935        let other = Stream {
936            project: "p1",
937            project_name: "edge",
938            exporter: "compose",
939        };
940        assert!(record(&c, &other, "a", "m", "[]", "save", None)
941            .unwrap()
942            .is_some());
943    }
944
945    #[test]
946    fn disabled_history_records_nothing() {
947        let c = db();
948        set_policy(&c, Some(false), None, None).unwrap();
949        assert!(rec(&c, "a").is_none());
950        set_policy(&c, Some(true), None, None).unwrap();
951        assert!(rec(&c, "a").is_some());
952    }
953
954    #[test]
955    fn default_views_read_the_masked_text_and_only_get_returns_the_real_one() {
956        let c = db();
957        let s1 = rec(&c, "key=REAL1").unwrap();
958        let s2 = rec(&c, "key=REAL2").unwrap();
959        let d = diff(&c, s1, s2, true, 3).unwrap();
960        assert!(d.contains(&format!("-{}", masked_of("key=REAL1"))));
961        assert!(d.contains(&format!("+{}", masked_of("key=REAL2"))));
962        assert!(
963            !d.contains("REAL"),
964            "a masked diff carried the real value: {d}"
965        );
966        let real = diff(&c, s1, s2, false, 3).unwrap();
967        assert!(real.contains("-key=REAL1") && real.contains("+key=REAL2"));
968    }
969
970    #[test]
971    fn the_default_diff_compares_the_two_newest_and_asks_when_a_project_has_two_configs() {
972        let c = db();
973        let a = rec(&c, "a").unwrap();
974        let b = rec(&c, "b").unwrap();
975        assert_eq!(
976            resolve_pair(&c, Some("edge"), None, None, None).unwrap(),
977            (a, b)
978        );
979        assert_eq!(
980            resolve_pair(&c, Some("edge"), None, Some(a), None).unwrap(),
981            (a, b)
982        );
983        assert_eq!(
984            resolve_pair(&c, None, None, Some(1), Some(2)).unwrap(),
985            (1, 2)
986        );
987        assert!(resolve_pair(&c, None, None, None, None).is_err());
988        let other = Stream {
989            project: "p1",
990            project_name: "edge",
991            exporter: "compose",
992        };
993        record(&c, &other, "x", "m", "[]", "save", None).unwrap();
994        let e = resolve_pair(&c, Some("edge"), None, None, None).unwrap_err();
995        assert!(e.contains("--exporter"), "{e}");
996        assert!(resolve_pair(&c, Some("edge"), Some("nginx"), None, None).is_ok());
997    }
998
999    #[test]
1000    fn one_snapshot_has_nothing_to_compare_with() {
1001        let c = db();
1002        rec(&c, "a");
1003        assert!(resolve_pair(&c, Some("edge"), None, None, None)
1004            .unwrap_err()
1005            .contains("only one"));
1006    }
1007
1008    #[test]
1009    fn a_diff_of_two_different_streams_is_refused() {
1010        let c = db();
1011        let a = rec(&c, "a").unwrap();
1012        let other = Stream {
1013            project: "p2",
1014            project_name: "x",
1015            exporter: "nginx",
1016        };
1017        let b = record(&c, &other, "b", "m", "[]", "save", None)
1018            .unwrap()
1019            .unwrap();
1020        assert!(diff(&c, a, b, true, 3)
1021            .unwrap_err()
1022            .contains("different configs"));
1023    }
1024
1025    fn ex(id: &str, fp: &str) -> String {
1026        serde_json::to_string(&vec![crate::blast::Exposed {
1027            entry_id: id.into(),
1028            provider: "P".into(),
1029            key_id: String::new(),
1030            field: "api_key".into(),
1031            fp: fp.into(),
1032            short: false,
1033        }])
1034        .unwrap()
1035    }
1036
1037    #[test]
1038    fn what_a_file_contained_is_the_union_over_every_snapshot_with_that_hash_and_none_when_unknown()
1039    {
1040        let c = db();
1041        record(&c, &S, "same", "m1", &ex("e1", "f1"), "save", None).unwrap();
1042        record(&c, &S, "other", "m2", "[]", "save", None).unwrap();
1043        // The same text again after a revert, now also matching a second entry.
1044        record(&c, &S, "same", "m1", &ex("e2", "f2"), "save", None).unwrap();
1045        let got = exposed_by_sha(&c, &sha("same")).unwrap().unwrap();
1046        let ids: Vec<&str> = got.iter().map(|e| e.entry_id.as_str()).collect();
1047        assert_eq!(ids, vec!["e1", "e2"]);
1048        assert_eq!(exposed_by_sha(&c, &sha("other")).unwrap().unwrap().len(), 0);
1049        assert!(exposed_by_sha(&c, &sha("never recorded"))
1050            .unwrap()
1051            .is_none());
1052    }
1053
1054    #[test]
1055    fn hiding_an_entry_from_the_exposed_list_breaks_the_chain() {
1056        let c = db();
1057        record(&c, &S, "t", "m", &ex("e1", "f1"), "save", None).unwrap();
1058        assert!(verify(&c).unwrap().problems.is_empty());
1059        c.execute(
1060            "UPDATE config_snapshots SET exposed = '[]' WHERE seq = 1",
1061            [],
1062        )
1063        .unwrap();
1064        assert!(
1065            verify(&c)
1066                .unwrap()
1067                .problems
1068                .iter()
1069                .any(|p| p.contains("#1 breaks the chain")),
1070            "an edited exposed list went unnoticed"
1071        );
1072    }
1073
1074    #[test]
1075    fn the_file_on_a_host_is_matched_to_the_snapshot_it_came_from() {
1076        let c = db();
1077        let first = rec(&c, "one").unwrap();
1078        rec(&c, "two");
1079        let hits = find_by_sha(&c, &sha("one"), 5).unwrap();
1080        assert_eq!(hits.len(), 1);
1081        assert_eq!(hits[0].seq, first);
1082        assert!(find_by_sha(&c, &sha("never rendered"), 5)
1083            .unwrap()
1084            .is_empty());
1085    }
1086
1087    #[test]
1088    fn verify_passes_on_an_untouched_history_and_catches_each_kind_of_tampering() {
1089        let c = db();
1090        rec(&c, "a");
1091        rec(&c, "b");
1092        rec(&c, "c");
1093        let ok = verify(&c).unwrap();
1094        assert_eq!((ok.snapshots, ok.problems.len()), (3, 0));
1095
1096        // Edited content.
1097        c.execute(
1098            "UPDATE config_snapshots SET content = 'evil' WHERE seq = 2",
1099            [],
1100        )
1101        .unwrap();
1102        assert!(verify(&c)
1103            .unwrap()
1104            .problems
1105            .iter()
1106            .any(|p| p.contains("#2 content")));
1107        c.execute(
1108            "UPDATE config_snapshots SET content = 'b' WHERE seq = 2",
1109            [],
1110        )
1111        .unwrap();
1112        assert!(verify(&c).unwrap().problems.is_empty());
1113
1114        // Edited masked text: covered by the chain, not by the content hash.
1115        c.execute("UPDATE config_snapshots SET masked = 'x' WHERE seq = 2", [])
1116            .unwrap();
1117        assert!(verify(&c)
1118            .unwrap()
1119            .problems
1120            .iter()
1121            .any(|p| p.contains("#2 breaks the chain")));
1122        c.execute(
1123            "UPDATE config_snapshots SET masked = ?1 WHERE seq = 2",
1124            [masked_of("b")],
1125        )
1126        .unwrap();
1127
1128        // A deleted middle snapshot.
1129        c.execute("DELETE FROM config_snapshots WHERE seq = 2", [])
1130            .unwrap();
1131        assert!(!verify(&c).unwrap().problems.is_empty());
1132    }
1133
1134    #[test]
1135    fn deleting_the_oldest_snapshots_without_a_checkpoint_is_detected() {
1136        let c = db();
1137        rec(&c, "a");
1138        rec(&c, "b");
1139        c.execute("DELETE FROM config_snapshots WHERE seq = 1", [])
1140            .unwrap();
1141        assert!(verify(&c)
1142            .unwrap()
1143            .problems
1144            .iter()
1145            .any(|p| p.contains("breaks the chain")));
1146    }
1147
1148    #[test]
1149    fn prune_keeps_the_newest_and_the_recent_and_leaves_a_verifiable_chain() {
1150        let c = db();
1151        for i in 0..6 {
1152            rec(&c, &format!("v{i}"));
1153        }
1154        // Make the first four old; the last two stay recent.
1155        for seq in 1..=4 {
1156            age(&c, seq, "2020-01-01T00:00:00Z");
1157        }
1158        let dry = prune(&c, 3, 30, true, None).unwrap();
1159        assert_eq!(
1160            (dry.would_delete, dry.deleted),
1161            (3, 0),
1162            "keep 3 newest: only #1..#3 are old and beyond"
1163        );
1164        assert_eq!(
1165            stats(&c).unwrap().snapshots,
1166            6,
1167            "a dry run deleted something"
1168        );
1169        let real = prune(&c, 3, 30, false, Some("owner")).unwrap();
1170        assert_eq!((real.deleted, real.streams_touched), (3, 1));
1171        let left: Vec<i64> = list(&c, None, None, None, 10)
1172            .unwrap()
1173            .iter()
1174            .map(|m| m.seq)
1175            .collect();
1176        assert_eq!(left, vec![6, 5, 4]);
1177        let v = verify(&c).unwrap();
1178        assert!(v.problems.is_empty(), "{:?}", v.problems);
1179        assert_eq!(v.checkpoints, 1);
1180
1181        // New snapshots extend the chain from the checkpoint and still verify.
1182        rec(&c, "v6");
1183        assert!(verify(&c).unwrap().problems.is_empty());
1184        // And a second prune stacks a second checkpoint.
1185        for seq in 4..=7 {
1186            age(&c, seq, "2020-02-01T00:00:00Z");
1187        }
1188        prune(&c, 1, 30, false, None).unwrap();
1189        let v = verify(&c).unwrap();
1190        assert!(v.problems.is_empty(), "{:?}", v.problems);
1191        assert_eq!(list(&c, None, None, None, 10).unwrap().len(), 1);
1192    }
1193
1194    // S13: the doomed set was "every old row beyond the newest keep" and the code
1195    // assumed that is always a prefix. With a clock that stepped back, a recent row can
1196    // sit between two old ones; deleting `seq <= last` then removed a row younger than the
1197    // retention window and the checkpoint claimed it was old.
1198    #[test]
1199    fn prune_stops_at_the_first_row_that_must_stay() {
1200        let c = db();
1201        for i in 0..4 {
1202            rec(&c, &format!("v{i}"));
1203        }
1204        age(&c, 1, "2020-01-01T00:00:00Z");
1205        // #2 keeps its real, recent timestamp; #3 was stamped by a clock that stepped back.
1206        age(&c, 3, "2020-01-02T00:00:00Z");
1207        let real = prune(&c, 1, 30, false, Some("owner")).unwrap();
1208        assert_eq!(
1209            real.deleted, 1,
1210            "only #1 is old with nothing recent before it"
1211        );
1212        let left: Vec<i64> = list(&c, None, None, None, 10)
1213            .unwrap()
1214            .iter()
1215            .map(|m| m.seq)
1216            .collect();
1217        assert_eq!(left, vec![4, 3, 2]);
1218        assert!(verify(&c).unwrap().problems.is_empty());
1219    }
1220
1221    #[test]
1222    fn a_stream_that_lost_every_row_after_a_prune_restarts_from_its_checkpoint() {
1223        // Not reachable through prune (it always keeps the newest), but reachable
1224        // by an operator deleting rows by hand; the next snapshot must extend the
1225        // checkpoint or the stream can never verify again.
1226        let c = db();
1227        rec(&c, "a");
1228        rec(&c, "b");
1229        age(&c, 1, "2000-01-01T00:00:00Z");
1230        prune(&c, 1, 30, false, Some("owner")).unwrap();
1231        c.execute("DELETE FROM config_snapshots", []).unwrap();
1232        rec(&c, "c");
1233        assert!(verify(&c).unwrap().problems.is_empty());
1234    }
1235
1236    #[test]
1237    fn prune_never_empties_a_stream() {
1238        let c = db();
1239        rec(&c, "a");
1240        age(&c, 1, "2000-01-01T00:00:00Z");
1241        let r = prune(&c, 1, 0, false, None).unwrap();
1242        assert_eq!(r.deleted, 0);
1243        assert_eq!(stats(&c).unwrap().snapshots, 1);
1244    }
1245
1246    #[test]
1247    fn a_forged_checkpoint_with_no_audit_row_is_caught() {
1248        let c = db();
1249        rec(&c, "a");
1250        rec(&c, "b");
1251        rec(&c, "c");
1252        // An attacker drops the first snapshot and writes a checkpoint to cover it.
1253        let chain1: String = c
1254            .query_row(
1255                "SELECT chain FROM config_snapshots WHERE seq = 1",
1256                [],
1257                |r| r.get(0),
1258            )
1259            .unwrap();
1260        c.execute("DELETE FROM config_snapshots WHERE seq = 1", [])
1261            .unwrap();
1262        c.execute(
1263            "INSERT INTO config_checkpoints (project, exporter, pruned_through_seq, chain_at, pruned_count, at) \
1264             VALUES ('p1','nginx',1,?1,1,'t')",
1265            [chain1],
1266        )
1267        .unwrap();
1268        let v = verify(&c).unwrap();
1269        assert!(
1270            v.problems
1271                .iter()
1272                .any(|p| p.contains("no matching row in the audit chain")),
1273            "{:?}",
1274            v.problems
1275        );
1276    }
1277
1278    #[test]
1279    fn a_real_prune_writes_the_audit_row_the_checkpoint_is_checked_against() {
1280        let c = db();
1281        rec(&c, "a");
1282        rec(&c, "b");
1283        age(&c, 1, "2000-01-01T00:00:00Z");
1284        prune(&c, 1, 30, false, Some("owner")).unwrap();
1285        let n: i64 = c
1286            .query_row(
1287                "SELECT COUNT(*) FROM vault_audit WHERE action = 'config.prune'",
1288                [],
1289                |r| r.get(0),
1290            )
1291            .unwrap();
1292        assert_eq!(n, 1);
1293    }
1294
1295    #[test]
1296    fn policy_has_defaults_and_refuses_nonsense() {
1297        let c = db();
1298        assert_eq!(
1299            policy(&c),
1300            Policy {
1301                enabled: true,
1302                keep: DEFAULT_KEEP,
1303                days: DEFAULT_DAYS
1304            }
1305        );
1306        assert!(set_policy(&c, None, Some(0), None).is_err());
1307        assert!(set_policy(&c, None, None, Some(-1)).is_err());
1308        let p = set_policy(&c, None, Some(5), Some(7)).unwrap();
1309        assert_eq!((p.keep, p.days), (5, 7));
1310    }
1311
1312    #[test]
1313    fn an_oversized_render_is_refused_not_truncated() {
1314        let c = db();
1315        let big = "x".repeat(MAX_BYTES + 1);
1316        assert!(record(&c, &S, &big, "m", "[]", "save", None)
1317            .unwrap_err()
1318            .contains("history keeps files up to"));
1319    }
1320}