Skip to main content

vault_core/
storage.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright the UnENVerse contributors.
3//! Row-per-entry storage, schema v2 (Phase 30, review-01 section 2.1; ADR-0138).
4//!
5//! Schema v1 kept the whole vault as one JSON string in one row, so every write
6//! parsed and re-serialised the lot, the compare-and-swap token was a hash of the
7//! blob (two people editing *different* entries conflicted, and both branches of
8//! the conflict prompt discarded someone's changeset), `version_history` grew
9//! inside the thing written most often, and nothing could be indexed.
10//!
11//! v2 stores one row per entry and per project, a row for the category list and a
12//! row for every other top-level key. The public document API is unchanged
13//! (`load_vault` returns the same JSON, `save_vault` takes it), so the desktop app,
14//! `unv-server` and `unv` need no change; what changes is what a save *does*:
15//!
16//! * only rows whose content changed are written;
17//! * `version_history` lives in its own table and is attached on load;
18//! * every save records which rows it changed in `vault_changes`, and a writer who
19//!   read an older version is **merged**, not refused: entries it left untouched
20//!   keep whatever the other writer did, and only an entry both sides changed (or
21//!   one side changed and the other deleted) is a conflict, named in the error.
22//!
23//! ## The version token
24//!
25//! `"<seq>.<state hash>"`. The hash is over every row's `(kind, key, position,
26//! content hash)`; the sequence number says *when*, so a stale token can be turned
27//! into "which rows changed since" instead of "something changed". The token is
28//! opaque to callers, as before; a token in the old bare-hex form fails the merge
29//! lookup and is a whole-vault conflict, which is what it always was.
30//!
31//! ## What a merge can and cannot know
32//!
33//! A row's content hash (`rev`) is the identity of its content. For each row the
34//! writer sends back, the changes since its base version tell us what that row
35//! looked like when it read it (`prev_rev` of the first later change). If the
36//! writer's copy still has that hash, the writer did not touch it and the stored
37//! row wins; if the writer's copy matches the stored row, there is nothing to
38//! decide; otherwise both sides edited it. History is bounded (the newest
39//! [`KEEP_SAVES`] saves); a token older than that is a whole-vault conflict.
40
41use rusqlite::{params, Connection, OptionalExtension};
42use serde_json::{Map, Value};
43use sha2::{Digest, Sha256};
44use std::collections::{HashMap, HashSet};
45
46/// The newest saves of change history that are always kept for merging stale
47/// writers, however old they are.
48pub const KEEP_SAVES: i64 = 2000;
49
50/// Saves newer than this many days are kept too (Phase 30.2): a script saving
51/// thousands of times a day used to burn through 2,000 saves in hours, and an
52/// hour-old token then became a whole-vault conflict.
53pub const KEEP_DAYS: i64 = 30;
54
55/// An absolute ceiling, so a runaway loop cannot grow the change log without bound.
56pub const HARD_KEEP_SAVES: i64 = 200_000;
57
58/// `now` minus [`KEEP_DAYS`], in the same ISO form `at` is stored in.
59fn retention_cutoff(now: &str) -> Option<String> {
60    let t =
61        time::OffsetDateTime::parse(now, &time::format_description::well_known::Rfc3339).ok()?;
62    let c = t.checked_sub(time::Duration::days(KEEP_DAYS))?;
63    Some(format!(
64        "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}Z",
65        c.year(),
66        c.month() as u8,
67        c.day(),
68        c.hour(),
69        c.minute(),
70        c.second()
71    ))
72}
73
74/// Drop change history a stale writer can no longer be merged against: older than
75/// the newest `keep` saves **and** older than [`KEEP_DAYS`], or beyond `hard`.
76/// With an unreadable `now` only the counts apply. A writer older than what is
77/// left gets a whole-vault conflict.
78fn prune_saves(conn: &Connection, seq: i64, now: &str, keep: i64, hard: i64) -> Result<(), String> {
79    let cutoff = retention_cutoff(now).unwrap_or_else(|| "0".into());
80    conn.execute(
81        "DELETE FROM vault_saves WHERE (seq <= ?1 AND at < ?2) OR seq <= ?3",
82        params![seq - keep, cutoff, seq - hard],
83    )
84    .map_err(|e| e.to_string())?;
85    conn.execute(
86        "DELETE FROM vault_changes WHERE seq < COALESCE((SELECT MIN(seq) FROM vault_saves), ?1)",
87        params![seq],
88    )
89    .map_err(|e| e.to_string())?;
90    Ok(())
91}
92
93/// How far back a stale writer can still be merged: the oldest kept save's time and
94/// how many saves are kept. `None` for a vault never saved.
95pub fn merge_window(conn: &Connection) -> Result<Option<(String, i64)>, String> {
96    conn.query_row("SELECT MIN(at), COUNT(*) FROM vault_saves", [], |r| {
97        Ok((r.get::<_, Option<String>>(0)?, r.get::<_, i64>(1)?))
98    })
99    .map(|(at, n)| at.map(|a| (a, n)))
100    .map_err(|e| e.to_string())
101}
102
103const KIND_ENTRY: &str = "entry";
104const KIND_PROJECT: &str = "project";
105const KIND_CHUNK: &str = "chunk";
106const KIND_CATEGORIES: &str = "categories";
107const KIND_DOC: &str = "doc";
108
109/// The three top-level keys that get their own rows; everything else rides in `doc`.
110/// Joins a project row key to its chunk's key in a chunk row.
111const CHUNK_SEP: char = '\u{3}';
112
113const SPLIT_KEYS: [&str; 3] = ["api_keys", "projects", "user_categories"];
114
115pub fn init_schema(conn: &Connection) -> Result<(), String> {
116    conn.execute_batch(
117        "CREATE TABLE IF NOT EXISTS vault_rows (
118             kind TEXT NOT NULL,
119             key  TEXT NOT NULL,
120             pos  INTEGER NOT NULL,
121             data TEXT NOT NULL,
122             rev  TEXT NOT NULL,
123             PRIMARY KEY (kind, key)
124         );
125         CREATE INDEX IF NOT EXISTS vault_rows_pos ON vault_rows (kind, pos);
126         CREATE TABLE IF NOT EXISTS vault_history (
127             key  TEXT PRIMARY KEY,
128             data TEXT NOT NULL,
129             rev  TEXT NOT NULL
130         );
131         CREATE TABLE IF NOT EXISTS vault_saves (
132             seq        INTEGER PRIMARY KEY AUTOINCREMENT,
133             state_hash TEXT NOT NULL,
134             at         TEXT NOT NULL
135         );
136         CREATE TABLE IF NOT EXISTS vault_changes (
137             seq      INTEGER NOT NULL,
138             kind     TEXT NOT NULL,
139             key      TEXT NOT NULL,
140             prev_rev TEXT,
141             new_rev  TEXT
142         );
143         CREATE INDEX IF NOT EXISTS vault_changes_seq ON vault_changes (seq);",
144    )
145    .map_err(|e| e.to_string())
146}
147
148fn sha(s: &str) -> String {
149    hex::encode(Sha256::digest(s.as_bytes()))
150}
151
152/// SHA-256 of a value's compact JSON, without building the string. Identical to
153/// `sha(&v.to_string())`, which is what `verify` recomputes from the stored text.
154struct HashWriter(Sha256);
155
156impl std::io::Write for HashWriter {
157    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
158        self.0.update(buf);
159        Ok(buf.len())
160    }
161    fn flush(&mut self) -> std::io::Result<()> {
162        Ok(())
163    }
164}
165
166fn rev_of(v: &Value) -> String {
167    let mut w = HashWriter(Sha256::new());
168    let _ = serde_json::to_writer(&mut w, v);
169    hex::encode(w.0.finalize())
170}
171
172/// One storable unit of the document.
173#[derive(Clone)]
174pub struct Ent {
175    pub kind: &'static str,
176    /// Unique within `kind`.
177    pub key: String,
178    /// The JSON stored in the row (for entries, without `version_history`).
179    pub data: Value,
180    pub rev: String,
181    /// An entry's `version_history`, kept apart from its row.
182    pub history: Option<Value>,
183}
184
185impl Ent {
186    fn new(kind: &'static str, key: String, data: Value, history: Option<Value>) -> Self {
187        let rev = rev_of(&data);
188        Self {
189            kind,
190            key,
191            data,
192            rev,
193            history,
194        }
195    }
196
197    /// The entry as the rest of the code sees it: row plus `version_history`.
198    pub fn full(&self) -> Value {
199        let mut v = self.data.clone();
200        if let (Some(h), Some(o)) = (&self.history, v.as_object_mut()) {
201            o.insert("version_history".into(), h.clone());
202        }
203        v
204    }
205
206    pub fn provider(&self) -> String {
207        self.data
208            .get("provider")
209            .and_then(Value::as_str)
210            .unwrap_or("")
211            .to_string()
212    }
213}
214
215/// A row key unique within the incoming list. Duplicate cks (legacy entries with
216/// no `id` and identical provider/account/key_id) get an ordinal so they do not
217/// collapse into one row.
218fn unique_keys(cks: Vec<String>) -> Vec<String> {
219    let mut seen: HashMap<String, usize> = HashMap::new();
220    cks.into_iter()
221        .map(|ck| {
222            let n = seen.entry(ck.clone()).or_insert(0);
223            *n += 1;
224            if *n == 1 {
225                ck
226            } else {
227                format!("{ck}\u{2}{n}")
228            }
229        })
230        .collect()
231}
232
233fn project_ck(p: &Value) -> String {
234    let id = p.get("id").and_then(Value::as_str).unwrap_or("");
235    if !id.is_empty() {
236        return format!("id\u{1}{id}");
237    }
238    format!(
239        "name\u{1}{}",
240        p.get("name").and_then(Value::as_str).unwrap_or("")
241    )
242}
243
244/// Split a vault document into storable units, in document order. Consumes the
245/// document so a large vault is moved, not cloned.
246pub fn split(mut doc: Value) -> Vec<Ent> {
247    let mut out = Vec::new();
248    let mut take = |k: &str| -> Vec<Value> {
249        match doc.get_mut(k).map(Value::take) {
250            Some(Value::Array(a)) => a,
251            _ => Vec::new(),
252        }
253    };
254
255    let entries = take("api_keys");
256    let keys = unique_keys(entries.iter().map(crate::entry_ck).collect());
257    for (e, key) in entries.into_iter().zip(keys) {
258        let mut data = e;
259        let history = data
260            .as_object_mut()
261            .and_then(|o| o.remove("version_history"));
262        out.push(Ent::new(KIND_ENTRY, key, data, history));
263    }
264    let projects = take("projects");
265    let keys = unique_keys(projects.iter().map(project_ck).collect());
266    let mut chunk_rows = Vec::new();
267    for (mut p, key) in projects.into_iter().zip(keys) {
268        // Phase 30.2 (ADR-0146): a project's chunks are rows of their own, so two people
269        // editing different chunks do not touch the same row. The project row keeps
270        // an empty `chunks` array to say the chunks live elsewhere.
271        if let Some(Value::Array(chunks)) = p.get_mut("chunks").map(Value::take) {
272            p["chunks"] = Value::Array(Vec::new());
273            let cks = unique_keys(
274                chunks
275                    .iter()
276                    .enumerate()
277                    .map(|(i, c)| match c.get("id").and_then(Value::as_str) {
278                        Some(id) if !id.is_empty() => format!("id\u{1}{id}"),
279                        _ => format!("pos\u{1}{i}"),
280                    })
281                    .collect(),
282            );
283            for (c, ck) in chunks.into_iter().zip(cks) {
284                chunk_rows.push(Ent::new(
285                    KIND_CHUNK,
286                    format!("{key}{CHUNK_SEP}{ck}"),
287                    c,
288                    None,
289                ));
290            }
291        }
292        out.push(Ent::new(KIND_PROJECT, key, p, None));
293    }
294    out.extend(chunk_rows);
295    let cats = take("user_categories");
296    out.push(Ent::new(
297        KIND_CATEGORIES,
298        String::new(),
299        Value::Array(cats),
300        None,
301    ));
302    let mut extra = Map::new();
303    if let Value::Object(o) = doc {
304        for (k, v) in o {
305            if !SPLIT_KEYS.contains(&k.as_str()) {
306                extra.insert(k, v);
307            }
308        }
309    }
310    out.push(Ent::new(
311        KIND_DOC,
312        String::new(),
313        Value::Object(extra),
314        None,
315    ));
316    out
317}
318
319/// Reassemble the document from units in order, consuming them.
320pub fn join(ents: Vec<Ent>) -> Value {
321    let mut doc = Map::new();
322    let mut entries = Vec::new();
323    let mut projects: Vec<(String, Value)> = Vec::new();
324    let mut chunks: HashMap<String, Vec<Value>> = HashMap::new();
325    let mut cats = Value::Array(vec![]);
326    for e in ents {
327        match e.kind {
328            KIND_ENTRY => {
329                let mut v = e.data;
330                if let (Some(h), Some(o)) = (e.history, v.as_object_mut()) {
331                    o.insert("version_history".into(), h);
332                }
333                entries.push(v);
334            }
335            KIND_PROJECT => projects.push((e.key, e.data)),
336            KIND_CHUNK => {
337                if let Some((pk, _)) = e.key.split_once(CHUNK_SEP) {
338                    chunks.entry(pk.to_string()).or_default().push(e.data);
339                }
340            }
341            KIND_CATEGORIES => cats = e.data,
342            KIND_DOC => {
343                if let Value::Object(o) = e.data {
344                    for (k, v) in o {
345                        doc.insert(k, v);
346                    }
347                }
348            }
349            _ => {}
350        }
351    }
352    doc.insert("api_keys".into(), Value::Array(entries));
353    let projects = projects
354        .into_iter()
355        .map(|(key, mut p)| {
356            // Rows win over a legacy inline array (a v2 vault not yet re-saved).
357            if let Some(c) = chunks.remove(&key) {
358                p["chunks"] = Value::Array(c);
359            }
360            p
361        })
362        .collect();
363    doc.insert("projects".into(), Value::Array(projects));
364    doc.insert("user_categories".into(), cats);
365    Value::Object(doc)
366}
367
368// ── Reading ──────────────────────────────────────────────────────────────────
369
370/// Parse many JSON strings, on worker threads once there are enough of them to
371/// pay for the threads (Phase 30.2: a full load of a large vault is dominated by
372/// parsing, and every string is independent).
373fn par_parse(texts: Vec<String>) -> Vec<Result<Value, serde_json::Error>> {
374    const MIN_PER_THREAD: usize = 512;
375    let threads = std::thread::available_parallelism()
376        .map(|n| n.get())
377        .unwrap_or(1)
378        .min(texts.len() / MIN_PER_THREAD)
379        .max(1);
380    if threads == 1 {
381        return texts.iter().map(|t| serde_json::from_str(t)).collect();
382    }
383    let per = texts.len().div_ceil(threads);
384    std::thread::scope(|sc| {
385        let handles: Vec<_> = texts
386            .chunks(per)
387            .map(|c| {
388                sc.spawn(move || {
389                    c.iter()
390                        .map(|t| serde_json::from_str(t))
391                        .collect::<Vec<_>>()
392                })
393            })
394            .collect();
395        handles
396            .into_iter()
397            .flat_map(|h| h.join().unwrap_or_default())
398            .collect()
399    })
400}
401
402fn history_map(conn: &Connection) -> Result<HashMap<String, Value>, String> {
403    let mut stmt = conn
404        .prepare("SELECT key, data FROM vault_history")
405        .map_err(|e| e.to_string())?;
406    let rows = stmt
407        .query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))
408        .map_err(|e| e.to_string())?;
409    let (keys, texts): (Vec<String>, Vec<String>) = rows
410        .collect::<Result<Vec<_>, _>>()
411        .map_err(|e| e.to_string())?
412        .into_iter()
413        .unzip();
414    Ok(keys
415        .into_iter()
416        .zip(par_parse(texts))
417        .filter_map(|(k, v)| v.ok().map(|v| (k, v)))
418        .collect())
419}
420
421fn ent_from_row(
422    kind: &'static str,
423    key: String,
424    data: &str,
425    rev: String,
426    history: Option<Value>,
427) -> Result<Ent, String> {
428    Ok(Ent {
429        kind,
430        key,
431        data: serde_json::from_str(data).map_err(|e| e.to_string())?,
432        rev,
433        history,
434    })
435}
436
437fn kind_static(k: &str) -> &'static str {
438    match k {
439        KIND_ENTRY => KIND_ENTRY,
440        KIND_PROJECT => KIND_PROJECT,
441        KIND_CHUNK => KIND_CHUNK,
442        KIND_CATEGORIES => KIND_CATEGORIES,
443        _ => KIND_DOC,
444    }
445}
446
447/// Every stored unit in document order, or `None` when nothing has been saved.
448pub fn load_ents(conn: &Connection) -> Result<Option<Vec<Ent>>, String> {
449    load_ents_opts(conn, true)
450}
451
452/// As [`load_ents`], optionally leaving out each entry's `version_history`, which
453/// is up to 50 revisions of secret material per entry and is not wanted by a
454/// selective read.
455/// Runs `f` against one consistent snapshot of the database.
456///
457/// A load is several statements (rows, then history; token, rows, accumulator for the
458/// integrity check). Run as separate autocommit statements, a save landing between them
459/// gave a document whose history belonged to a different version than its rows (and a
460/// writer that then saved that copy lost a rotation record), or an integrity check that
461/// reported tampering on a healthy vault. Inside a caller's own transaction this just
462/// runs `f`: that transaction is already one snapshot.
463pub fn in_snapshot<T>(
464    conn: &Connection,
465    f: impl FnOnce() -> Result<T, String>,
466) -> Result<T, String> {
467    if !conn.is_autocommit() {
468        return f();
469    }
470    conn.execute_batch("BEGIN").map_err(|e| e.to_string())?;
471    let r = f();
472    // Read-only: there is nothing to lose if the end of the snapshot fails.
473    let _ = conn.execute_batch("COMMIT");
474    r
475}
476
477pub fn load_ents_opts(conn: &Connection, with_history: bool) -> Result<Option<Vec<Ent>>, String> {
478    in_snapshot(conn, || load_ents_inner(conn, with_history))
479}
480
481fn load_ents_inner(conn: &Connection, with_history: bool) -> Result<Option<Vec<Ent>>, String> {
482    let mut stmt = conn
483        .prepare("SELECT kind, key, data, rev FROM vault_rows ORDER BY kind, pos")
484        .map_err(|e| e.to_string())?;
485    let rows = stmt
486        .query_map([], |r| {
487            Ok((
488                r.get::<_, String>(0)?,
489                r.get::<_, String>(1)?,
490                r.get::<_, String>(2)?,
491                r.get::<_, String>(3)?,
492            ))
493        })
494        .map_err(|e| e.to_string())?;
495    let mut hist = if with_history {
496        history_map(conn)?
497    } else {
498        HashMap::new()
499    };
500    let mut stored = Vec::new();
501    let mut texts = Vec::new();
502    for r in rows {
503        let (kind, key, data, rev) = r.map_err(|e| e.to_string())?;
504        stored.push((kind, key, rev));
505        texts.push(data);
506    }
507    let mut by_kind: HashMap<&'static str, Vec<Ent>> = HashMap::new();
508    for ((kind, key, rev), parsed) in stored.into_iter().zip(par_parse(texts)) {
509        let k = kind_static(&kind);
510        let h = if k == KIND_ENTRY {
511            hist.remove(&key)
512        } else {
513            None
514        };
515        by_kind.entry(k).or_default().push(Ent {
516            kind: k,
517            key,
518            data: parsed.map_err(|e| e.to_string())?,
519            rev,
520            history: h,
521        });
522    }
523    if !by_kind.contains_key(KIND_DOC) {
524        return Ok(None); // the doc row exists iff something was ever saved
525    }
526    let mut out = Vec::new();
527    for k in [
528        KIND_ENTRY,
529        KIND_PROJECT,
530        KIND_CHUNK,
531        KIND_CATEGORIES,
532        KIND_DOC,
533    ] {
534        out.extend(by_kind.remove(k).unwrap_or_default());
535    }
536    Ok(Some(out))
537}
538
539pub fn load(conn: &Connection) -> Result<Option<Value>, String> {
540    Ok(load_ents(conn)?.map(join))
541}
542
543/// The document without any entry's `version_history`.
544pub fn load_lite(conn: &Connection) -> Result<Option<Value>, String> {
545    Ok(load_ents_opts(conn, false)?.map(join))
546}
547
548/// Every row's `(rev, pos)`, read once per save.
549pub type Snapshot = HashMap<(String, String), (String, i64)>;
550
551pub fn snapshot(conn: &Connection) -> Result<Snapshot, String> {
552    let mut stmt = conn
553        .prepare("SELECT kind, key, pos, rev FROM vault_rows")
554        .map_err(|e| e.to_string())?;
555    let rows = stmt
556        .query_map([], |r| {
557            Ok((
558                r.get::<_, String>(0)?,
559                r.get::<_, String>(1)?,
560                r.get::<_, i64>(2)?,
561                r.get::<_, String>(3)?,
562            ))
563        })
564        .map_err(|e| e.to_string())?;
565    let mut m = HashMap::new();
566    for r in rows {
567        let (k, key, pos, rev) = r.map_err(|e| e.to_string())?;
568        m.insert((k, key), (rev, pos));
569    }
570    Ok(m)
571}
572
573/// One stored row by key, with its history attached for entries.
574pub fn load_ent(conn: &Connection, kind: &'static str, key: &str) -> Result<Option<Ent>, String> {
575    let row: Option<(String, String)> = conn
576        .query_row(
577            "SELECT data, rev FROM vault_rows WHERE kind = ?1 AND key = ?2",
578            params![kind, key],
579            |r| Ok((r.get(0)?, r.get(1)?)),
580        )
581        .optional()
582        .map_err(|e| e.to_string())?;
583    let Some((data, rev)) = row else {
584        return Ok(None);
585    };
586    let history: Option<Value> = if kind == KIND_ENTRY {
587        conn.query_row(
588            "SELECT data FROM vault_history WHERE key = ?1",
589            params![key],
590            |r| r.get::<_, String>(0),
591        )
592        .optional()
593        .map_err(|e| e.to_string())?
594        .and_then(|s| serde_json::from_str(&s).ok())
595    } else {
596        None
597    };
598    Ok(Some(ent_from_row(
599        kind,
600        key.to_string(),
601        &data,
602        rev,
603        history,
604    )?))
605}
606
607/// One entry's `version_history`, read without loading anything else (Phase 30.2).
608/// `None` when no entry has that id; an empty array when it has no history.
609pub fn entry_history(conn: &Connection, id: &str) -> Result<Option<Value>, String> {
610    let key = format!("id\u{1}{id}");
611    let exists: bool = conn
612        .query_row(
613            "SELECT 1 FROM vault_rows WHERE kind = 'entry' AND key = ?1",
614            params![key],
615            |_| Ok(true),
616        )
617        .optional()
618        .map_err(|e| e.to_string())?
619        .unwrap_or(false);
620    if !exists {
621        return Ok(None);
622    }
623    let text: Option<String> = conn
624        .query_row(
625            "SELECT data FROM vault_history WHERE key = ?1",
626            params![key],
627            |r| r.get(0),
628        )
629        .optional()
630        .map_err(|e| e.to_string())?;
631    Ok(Some(match text {
632        Some(t) => serde_json::from_str(&t).map_err(|e| e.to_string())?,
633        None => Value::Array(Vec::new()),
634    }))
635}
636
637// ── Version token ────────────────────────────────────────────────────────────
638
639/// The state hash is the XOR of a hash of every row's `(kind, key, pos, rev)`.
640/// XOR is order-independent and every row is unique, so a save can update it by
641/// removing the old row's hash and adding the new one: O(changed), not O(vault).
642/// `verify` recomputes it from the rows and compares.
643type Acc = [u8; 32];
644
645fn row_hash(kind: &str, key: &str, pos: i64, rev: &str) -> Acc {
646    let mut h = Sha256::new();
647    h.update(kind.as_bytes());
648    h.update([1]);
649    h.update(key.as_bytes());
650    h.update([1]);
651    h.update(pos.to_string().as_bytes());
652    h.update([1]);
653    h.update(rev.as_bytes());
654    h.finalize().into()
655}
656
657fn xor(acc: &mut Acc, other: &Acc) {
658    for (a, b) in acc.iter_mut().zip(other) {
659        *a ^= b;
660    }
661}
662
663fn acc_from_rows(snap: &Snapshot) -> Acc {
664    let mut acc = [0u8; 32];
665    for ((k, key), (rev, pos)) in snap {
666        xor(&mut acc, &row_hash(k, key, *pos, rev));
667    }
668    acc
669}
670
671fn acc_hex(acc: &Acc) -> String {
672    acc.iter().map(|b| format!("{b:02x}")).collect()
673}
674
675fn acc_parse(s: &str) -> Option<Acc> {
676    if s.len() != 64 {
677        return None;
678    }
679    let mut out = [0u8; 32];
680    for (i, o) in out.iter_mut().enumerate() {
681        *o = u8::from_str_radix(&s[i * 2..i * 2 + 2], 16).ok()?;
682    }
683    Some(out)
684}
685
686fn stored_acc(conn: &Connection) -> Result<Option<Acc>, String> {
687    Ok(conn
688        .query_row(
689            "SELECT value FROM vault_meta WHERE key = 'state_acc'",
690            [],
691            |r| r.get::<_, String>(0),
692        )
693        .optional()
694        .map_err(|e| e.to_string())?
695        .and_then(|s| acc_parse(&s)))
696}
697
698fn token(seq: i64, hash: &str) -> String {
699    format!("{seq}.{hash}")
700}
701
702fn parse_token(t: &str) -> Option<(i64, &str)> {
703    let (s, h) = t.split_once('.')?;
704    Some((s.parse().ok()?, h))
705}
706
707/// The current version token, or `None` for an empty vault.
708pub fn version(conn: &Connection) -> Result<Option<String>, String> {
709    conn.query_row(
710        "SELECT value FROM vault_meta WHERE key = 'data_hash'",
711        [],
712        |r| r.get(0),
713    )
714    .optional()
715    .map_err(|e| e.to_string())
716}
717
718/// Integrity: every row hashes to its `rev`, and the rows hash to the stored token.
719pub fn verify(conn: &Connection) -> Result<bool, String> {
720    in_snapshot(conn, || verify_inner(conn))
721}
722
723fn verify_inner(conn: &Connection) -> Result<bool, String> {
724    let mut stmt = conn
725        .prepare("SELECT data, rev FROM vault_rows")
726        .map_err(|e| e.to_string())?;
727    let rows = stmt
728        .query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))
729        .map_err(|e| e.to_string())?;
730    let mut any = false;
731    for r in rows {
732        let (data, rev) = r.map_err(|e| e.to_string())?;
733        any = true;
734        if sha(&data) != rev {
735            return Ok(false);
736        }
737    }
738    // Version history holds the OLD secrets and sat outside every check: a row edited
739    // in place (a forged rotation record, an altered old value) verified as intact.
740    let mut hist = conn
741        .prepare("SELECT data, rev FROM vault_history")
742        .map_err(|e| e.to_string())?;
743    let hist_rows = hist
744        .query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))
745        .map_err(|e| e.to_string())?;
746    for r in hist_rows {
747        let (data, rev) = r.map_err(|e| e.to_string())?;
748        match serde_json::from_str::<Value>(&data) {
749            Ok(v) if rev_of(&v) == rev => {}
750            _ => return Ok(false),
751        }
752    }
753    if !any {
754        return Ok(true);
755    }
756    let Some(stored) = version(conn)? else {
757        return Ok(true);
758    };
759    let fresh = acc_hex(&acc_from_rows(&snapshot(conn)?));
760    let recorded = stored_acc(conn)?.map(|a| acc_hex(&a));
761    Ok(parse_token(&stored)
762        .map(|(_, h)| h == fresh)
763        .unwrap_or(false)
764        && recorded.as_deref().map(|r| r == fresh).unwrap_or(true))
765}
766
767// ── Merge ────────────────────────────────────────────────────────────────────
768
769type Id = (String, String);
770
771/// Resolve the writer's units against what is stored. Returns the units to
772/// persist, or the conflicting row labels.
773///
774/// `expect` is the version the writer read. `None` writes unconditionally.
775pub fn merge(
776    conn: &Connection,
777    stored: &Snapshot,
778    incoming: Vec<Ent>,
779    expect: Option<&str>,
780) -> Result<(Vec<Ent>, bool), String> {
781    let cur_version = version(conn)?;
782    let expect = expect.map(|e| e.strip_suffix(crate::MERGED_SUFFIX).unwrap_or(e));
783    // Rows changed since the writer's base, by the first prior revision they had.
784    let mut touched: HashMap<Id, Option<String>> = HashMap::new();
785    match expect {
786        None => {}
787        Some(e) if cur_version.as_deref() == Some(e) => {}
788        Some(e) => {
789            let ok = parse_token(e).and_then(|(seq, hash)| {
790                let found: Option<String> = conn
791                    .query_row(
792                        "SELECT state_hash FROM vault_saves WHERE seq = ?1",
793                        params![seq],
794                        |r| r.get(0),
795                    )
796                    .optional()
797                    .ok()
798                    .flatten();
799                (found.as_deref() == Some(hash)).then_some(seq)
800            });
801            let Some(base) = ok else {
802                return Err(conflict(&[]));
803            };
804            let mut stmt = conn
805                .prepare("SELECT kind, key, prev_rev FROM vault_changes WHERE seq > ?1 ORDER BY seq ASC, rowid ASC")
806                .map_err(|e| e.to_string())?;
807            let rows = stmt
808                .query_map(params![base], |r| {
809                    Ok((
810                        r.get::<_, String>(0)?,
811                        r.get::<_, String>(1)?,
812                        r.get::<_, Option<String>>(2)?,
813                    ))
814                })
815                .map_err(|e| e.to_string())?;
816            for r in rows {
817                let (k, key, prev) = r.map_err(|e| e.to_string())?;
818                touched.entry((k, key)).or_insert(prev);
819            }
820        }
821    }
822    if touched.is_empty() {
823        return Ok((incoming, false)); // nothing concurrent: the writer's document wins as written
824    }
825
826    let mut conflicts: Vec<String> = Vec::new();
827    let mut out: Vec<Ent> = Vec::new();
828    let mut seen: HashSet<Id> = HashSet::new();
829    // True when the result differs from the writer's own view of the vault, so the
830    // writer must not adopt the new version as its base (see `save_vault_txn`).
831    let mut adopted_theirs = false;
832
833    for ent in incoming {
834        let id: Id = (ent.kind.to_string(), ent.key.clone());
835        seen.insert(id.clone());
836        let Some(base_prev) = touched.get(&id) else {
837            out.push(ent);
838            continue;
839        };
840        let cur = stored.get(&id).map(|(rev, _)| rev);
841        if cur == Some(&ent.rev) {
842            out.push(ent); // both sides arrived at the same content
843            continue;
844        }
845        match base_prev {
846            // The writer did not touch it: whatever the other side did stands.
847            Some(b) if *b == ent.rev => {
848                adopted_theirs = true;
849                if cur.is_some() {
850                    if let Some(theirs) = load_ent(conn, ent.kind, &ent.key)? {
851                        out.push(theirs);
852                    }
853                } // else the other side deleted it and the writer left it alone
854            }
855            _ => conflicts.push(label(&ent)),
856        }
857    }
858    // Rows the writer does not have, in a stable order.
859    let mut leftovers: Vec<&Id> = stored.keys().filter(|id| !seen.contains(*id)).collect();
860    leftovers.sort();
861    for id in leftovers {
862        let kind = kind_static(&id.0);
863        match touched.get(id) {
864            None => {} // existed at the base, untouched: the writer deleted it
865            Some(None) => {
866                // Created after the writer read: not theirs to delete.
867                adopted_theirs = true;
868                if let Some(theirs) = load_ent(conn, kind, &id.1)? {
869                    out.push(theirs);
870                }
871            }
872            Some(Some(_)) => conflicts.push(
873                load_ent(conn, kind, &id.1)?
874                    .map(|e| label(&e))
875                    .unwrap_or_else(|| id.1.clone()),
876            ),
877        }
878    }
879    if !conflicts.is_empty() {
880        conflicts.sort();
881        conflicts.dedup();
882        return Err(conflict(&conflicts));
883    }
884    // Keep the writer's order, with rows they did not have after their own kind.
885    let order = |k: &str| match k {
886        KIND_ENTRY => 0,
887        KIND_PROJECT => 1,
888        KIND_CHUNK => 2,
889        KIND_CATEGORIES => 3,
890        _ => 4,
891    };
892    // A chunk whose project is gone (the other writer deleted it, ours added a
893    // chunk) would be an orphan row nothing reads: drop it.
894    let live: HashSet<String> = out
895        .iter()
896        .filter(|e| e.kind == KIND_PROJECT)
897        .map(|e| e.key.clone())
898        .collect();
899    out.retain(|e| {
900        e.kind != KIND_CHUNK
901            || e.key
902                .split_once(CHUNK_SEP)
903                .is_some_and(|(pk, _)| live.contains(pk))
904    });
905    out.sort_by_key(|e| order(e.kind)); // stable: preserves relative order within a kind
906    Ok((out, adopted_theirs))
907}
908
909fn label(e: &Ent) -> String {
910    match e.kind {
911        KIND_ENTRY => {
912            let p = e.provider();
913            if p.is_empty() {
914                e.key.replace('\u{1}', ":")
915            } else {
916                p
917            }
918        }
919        KIND_PROJECT => e
920            .data
921            .get("name")
922            .and_then(Value::as_str)
923            .unwrap_or(&e.key)
924            .to_string(),
925        KIND_CHUNK => {
926            let name = e.data.get("name").and_then(Value::as_str).unwrap_or("");
927            let project = e.key.split_once(CHUNK_SEP).map_or("", |(pk, _)| pk);
928            let project = project.split_once('\u{1}').map_or(project, |(_, v)| v);
929            format!(
930                "{project}: {}",
931                if name.is_empty() { "a chunk" } else { name }
932            )
933        }
934        KIND_CATEGORIES => "categories".into(),
935        _ => "vault settings".into(),
936    }
937}
938
939fn conflict(names: &[String]) -> String {
940    if names.is_empty() {
941        format!(
942            "{}: the vault changed since you last read it — reload and retry",
943            crate::CONFLICT_ERR
944        )
945    } else {
946        format!(
947            "{}: the vault changed since you last read it — you and another writer both changed: {}",
948            crate::CONFLICT_ERR,
949            names.join(", ")
950        )
951    }
952}
953
954/// The stored history of the entry row with this storage key, if any.
955fn history_by_key(conn: &Connection, key: &str) -> Result<Option<Value>, String> {
956    let text: Option<String> = conn
957        .query_row(
958            "SELECT data FROM vault_history WHERE key = ?1",
959            params![key],
960            |r| r.get(0),
961        )
962        .optional()
963        .map_err(|e| e.to_string())?;
964    text.map(|t| serde_json::from_str(&t).map_err(|e| e.to_string()))
965        .transpose()
966}
967
968/// Union of two copies of one entry's `version_history`, newest first, capped at 50.
969///
970/// History is append-only. A writer's copy of an entry carries the history it read, so
971/// when it saves a row that did not change (a retried PUT, two clients arriving at the
972/// same value) or one that changed while another writer rotated a secret in between,
973/// replacing the stored history with that copy erased the other writer's record of the
974/// old secret, with no conflict raised. Records are identified by their whole content.
975pub fn merge_history(stored: Option<&Value>, writer: Option<&Value>) -> Option<Value> {
976    let list = |v: Option<&Value>| -> Vec<Value> {
977        v.and_then(Value::as_array).cloned().unwrap_or_default()
978    };
979    let (a, b) = (list(stored), list(writer));
980    // The longer copy is the base (it already has the order: newest first, as the save
981    // path inserts them); a tie goes to the stored one. Records only the other copy has
982    // are placed before the first base record that is strictly older, else at the end.
983    let (mut base, other) = if b.len() > a.len() { (b, a) } else { (a, b) };
984    let at = |v: &Value| {
985        v.get("saved_at")
986            .and_then(Value::as_str)
987            .unwrap_or("")
988            .to_string()
989    };
990    for rec in other {
991        if base.contains(&rec) {
992            continue;
993        }
994        let pos = base
995            .iter()
996            .position(|x| at(x) < at(&rec))
997            .unwrap_or(base.len());
998        base.insert(pos, rec);
999    }
1000    if base.is_empty() {
1001        return None;
1002    }
1003    base.truncate(50);
1004    Some(Value::Array(base))
1005}
1006
1007/// Drops references to things that no longer exist, after a merge.
1008///
1009/// A merge keeps a row only one writer touched, so a project one writer deleted and an
1010/// entry another writer added to it merge cleanly row by row and leave the entry pointing
1011/// at a project that is gone (the cascade that remaps `projectIds` only ever sees the
1012/// writer's own document). The same holds for a bundle dissolved while a member was being
1013/// attached. Such an entry stays valid and visible: an unknown project id is removed (the
1014/// entry falls back to Universal) and an unknown `bundle_id` is cleared, which turns the
1015/// entry into an ordinary one. Returns whether anything changed.
1016pub fn repair_references(ents: &mut [Ent]) -> bool {
1017    use std::collections::HashSet;
1018    let projects: HashSet<String> = ents
1019        .iter()
1020        .filter(|e| e.kind == KIND_PROJECT)
1021        .filter_map(|e| e.data.get("id").and_then(Value::as_str).map(String::from))
1022        .collect();
1023    let bundles: HashSet<String> = ents
1024        .iter()
1025        .filter(|e| e.kind == KIND_ENTRY)
1026        .filter(|e| e.data.get("secretType").and_then(Value::as_str) == Some("bundle"))
1027        .filter_map(|e| e.data.get("id").and_then(Value::as_str).map(String::from))
1028        .collect();
1029    let mut changed = false;
1030    for ent in ents.iter_mut().filter(|e| e.kind == KIND_ENTRY) {
1031        let mut touched = false;
1032        if let Some(ids) = ent.data.get("projectIds").and_then(Value::as_array) {
1033            let keep: Vec<Value> = ids
1034                .iter()
1035                .filter(|v| {
1036                    v.as_str()
1037                        .is_some_and(|id| id == "Universal" || projects.contains(id))
1038                })
1039                .cloned()
1040                .collect();
1041            if keep.len() != ids.len() {
1042                let keep = if keep.is_empty() {
1043                    vec![Value::String("Universal".into())]
1044                } else {
1045                    keep
1046                };
1047                ent.data["projectIds"] = Value::Array(keep);
1048                touched = true;
1049            }
1050        }
1051        let dangling_bundle = ent
1052            .data
1053            .get("bundle_id")
1054            .and_then(Value::as_str)
1055            .is_some_and(|b| !bundles.contains(b));
1056        if dangling_bundle {
1057            if let Some(o) = ent.data.as_object_mut() {
1058                for k in ["bundle_id", "bundle_slot", "bundle_order"] {
1059                    o.remove(k);
1060                }
1061            }
1062            touched = true;
1063        }
1064        if touched {
1065            ent.rev = rev_of(&ent.data);
1066            changed = true;
1067        }
1068    }
1069    changed
1070}
1071
1072// ── Writing ──────────────────────────────────────────────────────────────────
1073
1074/// Persist `ents` as the new state. Must run inside a write transaction. Only rows
1075/// whose content, position or history changed are touched. Returns the new token
1076/// (the current one, unchanged, when nothing differs).
1077pub fn write(
1078    conn: &Connection,
1079    stored: &Snapshot,
1080    ents: &[Ent],
1081    now: &str,
1082) -> Result<String, String> {
1083    // The state accumulator before any row moves; updated row by row below.
1084    let mut acc = match stored_acc(conn)? {
1085        Some(a) => a,
1086        None => acc_from_rows(stored),
1087    };
1088    let stored_hist: HashMap<String, String> = {
1089        let mut stmt = conn
1090            .prepare("SELECT key, rev FROM vault_history")
1091            .map_err(|e| e.to_string())?;
1092        let rows = stmt
1093            .query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))
1094            .map_err(|e| e.to_string())?;
1095        let mut m = HashMap::new();
1096        for r in rows {
1097            let (k, v) = r.map_err(|e| e.to_string())?;
1098            m.insert(k, v);
1099        }
1100        m
1101    };
1102
1103    let mut changes: Vec<(String, String, Option<String>, Option<String>)> = Vec::new();
1104    let mut dirty = false;
1105    let mut pos_by_kind: HashMap<&str, i64> = HashMap::new();
1106    let mut keep: HashSet<Id> = HashSet::new();
1107    let mut keep_hist: HashSet<String> = HashSet::new();
1108
1109    for e in ents {
1110        let p = pos_by_kind.entry(e.kind).or_insert(0);
1111        let pos = *p;
1112        *p += 1;
1113        let id: Id = (e.kind.to_string(), e.key.clone());
1114        keep.insert(id.clone());
1115        match stored.get(&id) {
1116            None => {
1117                conn.execute(
1118                    "INSERT INTO vault_rows (kind, key, pos, data, rev) VALUES (?1, ?2, ?3, ?4, ?5)",
1119                    params![e.kind, e.key, pos, e.data.to_string(), e.rev],
1120                )
1121                .map_err(|x| x.to_string())?;
1122                xor(&mut acc, &row_hash(e.kind, &e.key, pos, &e.rev));
1123                changes.push((e.kind.into(), e.key.clone(), None, Some(e.rev.clone())));
1124                dirty = true;
1125            }
1126            Some((rev, old_pos)) if *rev != e.rev => {
1127                xor(&mut acc, &row_hash(e.kind, &e.key, *old_pos, rev));
1128                xor(&mut acc, &row_hash(e.kind, &e.key, pos, &e.rev));
1129                conn.execute(
1130                    "UPDATE vault_rows SET pos = ?3, data = ?4, rev = ?5 WHERE kind = ?1 AND key = ?2",
1131                    params![e.kind, e.key, pos, e.data.to_string(), e.rev],
1132                )
1133                .map_err(|x| x.to_string())?;
1134                changes.push((
1135                    e.kind.into(),
1136                    e.key.clone(),
1137                    Some(rev.clone()),
1138                    Some(e.rev.clone()),
1139                ));
1140                dirty = true;
1141            }
1142            Some((rev, old_pos)) => {
1143                if *old_pos != pos {
1144                    xor(&mut acc, &row_hash(e.kind, &e.key, *old_pos, rev));
1145                    xor(&mut acc, &row_hash(e.kind, &e.key, pos, rev));
1146                    conn.execute(
1147                        "UPDATE vault_rows SET pos = ?3 WHERE kind = ?1 AND key = ?2",
1148                        params![e.kind, e.key, pos],
1149                    )
1150                    .map_err(|x| x.to_string())?;
1151                    dirty = true;
1152                }
1153            }
1154        }
1155        if e.kind == KIND_ENTRY {
1156            let writer = e
1157                .history
1158                .as_ref()
1159                .filter(|h| h.as_array().map(|a| !a.is_empty()).unwrap_or(false));
1160            match (writer, stored_hist.get(&e.key)) {
1161                (None, None) => {}
1162                // A row that lost its history in the writer's copy keeps the stored
1163                // one: history is only ever removed together with its entry.
1164                (None, Some(_)) => {
1165                    keep_hist.insert(e.key.clone());
1166                }
1167                (Some(h), stored_rev) => {
1168                    keep_hist.insert(e.key.clone());
1169                    let hrev = rev_of(h);
1170                    if stored_rev != Some(&hrev) {
1171                        let merged = if stored_rev.is_some() {
1172                            let stored = history_by_key(conn, &e.key)?;
1173                            merge_history(stored.as_ref(), Some(h))
1174                        } else {
1175                            Some(h.clone())
1176                        };
1177                        if let Some(m) = merged {
1178                            let mrev = rev_of(&m);
1179                            if stored_rev != Some(&mrev) {
1180                                conn.execute(
1181                                    "INSERT OR REPLACE INTO vault_history (key, data, rev) VALUES (?1, ?2, ?3)",
1182                                    params![e.key, m.to_string(), mrev],
1183                                )
1184                                .map_err(|x| x.to_string())?;
1185                                dirty = true;
1186                            }
1187                        }
1188                    }
1189                }
1190            }
1191        }
1192    }
1193    for (id, (rev, old_pos)) in stored {
1194        if !keep.contains(id) {
1195            xor(&mut acc, &row_hash(&id.0, &id.1, *old_pos, rev));
1196            conn.execute(
1197                "DELETE FROM vault_rows WHERE kind = ?1 AND key = ?2",
1198                params![id.0, id.1],
1199            )
1200            .map_err(|x| x.to_string())?;
1201            changes.push((id.0.clone(), id.1.clone(), Some(rev.clone()), None));
1202            dirty = true;
1203        }
1204    }
1205    for k in stored_hist.keys() {
1206        if !keep_hist.contains(k) {
1207            conn.execute("DELETE FROM vault_history WHERE key = ?1", params![k])
1208                .map_err(|x| x.to_string())?;
1209            dirty = true;
1210        }
1211    }
1212
1213    if !dirty {
1214        if let Some(v) = version(conn)? {
1215            return Ok(v);
1216        }
1217    }
1218    let hash = acc_hex(&acc);
1219    conn.execute(
1220        "INSERT OR REPLACE INTO vault_meta (key, value) VALUES ('state_acc', ?1)",
1221        params![hash],
1222    )
1223    .map_err(|e| e.to_string())?;
1224    conn.execute(
1225        "INSERT INTO vault_saves (state_hash, at) VALUES (?1, ?2)",
1226        params![hash, now],
1227    )
1228    .map_err(|e| e.to_string())?;
1229    let seq = conn.last_insert_rowid();
1230    for (k, key, prev, new) in changes {
1231        conn.execute(
1232            "INSERT INTO vault_changes (seq, kind, key, prev_rev, new_rev) VALUES (?1, ?2, ?3, ?4, ?5)",
1233            params![seq, k, key, prev, new],
1234        )
1235        .map_err(|e| e.to_string())?;
1236    }
1237    prune_saves(conn, seq, now, KEEP_SAVES, HARD_KEEP_SAVES)?;
1238    let tok = token(seq, &hash);
1239    conn.execute(
1240        "INSERT OR REPLACE INTO vault_meta (key, value) VALUES ('data_hash', ?1)",
1241        params![tok],
1242    )
1243    .map_err(|e| e.to_string())?;
1244    Ok(tok)
1245}
1246
1247// ── Migration from v1 ────────────────────────────────────────────────────────
1248
1249fn legacy_blob(conn: &Connection) -> Result<Option<String>, String> {
1250    conn.query_row("SELECT data FROM vault WHERE id = 1", [], |r| r.get(0))
1251        .optional()
1252        .map_err(|e| e.to_string())
1253}
1254
1255/// True when a v1 blob is waiting to be converted.
1256pub fn needs_migration(conn: &Connection) -> Result<bool, String> {
1257    Ok(legacy_blob(conn)?.is_some())
1258}
1259
1260/// Copy `vault.db` to `vault.db.v1.bak` (owner-only) before the one-way conversion.
1261fn backup_v1(conn: &Connection) {
1262    let Some(path) = conn.path().map(std::path::PathBuf::from) else {
1263        return;
1264    };
1265    if path.as_os_str().is_empty() {
1266        return;
1267    }
1268    let _ = conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE);");
1269    let mut bak = path.as_os_str().to_owned();
1270    bak.push(".v1.bak");
1271    let bak = std::path::PathBuf::from(bak);
1272    // Replaced on every attempt, through a temp file and a rename: an earlier attempt's
1273    // half-written copy used to count as "the backup exists" and was kept forever, and a
1274    // backup from before later writes would not hold the vault being converted.
1275    // ponytail: a plain file copy, so a v1 build writing during the copy could still tear it;
1276    // the online backup API would close that if two builds sharing one vault ever matters.
1277    let mut tmp = bak.as_os_str().to_owned();
1278    tmp.push(".tmp");
1279    let tmp = std::path::PathBuf::from(tmp);
1280    if std::fs::copy(&path, &tmp).is_ok() {
1281        let _ = crate::restrict_to_owner(&tmp);
1282        if std::fs::rename(&tmp, &bak).is_err() {
1283            let _ = std::fs::remove_file(&tmp);
1284        }
1285    }
1286}
1287
1288/// Convert the v1 blob into rows. Must run inside a write transaction. No audit
1289/// rows are written: nothing about the data changed, only where it lives.
1290pub fn migrate_in_txn(conn: &Connection, now: &str) -> Result<bool, String> {
1291    let Some(raw) = legacy_blob(conn)? else {
1292        return Ok(false);
1293    };
1294    // A blob next to rows means an older build opened an already-converted vault and
1295    // wrote its own copy. Converting would DELETE every row first: whichever side was the
1296    // newer one is gone, silently. Neither is provably newer, so touch nothing.
1297    let rows: i64 = conn
1298        .query_row("SELECT COUNT(*) FROM vault_rows", [], |r| r.get(0))
1299        .map_err(|e| e.to_string())?;
1300    if rows > 0 {
1301        return Err(
1302            "This vault holds both the current storage and an older-format copy, which \
1303             an older build must have written after the upgrade. Nothing was changed. Keep \
1304             the copy you trust (the older one is in the `vault` table; `vault.db.v1.bak` is \
1305             the file from before the upgrade) and remove the other before opening again."
1306                .to_string(),
1307        );
1308    }
1309    let doc: Value =
1310        serde_json::from_str(&raw).map_err(|e| format!("legacy vault is unreadable: {e}"))?;
1311    conn.execute("DELETE FROM vault_rows", [])
1312        .map_err(|e| e.to_string())?;
1313    conn.execute("DELETE FROM vault_history", [])
1314        .map_err(|e| e.to_string())?;
1315    conn.execute("DELETE FROM vault_meta WHERE key = 'state_acc'", [])
1316        .map_err(|e| e.to_string())?;
1317    write(conn, &snapshot(conn)?, &split(doc), now)?;
1318    conn.execute("DELETE FROM vault WHERE id = 1", [])
1319        .map_err(|e| e.to_string())?;
1320    Ok(true)
1321}
1322
1323/// Migrate on its own transaction (the read path). Cheap when nothing is pending.
1324pub fn migrate_if_needed(conn: &Connection, now: &str) -> Result<(), String> {
1325    if !needs_migration(conn)? {
1326        return Ok(());
1327    }
1328    backup_v1(conn);
1329    conn.execute_batch("BEGIN IMMEDIATE")
1330        .map_err(|e| e.to_string())?;
1331    let r = migrate_in_txn(conn, now).and_then(|_| {
1332        conn.execute(
1333            "INSERT OR REPLACE INTO vault_meta (key, value) VALUES ('schema_version', ?1)",
1334            params![crate::VAULT_SCHEMA_VERSION.to_string()],
1335        )
1336        .map(|_| ())
1337        .map_err(|e| e.to_string())
1338    });
1339    match r {
1340        Ok(()) => crate::commit(conn),
1341        Err(e) => {
1342            let _ = conn.execute_batch("ROLLBACK");
1343            Err(e)
1344        }
1345    }
1346}
1347
1348#[cfg(test)]
1349mod tests {
1350    use super::*;
1351    use crate::{load_vault, save_vault, vault_version, SaveCtx, CONFLICT_ERR};
1352    use serde_json::json;
1353
1354    fn open(tag: &str) -> (Connection, std::path::PathBuf) {
1355        // A counter beside the process id, not the clock: two tests starting within one clock tick
1356        // (macOS has a coarse one) shared a directory and failed with "database is locked".
1357        let nanos = {
1358            use std::sync::atomic::{AtomicU64, Ordering};
1359            static SEQ: AtomicU64 = AtomicU64::new(0);
1360            format!(
1361                "{}-{}",
1362                std::process::id(),
1363                SEQ.fetch_add(1, Ordering::SeqCst)
1364            )
1365        };
1366        let dir =
1367            std::env::temp_dir().join(format!("vc-storage-{tag}-{}-{nanos}", std::process::id()));
1368        std::fs::create_dir_all(&dir).unwrap();
1369        let key = crate::derive_key("correct horse battery staple", b"0123456789abcdef").unwrap();
1370        let conn = crate::open_db(&dir.join("vault.db"), &key).unwrap();
1371        crate::init_schema(&conn).unwrap();
1372        (conn, dir)
1373    }
1374
1375    fn e(id: &str, provider: &str) -> Value {
1376        json!({ "id": id, "provider": provider, "api_key": format!("key-{id}") })
1377    }
1378
1379    fn save(conn: &Connection, doc: Value, base: Option<&str>) -> Result<String, String> {
1380        save_vault(
1381            conn,
1382            doc,
1383            SaveCtx {
1384                actor: None,
1385                expect_version: base,
1386            },
1387        )
1388    }
1389
1390    fn names(conn: &Connection) -> Vec<String> {
1391        load_vault(conn).unwrap().unwrap()["api_keys"]
1392            .as_array()
1393            .unwrap()
1394            .iter()
1395            .map(|x| x["provider"].as_str().unwrap().to_string())
1396            .collect()
1397    }
1398
1399    #[test]
1400    fn the_document_round_trips_including_unknown_top_level_keys_and_order() {
1401        let (conn, _d) = open("roundtrip");
1402        let doc = json!({
1403            "api_keys": [e("b", "B"), e("a", "A"), e("c", "C")],
1404            "projects": [{ "id": "p2", "name": "Two" }, { "id": "p1", "name": "One" }],
1405            "user_categories": ["x", "a/b"],
1406            "someFutureKey": { "nested": [1, 2, 3] }
1407        });
1408        save(&conn, doc.clone(), None).unwrap();
1409        let got = load_vault(&conn).unwrap().unwrap();
1410        assert_eq!(got, doc);
1411    }
1412
1413    #[test]
1414    fn a_save_writes_only_the_rows_that_changed() {
1415        let (conn, _d) = open("minimal");
1416        let v1 = save(
1417            &conn,
1418            json!({ "api_keys": [e("1", "A"), e("2", "B"), e("3", "C")] }),
1419            None,
1420        )
1421        .unwrap();
1422        save(
1423            &conn,
1424            json!({ "api_keys": [e("1", "A"), e("2", "B-edited"), e("3", "C")] }),
1425            Some(&v1),
1426        )
1427        .unwrap();
1428        let last: i64 = conn
1429            .query_row("SELECT MAX(seq) FROM vault_saves", [], |r| r.get(0))
1430            .unwrap();
1431        let changed: Vec<(String, String)> = conn
1432            .prepare("SELECT kind, key FROM vault_changes WHERE seq = ?1")
1433            .unwrap()
1434            .query_map(params![last], |r| Ok((r.get(0)?, r.get(1)?)))
1435            .unwrap()
1436            .map(|x| x.unwrap())
1437            .collect();
1438        assert_eq!(changed, vec![("entry".to_string(), "id\u{1}2".to_string())]);
1439    }
1440
1441    #[test]
1442    fn an_identical_save_creates_no_new_version() {
1443        let (conn, _d) = open("noop");
1444        let doc = json!({ "api_keys": [e("1", "A")] });
1445        let v1 = save(&conn, doc.clone(), None).unwrap();
1446        let v2 = save(&conn, doc, Some(&v1)).unwrap();
1447        assert_eq!(v1, v2);
1448        let n: i64 = conn
1449            .query_row("SELECT COUNT(*) FROM vault_saves", [], |r| r.get(0))
1450            .unwrap();
1451        assert_eq!(n, 1);
1452    }
1453
1454    #[test]
1455    fn two_writers_editing_different_entries_both_land() {
1456        let (conn, _d) = open("disjoint");
1457        let base = json!({ "api_keys": [e("1", "A"), e("2", "B")] });
1458        let v1 = save(&conn, base, None).unwrap();
1459        // Writer one edits entry 1 and saves.
1460        save(
1461            &conn,
1462            json!({ "api_keys": [e("1", "A-one"), e("2", "B")] }),
1463            Some(&v1),
1464        )
1465        .unwrap();
1466        // Writer two, still holding v1, edits entry 2. Their copy of entry 1 is stale.
1467        let out = save(
1468            &conn,
1469            json!({ "api_keys": [e("1", "A"), e("2", "B-two")] }),
1470            Some(&v1),
1471        );
1472        assert!(out.is_ok(), "{out:?}");
1473        assert_eq!(names(&conn), vec!["A-one", "B-two"]);
1474    }
1475
1476    fn proj(id: &str, chunks: Value) -> Value {
1477        json!({ "id": id, "name": id, "chunks": chunks })
1478    }
1479    fn ch(id: &str, v: &str) -> Value {
1480        json!({ "id": id, "name": id, "value": v })
1481    }
1482    fn chunk_values(conn: &Connection, p: usize) -> Vec<String> {
1483        load_vault(conn).unwrap().unwrap()["projects"][p]["chunks"]
1484            .as_array()
1485            .unwrap()
1486            .iter()
1487            .map(|c| c["value"].as_str().unwrap().to_string())
1488            .collect()
1489    }
1490
1491    #[test]
1492    fn chunks_are_rows_of_their_own_and_the_document_round_trips() {
1493        let (conn, _d) = open("chunk-rows");
1494        let doc = json!({
1495            "api_keys": [],
1496            "projects": [
1497                proj("p1", json!([ch("c1", "a"), ch("c2", "b")])),
1498                proj("p2", json!([])),
1499                { "id": "p3", "name": "no chunks key" }
1500            ]
1501        });
1502        save(&conn, doc.clone(), None).unwrap();
1503        let rows: i64 = conn
1504            .query_row(
1505                "SELECT COUNT(*) FROM vault_rows WHERE kind='chunk'",
1506                [],
1507                |r| r.get(0),
1508            )
1509            .unwrap();
1510        assert_eq!(rows, 2);
1511        let got = load_vault(&conn).unwrap().unwrap();
1512        assert_eq!(got["projects"], doc["projects"]);
1513    }
1514
1515    #[test]
1516    fn inline_chunks_from_an_unconverted_vault_still_load() {
1517        let doc = json!({ "api_keys": [], "projects": [proj("p1", json!([ch("c1", "a")]))] });
1518        let ents = split(doc.clone());
1519        // Rebuild what a v2 build stored: the chunks inside the project row.
1520        let mut legacy = ents
1521            .into_iter()
1522            .filter(|e| e.kind != KIND_CHUNK)
1523            .collect::<Vec<_>>();
1524        for e in legacy.iter_mut().filter(|e| e.kind == KIND_PROJECT) {
1525            e.data["chunks"] = json!([ch("c1", "a")]);
1526        }
1527        assert_eq!(join(legacy)["projects"], doc["projects"]);
1528    }
1529
1530    #[test]
1531    fn two_writers_editing_different_chunks_of_one_project_both_land() {
1532        let (conn, _d) = open("chunk-disjoint");
1533        let base = json!({ "api_keys": [], "projects": [proj("p", json!([ch("c1", "a"), ch("c2", "b")]))] });
1534        let v1 = save(&conn, base, None).unwrap();
1535        save(
1536            &conn,
1537            json!({ "api_keys": [], "projects": [proj("p", json!([ch("c1", "a-one"), ch("c2", "b")]))] }),
1538            Some(&v1),
1539        )
1540        .unwrap();
1541        let out = save(
1542            &conn,
1543            json!({ "api_keys": [], "projects": [proj("p", json!([ch("c1", "a"), ch("c2", "b-two")]))] }),
1544            Some(&v1),
1545        );
1546        assert!(out.is_ok(), "{out:?}");
1547        assert_eq!(chunk_values(&conn, 0), vec!["a-one", "b-two"]);
1548    }
1549
1550    #[test]
1551    fn two_writers_editing_the_same_chunk_conflict_and_name_it() {
1552        let (conn, _d) = open("chunk-conflict");
1553        let base = json!({ "api_keys": [], "projects": [proj("p", json!([ch("c1", "a")]))] });
1554        let v1 = save(&conn, base, None).unwrap();
1555        save(
1556            &conn,
1557            json!({ "api_keys": [], "projects": [proj("p", json!([ch("c1", "one")]))] }),
1558            Some(&v1),
1559        )
1560        .unwrap();
1561        let err = save(
1562            &conn,
1563            json!({ "api_keys": [], "projects": [proj("p", json!([ch("c1", "two")]))] }),
1564            Some(&v1),
1565        )
1566        .unwrap_err();
1567        assert!(err.starts_with(CONFLICT_ERR) && err.contains("c1"), "{err}");
1568    }
1569
1570    #[test]
1571    fn deleting_a_project_removes_its_chunk_rows_and_a_stale_chunk_add_is_dropped() {
1572        let (conn, _d) = open("chunk-orphan");
1573        let v1 = save(
1574            &conn,
1575            json!({ "api_keys": [], "projects": [proj("p", json!([ch("c1", "a")]))] }),
1576            None,
1577        )
1578        .unwrap();
1579        // Someone deletes the project; the stale writer adds a chunk to it.
1580        save(&conn, json!({ "api_keys": [], "projects": [] }), Some(&v1)).unwrap();
1581        save(
1582            &conn,
1583            json!({ "api_keys": [], "projects": [proj("p", json!([ch("c1", "a"), ch("c2", "new")]))] }),
1584            Some(&v1),
1585        )
1586        .unwrap();
1587        let rows: i64 = conn
1588            .query_row(
1589                "SELECT COUNT(*) FROM vault_rows WHERE kind='chunk'",
1590                [],
1591                |r| r.get(0),
1592            )
1593            .unwrap();
1594        assert_eq!(rows, 0, "no orphan chunk rows");
1595        assert!(verify(&conn).unwrap());
1596    }
1597
1598    #[test]
1599    fn change_history_is_kept_by_age_as_well_as_by_count() {
1600        let (conn, _d) = open("retention");
1601        for i in 0..12 {
1602            save(
1603                &conn,
1604                json!({ "api_keys": [e("1", &format!("v{i}"))] }),
1605                None,
1606            )
1607            .unwrap();
1608        }
1609        // Age the first six saves to a year ago; the rest are "now".
1610        conn.execute(
1611            "UPDATE vault_saves SET at = '2000-01-01T00:00:00Z' WHERE seq <= 6",
1612            [],
1613        )
1614        .unwrap();
1615        let max: i64 = conn
1616            .query_row("SELECT MAX(seq) FROM vault_saves", [], |r| r.get(0))
1617            .unwrap();
1618        let now = crate::iso_now();
1619        // keep=4: old AND beyond the newest four goes; the recent ones stay even beyond four.
1620        prune_saves(&conn, max, &now, 4, 1000).unwrap();
1621        let left: i64 = conn
1622            .query_row("SELECT COUNT(*) FROM vault_saves", [], |r| r.get(0))
1623            .unwrap();
1624        assert_eq!(left, 6, "six old saves dropped, six recent kept");
1625        let low: i64 = conn
1626            .query_row(
1627                "SELECT COUNT(*) FROM vault_changes WHERE seq <= 6",
1628                [],
1629                |r| r.get(0),
1630            )
1631            .unwrap();
1632        assert_eq!(low, 0, "their change rows go with them");
1633        // The hard cap beats age.
1634        prune_saves(&conn, max, &now, 4, 3).unwrap();
1635        let left: i64 = conn
1636            .query_row("SELECT COUNT(*) FROM vault_saves", [], |r| r.get(0))
1637            .unwrap();
1638        assert_eq!(left, 3);
1639        assert_eq!(merge_window(&conn).unwrap().unwrap().1, 3);
1640    }
1641
1642    #[test]
1643    fn one_entrys_history_can_be_read_alone() {
1644        let (conn, _d) = open("hist-one");
1645        let mut a = e("a", "A");
1646        a["version_history"] = json!([{ "value": "old", "saved_at": "2026-01-01T00:00:00Z" }]);
1647        save(&conn, json!({ "api_keys": [a, e("b", "B")] }), None).unwrap();
1648        assert_eq!(
1649            entry_history(&conn, "a").unwrap().unwrap()[0]["value"],
1650            "old"
1651        );
1652        assert_eq!(entry_history(&conn, "b").unwrap().unwrap(), json!([]));
1653        assert!(entry_history(&conn, "missing").unwrap().is_none());
1654    }
1655
1656    #[test]
1657    fn a_stale_writer_neither_deletes_nor_overwrites_what_it_never_saw() {
1658        let (conn, _d) = open("unseen");
1659        let v1 = save(&conn, json!({ "api_keys": [e("1", "A")] }), None).unwrap();
1660        // Someone else adds entry 2.
1661        save(
1662            &conn,
1663            json!({ "api_keys": [e("1", "A"), e("2", "Added")] }),
1664            Some(&v1),
1665        )
1666        .unwrap();
1667        // The stale writer edits entry 1 and does not have entry 2.
1668        save(&conn, json!({ "api_keys": [e("1", "A-edit")] }), Some(&v1)).unwrap();
1669        assert_eq!(names(&conn), vec!["A-edit", "Added"]);
1670    }
1671
1672    #[test]
1673    fn deleting_an_untouched_entry_while_another_is_added_applies_both() {
1674        let (conn, _d) = open("delete-add");
1675        let v1 = save(
1676            &conn,
1677            json!({ "api_keys": [e("1", "A"), e("2", "B")] }),
1678            None,
1679        )
1680        .unwrap();
1681        save(
1682            &conn,
1683            json!({ "api_keys": [e("1", "A"), e("2", "B"), e("3", "C")] }),
1684            Some(&v1),
1685        )
1686        .unwrap();
1687        save(&conn, json!({ "api_keys": [e("1", "A")] }), Some(&v1)).unwrap();
1688        assert_eq!(names(&conn), vec!["A", "C"]);
1689    }
1690
1691    #[test]
1692    fn a_merged_save_says_so_and_a_writer_that_reloads_carries_on() {
1693        let (conn, _d) = open("merged-token");
1694        let v1 = save(
1695            &conn,
1696            json!({ "api_keys": [e("1", "A"), e("2", "B")] }),
1697            None,
1698        )
1699        .unwrap();
1700        // Someone else edits entry 1.
1701        save(
1702            &conn,
1703            json!({ "api_keys": [e("1", "A-theirs"), e("2", "B")] }),
1704            Some(&v1),
1705        )
1706        .unwrap();
1707        // The stale writer edits entry 2; entry 1 in its copy is behind.
1708        let t = save(
1709            &conn,
1710            json!({ "api_keys": [e("1", "A"), e("2", "B-mine")] }),
1711            Some(&v1),
1712        )
1713        .unwrap();
1714        let bare = t
1715            .strip_suffix(crate::MERGED_SUFFIX)
1716            .expect("a merge is marked");
1717        assert_eq!(vault_version(&conn).unwrap().as_deref(), Some(bare));
1718        // Reloading gives the merged document, and its token is a valid base.
1719        assert_eq!(names(&conn), vec!["A-theirs", "B-mine"]);
1720        let mut doc = load_vault(&conn).unwrap().unwrap();
1721        doc["api_keys"][1]["provider"] = json!("B-mine-2");
1722        save(&conn, doc, Some(bare)).unwrap();
1723        assert_eq!(names(&conn), vec!["A-theirs", "B-mine-2"]);
1724    }
1725
1726    #[test]
1727    fn the_marked_token_is_accepted_as_a_base() {
1728        let (conn, _d) = open("marked");
1729        let v1 = save(
1730            &conn,
1731            json!({ "api_keys": [e("1", "A"), e("2", "B")] }),
1732            None,
1733        )
1734        .unwrap();
1735        save(
1736            &conn,
1737            json!({ "api_keys": [e("1", "A-theirs"), e("2", "B")] }),
1738            Some(&v1),
1739        )
1740        .unwrap();
1741        let t = save(
1742            &conn,
1743            json!({ "api_keys": [e("1", "A"), e("2", "B-mine")] }),
1744            Some(&v1),
1745        )
1746        .unwrap();
1747        assert!(t.ends_with(crate::MERGED_SUFFIX));
1748        let mut doc = load_vault(&conn).unwrap().unwrap();
1749        doc["api_keys"][0]["api_key"] = json!("changed");
1750        assert!(save(&conn, doc, Some(&t)).is_ok());
1751    }
1752
1753    #[test]
1754    fn a_save_with_nothing_to_merge_returns_the_new_version() {
1755        let (conn, _d) = open("clean-token");
1756        let v1 = save(&conn, json!({ "api_keys": [e("1", "A")] }), None).unwrap();
1757        let v2 = save(&conn, json!({ "api_keys": [e("1", "A2")] }), Some(&v1)).unwrap();
1758        assert_ne!(v1, v2);
1759        assert!(!v2.contains('+'), "no merge happened: {v2}");
1760        assert_eq!(vault_version(&conn).unwrap().as_deref(), Some(v2.as_str()));
1761    }
1762
1763    #[test]
1764    fn deleting_an_entry_someone_else_edited_is_a_conflict_that_names_it() {
1765        let (conn, _d) = open("delete-edited");
1766        let v1 = save(
1767            &conn,
1768            json!({ "api_keys": [e("1", "Keep"), e("2", "Contested")] }),
1769            None,
1770        )
1771        .unwrap();
1772        save(
1773            &conn,
1774            json!({ "api_keys": [e("1", "Keep"), e("2", "Contested-edited")] }),
1775            Some(&v1),
1776        )
1777        .unwrap();
1778        let err = save(&conn, json!({ "api_keys": [e("1", "Keep")] }), Some(&v1)).unwrap_err();
1779        assert!(err.starts_with(CONFLICT_ERR));
1780        assert!(err.contains("Contested-edited"), "{err}");
1781        assert_eq!(names(&conn), vec!["Keep", "Contested-edited"]);
1782    }
1783
1784    #[test]
1785    fn editing_an_entry_someone_else_deleted_is_a_conflict() {
1786        let (conn, _d) = open("edit-deleted");
1787        let v1 = save(
1788            &conn,
1789            json!({ "api_keys": [e("1", "A"), e("2", "B")] }),
1790            None,
1791        )
1792        .unwrap();
1793        save(&conn, json!({ "api_keys": [e("1", "A")] }), Some(&v1)).unwrap();
1794        let err = save(
1795            &conn,
1796            json!({ "api_keys": [e("1", "A"), e("2", "B-edit")] }),
1797            Some(&v1),
1798        )
1799        .unwrap_err();
1800        assert!(err.starts_with(CONFLICT_ERR), "{err}");
1801    }
1802
1803    #[test]
1804    fn two_writers_arriving_at_the_same_content_do_not_conflict() {
1805        let (conn, _d) = open("same");
1806        let v1 = save(&conn, json!({ "api_keys": [e("1", "A")] }), None).unwrap();
1807        save(&conn, json!({ "api_keys": [e("1", "Same")] }), Some(&v1)).unwrap();
1808        assert!(save(&conn, json!({ "api_keys": [e("1", "Same")] }), Some(&v1)).is_ok());
1809    }
1810
1811    #[test]
1812    fn projects_and_categories_merge_like_entries() {
1813        let (conn, _d) = open("projects");
1814        let v1 = save(
1815            &conn,
1816            json!({ "api_keys": [], "projects": [{ "id": "p1", "name": "One" }, { "id": "p2", "name": "Two" }], "user_categories": ["a"] }),
1817            None,
1818        )
1819        .unwrap();
1820        save(
1821            &conn,
1822            json!({ "api_keys": [], "projects": [{ "id": "p1", "name": "One-renamed" }, { "id": "p2", "name": "Two" }], "user_categories": ["a"] }),
1823            Some(&v1),
1824        )
1825        .unwrap();
1826        save(
1827            &conn,
1828            json!({ "api_keys": [], "projects": [{ "id": "p1", "name": "One" }, { "id": "p2", "name": "Two-renamed" }], "user_categories": ["a", "b"] }),
1829            Some(&v1),
1830        )
1831        .unwrap();
1832        let got = load_vault(&conn).unwrap().unwrap();
1833        assert_eq!(got["projects"][0]["name"], "One-renamed");
1834        assert_eq!(got["projects"][1]["name"], "Two-renamed");
1835        assert_eq!(got["user_categories"], json!(["a", "b"]));
1836    }
1837
1838    #[test]
1839    fn a_token_in_the_old_form_or_from_a_pruned_save_is_a_whole_vault_conflict() {
1840        let (conn, _d) = open("oldtoken");
1841        let v1 = save(&conn, json!({ "api_keys": [e("1", "A")] }), None).unwrap();
1842        save(&conn, json!({ "api_keys": [e("1", "A2")] }), Some(&v1)).unwrap();
1843        for bad in [
1844            "deadbeef".to_string(),
1845            "1.0000".to_string(),
1846            "x.y".to_string(),
1847        ] {
1848            let err = save(&conn, json!({ "api_keys": [e("9", "Z")] }), Some(&bad)).unwrap_err();
1849            assert!(err.starts_with(CONFLICT_ERR), "{bad}: {err}");
1850        }
1851        // The base save has aged out of the retained history.
1852        conn.execute("DELETE FROM vault_saves WHERE seq = 1", [])
1853            .unwrap();
1854        let err = save(&conn, json!({ "api_keys": [e("1", "mine")] }), Some(&v1)).unwrap_err();
1855        assert!(err.starts_with(CONFLICT_ERR), "{err}");
1856    }
1857
1858    #[test]
1859    fn history_lives_in_its_own_table_and_not_in_the_row() {
1860        let (conn, _d) = open("history");
1861        let v1 = save(&conn, json!({ "api_keys": [e("1", "A")] }), None).unwrap();
1862        let mut changed = e("1", "A");
1863        changed["api_key"] = json!("rotated");
1864        save(&conn, json!({ "api_keys": [changed] }), Some(&v1)).unwrap();
1865        let row: String = conn
1866            .query_row(
1867                "SELECT data FROM vault_rows WHERE kind = 'entry'",
1868                [],
1869                |r| r.get(0),
1870            )
1871            .unwrap();
1872        assert!(!row.contains("version_history"), "{row}");
1873        assert!(
1874            !row.contains("key-1"),
1875            "the old key belongs in the history table only"
1876        );
1877        let hist: String = conn
1878            .query_row("SELECT data FROM vault_history", [], |r| r.get(0))
1879            .unwrap();
1880        assert!(hist.contains("key-1"));
1881        // And it comes back attached to the entry.
1882        let doc = load_vault(&conn).unwrap().unwrap();
1883        assert_eq!(doc["api_keys"][0]["version_history"][0]["value"], "key-1");
1884    }
1885
1886    #[test]
1887    fn deleting_an_entry_deletes_its_history() {
1888        let (conn, _d) = open("history-delete");
1889        let v1 = save(&conn, json!({ "api_keys": [e("1", "A")] }), None).unwrap();
1890        let mut changed = e("1", "A");
1891        changed["api_key"] = json!("rotated");
1892        let v2 = save(&conn, json!({ "api_keys": [changed] }), Some(&v1)).unwrap();
1893        save(&conn, json!({ "api_keys": [] }), Some(&v2)).unwrap();
1894        let n: i64 = conn
1895            .query_row("SELECT COUNT(*) FROM vault_history", [], |r| r.get(0))
1896            .unwrap();
1897        assert_eq!(n, 0);
1898    }
1899
1900    #[test]
1901    fn legacy_entries_with_the_same_identity_both_survive() {
1902        let (conn, _d) = open("dupes");
1903        let doc = json!({ "api_keys": [
1904            { "provider": "Same", "api_key": "one" },
1905            { "provider": "Same", "api_key": "two" }
1906        ] });
1907        save(&conn, doc, None).unwrap();
1908        let got = load_vault(&conn).unwrap().unwrap();
1909        let keys: Vec<&str> = got["api_keys"]
1910            .as_array()
1911            .unwrap()
1912            .iter()
1913            .map(|x| x["api_key"].as_str().unwrap())
1914            .collect();
1915        assert_eq!(keys, vec!["one", "two"]);
1916    }
1917
1918    #[test]
1919    fn reordering_is_a_change_but_not_a_content_conflict() {
1920        let (conn, _d) = open("reorder");
1921        let v1 = save(
1922            &conn,
1923            json!({ "api_keys": [e("1", "A"), e("2", "B")] }),
1924            None,
1925        )
1926        .unwrap();
1927        let v2 = save(
1928            &conn,
1929            json!({ "api_keys": [e("2", "B"), e("1", "A")] }),
1930            Some(&v1),
1931        )
1932        .unwrap();
1933        assert_ne!(v1, v2);
1934        assert_eq!(names(&conn), vec!["B", "A"]);
1935    }
1936
1937    #[test]
1938    fn tampering_with_a_row_or_with_the_token_fails_integrity() {
1939        let (conn, _d) = open("verify");
1940        save(&conn, json!({ "api_keys": [e("1", "A")] }), None).unwrap();
1941        assert!(crate::verify_vault_integrity(&conn).unwrap());
1942        conn.execute("UPDATE vault_rows SET pos = 7 WHERE kind = 'entry'", [])
1943            .unwrap();
1944        assert!(
1945            !crate::verify_vault_integrity(&conn).unwrap(),
1946            "a moved row changes the state hash"
1947        );
1948    }
1949
1950    // ── v1 -> v2 ───────────────────────────────────────────────────────────────
1951
1952    fn plant_v1(conn: &Connection, doc: &Value) {
1953        conn.execute(
1954            "INSERT OR REPLACE INTO vault (id, data) VALUES (1, ?1)",
1955            params![doc.to_string()],
1956        )
1957        .unwrap();
1958        conn.execute(
1959            "INSERT OR REPLACE INTO vault_meta (key, value) VALUES ('schema_version', '1')",
1960            [],
1961        )
1962        .unwrap();
1963        conn.execute(
1964            "INSERT OR REPLACE INTO vault_meta (key, value) VALUES ('data_hash', 'abc')",
1965            [],
1966        )
1967        .unwrap();
1968    }
1969
1970    // S10: a leftover half-written backup counted as "the backup exists" and was kept.
1971    // S12: vault_history (old secrets) was outside every integrity check.
1972    #[test]
1973    fn verify_notices_an_edited_history_row() {
1974        let (conn, _dir) = open("hist-verify");
1975        let doc = json!({ "api_keys": [{ "id": "1", "provider": "A", "api_key": "k",
1976            "version_history": [{ "value": "old", "saved_at": "2026-01-01T00:00:00Z" }] }] });
1977        crate::save_vault(&conn, doc, crate::SaveCtx::default()).unwrap();
1978        assert!(verify(&conn).unwrap());
1979        conn.execute(
1980            "UPDATE vault_history SET data = replace(data, 'old', 'forged')",
1981            [],
1982        )
1983        .unwrap();
1984        assert!(!verify(&conn).unwrap());
1985    }
1986
1987    #[test]
1988    fn a_stale_or_torn_backup_is_replaced_by_a_copy_of_the_vault_being_converted() {
1989        let (conn, dir) = open("stale-bak");
1990        plant_v1(
1991            &conn,
1992            &json!({ "api_keys": [{ "id": "1", "provider": "A", "api_key": "k" }] }),
1993        );
1994        std::fs::write(dir.join("vault.db.v1.bak"), b"torn").unwrap();
1995        load_vault(&conn).unwrap();
1996        let bak = std::fs::read(dir.join("vault.db.v1.bak")).unwrap();
1997        assert!(
1998            bak.len() > 1024,
1999            "the backup is a copy of the database, not the old leftover"
2000        );
2001        assert!(!dir.join("vault.db.v1.bak.tmp").exists());
2002    }
2003
2004    #[test]
2005    fn a_v1_vault_is_converted_on_first_open_with_a_backup_and_nothing_lost() {
2006        let (conn, dir) = open("migrate");
2007        let doc = json!({
2008            "api_keys": [
2009                { "id": "1", "provider": "A", "api_key": "k", "version_history": [{ "value": "old", "saved_at": "2026-01-01T00:00:00Z" }] },
2010                { "id": "2", "provider": "B", "api_key": "k2" }
2011            ],
2012            "projects": [{ "id": "p", "name": "P", "chunks": [] }],
2013            "user_categories": ["c"],
2014            "extra": 1
2015        });
2016        plant_v1(&conn, &doc);
2017        let audit_before = crate::load_audit(&conn).unwrap().len();
2018
2019        let got = load_vault(&conn).unwrap().unwrap();
2020        assert_eq!(got, doc, "same document, new storage");
2021        assert_eq!(
2022            crate::vault_schema_version(&conn).unwrap(),
2023            Some(crate::VAULT_SCHEMA_VERSION)
2024        );
2025        assert!(
2026            dir.join("vault.db.v1.bak").exists(),
2027            "the one-way conversion is backed up first"
2028        );
2029        let blob: i64 = conn
2030            .query_row("SELECT COUNT(*) FROM vault", [], |r| r.get(0))
2031            .unwrap();
2032        assert_eq!(blob, 0, "no second copy of every secret is left behind");
2033        assert_eq!(
2034            crate::load_audit(&conn).unwrap().len(),
2035            audit_before,
2036            "a move is not an edit"
2037        );
2038        assert!(crate::verify_vault_integrity(&conn).unwrap());
2039        // The old history is where history now lives.
2040        let h: i64 = conn
2041            .query_row("SELECT COUNT(*) FROM vault_history", [], |r| r.get(0))
2042            .unwrap();
2043        assert_eq!(h, 1);
2044        // Idempotent.
2045        assert_eq!(load_vault(&conn).unwrap().unwrap(), doc);
2046    }
2047
2048    #[test]
2049    fn the_version_read_before_the_data_is_valid_after_a_conversion() {
2050        let (conn, _d) = open("v1-version-order");
2051        plant_v1(&conn, &json!({ "api_keys": [e("1", "A")] }));
2052        crate::ensure_current_schema(&conn).unwrap();
2053        let v = vault_version(&conn).unwrap().unwrap();
2054        let doc = load_vault(&conn).unwrap().unwrap();
2055        let mut edited = doc;
2056        edited["api_keys"][0]["provider"] = json!("A2");
2057        assert!(
2058            save(&conn, edited, Some(&v)).is_ok(),
2059            "the first save after an upgrade must not conflict"
2060        );
2061    }
2062
2063    #[test]
2064    fn saving_a_v1_vault_converts_it_in_the_same_transaction() {
2065        let (conn, _d) = open("migrate-save");
2066        plant_v1(&conn, &json!({ "api_keys": [e("1", "A")] }));
2067        let v = vault_version(&conn).unwrap().unwrap();
2068        assert_eq!(
2069            v, "abc",
2070            "before conversion the old token is still what is stored"
2071        );
2072        let out = save(
2073            &conn,
2074            json!({ "api_keys": [e("1", "A"), e("2", "B")] }),
2075            None,
2076        )
2077        .unwrap();
2078        assert_ne!(out, "abc");
2079        assert_eq!(names(&conn), vec!["A", "B"]);
2080        let blob: i64 = conn
2081            .query_row("SELECT COUNT(*) FROM vault", [], |r| r.get(0))
2082            .unwrap();
2083        assert_eq!(blob, 0);
2084    }
2085
2086    // S14: an older build opened a converted vault and wrote its own blob; the next open
2087    // of this build deleted every row and replaced them with that blob.
2088    #[test]
2089    fn a_blob_beside_converted_rows_is_refused_not_converted_over_them() {
2090        let (conn, _d) = open("blob-and-rows");
2091        save(&conn, json!({ "api_keys": [e("1", "Real")] }), None).unwrap();
2092        plant_v1(
2093            &conn,
2094            &json!({ "api_keys": [{ "id": "9", "provider": "FromOldBuild" }] }),
2095        );
2096        let err = load_vault(&conn).unwrap_err();
2097        assert!(err.contains("Nothing was changed"), "{err}");
2098        let n: i64 = conn
2099            .query_row(
2100                "SELECT COUNT(*) FROM vault_rows WHERE data LIKE '%Real%'",
2101                [],
2102                |r| r.get(0),
2103            )
2104            .unwrap();
2105        assert_eq!(n, 1, "the rows survived the attempt");
2106    }
2107
2108    #[test]
2109    fn a_vault_with_rows_but_a_v1_stamp_and_no_blob_is_left_alone() {
2110        let (conn, _d) = open("stamp-only");
2111        save(&conn, json!({ "api_keys": [e("1", "A")] }), None).unwrap();
2112        conn.execute(
2113            "INSERT OR REPLACE INTO vault_meta (key, value) VALUES ('schema_version', '1')",
2114            [],
2115        )
2116        .unwrap();
2117        assert_eq!(names(&conn), vec!["A"]);
2118    }
2119
2120    /// Not a test: a measurement, run with `--ignored --nocapture`. Nothing here
2121    /// should be optimised before it is instrumented, and the claim behind schema
2122    /// v2 is that one edit costs O(1) rows instead of O(vault).
2123    #[test]
2124    #[ignore]
2125    fn measure_one_edit_against_the_blob() {
2126        use std::time::Instant;
2127        let (conn, _d) = open("bench");
2128        let n = 5000;
2129        let entries: Vec<Value> = (0..n)
2130            .map(|i| {
2131                json!({
2132                    "id": format!("id-{i}"), "provider": format!("Provider {i}"),
2133                    "api_key": "x".repeat(48), "description": "d".repeat(200),
2134                    "tags": ["a", "b"], "extra_vars": [{"key": "K", "value": "v".repeat(64)}],
2135                    "version_history": (0..3).map(|j| json!({"value": "o".repeat(48), "saved_at": format!("2026-01-0{}T00:00:00Z", j + 1)})).collect::<Vec<_>>()
2136                })
2137            })
2138            .collect();
2139        let mut doc = json!({ "api_keys": entries, "projects": [], "user_categories": [] });
2140        let t = Instant::now();
2141        let mut base = save(&conn, doc.clone(), None).unwrap();
2142        println!("first save of {n} entries: {:?}", t.elapsed());
2143
2144        // One edit, v2.
2145        doc["api_keys"][2500]["description"] = json!("edited");
2146        let t = Instant::now();
2147        base = save(&conn, doc.clone(), Some(&base)).unwrap();
2148        let v2 = t.elapsed();
2149        println!("v2: one edit in {n}: {v2:?}");
2150        let t = Instant::now();
2151        let _parts = split(doc.clone());
2152        println!("  split: {:?}", t.elapsed());
2153        // What v1 did for the same edit: read the blob, parse it, index every entry
2154        // (cloning, as the old code did), serialise the new document, hash it and
2155        // rewrite the one row.
2156        conn.execute_batch(
2157            "CREATE TABLE IF NOT EXISTS old_blob (id INTEGER PRIMARY KEY, data TEXT)",
2158        )
2159        .unwrap();
2160        let first = serde_json::to_string(&doc).unwrap();
2161        conn.execute(
2162            "INSERT OR REPLACE INTO old_blob (id, data) VALUES (1, ?1)",
2163            params![first],
2164        )
2165        .unwrap();
2166        let t = Instant::now();
2167        conn.execute_batch("BEGIN IMMEDIATE").unwrap();
2168        let old: String = conn
2169            .query_row("SELECT data FROM old_blob WHERE id = 1", [], |r| r.get(0))
2170            .unwrap();
2171        let old_doc: Value = serde_json::from_str(&old).unwrap();
2172        let old_map: HashMap<String, Value> = old_doc["api_keys"]
2173            .as_array()
2174            .unwrap()
2175            .iter()
2176            .map(|e| (crate::entry_ck(e), e.clone()))
2177            .collect();
2178        let _same = doc["api_keys"]
2179            .as_array()
2180            .unwrap()
2181            .iter()
2182            .filter(|e| old_map.contains_key(&crate::entry_ck(e)))
2183            .count();
2184        let raw = serde_json::to_string(&doc).unwrap();
2185        let _h = sha(&raw);
2186        conn.execute(
2187            "INSERT OR REPLACE INTO old_blob (id, data) VALUES (1, ?1)",
2188            params![raw],
2189        )
2190        .unwrap();
2191        conn.execute_batch("COMMIT").unwrap();
2192        let v1 = t.elapsed();
2193        println!(
2194            "v1 (read blob, parse, index, serialise, hash, rewrite; {} KB): {v1:?}",
2195            raw.len() / 1024
2196        );
2197
2198        let t = Instant::now();
2199        let loaded = load_vault(&conn).unwrap().unwrap();
2200        println!("load of {n} entries with history: {:?}", t.elapsed());
2201        let t = Instant::now();
2202        let lite = load_lite(&conn).unwrap().unwrap();
2203        println!("selective load without history: {:?}", t.elapsed());
2204        assert_eq!(
2205            loaded["api_keys"].as_array().unwrap().len(),
2206            lite["api_keys"].as_array().unwrap().len()
2207        );
2208        let _ = base;
2209    }
2210}