Skip to main content

vault_core/
lib.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright the UnENVerse contributors.
3//! vault-core — shared encryption, storage, and tooling for UnENVerse.
4//!
5//! Used by the Tauri desktop app, the HTTP server (`unv-server`), and the CLI
6//! (`unv-cli`).  Has no dependency on Tauri; accepts `&Path` for all I/O.
7
8use argon2::{Algorithm, Argon2, Params, Version};
9pub use rusqlite::Connection as SqlConnection;
10use rusqlite::{Connection, OpenFlags, OptionalExtension};
11use std::fs;
12use std::path::Path;
13pub use zeroize::Zeroize;
14
15pub mod generators;
16pub mod identity;
17pub mod jwks;
18#[cfg(windows)]
19mod winacl;
20pub use generators::{generate_certificate, generate_ssh_keypair};
21
22// Phase 24.3: the one Rust builder for the .ics feed — moved here from
23// unv-cli so `unv-server` can serve it too. See the module doc for why the
24// TypeScript twin was deleted rather than kept as a second answer.
25pub mod calendar;
26// Phase 24.3: the ics_feeds table (token issuance/lookup/revocation). Storage
27// only — rate limiting and RBAC filtering live in unv-server, same split as
28// `users`.
29pub mod ics_feeds;
30// Phase 24.4: the unique-ID registry — a separate SQLCipher file keyed from a
31// secret stored in this vault's vault_meta. Storage and hashing only; rate
32// limiting lives in unv-server.
33pub mod uid_registry;
34
35// Phase 34: nodes. The protocol, the hub registry and the node config (`nodes`),
36// and the transactional file apply a node performs (`nodes_apply`).
37pub mod nodes;
38pub mod nodes_apply;
39
40// Phase 35: the config time machine, and the line diff it shares with the CLI,
41// the server and the app.
42pub mod blast;
43pub mod config_history;
44
45// Phase 38: stack integrations (Prometheus, Grafana, Homepage) as descriptors in
46// data/stack-adapters.json, interpreted here and in src/ts/stack.ts.
47pub mod stack;
48pub mod textdiff;
49// Phase 24.5: the secret-type registry — one JSON descriptor file, read here
50// and imported as plain JSON by the TypeScript side.
51pub mod login;
52pub mod recipe;
53pub mod secret_types;
54pub mod sites;
55// Phase 24.5: FIDO CXF import/export.
56pub mod cxf;
57// Phase 24.1: bundle-local and sibling-value template resolution.
58pub mod bundle_import;
59pub mod bundle_scope;
60pub mod catalogue;
61pub mod certinfo;
62pub mod config_check;
63pub mod forget;
64pub mod lifecycle;
65pub mod migrate_schema;
66pub mod migration;
67pub mod oauth;
68pub mod ops;
69pub mod pgp;
70pub mod php_config;
71pub mod platform;
72pub mod plugin;
73pub mod recovery;
74pub mod rekey;
75pub mod rotation;
76pub mod session_import;
77pub mod ssh_agent;
78pub mod storage;
79pub mod templates;
80pub mod toml_import;
81pub mod type_emit;
82pub mod update;
83
84pub mod permex;
85pub mod pool;
86
87// No outer `///` here either — same reason as `totp` and `totp_import` below:
88// this module's own `//!` block would merge with one and break intra-doc links.
89pub mod composite;
90
91// Both modules carry their own `//!` docs. Adding an outer `///` here as well
92// makes rustdoc merge the two and resolve the *combined* text in this file's
93// scope, so every intra-doc link written inside the module — `[`Source::Os`]`,
94// `[`TlsPolicy::Pin`]` — fails with "no item named … in scope" and
95// `-D warnings` turns that into a failed docs build.
96pub mod entropy;
97
98#[cfg(feature = "tls")]
99pub mod tls;
100
101#[cfg(feature = "telemetry")]
102pub mod telemetry;
103pub use permex::{
104    eval as eval_perm_expr, parse as parse_perm_expr, EntryView, Expr as PermExpr,
105    Field as PermField,
106};
107
108pub mod users;
109
110// `totp` carries its own `//!` docs. No outer `///` here, for the same reason
111// as `entropy` above: rustdoc merges the two and resolves the combined text in
112// *this* file's scope, so `[`verify`]` written inside the module fails with
113// "no item named `verify` in module `vault_core`" and `-D warnings` turns that
114// into a failed docs build.
115pub mod totp;
116
117// Reading and writing the export files other authenticator apps produce.
118// Documented inside the module: an outer `///` here would merge with its own
119// `//!` block and resolve every intra-doc link in *this* file's scope, which is
120// how `entropy` and `totp` have each broken the docs build before.
121pub mod totp_import;
122pub use users::{
123    assign_user_class, authority_tier, class_authority_tier, class_member_count, create_user,
124    create_user_class, create_user_token, delete_user, delete_user_class,
125    effective_permission_expr, ensure_owner_user, ensure_peer_account, filter_vault_for_user,
126    get_class_permissions, get_permission_expr, get_user_capabilities, get_user_permissions,
127    glob_matches, init_users_schema, list_user_classes, list_user_tokens, list_users,
128    merge_user_vault_write, rename_user, revoke_user_token, seed_default_admin,
129    set_class_permissions, set_permission_expr, set_user_password, set_user_permissions,
130    token_user_id, update_user_class, user_authority_tier, verify_user_password, verify_user_token,
131    AdminSeed, ClassPermission, PermissionRecord, TokenRecord, UserClass, UserRecord,
132};
133
134// ── Constants ──────────────────────────────────────────────────────────────────
135
136pub const SALT_LEN: usize = 16;
137pub const KEY_LEN: usize = 32;
138
139const A2_M_COST: u32 = 65_536;
140const A2_T_COST: u32 = 3;
141const A2_P_COST: u32 = 1;
142
143/// In-memory AES-256 vault key.
144pub type VaultKey = [u8; KEY_LEN];
145
146// ── KDF ────────────────────────────────────────────────────────────────────────
147
148/// Derives a 32-byte AES-256 key from `password` and `salt` using Argon2id
149/// (m=65536 KiB, t=3, p=1 — OWASP 2023 recommendation).
150pub fn derive_key(password: &str, salt: &[u8]) -> Result<VaultKey, String> {
151    let params =
152        Params::new(A2_M_COST, A2_T_COST, A2_P_COST, Some(KEY_LEN)).map_err(|e| e.to_string())?;
153    let argon2 = Argon2::new(Algorithm::Argon2id, Version::V0x13, params);
154    let mut key = [0u8; KEY_LEN];
155    argon2
156        .hash_password_into(password.as_bytes(), salt, &mut key)
157        .map_err(|e| e.to_string())?;
158    Ok(key)
159}
160
161/// Writes `bytes` to `path` so that no other user can read them at any moment: on Unix the file is
162/// created with mode 0600 (not written world-readable and tightened afterwards), and on every
163/// platform `restrict_to_owner` then settles an existing file's mode or access list.
164pub fn write_private(path: &Path, bytes: &[u8]) -> Result<(), String> {
165    use std::io::Write;
166    let mut opts = fs::OpenOptions::new();
167    opts.write(true).create(true).truncate(true);
168    #[cfg(unix)]
169    {
170        use std::os::unix::fs::OpenOptionsExt;
171        opts.mode(0o600);
172    }
173    opts.open(path)
174        .and_then(|mut f| f.write_all(bytes))
175        .map_err(|e| e.to_string())?;
176    restrict_to_owner(path)
177}
178
179/// Restrict a file to its owner. Unix sets mode 0600; Windows replaces the access list with a
180/// protected one that allows only the current user (`winacl`).
181pub fn restrict_to_owner(path: &Path) -> Result<(), String> {
182    #[cfg(unix)]
183    {
184        use std::os::unix::fs::PermissionsExt;
185        fs::set_permissions(path, fs::Permissions::from_mode(0o600)).map_err(|e| e.to_string())?;
186    }
187    #[cfg(windows)]
188    {
189        // Every open of the database comes through here for the file and its two sidecars; the
190        // access list only needs setting once per path per process, and setting it on every open
191        // took the security lock often enough to stall concurrent opens.
192        use std::collections::HashSet;
193        use std::sync::{Mutex, OnceLock};
194        static DONE: OnceLock<Mutex<HashSet<std::path::PathBuf>>> = OnceLock::new();
195        let done = DONE.get_or_init(|| Mutex::new(HashSet::new()));
196        if !done.lock().is_ok_and(|d| d.contains(path)) {
197            winacl::restrict_to_owner(path, false)?;
198            if let Ok(mut d) = done.lock() {
199                d.insert(path.to_path_buf());
200            }
201        }
202    }
203    #[cfg(not(any(unix, windows)))]
204    {
205        let _ = path;
206    }
207    Ok(())
208}
209
210/// Create a directory only its owner can enter, failing if the path already exists.
211///
212/// `create_dir_all` followed by `chmod` leaves a window in which the directory is
213/// world-readable, and accepts a path an attacker pre-created in a shared temp directory
214/// (including a symlink to somewhere they control). This creates the final component with
215/// mode 0700 in one step and refuses an existing one. The parent must already exist.
216/// On Windows the directory gets a protected owner-only access list that its contents inherit.
217pub fn create_private_dir(path: &Path) -> Result<(), String> {
218    #[cfg(unix)]
219    {
220        use std::os::unix::fs::DirBuilderExt;
221        fs::DirBuilder::new()
222            .mode(0o700)
223            .create(path)
224            .map_err(|e| e.to_string())
225    }
226    #[cfg(not(unix))]
227    {
228        fs::create_dir(path).map_err(|e| e.to_string())?;
229        #[cfg(windows)]
230        winacl::restrict_to_owner(path, true)?;
231        Ok(())
232    }
233}
234
235/// On Windows, makes a vault folder this program just created owner-only, so the files created in
236/// it (the database, the salt, the WAL sidecars) inherit that. A folder that already existed is left
237/// alone: it may be somewhere the user keeps other files. Elsewhere there is nothing to do: the
238/// files carry their own mode.
239#[cfg(windows)]
240fn secure_new_vault_dir(path: &Path, existed: bool) -> Result<(), String> {
241    if existed {
242        return Ok(());
243    }
244    winacl::restrict_to_owner(path, true)
245}
246
247/// Refuse to derive a key when a database exists but its salt does not.
248///
249/// [`read_or_create_salt`] generates a salt when the file is absent, which is
250/// right for a first run and catastrophic for an existing vault: the new salt
251/// derives a different key, every unlock reports **"Wrong master password"**,
252/// and the user spends the afternoon convinced they have forgotten it. The
253/// evidence that anything else happened is gone by then, because the missing
254/// file has been silently replaced.
255///
256/// Called before key derivation by every path that opens an existing vault.
257pub fn check_salt_pairing(db_path: &Path, salt_path: &Path) -> Result<(), String> {
258    let db_exists = fs::metadata(db_path).map(|m| m.len() > 0).unwrap_or(false);
259    if db_exists && !salt_path.exists() {
260        return Err(format!(
261            "{} exists but {} is missing.\n\
262             The salt is 16 random bytes written once and stored nowhere else — without \n\
263             it this database cannot be opened by anyone, and nothing can recompute it.\n\
264             Restore both from an archive (`unv backup restore-archive`), or restore the \n\
265             vault contents from a .vaultbak (`unv backup import`), which does not need \n\
266             the original salt.",
267            db_path.display(),
268            salt_path.display()
269        ));
270    }
271    Ok(())
272}
273
274/// Reads salt from `salt_path`; generates and writes a fresh 16-byte salt if absent.
275pub fn read_or_create_salt(salt_path: &Path) -> Result<[u8; SALT_LEN], String> {
276    if salt_path.exists() {
277        let raw = fs::read(salt_path).map_err(|e| e.to_string())?;
278        raw.try_into()
279            .map_err(|_| "vault.salt is corrupt (wrong length)".to_string())
280    } else {
281        let s: [u8; SALT_LEN] = rand::random();
282        if let Some(parent) = salt_path.parent() {
283            #[cfg(windows)]
284            let existed = parent.exists();
285            fs::create_dir_all(parent).map_err(|e| e.to_string())?;
286            #[cfg(windows)]
287            secure_new_vault_dir(parent, existed)?;
288        }
289        fs::write(salt_path, s).map_err(|e| e.to_string())?;
290        // The salt is half of what opens the vault. It was written with whatever
291        // the umask gave it — 0644 on a default Linux install, which `unv
292        // doctor` is what finally noticed.
293        restrict_to_owner(salt_path)?;
294        Ok(s)
295    }
296}
297
298// ── Database ───────────────────────────────────────────────────────────────────
299
300/// Upgrades a SQLCipher 3 vault to the current format in place, keeping the
301/// original as `<db>.sqlcipher3.bak`.
302fn migrate_sqlcipher3(db_path: &Path, key: &VaultKey) -> bool {
303    // `cipher_migrate` needs CREATE because it attaches a temporary database.
304    let Ok(conn) = Connection::open_with_flags(
305        db_path,
306        OpenFlags::SQLITE_OPEN_READ_WRITE | OpenFlags::SQLITE_OPEN_CREATE,
307    ) else {
308        return false;
309    };
310    if conn
311        .execute_batch(&format!("PRAGMA key = \"x'{}'\";", hex::encode(key)))
312        .is_err()
313    {
314        return false;
315    }
316    // The migration rewrites the file in place; keep the original beside it. A
317    // wrong password also lands here, so the copy goes again unless it worked.
318    let mut bak = db_path.as_os_str().to_owned();
319    bak.push(".sqlcipher3.bak");
320    let bak = std::path::PathBuf::from(bak);
321    // Never replace a backup that is already there: a later wrong password
322    // would otherwise overwrite and then delete the real one.
323    if bak.exists() || fs::copy(db_path, &bak).is_err() {
324        return false;
325    }
326    let _ = restrict_to_owner(&bak);
327    let ok = conn
328        .query_row("PRAGMA cipher_migrate;", [], |r| r.get::<_, String>(0))
329        .is_ok_and(|rc| rc == "0");
330    if !ok {
331        let _ = fs::remove_file(&bak);
332    }
333    ok
334}
335
336/// Opens (or creates) the SQLCipher database at `db_path` using the 32-byte `key`.
337///
338/// Executes a verification query; returns `Err("Wrong master password")` on
339/// decryption failure so callers can distinguish auth errors from I/O errors.
340pub fn open_db(db_path: &Path, key: &VaultKey) -> Result<Connection, String> {
341    if let Some(p) = db_path.parent() {
342        #[cfg(windows)]
343        let existed = p.exists();
344        fs::create_dir_all(p).map_err(|e| e.to_string())?;
345        #[cfg(windows)]
346        secure_new_vault_dir(p, existed)?;
347    }
348    let conn = Connection::open_with_flags(
349        db_path,
350        OpenFlags::SQLITE_OPEN_READ_WRITE | OpenFlags::SQLITE_OPEN_CREATE,
351    )
352    .map_err(|e| e.to_string())?;
353    conn.execute_batch(&format!("PRAGMA key = \"x'{}'\";", hex::encode(key)))
354        .map_err(|e| e.to_string())?;
355    if conn
356        .execute_batch("SELECT count(*) FROM sqlite_master;")
357        .is_err()
358    {
359        // A vault written by SQLCipher 3 (Debian's libsqlcipher0 in the old
360        // server image) fails the HMAC check under SQLCipher 4 defaults, which
361        // reads exactly like a wrong password. `cipher_migrate` only succeeds with the
362        // right key, so a real wrong password leaves the file as it was.
363        drop(conn);
364        if !migrate_sqlcipher3(db_path, key) {
365            return Err("Wrong master password".to_string());
366        }
367        return open_db(db_path, key);
368    }
369    // WAL mode: allows concurrent reads + one writer, avoids full locks (item 17)
370    conn.execute_batch("PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL;")
371        .map_err(|e| e.to_string())?;
372    // Both explicit rather than inherited: rusqlite's implicit 5 s busy timeout is
373    // a library default that could change under an upgrade, and without a size
374    // limit a long-lived reader lets the WAL grow without bound.
375    conn.busy_timeout(std::time::Duration::from_secs(5))
376        .map_err(|e| e.to_string())?;
377    conn.execute_batch("PRAGMA journal_size_limit=67108864;")
378        .map_err(|e| e.to_string())?;
379    // SQLCipher creates the file with the process umask — 0644 on a default
380    // Linux install. The contents are encrypted, so this is not a disclosure of
381    // secrets; it is a disclosure of the ciphertext to anyone with a login on
382    // the box, which is an offline-attack head start nobody asked to give.
383    // WAL mode means two sidecars carry the same data.
384    restrict_to_owner(db_path)?;
385    for suffix in ["-wal", "-shm"] {
386        let mut side = db_path.as_os_str().to_owned();
387        side.push(suffix);
388        let side = std::path::PathBuf::from(side);
389        if side.exists() {
390            restrict_to_owner(&side)?;
391        }
392    }
393    Ok(conn)
394}
395
396/// Brings the encrypted database to the current additive schema.
397///
398/// All schema changes now run through numbered, recorded migrations. Keeping
399/// this compatibility entry point prevents older callers from bypassing them.
400pub fn init_schema(conn: &Connection) -> Result<(), String> {
401    migrate_schema::migrate_schema(conn)?;
402    // A restore leaves a marker beside the database: this open is the first of a new instance.
403    if let Some(path) = conn.path().filter(|p| !p.is_empty()) {
404        identity::on_open(conn, Path::new(path))?;
405    }
406    Ok(())
407}
408
409// ── Entry identity ────────────────────────────────────────────────────────────
410
411/// Canonical identity key for a vault entry.
412///
413/// Prefers the stable `id` (a UUID the frontend assigns on creation and never
414/// mutates). Falls back to `provider|account_name|key_id` for entries written
415/// before `id` existed.
416///
417/// Every consumer must use this one function. `save_vault` and
418/// [`merge_user_vault_write`] previously disagreed — the former ignored
419/// `key_id`, so two entries sharing provider+account collapsed into one key and
420/// `version_history` / audit rows landed on the wrong entry, while the RBAC
421/// merge treated them as distinct.
422pub fn entry_ck(entry: &serde_json::Value) -> String {
423    if let Some(id) = entry.get("id").and_then(|v| v.as_str()) {
424        if !id.is_empty() {
425            return format!("id\u{1}{id}");
426        }
427    }
428    let field = |k: &str| entry.get(k).and_then(|v| v.as_str()).unwrap_or("");
429    format!(
430        "legacy\u{1}{}\u{1}{}\u{1}{}",
431        field("provider"),
432        field("account_name"),
433        field("key_id"),
434    )
435}
436
437// ── Schema versioning ─────────────────────────────────────────────────────────
438
439/// The vault-document schema this build writes.
440///
441/// Three binaries — the desktop app, `unv-server` and `unv` — read and write
442/// one untyped JSON blob, and until this existed nothing recorded which shape it
443/// was in. The problem had already been hit once and solved by convention: the
444/// legacy `rate_limit` string is dual-written so a vault edited by a current
445/// build stays readable to an older one. The next field that skips that
446/// convention breaks old readers with no way to detect it and no way to refuse.
447///
448/// Bump this when a change makes a document unreadable to the previous build —
449/// not for an added optional field, which older readers ignore harmlessly.
450///
451/// Version 1 is the document shape as of 0.8.1: the whole vault as one JSON
452/// string in one row. Vaults written before this constant existed carry no
453/// version at all; that is treated as 1, because it is.
454///
455/// **Version 2 (Phase 30) is row-per-entry storage** (see [`storage`]). A v1 vault
456/// is converted on first open, after a `vault.db.v1.bak` copy; a v1 build then
457/// refuses the file with [`SCHEMA_ERR`] instead of reading an empty blob.
458///
459/// **Version 3 (Phase 30.2) gives every chunk of a project a row of its own.** A v2
460/// vault loads unchanged (a project row with inline chunks is understood) and is
461/// rewritten into chunk rows by its first save; a v2 build then refuses the file,
462/// because it would read a project with no chunks and delete the chunk rows.
463pub const VAULT_SCHEMA_VERSION: u32 = 3;
464
465/// Marker prefix on the error returned when the stored vault was written by a
466/// newer build than this one. Callers match on it to tell "upgrade me" from a
467/// real failure.
468pub const SCHEMA_ERR: &str = "VAULT_SCHEMA_TOO_NEW";
469
470/// The schema version stamped on the stored vault, or `None` for a vault
471/// written before versioning existed (or an empty database).
472pub fn vault_schema_version(conn: &Connection) -> Result<Option<u32>, String> {
473    let raw: Option<String> = conn
474        .query_row(
475            "SELECT value FROM vault_meta WHERE key = 'schema_version'",
476            [],
477            |r| r.get(0),
478        )
479        .optional()
480        .map_err(|e| e.to_string())?;
481    match raw {
482        None => Ok(None),
483        // An unparseable stamp is not "no stamp": something wrote a value this
484        // build cannot interpret, which is the same situation as a future
485        // version and gets the same refusal.
486        Some(s) => s
487            .trim()
488            .parse::<u32>()
489            .map(Some)
490            .map_err(|_| format!("{SCHEMA_ERR}: unreadable schema_version {s:?}")),
491    }
492}
493
494/// Refuses to touch a vault written by a newer build.
495///
496/// Refuse-with-a-message beats corrupt-on-round-trip: an old binary that reads a
497/// future document, drops the fields it does not know and writes it back has
498/// silently destroyed data, which is this project's worst bug class.
499pub fn check_schema_version(conn: &Connection) -> Result<(), String> {
500    match vault_schema_version(conn)? {
501        Some(v) if v > VAULT_SCHEMA_VERSION => Err(format!(
502            "{SCHEMA_ERR}: this vault was written by a newer version of UnENVerse \
503             (vault schema v{v}, this build understands v{VAULT_SCHEMA_VERSION}). \
504             Upgrade UnENVerse to open it — writing it with this build would drop \
505             the fields it does not understand."
506        )),
507        _ => Ok(()),
508    }
509}
510
511// ── Vault I/O ─────────────────────────────────────────────────────────────────
512
513/// Loads the raw vault JSON from an open connection.
514///
515/// Refuses a vault stamped with a schema this build does not understand, rather
516/// than handing back a document it would silently truncate on the next save.
517pub fn load_vault(conn: &Connection) -> Result<Option<serde_json::Value>, String> {
518    ensure_current_schema(conn)?;
519    storage::load(conn)
520}
521
522/// Appended to the version returned by a save that folded in other writers'
523/// changes (Phase 30). The part before it is the current version token; a writer
524/// that sends the whole thing back as `expect_version` is understood.
525pub const MERGED_SUFFIX: &str = "+merged";
526
527/// Refuse a newer schema and convert a v1 vault, so that a version read *after*
528/// this is a version of the converted vault. A caller that reads the version
529/// before the data (the safe order, see the server's PUT handler) must call this
530/// first, or it pairs a v1 hash with a v2 document and its first save conflicts.
531pub fn ensure_current_schema(conn: &Connection) -> Result<(), String> {
532    check_schema_version(conn)?;
533    // `snapshot_vault` calls us before it opens a read snapshot. Inside that
534    // snapshot, an outer writer/read transaction already owns the boundary and
535    // SQLite correctly refuses a nested BEGIN IMMEDIATE.
536    if conn.is_autocommit() {
537        // `load_vault` is public and a restored archive can reach it directly,
538        // without going through Access::local_key. Apply recorded additive
539        // migrations before lifecycle seeding queries their new tables.
540        migrate_schema::migrate_schema(conn)?;
541        storage::migrate_if_needed(conn, &iso_now())?;
542    }
543    if let Some(document) = storage::load(conn)? {
544        lifecycle::seed_existing(conn, &document)?;
545    }
546    Ok(())
547}
548
549/// The vault document without any entry's `version_history`: what a selective
550/// read needs, without the 50-revision secret trail per entry that a full read
551/// carries (Phase 30).
552pub fn load_vault_lite(conn: &Connection) -> Result<Option<serde_json::Value>, String> {
553    ensure_current_schema(conn)?;
554    storage::load_lite(conn)
555}
556
557/// Marker prefix on the error returned when a compare-and-swap write is refused.
558/// Callers match on this to tell "someone else wrote first" from a real failure.
559pub const CONFLICT_ERR: &str = "VAULT_CONFLICT";
560
561/// Starts the error for an edit to a secret field of an entry whose source owns it (a SOPS, pass
562/// or gopass import that has not been cut over). Callers map it to a conflict, like
563/// [`CONFLICT_ERR`], and show the text, which names the source and what to do.
564pub const SOURCE_OWNED_ERR: &str = "Managed by its source:";
565
566/// Who is writing, and what they believe the vault currently is.
567///
568/// A struct rather than two positional `Option<&str>` arguments: silently
569/// swapping an actor id for a version hash would disable the concurrency check
570/// while still compiling and still passing tests.
571#[derive(Debug, Default, Clone, Copy)]
572pub struct SaveCtx<'a> {
573    /// User id responsible for the change, recorded in the audit log.
574    /// `None` for contexts where the owner is implicit.
575    pub actor: Option<&'a str>,
576    /// The version the caller last read. When set, the write is refused unless
577    /// the stored vault is *still* at that version. `None` writes unconditionally
578    /// — only correct when nothing else can be writing.
579    pub expect_version: Option<&'a str>,
580}
581
582/// Current version of the stored vault, or `None` when the vault is empty.
583///
584/// This is the `data_hash` that `save_vault` writes, so it is by construction
585/// the hash of exactly the bytes on disk — no re-serialisation, no assumptions
586/// about map ordering.
587pub fn vault_version(conn: &Connection) -> Result<Option<String>, String> {
588    storage::version(conn)
589}
590
591/// Entry fields whose change is worth a `version_history` snapshot.
592///
593/// The pair is (JSON field, the word the audit row uses). `api_key` is first and
594/// is the one that writes no `field` discriminator into the record — see
595/// `save_vault_with_actor`.
596const HISTORIED_SECRET_FIELDS: [(&str, &str); 3] = [
597    ("api_key", "api_key"),
598    ("api_secret", "api_secret"),
599    ("totp_secret", "totp_secret"),
600];
601
602/// Previous values of an entry's `extra_vars`, keyed by var name.
603///
604/// Phase 23, E8. A named variable is where the real payload of an `env_var`
605/// entry lives, and for an AWS or Twilio credential it is where *all* of it
606/// lives — so before this, the only entries whose secrets were versioned were
607/// the ones that happened to use the primary slot. An `env_var` entry had **no
608/// history at all**, which E8 itself calls the one unacceptable option.
609///
610/// A var marked `public` is skipped: it is a region or a client id by
611/// declaration, and filling a 50-record history with them evicts the values
612/// that cannot be recovered any other way.
613fn historied_extra_vars(entry: &serde_json::Value) -> Vec<(String, String)> {
614    entry
615        .get("extra_vars")
616        .and_then(|v| v.as_array())
617        .map(|arr| {
618            arr.iter()
619                .filter(|xv| !xv.get("public").and_then(|p| p.as_bool()).unwrap_or(false))
620                .filter_map(|xv| {
621                    let k = xv.get("key").and_then(|v| v.as_str())?;
622                    let v = xv.get("value").and_then(|v| v.as_str())?;
623                    if k.is_empty() {
624                        return None;
625                    }
626                    Some((k.to_string(), v.to_string()))
627                })
628                .collect()
629        })
630        .unwrap_or_default()
631}
632
633/// The stored version and the document, read as one snapshot (`None` for an empty vault).
634///
635/// `GET /api/vault` read the document and then the version as two statements; a save
636/// landing between them paired the document with a newer token.
637pub fn snapshot_vault(
638    conn: &Connection,
639) -> Result<(Option<String>, Option<serde_json::Value>), String> {
640    // Migration has to happen before the read transaction. A snapshot can then
641    // call the row loader directly without attempting a nested transaction.
642    ensure_current_schema(conn)?;
643    storage::in_snapshot(conn, || Ok((vault_version(conn)?, storage::load(conn)?)))
644}
645
646/// The base version and the current document a row patch is applied to.
647///
648/// Both come from one snapshot, and when the caller names no version the one read here is
649/// the base. `PATCH /api/vault` without an `If-Match` used to load the document and then
650/// save it with no expected version at all, which `storage::merge` treats as "the writer's
651/// document is the whole truth": any row another writer committed between the load and the
652/// save was silently reverted, or deleted if it was new. With the version read first, that
653/// writer's rows are merged (or reported as a conflict) like any stale save.
654pub fn begin_row_patch(
655    conn: &Connection,
656    expect: Option<&str>,
657) -> Result<(Option<String>, serde_json::Value), String> {
658    storage::in_snapshot(conn, || {
659        let base = match expect {
660            Some(v) => Some(v.to_string()),
661            None => vault_version(conn)?,
662        };
663        let doc = load_vault(conn)?.unwrap_or_else(
664            || serde_json::json!({ "api_keys": [], "user_categories": [], "projects": [] }),
665        );
666        Ok((base, doc))
667    })
668}
669
670/// Phase 30.1: apply a delta to a stored vault document. Shared by `PATCH
671/// /api/vault` and the desktop's `save_vault_rows` so they cannot differ.
672///
673/// `{ put, delete }` change `api_keys` by `id`; `projects_put`/`projects_delete`
674/// change `projects` by `id`; `categories`, when present, replaces
675/// `user_categories` (a flat list of strings, small). Every put needs a
676/// non-empty string `id`. Unknown keys are ignored.
677pub fn apply_row_patch(
678    mut doc: serde_json::Value,
679    patch: &serde_json::Value,
680) -> Result<serde_json::Value, String> {
681    use serde_json::Value;
682    fn ids(v: Option<&Value>, what: &str) -> Result<Vec<String>, String> {
683        let mut out = Vec::new();
684        for d in v.and_then(Value::as_array).into_iter().flatten() {
685            match d.as_str() {
686                Some(id) if !id.is_empty() => out.push(id.to_string()),
687                _ => return Err(format!("{what} takes a list of ids")),
688            }
689        }
690        Ok(out)
691    }
692    fn puts(v: Option<&Value>, what: &str) -> Result<Vec<(String, Value)>, String> {
693        let mut out = Vec::new();
694        for e in v.and_then(Value::as_array).into_iter().flatten() {
695            match e.get("id").and_then(Value::as_str) {
696                Some(id) if !id.is_empty() => out.push((id.to_string(), e.clone())),
697                _ => return Err(format!("Every {what} needs a string id")),
698            }
699        }
700        Ok(out)
701    }
702    fn apply(
703        doc: &mut Value,
704        key: &str,
705        put: Vec<(String, Value)>,
706        del: Vec<String>,
707    ) -> Result<(), String> {
708        let list = doc
709            .get_mut(key)
710            .and_then(Value::as_array_mut)
711            .ok_or_else(|| format!("stored vault has no {key}"))?;
712        let id_of = |e: &Value| e.get("id").and_then(Value::as_str).map(str::to_string);
713        list.retain(|e| id_of(e).is_none_or(|id| !del.contains(&id)));
714        for (id, entry) in put {
715            match list
716                .iter()
717                .position(|e| id_of(e).as_deref() == Some(id.as_str()))
718            {
719                Some(i) => list[i] = entry,
720                None => list.push(entry),
721            }
722        }
723        Ok(())
724    }
725    let (ep, ed) = (
726        puts(patch.get("put"), "put entry")?,
727        ids(patch.get("delete"), "delete")?,
728    );
729    let (pp, pd) = (
730        puts(patch.get("projects_put"), "put project")?,
731        ids(patch.get("projects_delete"), "projects_delete")?,
732    );
733    let cats = match patch.get("categories") {
734        None | Some(Value::Null) => None,
735        Some(Value::Array(a)) if a.iter().all(Value::is_string) => Some(Value::Array(a.clone())),
736        Some(_) => return Err("categories takes a list of strings".into()),
737    };
738    apply(&mut doc, "api_keys", ep, ed)?;
739    if !pp.is_empty() || !pd.is_empty() {
740        if doc.get("projects").is_none() {
741            doc["projects"] = Value::Array(Vec::new());
742        }
743        apply(&mut doc, "projects", pp, pd)?;
744    }
745    if let Some(c) = cats {
746        doc["user_categories"] = c;
747    }
748    Ok(doc)
749}
750
751/// `COMMIT`, and if it fails, `ROLLBACK`. A failed COMMIT (busy, I/O error, a deferred
752/// constraint) can leave the transaction open; the connection would then refuse every
753/// later `BEGIN` ("cannot start a transaction within a transaction") until it was dropped.
754pub(crate) fn commit(conn: &Connection) -> Result<(), String> {
755    conn.execute_batch("COMMIT").map_err(|e| {
756        if !conn.is_autocommit() {
757            let _ = conn.execute_batch("ROLLBACK");
758        }
759        e.to_string()
760    })
761}
762
763/// Serialises `data` to the vault, updating `version_history` on key changes
764/// and appending to the `vault_audit` hash chain. Returns the new version.
765///
766/// # Concurrency
767///
768/// When `ctx.expect_version` is set this is a **compare-and-swap**: the whole
769/// operation runs inside one `BEGIN IMMEDIATE` transaction, and if another
770/// writer has changed the vault since the caller read it, nothing is written and
771/// [`CONFLICT_ERR`] is returned.
772///
773/// Doing the check here rather than in each caller matters for two reasons.
774/// A caller that reads, compares, then writes has a race between the compare and
775/// the write — which is what the server's `If-Match` handling used to be. And a
776/// caller that simply forgets is silently unprotected, which is how the desktop
777/// could clobber a LAN peer's edit.
778///
779/// The audit appends are inside the same transaction. They used to run before it,
780/// so a rejected or failed write still left audit rows describing changes that
781/// never happened.
782pub fn save_vault(
783    conn: &Connection,
784    data: serde_json::Value,
785    ctx: SaveCtx<'_>,
786) -> Result<String, String> {
787    conn.execute_batch("BEGIN IMMEDIATE")
788        .map_err(|e| e.to_string())?;
789    match save_vault_txn(conn, data, ctx, false) {
790        Ok(hash) => {
791            commit(conn)?;
792            Ok(hash)
793        }
794        Err(e) => {
795            let _ = conn.execute_batch("ROLLBACK");
796            Err(e)
797        }
798    }
799}
800
801/// Saves the document and a migration manifest as one SQLCipher transaction.
802///
803/// The manifest contains source identities and encrypted archive payloads. A
804/// failed vault save therefore cannot leave an import marked applied, and a
805/// failed archive write cannot leave imported entries without their provenance.
806pub fn save_vault_with_migration(
807    conn: &Connection,
808    data: serde_json::Value,
809    ctx: SaveCtx<'_>,
810    migration: &migration::MigrationRecord,
811) -> Result<String, String> {
812    conn.execute_batch("BEGIN IMMEDIATE")
813        .map_err(|e| e.to_string())?;
814    // A migration is the source speaking, so it may rewrite what the source owns.
815    match save_vault_txn(conn, data, ctx, true).and_then(|hash| {
816        migration::record_txn(conn, migration)?;
817        Ok(hash)
818    }) {
819        Ok(hash) => {
820            commit(conn)?;
821            Ok(hash)
822        }
823        Err(e) => {
824            let _ = conn.execute_batch("ROLLBACK");
825            Err(e)
826        }
827    }
828}
829
830/// The fields of an entry that hold a secret, as one comparable string.
831pub fn secret_digest(entry: &serde_json::Value) -> String {
832    let mut parts = Vec::new();
833    for key in [
834        "api_key",
835        "api_secret",
836        "totp_secret",
837        "certificate_data",
838        "cert_key_data",
839        "blob_ref",
840    ] {
841        parts.push(entry.get(key).cloned().unwrap_or(serde_json::Value::Null));
842    }
843    parts.push(
844        entry
845            .get("extra_vars")
846            .cloned()
847            .unwrap_or(serde_json::Value::Null),
848    );
849    serde_json::to_string(&parts).unwrap_or_default()
850}
851
852/// Refuses a change to a secret field of an entry whose source owns it.
853///
854/// An entry imported from a Git store (SOPS, pass, gopass) records `authority.owner = "source"`.
855/// Until the migration is cut over, the source is where the value is changed and the import
856/// refreshes it; an edit here would be overwritten by the next sync, or worse, silently diverge.
857/// Everything that is not a secret (tags, notes, categories, projects) stays editable.
858fn refuse_source_owned_edit(
859    old: &serde_json::Value,
860    new: &serde_json::Value,
861) -> Result<(), String> {
862    let authority = old.get("authority");
863    let owner = authority
864        .and_then(|a| a.get("owner"))
865        .and_then(|o| o.as_str());
866    // Only the Git stores stay authoritative after an import. A password-manager migration (a
867    // Bitwarden, 1Password or KeePass export) is a move: the vault holds the record afterwards,
868    // and an edit that disagrees with the export is reported as a conflict at the next import.
869    let kind = authority
870        .and_then(|a| a.get("source_kind"))
871        .and_then(|k| k.as_str());
872    if owner != Some("source")
873        || !matches!(kind, Some("sops" | "pass" | "gopass"))
874        || secret_digest(old) == secret_digest(new)
875    {
876        return Ok(());
877    }
878    let text = |key: &str| {
879        authority
880            .and_then(|a| a.get(key))
881            .and_then(|v| v.as_str())
882            .unwrap_or("its source")
883            .to_string()
884    };
885    let provider = old
886        .get("provider")
887        .and_then(|p| p.as_str())
888        .unwrap_or("this entry");
889    Err(format!(
890        "{SOURCE_OWNED_ERR} '{provider}' belongs to {} (source {}). Change its secret there and \
891         import again, or take it over with `unv migrate cutover`.",
892        text("source_kind"),
893        text("source_id"),
894    ))
895}
896
897/// Body of [`save_vault`]. Must only be called inside a write transaction.
898///
899/// Phase 30: the document is split into rows, a stale writer is merged with what
900/// others saved since (see [`storage`]), and only rows whose content changed are
901/// written, audited and given history.
902fn save_vault_txn(
903    conn: &Connection,
904    data: serde_json::Value,
905    ctx: SaveCtx<'_>,
906    source_sync: bool,
907) -> Result<String, String> {
908    let actor = ctx.actor;
909    let now_str = iso_now();
910
911    // Refuse before doing any work: a newer document read by this build would
912    // lose every field this build does not know about.
913    check_schema_version(conn)?;
914    // A v1 blob still waiting is converted inside this same transaction.
915    storage::migrate_in_txn(conn, &now_str)?;
916    // Existing entries receive generation one before a new save can compare
917    // values. This is safe inside the save transaction and handles callers that
918    // create a new connection and save without loading first.
919    if let Some(document) = storage::load(conn)? {
920        lifecycle::seed_existing(conn, &document)?;
921    }
922
923    // Compare-and-swap, now per row: inside the transaction, so no writer can slip
924    // between this check and the write below. An absent version means an empty
925    // vault; a caller expecting a specific version against one is out of date.
926    let snap = storage::snapshot(conn)?;
927    let (mut ents, merged) = storage::merge(conn, &snap, storage::split(data), ctx.expect_version)?;
928    // Rows only one writer touched merge cleanly, so a reference to something the other writer
929    // deleted can survive the merge. Repair it here, where the merged whole is visible.
930    storage::repair_references(&mut ents);
931
932    let stored: std::collections::HashMap<&str, &str> = snap
933        .iter()
934        .filter(|((kind, _), _)| kind == "entry")
935        .map(|((_, key), (rev, _))| (key.as_str(), rev.as_str()))
936        .collect();
937    let mut lifecycle_old = std::collections::BTreeMap::new();
938    for ent in ents.iter().filter(|ent| ent.kind == "entry") {
939        if stored.contains_key(ent.key.as_str()) {
940            if let Some(old) = storage::load_ent(conn, "entry", &ent.key)? {
941                if let Some(id) = old.full().get("id").and_then(|v| v.as_str()) {
942                    lifecycle_old.insert(id.to_string(), old.full());
943                }
944            }
945        }
946    }
947    let kept: std::collections::HashSet<&str> = ents
948        .iter()
949        .filter(|e| e.kind == "entry")
950        .map(|e| e.key.as_str())
951        .collect();
952    for key in stored.keys() {
953        if !kept.contains(*key) {
954            if let Some(old) = storage::load_ent(conn, "entry", key)? {
955                append_audit(conn, "delete", &old.provider(), &now_str, None, actor)?;
956            }
957        }
958    }
959
960    for ent in ents.iter_mut().filter(|e| e.kind == "entry") {
961        match stored.get(ent.key.as_str()) {
962            // Content unchanged: no history, no audit, no write.
963            Some(rev) if *rev == ent.rev => continue,
964            Some(_) => {
965                let Some(old) = storage::load_ent(conn, "entry", &ent.key)? else {
966                    continue;
967                };
968                let old_e = old.full();
969                let mut entry = ent.full();
970                if !source_sync {
971                    refuse_source_owned_edit(&old_e, &entry)?;
972                }
973                let provider = ent.provider();
974                let entry = &mut entry;
975                // The writer's copy of the history may be older than what is stored
976                // (another writer rotated the secret first): start from the union.
977                if let Some(h) = storage::merge_history(old.history.as_ref(), ent.history.as_ref())
978                {
979                    if let Some(obj) = entry.as_object_mut() {
980                        obj.insert("version_history".to_string(), h);
981                    }
982                }
983                // Every secret-carrying value the entry holds, snapshot into one
984                // history. `api_key` writes no `field` discriminator so a vault
985                // stays readable to a build that predates the others — an
986                // absent `field` means `api_key`, and always has.
987                //
988                // `totp_secret` is here because a re-enrolled authenticator seed
989                // is exactly as unrecoverable as a replaced API key, and losing
990                // it silently is how a user finds out at the login screen.
991                for (field, label) in HISTORIED_SECRET_FIELDS {
992                    let new_val = entry.get(field).and_then(|v| v.as_str()).unwrap_or("");
993                    let old_val = old_e.get(field).and_then(|v| v.as_str()).unwrap_or("");
994                    if new_val == old_val || old_val.is_empty() {
995                        continue;
996                    }
997                    let mut history: Vec<serde_json::Value> = entry
998                        .get("version_history")
999                        .and_then(|v| v.as_array())
1000                        .cloned()
1001                        .unwrap_or_else(|| {
1002                            old_e
1003                                .get("version_history")
1004                                .and_then(|v| v.as_array())
1005                                .cloned()
1006                                .unwrap_or_default()
1007                        });
1008                    let mut record = serde_json::json!({ "value": old_val, "saved_at": now_str });
1009                    if field != "api_key" {
1010                        record["field"] = serde_json::json!(field);
1011                    }
1012                    history.insert(0, record);
1013                    // The cap is per entry, not per field, so a chatty seed
1014                    // cannot evict an API key's history — which is why they all
1015                    // share one list rather than getting one each.
1016                    history.truncate(50);
1017                    if let Some(obj) = entry.as_object_mut() {
1018                        obj.insert(
1019                            "version_history".to_string(),
1020                            serde_json::Value::Array(history),
1021                        );
1022                    }
1023                    append_audit(
1024                        conn,
1025                        "update",
1026                        &provider,
1027                        &now_str,
1028                        Some(&format!("{label} rotated")),
1029                        actor,
1030                    )?;
1031                }
1032
1033                // The same, for named variables (E8). Matched by **name**, not
1034                // by position: `extra_vars` is an array the form rebuilds on
1035                // every save, so an index captured across an edit points at
1036                // whatever took its place — invariant 1, in the one place where
1037                // getting it wrong writes the wrong secret into history.
1038                //
1039                // A var that is *removed* leaves its last value in history: the
1040                // user deleting a row is exactly as unable to recover it as the
1041                // user overwriting one, and the row's absence is not evidence
1042                // that they meant to lose it.
1043                let old_vars = historied_extra_vars(&old_e);
1044                if !old_vars.is_empty() {
1045                    let new_vars: std::collections::HashMap<String, String> =
1046                        historied_extra_vars(entry).into_iter().collect();
1047                    for (key, old_val) in old_vars {
1048                        if old_val.is_empty() {
1049                            continue;
1050                        }
1051                        if new_vars.get(&key).map(String::as_str) == Some(old_val.as_str()) {
1052                            continue;
1053                        }
1054                        let mut history: Vec<serde_json::Value> = entry
1055                            .get("version_history")
1056                            .and_then(|v| v.as_array())
1057                            .cloned()
1058                            .unwrap_or_default();
1059                        history.insert(
1060                            0,
1061                            serde_json::json!({
1062                                "value": old_val,
1063                                "saved_at": now_str,
1064                                // Namespaced so a restore can tell a var called
1065                                // `api_key` from the field of that name.
1066                                "field": format!("extra_vars/{key}"),
1067                            }),
1068                        );
1069                        history.truncate(50);
1070                        if let Some(obj) = entry.as_object_mut() {
1071                            obj.insert(
1072                                "version_history".to_string(),
1073                                serde_json::Value::Array(history),
1074                            );
1075                        }
1076                        append_audit(
1077                            conn,
1078                            "update",
1079                            &provider,
1080                            &now_str,
1081                            // Marking, restoring or importing a recovery code all change
1082                            // this one variable; "rotated" would misdescribe a code being used.
1083                            Some(&if key == "codes" {
1084                                "recovery codes changed".to_string()
1085                            } else {
1086                                format!("{key} rotated")
1087                            }),
1088                            actor,
1089                        )?;
1090                    }
1091                }
1092                // Split the (possibly extended) history back off the row.
1093                if let Some(h) = entry
1094                    .as_object_mut()
1095                    .and_then(|o| o.remove("version_history"))
1096                {
1097                    ent.history = Some(h);
1098                }
1099            }
1100            None => {
1101                append_audit(conn, "add", &ent.provider(), &now_str, None, actor)?;
1102            }
1103        }
1104    }
1105
1106    let lifecycle_next: Vec<serde_json::Value> = ents
1107        .iter()
1108        .filter(|ent| ent.kind == "entry")
1109        .map(storage::Ent::full)
1110        .collect();
1111    lifecycle::record_save(conn, &lifecycle_old, &lifecycle_next, &now_str)?;
1112
1113    // Data and token move together, so the integrity check never sees a mismatch.
1114    let token = storage::write(conn, &snap, &ents, &now_str)?;
1115    // Stamp the shape alongside the data, in the same transaction. A vault that
1116    // has been written by this build is by definition in this build's schema,
1117    // so there is no separate migration step to forget to run.
1118    conn.execute(
1119        "INSERT OR REPLACE INTO vault_meta (key, value) VALUES ('schema_version', ?1)",
1120        rusqlite::params![VAULT_SCHEMA_VERSION.to_string()],
1121    )
1122    .map_err(|e| e.to_string())?;
1123
1124    // When other writers' changes were folded in, the caller's copy of the vault
1125    // is *behind* what was just stored. Treating the new token as its base would
1126    // let it overwrite those changes on its next save, and keeping its old base
1127    // would make that save conflict with its own previous one. So the token comes
1128    // back marked [`MERGED_SUFFIX`]: a client that holds a document reloads it; a
1129    // one-shot client (the CLI) never looks.
1130    if merged {
1131        Ok(format!("{token}{MERGED_SUFFIX}"))
1132    } else {
1133        Ok(token)
1134    }
1135}
1136
1137/// Verifies the stored vault data against its SHA-256 integrity hash.
1138/// Returns `Ok(true)` if hash matches, `Ok(false)` if tampered or hash absent, `Err` on I/O.
1139pub fn verify_vault_integrity(conn: &Connection) -> Result<bool, String> {
1140    storage::verify(conn)
1141}
1142
1143/// Returns vault entries whose `expires_at` date falls within `within_days` days
1144/// from today (inclusive of today, exclusive of entries already expired).
1145///
1146/// Uses lexicographic YYYY-MM-DD comparison — no parsing feature required.
1147pub fn get_expiring_entries(
1148    conn: &Connection,
1149    within_days: u32,
1150) -> Result<Vec<serde_json::Value>, String> {
1151    let data = load_vault(conn)?.unwrap_or_else(|| serde_json::json!({ "api_keys": [] }));
1152    Ok(expiring_from_value(&data, within_days))
1153}
1154
1155/// Like [`get_expiring_entries`] but first filters the vault to the entries the
1156/// user is permitted to read.  Prevents non-owner sessions from learning about
1157/// the expiry (and full contents) of secrets outside their RBAC scope.
1158pub fn get_expiring_entries_for_user(
1159    conn: &Connection,
1160    within_days: u32,
1161    read: Option<&permex::Expr>,
1162) -> Result<Vec<serde_json::Value>, String> {
1163    let data = load_vault(conn)?.unwrap_or_else(|| serde_json::json!({ "api_keys": [] }));
1164    let filtered = filter_vault_for_user(data, read);
1165    Ok(expiring_from_value(&filtered, within_days))
1166}
1167
1168/// Extracts the `api_keys` whose `expires_at` falls within `within_days` of today.
1169fn expiring_from_value(data: &serde_json::Value, within_days: u32) -> Vec<serde_json::Value> {
1170    let now = time::OffsetDateTime::now_utc();
1171    let cutoff = now + time::Duration::days(within_days as i64);
1172    let today_str = fmt_date(&now);
1173    let cutoff_str = fmt_date(&cutoff);
1174
1175    data.get("api_keys")
1176        .and_then(|k| k.as_array())
1177        .cloned()
1178        .unwrap_or_default()
1179        .into_iter()
1180        .filter(|entry| {
1181            entry
1182                .get("expires_at")
1183                .and_then(|v| v.as_str())
1184                .is_some_and(|s| {
1185                    let d = &s[..s.len().min(10)];
1186                    d >= today_str.as_str() && d <= cutoff_str.as_str()
1187                })
1188        })
1189        .collect()
1190}
1191
1192fn fmt_date(dt: &time::OffsetDateTime) -> String {
1193    format!("{:04}-{:02}-{:02}", dt.year(), dt.month() as u8, dt.day())
1194}
1195
1196// ── Audit log ─────────────────────────────────────────────────────────────────
1197
1198/// A single audit log row, including the hash-chain fields.
1199#[derive(Debug, serde::Serialize, serde::Deserialize)]
1200pub struct AuditRow {
1201    pub id: i64,
1202    pub action: String,
1203    pub entry_provider: Option<String>,
1204    pub timestamp: String,
1205    pub details: Option<String>,
1206    pub entry_hash: Option<String>,
1207    pub prev_hash: Option<String>,
1208    /// User id that performed the action. `None` for rows written before actor
1209    /// tracking, and for local desktop edits where the owner is implicit.
1210    pub actor: Option<String>,
1211}
1212
1213/// Appends an audit entry and computes `entry_hash = SHA256(action|provider|ts|prev_hash)`.
1214fn append_audit(
1215    conn: &Connection,
1216    action: &str,
1217    provider: &str,
1218    timestamp: &str,
1219    details: Option<&str>,
1220    actor: Option<&str>,
1221) -> Result<(), String> {
1222    // Reading the previous hash and inserting the next row are two statements. Run
1223    // as two autocommit statements, two writers (a node event beside a vault save, two
1224    // server threads) both read the same `prev` and write two rows that claim it: the
1225    // chain forks and can never verify again, because rows cannot be repaired. Inside
1226    // `save_vault` the caller's `BEGIN IMMEDIATE` already makes them one unit; anywhere
1227    // else this opens its own.
1228    if conn.is_autocommit() {
1229        conn.execute_batch("BEGIN IMMEDIATE")
1230            .map_err(|e| e.to_string())?;
1231        return match append_audit_in_txn(conn, action, provider, timestamp, details, actor) {
1232            Ok(()) => commit(conn),
1233            Err(e) => {
1234                let _ = conn.execute_batch("ROLLBACK");
1235                Err(e)
1236            }
1237        };
1238    }
1239    append_audit_in_txn(conn, action, provider, timestamp, details, actor)
1240}
1241
1242fn append_audit_in_txn(
1243    conn: &Connection,
1244    action: &str,
1245    provider: &str,
1246    timestamp: &str,
1247    details: Option<&str>,
1248    actor: Option<&str>,
1249) -> Result<(), String> {
1250    let prev_hash: Option<String> = conn
1251        .query_row(
1252            "SELECT entry_hash FROM vault_audit ORDER BY id DESC LIMIT 1",
1253            [],
1254            |row| row.get(0),
1255        )
1256        .optional()
1257        .map_err(|e| e.to_string())?
1258        .flatten();
1259
1260    let entry_hash = compute_audit_hash(
1261        action,
1262        provider,
1263        timestamp,
1264        actor,
1265        prev_hash.as_deref().unwrap_or("genesis"),
1266    );
1267
1268    conn.execute(
1269        "INSERT INTO vault_audit \
1270         (action, entry_provider, timestamp, details, entry_hash, prev_hash, actor) \
1271         VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
1272        rusqlite::params![action, provider, timestamp, details, entry_hash, prev_hash, actor],
1273    )
1274    .map_err(|e| e.to_string())?;
1275    Ok(())
1276}
1277
1278/// Records a hash-chained audit event with the current timestamp.
1279pub fn record_event(
1280    conn: &Connection,
1281    action: &str,
1282    provider: &str,
1283    details: Option<&str>,
1284    actor: Option<&str>,
1285) -> Result<(), String> {
1286    append_audit(conn, action, provider, &iso_now(), details, actor)
1287}
1288
1289/// Like [`record_event`], but does nothing if an identical event (same action, subject and
1290/// details) is already in the chain. For a report that may arrive twice because its
1291/// acknowledgement was lost: the second delivery must not become a second audit row.
1292/// Returns whether a row was written.
1293pub fn record_event_once(
1294    conn: &Connection,
1295    action: &str,
1296    provider: &str,
1297    details: &str,
1298    actor: Option<&str>,
1299) -> Result<bool, String> {
1300    let own_txn = conn.is_autocommit();
1301    if own_txn {
1302        conn.execute_batch("BEGIN IMMEDIATE")
1303            .map_err(|e| e.to_string())?;
1304    }
1305    let run = || -> Result<bool, String> {
1306        let seen: bool = conn
1307            .query_row(
1308                "SELECT EXISTS(SELECT 1 FROM vault_audit \
1309                 WHERE action = ?1 AND entry_provider = ?2 AND details = ?3)",
1310                rusqlite::params![action, provider, details],
1311                |r| r.get(0),
1312            )
1313            .map_err(|e| e.to_string())?;
1314        if seen {
1315            return Ok(false);
1316        }
1317        append_audit_in_txn(conn, action, provider, &iso_now(), Some(details), actor)?;
1318        Ok(true)
1319    };
1320    let r = run();
1321    if own_txn {
1322        match &r {
1323            Ok(_) => commit(conn)?,
1324            Err(_) => {
1325                let _ = conn.execute_batch("ROLLBACK");
1326            }
1327        }
1328    }
1329    r
1330}
1331
1332/// Hash for one audit row, binding it to its predecessor.
1333///
1334/// Two formats coexist:
1335/// - **v1** `action|provider|timestamp|prev` — rows written before actor tracking.
1336/// - **v2** `action|provider|timestamp|actor|prev` — includes the acting user, so
1337///   attribution is covered by the chain and cannot be rewritten undetected.
1338///
1339/// A row with no actor keeps using v1 so existing chains stay verifiable; the
1340/// verifier tries v2 first and falls back to v1.
1341fn compute_audit_hash(
1342    action: &str,
1343    provider: &str,
1344    timestamp: &str,
1345    actor: Option<&str>,
1346    prev_hash: &str,
1347) -> String {
1348    use sha2::{Digest, Sha256};
1349    let mut h = Sha256::new();
1350    match actor {
1351        Some(a) => {
1352            for part in [
1353                action, "|", provider, "|", timestamp, "|", a, "|", prev_hash,
1354            ] {
1355                h.update(part.as_bytes());
1356            }
1357        }
1358        None => {
1359            for part in [action, "|", provider, "|", timestamp, "|", prev_hash] {
1360                h.update(part.as_bytes());
1361            }
1362        }
1363    }
1364    hex::encode(h.finalize())
1365}
1366
1367/// Returns all audit rows ordered newest-first.
1368pub fn load_audit(conn: &Connection) -> Result<Vec<AuditRow>, String> {
1369    let mut stmt = conn
1370        .prepare(
1371            "SELECT id, action, entry_provider, timestamp, details, entry_hash, prev_hash, actor \
1372         FROM vault_audit ORDER BY id DESC",
1373        )
1374        .map_err(|e| e.to_string())?;
1375
1376    let rows: Vec<Result<AuditRow, _>> = stmt
1377        .query_map([], |row| {
1378            Ok(AuditRow {
1379                id: row.get(0)?,
1380                action: row.get(1)?,
1381                entry_provider: row.get(2)?,
1382                timestamp: row.get(3)?,
1383                details: row.get(4)?,
1384                entry_hash: row.get(5)?,
1385                prev_hash: row.get(6)?,
1386                actor: row.get(7)?,
1387            })
1388        })
1389        .map_err(|e| e.to_string())?
1390        .collect();
1391    rows.into_iter()
1392        .map(|r| r.map_err(|e| e.to_string()))
1393        .collect()
1394}
1395
1396/// Verifies the audit hash chain from its genesis anchor forward.
1397pub fn verify_audit(conn: &Connection) -> Result<bool, String> {
1398    let mut rows = load_audit(conn)?;
1399    rows.reverse();
1400    let mut previous: Option<String> = None;
1401    for row in rows {
1402        let expected_prev = previous.as_deref().unwrap_or("genesis");
1403        if row.prev_hash.as_deref() != previous.as_deref() {
1404            return Ok(false);
1405        }
1406        let provider = row.entry_provider.as_deref().unwrap_or("");
1407        let expected = compute_audit_hash(
1408            &row.action,
1409            provider,
1410            &row.timestamp,
1411            row.actor.as_deref(),
1412            expected_prev,
1413        );
1414        if row.entry_hash.as_deref() != Some(expected.as_str()) {
1415            return Ok(false);
1416        }
1417        previous = Some(expected);
1418    }
1419    Ok(true)
1420}
1421
1422// ── Migration helpers ─────────────────────────────────────────────────────────
1423
1424/// Inserts raw JSON from a legacy `vault.json` into the `vault` table.
1425/// Called once on first unlock after a Phase 1 → Phase 2 upgrade.
1426pub fn migrate_legacy_json(conn: &Connection, raw_json: &str) -> Result<(), String> {
1427    let doc: serde_json::Value = serde_json::from_str(raw_json).map_err(|e| e.to_string())?;
1428    save_vault(conn, doc, SaveCtx::default()).map(|_| ())
1429}
1430
1431// ── Helpers ────────────────────────────────────────────────────────────────────
1432
1433/// Returns the current UTC time as an ISO-8601 string (`YYYY-MM-DDTHH:MM:SSZ`).
1434/// A random UUID v4, with the version and variant bits set.
1435///
1436/// Hand-rolled rather than pulled in as a crate for the same reason base32 is:
1437/// it is eleven lines, and `rand` is already here. `users.rs` and the TOTP
1438/// importer both call it, so an entry created by the desktop app's import gets
1439/// an id shaped exactly like one created anywhere else — which matters because
1440/// `entry_ck` falls back to a legacy tuple for entries that have none.
1441pub fn new_uuid() -> String {
1442    use rand::Rng;
1443    let mut b = [0u8; 16];
1444    rand::rng().fill_bytes(&mut b);
1445    b[6] = (b[6] & 0x0f) | 0x40;
1446    b[8] = (b[8] & 0x3f) | 0x80;
1447    format!(
1448        "{}-{}-{}-{}-{}",
1449        hex::encode(&b[0..4]),
1450        hex::encode(&b[4..6]),
1451        hex::encode(&b[6..8]),
1452        hex::encode(&b[8..10]),
1453        hex::encode(&b[10..16]),
1454    )
1455}
1456
1457pub fn iso_now() -> String {
1458    let t = time::OffsetDateTime::now_utc();
1459    format!(
1460        "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}Z",
1461        t.year(),
1462        t.month() as u8,
1463        t.day(),
1464        t.hour(),
1465        t.minute(),
1466        t.second()
1467    )
1468}
1469
1470// ── Tests ──────────────────────────────────────────────────────────────────────
1471
1472#[cfg(test)]
1473mod tests {
1474    #[test]
1475    fn a_row_patch_replaces_by_id_appends_deletes_and_refuses_bad_input() {
1476        use serde_json::json;
1477        let doc = json!({
1478            "api_keys": [{"id":"a","provider":"A"},{"id":"b","provider":"B"}],
1479            "user_categories": ["x"],
1480            "projects": [{"id":"p","name":"P"}]
1481        });
1482        let out = apply_row_patch(
1483            doc.clone(),
1484            &json!({
1485                "put": [{"id":"b","provider":"B2"},{"id":"c","provider":"C"}],
1486                "delete": ["a"],
1487                "projects_put": [{"id":"q","name":"Q"}],
1488                "projects_delete": ["p"],
1489                "categories": ["y","z"]
1490            }),
1491        )
1492        .unwrap();
1493        assert_eq!(
1494            out,
1495            json!({
1496                "api_keys": [{"id":"b","provider":"B2"},{"id":"c","provider":"C"}],
1497                "user_categories": ["y","z"],
1498                "projects": [{"id":"q","name":"Q"}]
1499            })
1500        );
1501        // An empty patch changes nothing.
1502        assert_eq!(apply_row_patch(doc.clone(), &json!({})).unwrap(), doc);
1503        for bad in [
1504            json!({"put": [{"provider":"no id"}]}),
1505            json!({"delete": [1]}),
1506            json!({"projects_put": [{"name":"no id"}]}),
1507            json!({"categories": [1]}),
1508        ] {
1509            assert!(apply_row_patch(doc.clone(), &bad).is_err(), "{bad}");
1510        }
1511    }
1512
1513    use super::*;
1514    use serde_json::json;
1515
1516    /// Unique scratch path per test; SQLCipher needs a real file, not `:memory:`.
1517    fn scratch(tag: &str) -> std::path::PathBuf {
1518        // A counter beside the process id, not the clock: two tests starting within one clock tick
1519        // (macOS has a coarse one) shared a directory and failed with "database is locked".
1520        let nanos = {
1521            use std::sync::atomic::{AtomicU64, Ordering};
1522            static SEQ: AtomicU64 = AtomicU64::new(0);
1523            format!(
1524                "{}-{}",
1525                std::process::id(),
1526                SEQ.fetch_add(1, Ordering::SeqCst)
1527            )
1528        };
1529        let dir = std::env::temp_dir().join(format!("unenverse-test-{tag}-{nanos}"));
1530        fs::create_dir_all(&dir).unwrap();
1531        dir
1532    }
1533
1534    fn open_scratch(tag: &str) -> (Connection, std::path::PathBuf) {
1535        let dir = scratch(tag);
1536        let key = derive_key(&new_uuid(), &new_uuid().as_bytes()[..16]).unwrap();
1537        let conn = open_db(&dir.join("vault.db"), &key).unwrap();
1538        init_schema(&conn).unwrap();
1539        (conn, dir)
1540    }
1541
1542    // ── version_history (Phase 23, E8) ─────────────────────────────────────────
1543
1544    fn history_of(conn: &Connection) -> Vec<serde_json::Value> {
1545        let raw = load_vault(conn).unwrap().unwrap_or(json!({}));
1546        raw["api_keys"][0]["version_history"]
1547            .as_array()
1548            .cloned()
1549            .unwrap_or_default()
1550    }
1551
1552    /// Every secret-carrying value is versioned, not just `api_key`.
1553    ///
1554    /// Before Phase 23 a refresh-token swap, a replaced client secret and every
1555    /// `extra_vars` edit left no history at all — and for an `env_var` entry,
1556    /// whose entire payload lives in named variables, *nothing* was versioned.
1557    /// E8 calls leaving a secret silently unversioned the one unacceptable
1558    /// option.
1559    #[test]
1560    fn every_secret_carrying_value_is_versioned() {
1561        let (conn, _d) = open_scratch("historyfields");
1562        let base = json!({ "api_keys": [{
1563            "id": "e1", "provider": "Aws",
1564            "api_key": "key-v1", "api_secret": "secret-v1",
1565            "extra_vars": [
1566                { "key": "SESSION_TOKEN", "value": "tok-v1" },
1567                { "key": "REGION", "value": "eu-west-1", "public": true },
1568            ],
1569        }]});
1570        save_vault(&conn, base.clone(), SaveCtx::default()).unwrap();
1571        assert!(history_of(&conn).is_empty(), "nothing changed yet");
1572
1573        let mut next = base.clone();
1574        next["api_keys"][0]["api_key"] = json!("key-v2");
1575        next["api_keys"][0]["api_secret"] = json!("secret-v2");
1576        next["api_keys"][0]["extra_vars"][0]["value"] = json!("tok-v2");
1577        next["api_keys"][0]["extra_vars"][1]["value"] = json!("us-east-1");
1578        save_vault(&conn, next.clone(), SaveCtx::default()).unwrap();
1579
1580        let hist = history_of(&conn);
1581        let found: Vec<(String, String)> = hist
1582            .iter()
1583            .map(|h| {
1584                (
1585                    h.get("field")
1586                        .and_then(|v| v.as_str())
1587                        .unwrap_or("api_key")
1588                        .to_string(),
1589                    h["value"].as_str().unwrap_or("").to_string(),
1590                )
1591            })
1592            .collect();
1593
1594        assert!(
1595            found.contains(&("api_key".into(), "key-v1".into())),
1596            "api_key still writes no discriminator — every pre-Phase-22 vault relies on that: {found:?}"
1597        );
1598        assert!(
1599            found.contains(&("api_secret".into(), "secret-v1".into())),
1600            "a replaced client secret is as unrecoverable as a replaced key: {found:?}"
1601        );
1602        assert!(
1603            found.contains(&("extra_vars/SESSION_TOKEN".into(), "tok-v1".into())),
1604            "a named variable is where an env_var entry's whole payload lives: {found:?}"
1605        );
1606        assert!(
1607            !found.iter().any(|(f, _)| f == "extra_vars/REGION"),
1608            "a var marked public is a region by declaration; filling a 50-record \
1609             history with them evicts the values that cannot be recovered: {found:?}"
1610        );
1611    }
1612
1613    /// A deleted variable leaves its last value behind.
1614    ///
1615    /// Deleting a row makes its value exactly as unrecoverable as overwriting
1616    /// one, and the row's absence is not evidence that the user meant to lose it.
1617    #[test]
1618    fn deleting_a_variable_still_versions_it() {
1619        let (conn, _d) = open_scratch("historydelete");
1620        let base = json!({ "api_keys": [{
1621            "id": "e1", "provider": "Aws", "api_key": "k",
1622            "extra_vars": [{ "key": "SESSION_TOKEN", "value": "tok-v1" }],
1623        }]});
1624        save_vault(&conn, base.clone(), SaveCtx::default()).unwrap();
1625
1626        let mut next = base.clone();
1627        next["api_keys"][0]["extra_vars"] = json!([]);
1628        save_vault(&conn, next, SaveCtx::default()).unwrap();
1629
1630        let hist = history_of(&conn);
1631        assert_eq!(hist.len(), 1, "{hist:?}");
1632        assert_eq!(hist[0]["field"], json!("extra_vars/SESSION_TOKEN"));
1633        assert_eq!(hist[0]["value"], json!("tok-v1"));
1634    }
1635
1636    /// Using a recovery code was audited as "codes rotated", which reads as a new set of
1637    /// codes. The row names the entry and the actor and now says the codes changed.
1638    #[test]
1639    fn using_a_recovery_code_is_audited_as_a_change() {
1640        let (conn, _d) = open_scratch("auditcodes");
1641        let base = json!({ "api_keys": [{
1642            "id": "e1", "provider": "Mail", "api_key": "k",
1643            "extra_vars": [{ "key": "codes", "value": "aaaa-1111\nbbbb-2222" }],
1644        }]});
1645        save_vault(&conn, base.clone(), SaveCtx::default()).unwrap();
1646        let mut next = base.clone();
1647        next["api_keys"][0]["extra_vars"][0]["value"] = json!("aaaa-1111 #used\nbbbb-2222");
1648        save_vault(
1649            &conn,
1650            next,
1651            SaveCtx {
1652                actor: Some("user-9"),
1653                ..Default::default()
1654            },
1655        )
1656        .unwrap();
1657        let rows = load_audit(&conn).unwrap();
1658        let row = rows
1659            .iter()
1660            .find(|r| r.action == "update" && r.entry_provider.as_deref() == Some("Mail"))
1661            .expect("an update row");
1662        assert_eq!(row.details.as_deref(), Some("recovery codes changed"));
1663        assert_eq!(row.actor.as_deref(), Some("user-9"));
1664    }
1665
1666    /// Variables are matched by **name**, never by position.
1667    ///
1668    /// `extra_vars` is an array the form rebuilds on every save, so an index
1669    /// captured across an edit points at whatever took its place — invariant 1,
1670    /// in the one place where getting it wrong writes the wrong secret into
1671    /// history.
1672    #[test]
1673    fn variables_are_matched_by_name_not_position() {
1674        let (conn, _d) = open_scratch("historyreorder");
1675        let base = json!({ "api_keys": [{
1676            "id": "e1", "provider": "Aws", "api_key": "k",
1677            "extra_vars": [
1678                { "key": "A", "value": "a1" },
1679                { "key": "B", "value": "b1" },
1680            ],
1681        }]});
1682        save_vault(&conn, base, SaveCtx::default()).unwrap();
1683
1684        // Reordered, and only B changed.
1685        let next = json!({ "api_keys": [{
1686            "id": "e1", "provider": "Aws", "api_key": "k",
1687            "extra_vars": [
1688                { "key": "B", "value": "b2" },
1689                { "key": "A", "value": "a1" },
1690            ],
1691        }]});
1692        save_vault(&conn, next, SaveCtx::default()).unwrap();
1693
1694        let hist = history_of(&conn);
1695        assert_eq!(hist.len(), 1, "only B changed: {hist:?}");
1696        assert_eq!(hist[0]["field"], json!("extra_vars/B"));
1697        assert_eq!(hist[0]["value"], json!("b1"));
1698    }
1699
1700    // ── Schema version ─────────────────────────────────────────────────────────
1701
1702    #[test]
1703    fn saving_stamps_the_schema_version() {
1704        let (conn, _d) = open_scratch("schemastamp");
1705        assert_eq!(
1706            vault_schema_version(&conn).unwrap(),
1707            None,
1708            "a fresh database carries no stamp until something is written"
1709        );
1710        save_vault(
1711            &conn,
1712            serde_json::json!({ "api_keys": [] }),
1713            SaveCtx::default(),
1714        )
1715        .unwrap();
1716        assert_eq!(
1717            vault_schema_version(&conn).unwrap(),
1718            Some(VAULT_SCHEMA_VERSION)
1719        );
1720    }
1721
1722    #[test]
1723    fn an_unstamped_vault_still_opens() {
1724        // Every vault written before this constant existed has no stamp. Treating
1725        // "absent" as a failure would refuse to open every vault in the field.
1726        let (conn, _d) = open_scratch("schemalegacy");
1727        save_vault(
1728            &conn,
1729            serde_json::json!({ "api_keys": [] }),
1730            SaveCtx::default(),
1731        )
1732        .unwrap();
1733        conn.execute("DELETE FROM vault_meta WHERE key = 'schema_version'", [])
1734            .unwrap();
1735        assert!(load_vault(&conn).unwrap().is_some());
1736    }
1737
1738    #[test]
1739    fn a_future_schema_is_refused_for_both_read_and_write() {
1740        // Refuse-with-a-message beats corrupt-on-round-trip. An old binary that
1741        // reads a newer document, drops the fields it does not know and saves it
1742        // back has silently destroyed data — the exact failure mode this project
1743        // hunts everywhere else.
1744        let (conn, _d) = open_scratch("schemafuture");
1745        save_vault(
1746            &conn,
1747            serde_json::json!({ "api_keys": [], "projects": [] }),
1748            SaveCtx::default(),
1749        )
1750        .unwrap();
1751        conn.execute(
1752            "INSERT OR REPLACE INTO vault_meta (key, value) VALUES ('schema_version', ?1)",
1753            rusqlite::params![(VAULT_SCHEMA_VERSION + 1).to_string()],
1754        )
1755        .unwrap();
1756
1757        let read = load_vault(&conn).unwrap_err();
1758        assert!(read.starts_with(SCHEMA_ERR), "load said: {read}");
1759        let write = save_vault(
1760            &conn,
1761            serde_json::json!({ "api_keys": [] }),
1762            SaveCtx::default(),
1763        )
1764        .unwrap_err();
1765        assert!(write.starts_with(SCHEMA_ERR), "save said: {write}");
1766
1767        // And the refusal must not have been a partial write.
1768        conn.execute(
1769            "INSERT OR REPLACE INTO vault_meta (key, value) VALUES ('schema_version', '1')",
1770            [],
1771        )
1772        .unwrap();
1773        let v = load_vault(&conn).unwrap().unwrap();
1774        assert!(
1775            v.get("projects").is_some(),
1776            "the refused save wrote nothing"
1777        );
1778    }
1779
1780    #[test]
1781    fn an_unparseable_stamp_is_treated_as_unknown_not_as_absent() {
1782        let (conn, _d) = open_scratch("schemajunk");
1783        conn.execute(
1784            "INSERT OR REPLACE INTO vault_meta (key, value) VALUES ('schema_version', 'tomorrow')",
1785            [],
1786        )
1787        .unwrap();
1788        let e = load_vault(&conn).unwrap_err();
1789        assert!(e.starts_with(SCHEMA_ERR), "said: {e}");
1790    }
1791
1792    // ── KDF ────────────────────────────────────────────────────────────────────
1793
1794    #[test]
1795    fn derive_key_is_deterministic_and_salt_sensitive() {
1796        let a = derive_key("hunter2", b"0123456789abcdef").unwrap();
1797        let b = derive_key("hunter2", b"0123456789abcdef").unwrap();
1798        let c = derive_key("hunter2", b"fedcba9876543210").unwrap();
1799        let d = derive_key("hunter3", b"0123456789abcdef").unwrap();
1800        assert_eq!(a, b, "same password + salt must derive the same key");
1801        assert_ne!(a, c, "different salt must derive a different key");
1802        assert_ne!(a, d, "different password must derive a different key");
1803    }
1804
1805    #[test]
1806    fn salt_is_persisted_and_reused() {
1807        let dir = scratch("salt");
1808        let path = dir.join("vault.salt");
1809        let first = read_or_create_salt(&path).unwrap();
1810        let second = read_or_create_salt(&path).unwrap();
1811        assert_eq!(first, second, "salt must be stable across reads");
1812        assert_eq!(first.len(), SALT_LEN);
1813    }
1814
1815    // ── Entry identity ─────────────────────────────────────────────────────────
1816
1817    #[test]
1818    fn entry_ck_prefers_stable_id() {
1819        let a = json!({ "id": "abc", "provider": "GitHub", "account_name": "x" });
1820        let b = json!({ "id": "abc", "provider": "Renamed", "account_name": "y" });
1821        assert_eq!(entry_ck(&a), entry_ck(&b), "id must dominate other fields");
1822    }
1823
1824    #[test]
1825    fn entry_ck_legacy_distinguishes_key_id() {
1826        // The historic save_vault key ignored key_id and collapsed these two into
1827        // one entry, misattributing version_history between them.
1828        let a = json!({ "provider": "AWS", "account_name": "prod", "key_id": "one" });
1829        let b = json!({ "provider": "AWS", "account_name": "prod", "key_id": "two" });
1830        assert_ne!(entry_ck(&a), entry_ck(&b));
1831    }
1832
1833    #[test]
1834    fn entry_ck_ignores_empty_id() {
1835        let with_empty = json!({ "id": "", "provider": "P" });
1836        let without = json!({ "provider": "P" });
1837        assert_eq!(entry_ck(&with_empty), entry_ck(&without));
1838    }
1839
1840    // ── Vault I/O ──────────────────────────────────────────────────────────────
1841
1842    #[test]
1843    fn save_then_load_roundtrips() {
1844        let (conn, _dir) = open_scratch("roundtrip");
1845        let data = json!({
1846            "api_keys": [{ "id": "1", "provider": "GitHub", "api_key": "ghp_aaa" }],
1847            "user_categories": ["dev"],
1848            "projects": [{ "id": "Universal", "name": "Universal" }],
1849        });
1850        save_vault(&conn, data.clone(), SaveCtx::default()).unwrap();
1851        let loaded = load_vault(&conn).unwrap().expect("vault should exist");
1852        assert_eq!(loaded["api_keys"][0]["provider"], "GitHub");
1853        assert_eq!(loaded["user_categories"][0], "dev");
1854    }
1855
1856    #[test]
1857    fn load_returns_none_for_fresh_vault() {
1858        let (conn, _dir) = open_scratch("fresh");
1859        assert!(load_vault(&conn).unwrap().is_none());
1860    }
1861
1862    #[test]
1863    fn changing_a_key_records_previous_value_in_history() {
1864        let (conn, _dir) = open_scratch("history");
1865        save_vault(
1866            &conn,
1867            json!({
1868                "api_keys": [{ "id": "1", "provider": "GitHub", "api_key": "old_value" }]
1869            }),
1870            SaveCtx::default(),
1871        )
1872        .unwrap();
1873        save_vault(
1874            &conn,
1875            json!({
1876                "api_keys": [{ "id": "1", "provider": "GitHub", "api_key": "new_value" }]
1877            }),
1878            SaveCtx::default(),
1879        )
1880        .unwrap();
1881
1882        let loaded = load_vault(&conn).unwrap().unwrap();
1883        let history = loaded["api_keys"][0]["version_history"].as_array().unwrap();
1884        assert_eq!(
1885            history.len(),
1886            1,
1887            "one rotation should append one history entry"
1888        );
1889        assert_eq!(history[0]["value"], "old_value");
1890    }
1891
1892    #[test]
1893    fn a_replaced_totp_seed_is_versioned_and_labelled() {
1894        // A re-enrolled authenticator seed is as unrecoverable as a replaced API
1895        // key. Before Phase 22 only `api_key` was snapshot, so swapping a seed
1896        // left no record at all — and the user would find out at a login screen.
1897        let (conn, _dir) = open_scratch("totp-history");
1898        save_vault(
1899            &conn,
1900            json!({
1901                "api_keys": [{
1902                    "id": "1", "provider": "GitHub",
1903                    "api_key": "k1", "totp_secret": "JBSWY3DPEHPK3PXP",
1904                }]
1905            }),
1906            SaveCtx::default(),
1907        )
1908        .unwrap();
1909        save_vault(
1910            &conn,
1911            json!({
1912                "api_keys": [{
1913                    "id": "1", "provider": "GitHub",
1914                    "api_key": "k1", "totp_secret": "MZXW6YTBOI======",
1915                }]
1916            }),
1917            SaveCtx::default(),
1918        )
1919        .unwrap();
1920
1921        let loaded = load_vault(&conn).unwrap().unwrap();
1922        let history = loaded["api_keys"][0]["version_history"].as_array().unwrap();
1923        assert_eq!(history.len(), 1, "the seed change is one revision");
1924        assert_eq!(history[0]["value"], "JBSWY3DPEHPK3PXP");
1925        // The discriminator is what tells a restore which field it is restoring.
1926        assert_eq!(history[0]["field"], "totp_secret");
1927    }
1928
1929    #[test]
1930    fn an_api_key_revision_still_carries_no_field_discriminator() {
1931        // Absent `field` means `api_key`, and every vault written before Phase 22
1932        // relies on that. Stamping it now would make an older build's history
1933        // viewer show a field name it has never heard of.
1934        let (conn, _dir) = open_scratch("legacy-history-shape");
1935        save_vault(
1936            &conn,
1937            json!({ "api_keys": [{ "id": "1", "provider": "GitHub", "api_key": "v1" }] }),
1938            SaveCtx::default(),
1939        )
1940        .unwrap();
1941        save_vault(
1942            &conn,
1943            json!({ "api_keys": [{ "id": "1", "provider": "GitHub", "api_key": "v2" }] }),
1944            SaveCtx::default(),
1945        )
1946        .unwrap();
1947
1948        let loaded = load_vault(&conn).unwrap().unwrap();
1949        let history = loaded["api_keys"][0]["version_history"].as_array().unwrap();
1950        assert!(history[0].get("field").is_none(), "{:?}", history[0]);
1951    }
1952
1953    #[test]
1954    fn history_follows_the_id_not_the_provider_name() {
1955        // Renaming an entry must not look like "delete + create", which would
1956        // lose its history. This is exactly what the old provider|account key broke.
1957        let (conn, _dir) = open_scratch("rename");
1958        save_vault(
1959            &conn,
1960            json!({
1961                "api_keys": [{ "id": "1", "provider": "OldName", "api_key": "v1" }]
1962            }),
1963            SaveCtx::default(),
1964        )
1965        .unwrap();
1966        save_vault(
1967            &conn,
1968            json!({
1969                "api_keys": [{ "id": "1", "provider": "NewName", "api_key": "v2" }]
1970            }),
1971            SaveCtx::default(),
1972        )
1973        .unwrap();
1974
1975        let loaded = load_vault(&conn).unwrap().unwrap();
1976        let history = loaded["api_keys"][0]["version_history"].as_array().unwrap();
1977        assert_eq!(history[0]["value"], "v1", "history must survive a rename");
1978    }
1979
1980    #[test]
1981    fn integrity_hash_matches_after_save() {
1982        let (conn, _dir) = open_scratch("integrity");
1983        save_vault(&conn, json!({ "api_keys": [] }), SaveCtx::default()).unwrap();
1984        assert!(verify_vault_integrity(&conn).unwrap());
1985    }
1986
1987    #[test]
1988    fn integrity_check_detects_tampering() {
1989        let (conn, _dir) = open_scratch("tamper");
1990        save_vault(
1991            &conn,
1992            json!({
1993                "api_keys": [{ "id": "1", "provider": "P", "api_key": "k" }]
1994            }),
1995            SaveCtx::default(),
1996        )
1997        .unwrap();
1998        // Rewrite the row behind save_vault's back, leaving the stored hash stale.
1999        conn.execute(
2000            "UPDATE vault_rows SET data = ?1 WHERE kind = 'entry'",
2001            rusqlite::params![r#"{"id":"1","provider":"EVIL","api_key":"k"}"#],
2002        )
2003        .unwrap();
2004        assert!(
2005            !verify_vault_integrity(&conn).unwrap(),
2006            "tampered data must fail the hash check"
2007        );
2008    }
2009
2010    #[test]
2011    fn empty_vault_is_trivially_intact() {
2012        let (conn, _dir) = open_scratch("empty-integrity");
2013        assert!(verify_vault_integrity(&conn).unwrap());
2014    }
2015
2016    // ── Optimistic concurrency ────────────────────────────────────────────────
2017
2018    #[test]
2019    fn version_changes_with_every_write() {
2020        let (conn, _dir) = open_scratch("version");
2021        assert!(
2022            vault_version(&conn).unwrap().is_none(),
2023            "empty vault has no version"
2024        );
2025        let v1 = save_vault(&conn, json!({ "api_keys": [] }), SaveCtx::default()).unwrap();
2026        let v2 = save_vault(
2027            &conn,
2028            json!({
2029                "api_keys": [{ "id": "1", "provider": "A", "api_key": "k" }]
2030            }),
2031            SaveCtx::default(),
2032        )
2033        .unwrap();
2034        assert_ne!(v1, v2);
2035        assert_eq!(vault_version(&conn).unwrap().as_deref(), Some(v2.as_str()));
2036    }
2037
2038    #[test]
2039    fn returned_version_is_the_stored_version() {
2040        // The value save_vault hands back must be exactly what a later
2041        // compare-and-swap will be checked against, or every write would conflict.
2042        let (conn, _dir) = open_scratch("version-match");
2043        let v = save_vault(&conn, json!({ "api_keys": [] }), SaveCtx::default()).unwrap();
2044        assert_eq!(vault_version(&conn).unwrap().unwrap(), v);
2045    }
2046
2047    #[test]
2048    fn writing_at_the_expected_version_succeeds() {
2049        let (conn, _dir) = open_scratch("cas-ok");
2050        let v1 = save_vault(&conn, json!({ "api_keys": [] }), SaveCtx::default()).unwrap();
2051        let res = save_vault(
2052            &conn,
2053            json!({
2054                "api_keys": [{ "id": "1", "provider": "A", "api_key": "k" }]
2055            }),
2056            SaveCtx {
2057                actor: None,
2058                expect_version: Some(&v1),
2059            },
2060        );
2061        assert!(res.is_ok());
2062    }
2063
2064    #[test]
2065    fn writing_at_a_stale_version_is_refused() {
2066        // The lost-update scenario: two writers read v1, one saves, the other
2067        // must not be allowed to overwrite it.
2068        let (conn, _dir) = open_scratch("cas-stale");
2069        let v1 = save_vault(
2070            &conn,
2071            json!({
2072                "api_keys": [{ "id": "1", "provider": "original", "api_key": "k" }]
2073            }),
2074            SaveCtx::default(),
2075        )
2076        .unwrap();
2077
2078        // Writer A lands first.
2079        save_vault(
2080            &conn,
2081            json!({
2082                "api_keys": [{ "id": "1", "provider": "written-by-A", "api_key": "k" }]
2083            }),
2084            SaveCtx {
2085                actor: None,
2086                expect_version: Some(&v1),
2087            },
2088        )
2089        .unwrap();
2090
2091        // Writer B still holds v1.
2092        let err = save_vault(
2093            &conn,
2094            json!({
2095                "api_keys": [{ "id": "1", "provider": "written-by-B", "api_key": "k" }]
2096            }),
2097            SaveCtx {
2098                actor: None,
2099                expect_version: Some(&v1),
2100            },
2101        )
2102        .expect_err("a stale write must be refused");
2103        assert!(
2104            err.starts_with(CONFLICT_ERR),
2105            "callers match on this prefix, got: {err}"
2106        );
2107
2108        // A's data survived intact.
2109        let stored = load_vault(&conn).unwrap().unwrap();
2110        assert_eq!(stored["api_keys"][0]["provider"], "written-by-A");
2111    }
2112
2113    #[test]
2114    fn a_refused_write_leaves_no_trace() {
2115        // The audit appends used to run before the transaction, so a rejected
2116        // write still logged changes that never happened.
2117        let (conn, _dir) = open_scratch("cas-clean");
2118        let v1 = save_vault(
2119            &conn,
2120            json!({
2121                "api_keys": [{ "id": "1", "provider": "A", "api_key": "k" }]
2122            }),
2123            SaveCtx::default(),
2124        )
2125        .unwrap();
2126        // Another writer edits the same entry.
2127        save_vault(
2128            &conn,
2129            json!({
2130                "api_keys": [{ "id": "1", "provider": "A-theirs", "api_key": "k" }]
2131            }),
2132            SaveCtx::default(),
2133        )
2134        .unwrap();
2135
2136        let audit_before = load_audit(&conn).unwrap().len();
2137        let version_before = vault_version(&conn).unwrap();
2138
2139        let err = save_vault(
2140            &conn,
2141            json!({
2142                "api_keys": [
2143                    { "id": "1", "provider": "A-mine", "api_key": "k" },
2144                    { "id": "9", "provider": "GHOST", "api_key": "k" }
2145                ]
2146            }),
2147            SaveCtx {
2148                actor: None,
2149                expect_version: Some(&v1),
2150            },
2151        )
2152        .expect_err("both sides edited entry 1");
2153        assert!(err.starts_with(CONFLICT_ERR), "{err}");
2154        assert!(
2155            err.contains("A-mine"),
2156            "the conflict names the entry: {err}"
2157        );
2158
2159        assert_eq!(
2160            load_audit(&conn).unwrap().len(),
2161            audit_before,
2162            "a refused write must not append audit rows"
2163        );
2164        assert_eq!(vault_version(&conn).unwrap(), version_before);
2165        assert!(!load_audit(&conn)
2166            .unwrap()
2167            .iter()
2168            .any(|r| r.entry_provider.as_deref() == Some("GHOST")));
2169        let stored = load_vault(&conn).unwrap().unwrap();
2170        assert_eq!(stored["api_keys"].as_array().unwrap().len(), 1);
2171        assert_eq!(stored["api_keys"][0]["provider"], "A-theirs");
2172    }
2173
2174    #[test]
2175    fn expecting_a_version_against_an_empty_vault_is_refused() {
2176        let (conn, _dir) = open_scratch("cas-empty");
2177        let err = save_vault(
2178            &conn,
2179            json!({ "api_keys": [] }),
2180            SaveCtx {
2181                actor: None,
2182                expect_version: Some("deadbeef"),
2183            },
2184        )
2185        .expect_err("nothing is stored, so no version can match");
2186        assert!(err.starts_with(CONFLICT_ERR));
2187    }
2188
2189    #[test]
2190    fn omitting_the_version_writes_unconditionally() {
2191        // The explicit escape hatch, used when the user chooses to overwrite.
2192        let (conn, _dir) = open_scratch("cas-force");
2193        save_vault(
2194            &conn,
2195            json!({
2196                "api_keys": [{ "id": "1", "provider": "first", "api_key": "k" }]
2197            }),
2198            SaveCtx::default(),
2199        )
2200        .unwrap();
2201        save_vault(
2202            &conn,
2203            json!({
2204                "api_keys": [{ "id": "1", "provider": "forced", "api_key": "k" }]
2205            }),
2206            SaveCtx::default(),
2207        )
2208        .unwrap();
2209        let stored = load_vault(&conn).unwrap().unwrap();
2210        assert_eq!(stored["api_keys"][0]["provider"], "forced");
2211    }
2212
2213    #[test]
2214    fn integrity_still_holds_after_a_refused_write() {
2215        let (conn, _dir) = open_scratch("cas-integrity");
2216        let v1 = save_vault(&conn, json!({ "api_keys": [] }), SaveCtx::default()).unwrap();
2217        save_vault(
2218            &conn,
2219            json!({
2220                "api_keys": [{ "id": "1", "provider": "A", "api_key": "k" }]
2221            }),
2222            SaveCtx::default(),
2223        )
2224        .unwrap();
2225        let _ = save_vault(
2226            &conn,
2227            json!({ "api_keys": [] }),
2228            SaveCtx {
2229                actor: None,
2230                expect_version: Some(&v1),
2231            },
2232        );
2233        assert!(
2234            verify_vault_integrity(&conn).unwrap(),
2235            "a rolled-back write must not desync data from its hash"
2236        );
2237    }
2238
2239    // ── Audit chain ────────────────────────────────────────────────────────────
2240
2241    #[test]
2242    fn audit_rows_form_a_hash_chain() {
2243        let (conn, _dir) = open_scratch("audit");
2244        save_vault(
2245            &conn,
2246            json!({
2247                "api_keys": [{ "id": "1", "provider": "A", "api_key": "k" }]
2248            }),
2249            SaveCtx::default(),
2250        )
2251        .unwrap();
2252        save_vault(
2253            &conn,
2254            json!({
2255                "api_keys": [
2256                    { "id": "1", "provider": "A", "api_key": "k" },
2257                    { "id": "2", "provider": "B", "api_key": "k2" }
2258                ]
2259            }),
2260            SaveCtx::default(),
2261        )
2262        .unwrap();
2263
2264        let mut rows = load_audit(&conn).unwrap();
2265        assert!(rows.len() >= 2, "expected an audit row per added entry");
2266        rows.sort_by_key(|r| r.id); // load_audit returns newest-first
2267        assert!(rows[0].entry_hash.is_some());
2268        // Each row must link to its predecessor.
2269        for pair in rows.windows(2) {
2270            assert_eq!(
2271                pair[1].prev_hash, pair[0].entry_hash,
2272                "row {} must chain to row {}",
2273                pair[1].id, pair[0].id
2274            );
2275        }
2276    }
2277
2278    #[test]
2279    fn deleting_an_entry_is_audited() {
2280        let (conn, _dir) = open_scratch("audit-delete");
2281        save_vault(
2282            &conn,
2283            json!({
2284                "api_keys": [{ "id": "1", "provider": "Doomed", "api_key": "k" }]
2285            }),
2286            SaveCtx::default(),
2287        )
2288        .unwrap();
2289        save_vault(&conn, json!({ "api_keys": [] }), SaveCtx::default()).unwrap();
2290        let rows = load_audit(&conn).unwrap();
2291        assert!(rows
2292            .iter()
2293            .any(|r| r.action == "delete" && r.entry_provider.as_deref() == Some("Doomed")));
2294    }
2295
2296    #[test]
2297    fn audit_rows_record_the_acting_user() {
2298        let (conn, _dir) = open_scratch("audit-actor");
2299        save_vault(
2300            &conn,
2301            json!({
2302                "api_keys": [{ "id": "1", "provider": "A", "api_key": "k" }]
2303            }),
2304            SaveCtx {
2305                actor: Some("user-123"),
2306                ..Default::default()
2307            },
2308        )
2309        .unwrap();
2310        let rows = load_audit(&conn).unwrap();
2311        let add = rows.iter().find(|r| r.action == "add").unwrap();
2312        assert_eq!(add.actor.as_deref(), Some("user-123"));
2313    }
2314
2315    #[test]
2316    fn actor_is_bound_into_the_hash_chain() {
2317        // Rewriting who did something must invalidate the row hash, otherwise
2318        // attribution would be forgeable while the chain still "verified".
2319        let with = compute_audit_hash("add", "P", "T", Some("alice"), "prev");
2320        let other = compute_audit_hash("add", "P", "T", Some("bob"), "prev");
2321        let without = compute_audit_hash("add", "P", "T", None, "prev");
2322        assert_ne!(with, other, "different actor must give a different hash");
2323        assert_ne!(with, without);
2324    }
2325
2326    #[test]
2327    fn actorless_rows_keep_the_v1_hash_format() {
2328        // Existing chains were written before the actor column; their hashes
2329        // must still reproduce or every old log would read as tampered.
2330        use sha2::{Digest, Sha256};
2331        let mut h = Sha256::new();
2332        for part in ["add", "|", "P", "|", "T", "|", "prev"] {
2333            h.update(part.as_bytes());
2334        }
2335        assert_eq!(
2336            compute_audit_hash("add", "P", "T", None, "prev"),
2337            hex::encode(h.finalize())
2338        );
2339    }
2340
2341    // ── Expiry ─────────────────────────────────────────────────────────────────
2342
2343    #[test]
2344    fn expiring_selects_only_the_window() {
2345        let now = time::OffsetDateTime::now_utc();
2346        let fmt = |d: i64| {
2347            let t = now + time::Duration::days(d);
2348            format!("{:04}-{:02}-{:02}", t.year(), t.month() as u8, t.day())
2349        };
2350        let data = json!({ "api_keys": [
2351            { "provider": "expired",  "expires_at": fmt(-5)  },
2352            { "provider": "soon",     "expires_at": fmt(3)   },
2353            { "provider": "far",      "expires_at": fmt(365) },
2354            { "provider": "no-expiry" },
2355        ]});
2356        let found = expiring_from_value(&data, 30);
2357        let names: Vec<&str> = found
2358            .iter()
2359            .map(|e| e["provider"].as_str().unwrap())
2360            .collect();
2361        assert_eq!(
2362            names,
2363            vec!["soon"],
2364            "already-expired, far-future and never-expiring entries are all excluded"
2365        );
2366    }
2367}
2368
2369#[cfg(test)]
2370mod salt_pairing_tests {
2371    use super::*;
2372
2373    fn tmp(name: &str) -> std::path::PathBuf {
2374        let d = std::env::temp_dir().join(format!("unv-salt-{name}-{}", std::process::id()));
2375        let _ = fs::remove_dir_all(&d);
2376        fs::create_dir_all(&d).unwrap();
2377        d
2378    }
2379
2380    /// The bug: a database whose salt vanished was silently given a new one, and
2381    /// every unlock then reported "Wrong master password" for a correct password.
2382    /// By the time anyone looked, the missing file had already been replaced.
2383    #[test]
2384    fn a_database_without_its_salt_is_refused_not_re_salted() {
2385        let d = tmp("orphan");
2386        let db = d.join("vault.db");
2387        let salt = d.join("vault.salt");
2388        fs::write(&db, b"pretend this is a SQLCipher file").unwrap();
2389
2390        let err = check_salt_pairing(&db, &salt).unwrap_err();
2391        assert!(err.contains("is missing"), "{err}");
2392        assert!(
2393            err.contains("nothing can recompute it"),
2394            "the message must not imply recovery is possible: {err}"
2395        );
2396        assert!(!salt.exists(), "the check must not create a salt");
2397        let _ = fs::remove_dir_all(&d);
2398    }
2399
2400    /// A first run has neither file, and must be allowed to create both.
2401    #[test]
2402    fn a_fresh_directory_is_fine() {
2403        let d = tmp("fresh");
2404        assert!(check_salt_pairing(&d.join("vault.db"), &d.join("vault.salt")).is_ok());
2405        let _ = fs::remove_dir_all(&d);
2406    }
2407
2408    /// An empty database file is a first run that got interrupted, not a vault.
2409    #[test]
2410    fn an_empty_database_file_is_not_treated_as_a_vault() {
2411        let d = tmp("empty");
2412        let db = d.join("vault.db");
2413        fs::write(&db, b"").unwrap();
2414        assert!(check_salt_pairing(&db, &d.join("vault.salt")).is_ok());
2415        let _ = fs::remove_dir_all(&d);
2416    }
2417
2418    /// New salts are owner-only. They were 0644 until `unv doctor` said so.
2419    #[test]
2420    #[cfg(unix)]
2421    fn a_generated_salt_is_owner_only() {
2422        use std::os::unix::fs::PermissionsExt;
2423        let d = tmp("mode");
2424        let salt = d.join("vault.salt");
2425        read_or_create_salt(&salt).unwrap();
2426        let mode = fs::metadata(&salt).unwrap().permissions().mode() & 0o777;
2427        assert_eq!(mode, 0o600, "salt was created world-readable");
2428        let _ = fs::remove_dir_all(&d);
2429    }
2430
2431    /// And so is a newly created database.
2432    #[test]
2433    #[cfg(unix)]
2434    fn a_created_database_is_owner_only() {
2435        use std::os::unix::fs::PermissionsExt;
2436        let d = tmp("dbmode");
2437        let db = d.join("vault.db");
2438        let key = derive_key(
2439            "correct-horse-battery",
2440            &read_or_create_salt(&d.join("vault.salt")).unwrap(),
2441        )
2442        .unwrap();
2443        let conn = open_db(&db, &key).unwrap();
2444        drop(conn);
2445        let mode = fs::metadata(&db).unwrap().permissions().mode() & 0o777;
2446        assert_eq!(mode, 0o600, "database was created world-readable");
2447        let _ = fs::remove_dir_all(&d);
2448    }
2449}
2450
2451/// True for a value safe to write bare in a `.env`. Deliberately narrow.
2452fn env_bare_ok(v: &str) -> bool {
2453    !v.is_empty()
2454        && v.chars()
2455            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '.' | '/' | ':' | '@' | '-'))
2456}
2457
2458/// A value as it must appear after the `=` in a `.env` (Phase 23, E1).
2459///
2460/// The empty string quotes to `""` rather than to nothing, because a bare `KEY=`
2461/// is how "unset" is spelled and a deliberately empty value must not read as
2462/// one. A newline is escaped rather than emitted, so the parser's backslash
2463/// line-continuation can never see one. Twin of `quoteEnvValue` in
2464/// `src/ts/state.ts`, pinned by `parity/env-names.json`.
2465pub fn env_quote(value: &str) -> String {
2466    if env_bare_ok(value) {
2467        return value.to_string();
2468    }
2469    let mut out = String::with_capacity(value.len() + 2);
2470    out.push('"');
2471    for ch in value.chars() {
2472        match ch {
2473            '\\' | '"' | '$' | '`' => {
2474                out.push('\\');
2475                out.push(ch);
2476            }
2477            '\n' => out.push_str("\\n"),
2478            '\r' => out.push_str("\\r"),
2479            '\t' => out.push_str("\\t"),
2480            _ => out.push(ch),
2481        }
2482    }
2483    out.push('"');
2484    out
2485}
2486
2487#[cfg(test)]
2488mod commit_tests {
2489    use super::*;
2490
2491    // S9: a COMMIT that failed left the transaction open, so the connection refused
2492    // every later BEGIN. A deferred foreign key is the portable way to make COMMIT fail.
2493    #[test]
2494    fn a_failed_commit_leaves_the_connection_usable() {
2495        let conn = Connection::open_in_memory().unwrap();
2496        conn.execute_batch(
2497            "PRAGMA foreign_keys = ON;
2498             CREATE TABLE p (id INTEGER PRIMARY KEY);
2499             CREATE TABLE c (pid INTEGER REFERENCES p(id) DEFERRABLE INITIALLY DEFERRED);",
2500        )
2501        .unwrap();
2502        conn.execute_batch("BEGIN IMMEDIATE; INSERT INTO c VALUES (99);")
2503            .unwrap();
2504        assert!(commit(&conn).is_err());
2505        assert!(
2506            conn.is_autocommit(),
2507            "the failed transaction was rolled back"
2508        );
2509        conn.execute_batch("BEGIN IMMEDIATE; COMMIT;").unwrap();
2510    }
2511}
2512
2513#[cfg(test)]
2514mod source_owned_tests {
2515    use super::*;
2516    use serde_json::json;
2517
2518    fn owned_vault(owner: &str) -> serde_json::Value {
2519        json!({ "api_keys": [{
2520            "id": "e1", "provider": "Mail", "api_key": "old-secret", "description": "a",
2521            "authority": { "owner": owner, "source_kind": "pass", "source_id": "email/gmail" }
2522        }]})
2523    }
2524
2525    fn open(tag: &str) -> (Connection, std::path::PathBuf) {
2526        let dir = std::env::temp_dir().join(format!("vc-srcown-{tag}-{}", new_uuid()));
2527        std::fs::create_dir_all(&dir).unwrap();
2528        let key = derive_key(&new_uuid(), &new_uuid().as_bytes()[..16]).unwrap();
2529        let conn = open_db(&dir.join("vault.db"), &key).unwrap();
2530        init_schema(&conn).unwrap();
2531        (conn, dir)
2532    }
2533
2534    /// An entry imported from a Git store, until it is cut over, belongs to that store: a secret
2535    /// edited here would be overwritten by the next sync, so the write is refused and names where
2536    /// to change it. Notes and tags are not secrets and stay editable.
2537    #[test]
2538    fn a_secret_edit_to_a_source_owned_entry_is_refused_and_a_note_edit_is_not() {
2539        let (conn, dir) = open("refuse");
2540        save_vault(&conn, owned_vault("source"), SaveCtx::default()).unwrap();
2541
2542        let mut changed = owned_vault("source");
2543        changed["api_keys"][0]["api_key"] = json!("new-secret");
2544        let err = save_vault(&conn, changed, SaveCtx::default()).unwrap_err();
2545        assert!(err.starts_with(SOURCE_OWNED_ERR), "{err}");
2546        assert!(err.contains("pass") && err.contains("email/gmail"), "{err}");
2547        assert!(err.contains("migrate cutover"), "{err}");
2548        assert_eq!(
2549            load_vault(&conn).unwrap().unwrap()["api_keys"][0]["api_key"],
2550            "old-secret",
2551            "the refused write changed nothing"
2552        );
2553
2554        let mut note = owned_vault("source");
2555        note["api_keys"][0]["description"] = json!("edited note");
2556        save_vault(&conn, note, SaveCtx::default()).unwrap();
2557        let _ = std::fs::remove_dir_all(dir);
2558    }
2559
2560    #[test]
2561    fn an_entry_owned_by_the_vault_or_another_party_is_editable() {
2562        for owner in ["unenverse", "platform"] {
2563            let (conn, dir) = open(owner);
2564            save_vault(&conn, owned_vault(owner), SaveCtx::default()).unwrap();
2565            let mut changed = owned_vault(owner);
2566            changed["api_keys"][0]["api_key"] = json!("new-secret");
2567            save_vault(&conn, changed, SaveCtx::default()).unwrap();
2568            let _ = std::fs::remove_dir_all(dir);
2569        }
2570    }
2571
2572    /// A password-manager export is a one-time move, so its entries stay editable.
2573    #[test]
2574    fn a_password_manager_import_is_not_source_owned_after_the_move() {
2575        let (conn, dir) = open("bitwarden");
2576        let mut v = owned_vault("source");
2577        v["api_keys"][0]["authority"]["source_kind"] = json!("bitwarden");
2578        save_vault(&conn, v.clone(), SaveCtx::default()).unwrap();
2579        v["api_keys"][0]["api_key"] = json!("new-secret");
2580        save_vault(&conn, v, SaveCtx::default()).unwrap();
2581        let _ = std::fs::remove_dir_all(dir);
2582    }
2583
2584    #[test]
2585    fn extra_variables_count_as_secrets() {
2586        let (conn, dir) = open("extra");
2587        let mut v = owned_vault("source");
2588        v["api_keys"][0]["extra_vars"] = json!([{ "key": "A", "value": "1" }]);
2589        save_vault(&conn, v.clone(), SaveCtx::default()).unwrap();
2590        v["api_keys"][0]["extra_vars"] = json!([{ "key": "A", "value": "2" }]);
2591        assert!(save_vault(&conn, v, SaveCtx::default())
2592            .unwrap_err()
2593            .starts_with(SOURCE_OWNED_ERR));
2594        let _ = std::fs::remove_dir_all(dir);
2595    }
2596}
2597
2598#[cfg(test)]
2599mod private_dir_tests {
2600    use super::create_private_dir;
2601
2602    fn scratch(tag: &str) -> std::path::PathBuf {
2603        std::env::temp_dir().join(format!("vc-private-{tag}-{}", crate::new_uuid()))
2604    }
2605
2606    /// A scratch directory used to be made with `create_dir_all` and then chmod'd, which left it
2607    /// world-readable for an instant and adopted any path already there. It is now 0700 from the
2608    /// start and refuses an existing path.
2609    #[cfg(unix)]
2610    #[test]
2611    fn creates_the_directory_owner_only_and_refuses_an_existing_one() {
2612        use std::os::unix::fs::PermissionsExt;
2613        let dir = scratch("mode");
2614        create_private_dir(&dir).unwrap();
2615        assert_eq!(
2616            std::fs::metadata(&dir).unwrap().permissions().mode() & 0o777,
2617            0o700
2618        );
2619        assert!(create_private_dir(&dir).is_err());
2620        let _ = std::fs::remove_dir_all(&dir);
2621    }
2622
2623    #[cfg(unix)]
2624    #[test]
2625    fn does_not_follow_a_symlink_someone_planted_at_the_path() {
2626        let target = scratch("target");
2627        std::fs::create_dir(&target).unwrap();
2628        let link = scratch("link");
2629        std::os::unix::fs::symlink(&target, &link).unwrap();
2630        assert!(create_private_dir(&link).is_err());
2631        let _ = std::fs::remove_file(&link);
2632        let _ = std::fs::remove_dir_all(&target);
2633    }
2634
2635    #[test]
2636    fn a_missing_parent_is_an_error_not_a_silent_create_all() {
2637        let nested = scratch("missing").join("child");
2638        assert!(create_private_dir(&nested).is_err());
2639    }
2640}
2641
2642#[cfg(all(test, windows))]
2643mod windows_acl_tests {
2644    use super::*;
2645
2646    /// `icacls` output for a path: one line per access entry.
2647    fn entries(path: &Path) -> String {
2648        let out = std::process::Command::new("icacls")
2649            .arg(path)
2650            .output()
2651            .unwrap();
2652        String::from_utf8_lossy(&out.stdout).into_owned()
2653    }
2654
2655    fn assert_owner_only(path: &Path) {
2656        let text = entries(path);
2657        let user = std::env::var("USERNAME").unwrap();
2658        assert!(text.contains(&user), "the current user is missing: {text}");
2659        for other in [
2660            "Everyone",
2661            "BUILTIN\\Users",
2662            "Authenticated Users",
2663            "BUILTIN\\Administrators",
2664            "NT AUTHORITY\\SYSTEM",
2665        ] {
2666            assert!(!text.contains(other), "{other} still has access: {text}");
2667        }
2668    }
2669
2670    fn scratch(tag: &str) -> std::path::PathBuf {
2671        let d = std::env::temp_dir().join(format!("vc-acl-{tag}-{}", new_uuid()));
2672        create_private_dir(&d).unwrap();
2673        d
2674    }
2675
2676    #[test]
2677    fn a_restricted_file_allows_only_its_owner() {
2678        let d = scratch("file");
2679        let f = d.join("secret.bin");
2680        fs::write(&f, b"x").unwrap();
2681        restrict_to_owner(&f).unwrap();
2682        assert_owner_only(&f);
2683        let _ = fs::remove_dir_all(&d);
2684    }
2685
2686    #[test]
2687    fn a_private_directory_and_what_is_created_in_it_are_owner_only() {
2688        let d = scratch("dir");
2689        assert_owner_only(&d);
2690        let inner = d.join("made-later.txt");
2691        fs::write(&inner, b"x").unwrap();
2692        assert_owner_only(&inner);
2693        let _ = fs::remove_dir_all(&d);
2694    }
2695
2696    #[test]
2697    fn the_database_the_salt_and_their_folder_are_owner_only() {
2698        let d = std::env::temp_dir().join(format!("vc-acl-vault-{}", new_uuid()));
2699        let db = d.join("vault.db");
2700        let salt = read_or_create_salt(&d.join("vault.salt")).unwrap();
2701        let key = derive_key(&new_uuid(), &salt).unwrap();
2702        let conn = open_db(&db, &key).unwrap();
2703        init_schema(&conn).unwrap();
2704        for p in [&d, &db, &d.join("vault.salt")] {
2705            assert_owner_only(p);
2706        }
2707        drop(conn);
2708        let _ = fs::remove_dir_all(&d);
2709    }
2710
2711    #[test]
2712    fn restricting_a_path_that_does_not_exist_is_an_error_not_a_panic() {
2713        assert!(restrict_to_owner(&std::env::temp_dir().join(new_uuid())).is_err());
2714    }
2715}
2716
2717#[cfg(all(test, unix))]
2718mod write_private_tests {
2719    use super::*;
2720
2721    // Bug: credential files were written with the default mode and chmodded afterwards, and the
2722    // server's TLS private key was left readable by every local user.
2723    #[test]
2724    fn write_private_creates_the_file_owner_only_even_over_a_loose_one() {
2725        use std::os::unix::fs::PermissionsExt;
2726        let dir = std::env::temp_dir().join(format!("vc-private-{}", new_uuid()));
2727        fs::create_dir_all(&dir).unwrap();
2728        let f = dir.join("k");
2729        write_private(&f, b"one").unwrap();
2730        assert_eq!(
2731            fs::metadata(&f).unwrap().permissions().mode() & 0o777,
2732            0o600
2733        );
2734        fs::set_permissions(&f, fs::Permissions::from_mode(0o644)).unwrap();
2735        write_private(&f, b"two").unwrap();
2736        assert_eq!(fs::read(&f).unwrap(), b"two");
2737        assert_eq!(
2738            fs::metadata(&f).unwrap().permissions().mode() & 0o777,
2739            0o600
2740        );
2741        let _ = fs::remove_dir_all(&dir);
2742    }
2743}