Skip to main content

agentmux_srv_core/backend/storage/
vault.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The Vault's rows in the identity store: `db_vault_entries` (each entry,
5//! its secret parts sealed by `backend::vault::seal`) and
6//! `db_vault_activity` (what was done with them, never a value).
7//! docs/specs/SPEC_VAULT_PANE_AGENTS_USE_SECRETS_UNSEEN_2026_10_19.md §5.5.
8
9use rusqlite::{params, OptionalExtension};
10
11use super::error::StoreError;
12use super::store::Store;
13
14/// The Vault's tables, in the identity store (`run_identity_store_schema`
15/// runs it): one store for every AgentMux on the computer, like the Vault key
16/// in the keychain that seals the entries. `sealed` holds an entry's secret
17/// parts, encrypted; no column holds a value.
18pub(super) const VAULT_SCHEMA: &str = "
19    CREATE TABLE IF NOT EXISTS db_vault_entries (
20        id           TEXT PRIMARY KEY,
21        kind         TEXT NOT NULL,
22        label        TEXT NOT NULL,
23        fields       TEXT NOT NULL DEFAULT '{}',
24        tags         TEXT NOT NULL DEFAULT '[]',
25        sealed       BLOB NOT NULL,
26        created_at   INTEGER NOT NULL DEFAULT 0,
27        updated_at   INTEGER NOT NULL DEFAULT 0,
28        last_used_at INTEGER NOT NULL DEFAULT 0,
29        vault_id     TEXT NOT NULL DEFAULT 'personal'
30    );
31    -- The person's Vaults on this machine: each entry belongs to exactly one. `agents` is who may
32    -- use its entries: `all`, `none`, or `named` with `agent_ids` a JSON array of agent ids.
33    -- `personal` is today's Vault, always there, and can't be deleted.
34    CREATE TABLE IF NOT EXISTS db_vaults (
35        id         TEXT PRIMARY KEY,
36        name       TEXT NOT NULL,
37        agents     TEXT NOT NULL DEFAULT 'all',
38        agent_ids  TEXT NOT NULL DEFAULT '[]',
39        position   INTEGER NOT NULL DEFAULT 0,
40        created_at INTEGER NOT NULL DEFAULT 0
41    );
42    INSERT OR IGNORE INTO db_vaults (id, name, agents, position) VALUES ('personal', 'Personal', 'all', 0);
43    -- The Vault each browser profile (`personal` or `profile:<id>`) saves its sign-ins to and offers
44    -- them from. A profile with no row uses Personal.
45    CREATE TABLE IF NOT EXISTS db_vault_signin_vaults (
46        profile  TEXT PRIMARY KEY,
47        vault_id TEXT NOT NULL
48    );
49    CREATE TABLE IF NOT EXISTS db_vault_activity (
50        seq         INTEGER PRIMARY KEY AUTOINCREMENT,
51        at          INTEGER NOT NULL,
52        entry_id    TEXT NOT NULL DEFAULT '',
53        entry_label TEXT NOT NULL DEFAULT '',
54        actor       TEXT NOT NULL DEFAULT '',
55        action      TEXT NOT NULL,
56        target      TEXT NOT NULL DEFAULT '',
57        outcome     TEXT NOT NULL DEFAULT ''
58    );
59    -- An entry's own lines: its expiry reminders, and who made its value.
60    CREATE INDEX IF NOT EXISTS idx_vault_activity_entry ON db_vault_activity (entry_id, seq);
61    -- Where the person let an agent use an entry without asking again: the
62    -- origin of a site, for one entry (spec section 6.4).
63    CREATE TABLE IF NOT EXISTS db_vault_grants (
64        entry_id   TEXT NOT NULL,
65        origin     TEXT NOT NULL,
66        granted_at INTEGER NOT NULL,
67        PRIMARY KEY (entry_id, origin)
68    );
69    -- The sign-ins a browser pane saved for a site that asked for a user name and password (HTTP
70    -- Basic Auth). The password is in the keychain under a hash, which can't be listed or turned
71    -- back into a site; this row is what the Vault lists. It holds no secret: the site, the realm
72    -- the site named, and the user name masked as the approval window shows it.
73    CREATE TABLE IF NOT EXISTS db_browser_signins (
74        identity_id TEXT NOT NULL,
75        origin      TEXT NOT NULL,
76        realm       TEXT NOT NULL,
77        is_proxy    INTEGER NOT NULL,
78        username    TEXT NOT NULL DEFAULT '',
79        saved_at    INTEGER NOT NULL,
80        PRIMARY KEY (identity_id, origin, realm, is_proxy)
81    );
82    -- Sites the person said never to offer saving a sign-in for, per browser profile
83    -- (`personal` or `profile:<id>`).
84    CREATE TABLE IF NOT EXISTS db_browser_signin_never (
85        profile TEXT NOT NULL,
86        origin  TEXT NOT NULL,
87        at      INTEGER NOT NULL,
88        PRIMARY KEY (profile, origin)
89    );
90    -- An entry's earlier values, sealed as the entry is (its id is the seal's
91    -- associated data, so a blob moves between the two tables unchanged), kept 7
92    -- days after they were replaced (`backend::vault::versions`). `entry_created_at`
93    -- ties each to one incarnation of a reused id; `state` is `previous`, or
94    -- `pending` for a rotation's value not yet in use.
95    CREATE TABLE IF NOT EXISTS db_vault_versions (
96        seq              INTEGER PRIMARY KEY AUTOINCREMENT,
97        entry_id         TEXT NOT NULL,
98        entry_created_at INTEGER NOT NULL,
99        sealed           BLOB NOT NULL,
100        replaced_at      INTEGER NOT NULL,
101        replaced_by      TEXT NOT NULL DEFAULT '',
102        how              TEXT NOT NULL DEFAULT '',
103        state            TEXT NOT NULL DEFAULT 'previous'
104    );
105    CREATE INDEX IF NOT EXISTS idx_vault_versions_entry ON db_vault_versions (entry_id, seq);
106    -- Which AgentMux instances show a Vault pane now, until when: agents'
107    -- whole-window captures of AgentMux are refused while any does.
108    CREATE TABLE IF NOT EXISTS db_vault_on_screen (
109        instance TEXT PRIMARY KEY,
110        until_ms INTEGER NOT NULL
111    );
112    -- Each entry's opaque id for links (docs/specs/SPEC_DEEP_LINKS_ONE_FRAMEWORK_2026_11_20.md G2, D7): assigned
113    -- once, kept, and never derived from the entry's kind or label.
114    CREATE TABLE IF NOT EXISTS db_vault_link_ids (
115        entry_id TEXT PRIMARY KEY,
116        link_id  TEXT NOT NULL UNIQUE
117    );
118";
119
120/// Columns added after the Vault's tables first shipped, applied like the identity store's others.
121pub(super) const VAULT_ALTERS: [&str; 8] = [
122    // Several Vaults: every entry made before belongs to `personal`.
123    "ALTER TABLE db_vault_entries ADD COLUMN vault_id TEXT NOT NULL DEFAULT 'personal'",
124    // The entry's history (docs/specs/SPEC_VAULT_PARITY_ENTRY_HISTORY_REASONS_AND_IMPORT_2026_11_06.md §5): rows made
125    // before these columns keep the defaults, and have no hash.
126    "ALTER TABLE db_vault_activity ADD COLUMN version INTEGER NOT NULL DEFAULT 0",
127    "ALTER TABLE db_vault_activity ADD COLUMN actor_kind TEXT NOT NULL DEFAULT ''",
128    "ALTER TABLE db_vault_activity ADD COLUMN host TEXT NOT NULL DEFAULT ''",
129    "ALTER TABLE db_vault_activity ADD COLUMN reason TEXT NOT NULL DEFAULT ''",
130    "ALTER TABLE db_vault_activity ADD COLUMN refs TEXT NOT NULL DEFAULT ''",
131    "ALTER TABLE db_vault_activity ADD COLUMN prev_hash TEXT NOT NULL DEFAULT ''",
132    "ALTER TABLE db_vault_activity ADD COLUMN hash TEXT NOT NULL DEFAULT ''",
133];
134
135#[derive(Debug, Clone, PartialEq)]
136pub struct VaultRow {
137    pub id: String,
138    pub kind: String,
139    pub label: String,
140    /// The plain fields, a JSON object.
141    pub fields: String,
142    /// Tags, a JSON array.
143    pub tags: String,
144    pub sealed: Vec<u8>,
145    pub created_at: i64,
146    pub updated_at: i64,
147    pub last_used_at: i64,
148    /// The Vault the entry belongs to (`db_vaults.id`).
149    pub vault_id: String,
150}
151
152/// A Vault of the person's on this machine.
153#[derive(Debug, Clone, PartialEq)]
154pub struct VaultInfoRow {
155    pub id: String,
156    pub name: String,
157    /// `all`, `none` or `named`.
158    pub agents: String,
159    /// With `named`: the agents' ids, a JSON array.
160    pub agent_ids: String,
161    pub position: i64,
162    pub created_at: i64,
163}
164
165/// The Vault every entry made before Vaults existed belongs to.
166pub const PERSONAL_VAULT: &str = "personal";
167
168/// How many additive changes the Vault's tables have had since they were first made: the revision `Vault health` names.
169pub fn schema_revision() -> usize {
170    VAULT_ALTERS.len()
171}
172
173/// The actions that give an entry a new value: each one is the next version of it.
174pub const VALUE_SETTING: [&str; 7] = ["generated", "captured", "rotated", "replaced", "restored", "created", "imported"];
175
176/// The actions that hand an entry's value to a process, a form or a sign-in: each is made under the version then current.
177pub const VALUE_USES: [&str; 7] = ["filled a web form", "signed in", "ran a command", "revealed", "copied", "sent on sign-up", "filled on sign-up"];
178
179#[derive(Debug, Clone, PartialEq, Default)]
180pub struct VaultActivityRow {
181    /// Order on this machine; the store gives it.
182    pub seq: i64,
183    pub at: i64,
184    pub entry_id: String,
185    pub entry_label: String,
186    /// "you" for the person, else the agent's name.
187    pub actor: String,
188    pub action: String,
189    /// Where: a site, a command, a file name.
190    pub target: String,
191    pub outcome: String,
192    /// The entry's value version this event made or used; 0 for one that touches no value. The store gives it.
193    pub version: i64,
194    /// `agent`, `person` or `srv`.
195    pub actor_kind: String,
196    /// The machine's name.
197    pub host: String,
198    /// The agent's reason, one line.
199    pub reason: String,
200    /// Short references (a task, a PR), a JSON array, or empty.
201    pub refs: String,
202    /// The hash of the row before it in the chain, empty for the first chained row.
203    pub prev_hash: String,
204    /// This row's place in the chain; empty for a row made before the chain.
205    pub hash: String,
206}
207
208/// A row's hash in the chain: SHA-256 over the previous row's hash and the row's own fields, each with its length in
209/// front so two rows can't be cut into each other. No value goes in: a row holds none.
210pub fn activity_hash(prev: &str, r: &VaultActivityRow) -> String {
211    use sha2::{Digest, Sha256};
212    let mut h = Sha256::new();
213    let mut put = |bytes: &[u8]| {
214        h.update((bytes.len() as u64).to_le_bytes());
215        h.update(bytes);
216    };
217    put(prev.as_bytes());
218    for n in [r.seq, r.at, r.version] {
219        put(&n.to_le_bytes());
220    }
221    for t in [&r.entry_id, &r.entry_label, &r.actor_kind, &r.actor, &r.host, &r.action, &r.target, &r.outcome, &r.reason, &r.refs] {
222        put(t.as_bytes());
223    }
224    hex::encode(h.finalize())
225}
226
227const ACTIVITY_COLUMNS: &str = "seq, at, entry_id, entry_label, actor, action, target, outcome, version, actor_kind, host, reason, refs, prev_hash, hash";
228
229fn activity_of(r: &rusqlite::Row<'_>) -> rusqlite::Result<VaultActivityRow> {
230    Ok(VaultActivityRow {
231        seq: r.get(0)?,
232        at: r.get(1)?,
233        entry_id: r.get(2)?,
234        entry_label: r.get(3)?,
235        actor: r.get(4)?,
236        action: r.get(5)?,
237        target: r.get(6)?,
238        outcome: r.get(7)?,
239        version: r.get(8)?,
240        actor_kind: r.get(9)?,
241        host: r.get(10)?,
242        reason: r.get(11)?,
243        refs: r.get(12)?,
244        prev_hash: r.get(13)?,
245        hash: r.get(14)?,
246    })
247}
248
249pub(super) const COLUMNS: &str = "id, kind, label, fields, tags, sealed, created_at, updated_at, last_used_at, vault_id";
250
251pub(super) fn row_of(r: &rusqlite::Row<'_>) -> rusqlite::Result<VaultRow> {
252    Ok(VaultRow {
253        id: r.get(0)?,
254        kind: r.get(1)?,
255        label: r.get(2)?,
256        fields: r.get(3)?,
257        tags: r.get(4)?,
258        sealed: r.get(5)?,
259        created_at: r.get(6)?,
260        updated_at: r.get(7)?,
261        last_used_at: r.get(8)?,
262        vault_id: r.get(9)?,
263    })
264}
265
266fn vault_of(r: &rusqlite::Row<'_>) -> rusqlite::Result<VaultInfoRow> {
267    Ok(VaultInfoRow { id: r.get(0)?, name: r.get(1)?, agents: r.get(2)?, agent_ids: r.get(3)?, position: r.get(4)?, created_at: r.get(5)? })
268}
269
270impl Store {
271    pub fn vault_insert(&self, row: &VaultRow) -> Result<(), StoreError> {
272        self.vault_insert_bound(row, None)
273    }
274
275    pub fn vault_insert_bound(&self, row: &VaultRow, link_id: Option<&str>) -> Result<(), StoreError> {
276        let conn = self.conn.lock().unwrap();
277        let tx = conn.unchecked_transaction()?;
278        tx.execute(
279            &format!("INSERT INTO db_vault_entries ({COLUMNS}) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)"),
280            params![row.id, row.kind, row.label, row.fields, row.tags, row.sealed, row.created_at, row.updated_at, row.last_used_at, row.vault_id],
281        )?;
282        if let Some(link_id) = link_id {
283            let inserted = tx.execute(
284                "INSERT INTO db_vault_link_ids (entry_id, link_id) SELECT ?1, ?2 WHERE NOT EXISTS(SELECT 1 FROM db_vault_link_retired WHERE link_id = ?2) AND NOT EXISTS(SELECT 1 FROM db_vault_link_aliases WHERE link_id = ?2)",
285                params![row.id, link_id],
286            )?;
287            if inserted == 0 { return Err(StoreError::AlreadyExists); }
288        }
289        tx.commit()?;
290        Ok(())
291    }
292
293    /// Replaces an entry's label, fields, tags and sealed parts. False if
294    /// there is no such entry. Tests only: an edit goes through
295    /// `vault_update_kept`, a capture through `vault_capture_commit`.
296    #[cfg(any(test, feature = "test-support"))]
297    pub fn vault_update(&self, row: &VaultRow) -> Result<bool, StoreError> {
298        let conn = self.conn.lock().unwrap();
299        let n = conn.execute(
300            "UPDATE db_vault_entries SET label = ?2, fields = ?3, tags = ?4, sealed = ?5, updated_at = ?6 WHERE id = ?1",
301            params![row.id, row.label, row.fields, row.tags, row.sealed, row.updated_at],
302        )?;
303        Ok(n > 0)
304    }
305
306    /// Replaces only an entry's plain fields (a card's default flag moving to
307    /// another card), leaving its value and its update time alone. False if
308    /// there is no such entry.
309    pub fn vault_set_fields(&self, id: &str, fields: &str) -> Result<bool, StoreError> {
310        let conn = self.conn.lock().unwrap();
311        let n = conn.execute("UPDATE db_vault_entries SET fields = ?2 WHERE id = ?1", params![id, fields])?;
312        Ok(n > 0)
313    }
314
315    /// Deletes an entry and the grants and earlier values it had.
316    pub fn vault_delete(&self, id: &str) -> Result<bool, StoreError> {
317        self.vault_delete_bound(id, None)
318    }
319
320    pub fn vault_delete_bound(&self, id: &str, link_id: Option<&str>) -> Result<bool, StoreError> {
321        let conn = self.conn.lock().unwrap();
322        let tx = conn.unchecked_transaction()?;
323        if let Some(link_id) = link_id {
324            if !super::vault_account_key::matches_link(&tx, id, link_id)? {
325                return Ok(false);
326            }
327        }
328        tx.execute("DELETE FROM db_vault_grants WHERE entry_id = ?1", params![id])?;
329        tx.execute("DELETE FROM db_vault_versions WHERE entry_id = ?1", params![id])?;
330        tx.execute("DELETE FROM db_vault_details_kept WHERE entry_id = ?1", params![id])?;
331        tx.execute("DELETE FROM db_vault_proposals WHERE entry_id = ?1", params![id])?;
332        // The ids that opened it are kept for good as retired, so none is given to another entry.
333        tx.execute(
334            "INSERT OR IGNORE INTO db_vault_link_retired (link_id) SELECT link_id FROM db_vault_link_ids WHERE entry_id = ?1 UNION SELECT link_id FROM db_vault_link_aliases WHERE entry_id = ?1",
335            params![id],
336        )?;
337        tx.execute("DELETE FROM db_vault_link_aliases WHERE entry_id = ?1", params![id])?;
338        tx.execute("DELETE FROM db_vault_link_ids WHERE entry_id = ?1", params![id])?;
339        let n = tx.execute("DELETE FROM db_vault_entries WHERE id = ?1", params![id])?;
340        tx.commit()?;
341        Ok(n > 0)
342    }
343
344    /// Notes that a browser pane saved a sign-in in the keychain (never its password):
345    /// how sign-ins were kept before the Vault held them, for tests of the move.
346    #[cfg(test)]
347    pub fn browser_signin_note(&self, identity_id: &str, origin: &str, realm: &str, is_proxy: bool, masked_username: &str, at_ms: i64) -> Result<(), StoreError> {
348        let conn = self.conn.lock().unwrap();
349        conn.execute(
350            "INSERT OR REPLACE INTO db_browser_signins (identity_id, origin, realm, is_proxy, username, saved_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
351            params![identity_id, origin, realm, is_proxy, masked_username, at_ms],
352        )?;
353        Ok(())
354    }
355
356    /// Forgets the note of a sign-in that was deleted.
357    pub fn browser_signin_forget(&self, identity_id: &str, origin: &str, realm: &str, is_proxy: bool) -> Result<(), StoreError> {
358        let conn = self.conn.lock().unwrap();
359        conn.execute("DELETE FROM db_browser_signins WHERE identity_id = ?1 AND origin = ?2 AND realm = ?3 AND is_proxy = ?4", params![identity_id, origin, realm, is_proxy])?;
360        Ok(())
361    }
362
363    /// Never offer saving a sign-in for `origin` in `profile`.
364    pub fn browser_signin_never_add(&self, profile: &str, origin: &str, at_ms: i64) -> Result<(), StoreError> {
365        let conn = self.conn.lock().unwrap();
366        conn.execute("INSERT OR REPLACE INTO db_browser_signin_never (profile, origin, at) VALUES (?1, ?2, ?3)", params![profile, origin, at_ms])?;
367        Ok(())
368    }
369
370    pub fn browser_signin_never_has(&self, profile: &str, origin: &str) -> Result<bool, StoreError> {
371        let conn = self.conn.lock().unwrap();
372        let n: i64 = conn.query_row("SELECT COUNT(*) FROM db_browser_signin_never WHERE profile = ?1 AND origin = ?2", params![profile, origin], |r| r.get(0))?;
373        Ok(n > 0)
374    }
375
376    /// Every noted sign-in's keychain address `(identity_id, origin, realm, is_proxy)`:
377    /// what the Vault moves in from the keychain.
378    pub fn browser_signins_saved(&self) -> Result<Vec<(String, String, String, bool)>, StoreError> {
379        let conn = self.conn.lock().unwrap();
380        let mut stmt = conn.prepare("SELECT identity_id, origin, realm, is_proxy FROM db_browser_signins ORDER BY saved_at, origin, realm")?;
381        let rows = stmt.query_map([], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get::<_, i64>(3)? != 0)))?;
382        Ok(rows.collect::<Result<Vec<_>, _>>()?)
383    }
384
385    /// The sign-ins browser panes saved that the Vault hasn't moved in yet, newest
386    /// first: `(origin, realm, is_proxy, masked username)`.
387    pub fn browser_signins(&self) -> Result<Vec<(String, String, bool, String)>, StoreError> {
388        let conn = self.conn.lock().unwrap();
389        let mut stmt = conn.prepare("SELECT origin, realm, is_proxy, username FROM db_browser_signins ORDER BY saved_at DESC, origin, realm")?;
390        let rows = stmt.query_map([], |r| Ok((r.get(0)?, r.get(1)?, r.get::<_, i64>(2)? != 0, r.get(3)?)))?.collect::<Result<Vec<_>, _>>()?;
391        Ok(rows)
392    }
393
394    pub fn vault_grant_add(&self, entry_id: &str, origin: &str, at_ms: i64, entry_created_at: i64) -> Result<(), StoreError> {
395        let conn = self.conn.lock().unwrap();
396        // Only for the entry the person was asked about: they have minutes to answer,
397        // in which time it can be deleted, and a re-created one of the same name (its
398        // id comes from its kind and label, its `created_at` is new) must not inherit
399        // the site.
400        conn.execute(
401            "INSERT OR REPLACE INTO db_vault_grants (entry_id, origin, granted_at) SELECT ?1, ?2, ?3 WHERE EXISTS (SELECT 1 FROM db_vault_entries WHERE id = ?1 AND created_at = ?4)",
402            params![entry_id, origin, at_ms, entry_created_at],
403        )?;
404        Ok(())
405    }
406
407    /// [`Self::vault_grant_add`], only if the entry is also still as the person was shown it (`entry_updated_at`): one
408    /// edited meanwhile, a share removed and made again included, gets no grant from an answer given to the old question.
409    pub fn vault_grant_add_unchanged(&self, entry_id: &str, origin: &str, at_ms: i64, entry_created_at: i64, entry_updated_at: i64) -> Result<(), StoreError> {
410        let conn = self.conn.lock().unwrap();
411        conn.execute(
412            "INSERT OR REPLACE INTO db_vault_grants (entry_id, origin, granted_at) SELECT ?1, ?2, ?3 WHERE EXISTS (SELECT 1 FROM db_vault_entries WHERE id = ?1 AND created_at = ?4 AND updated_at = ?5)",
413            params![entry_id, origin, at_ms, entry_created_at, entry_updated_at],
414        )?;
415        Ok(())
416    }
417
418    pub fn vault_grant_revoke(&self, entry_id: &str, origin: &str) -> Result<bool, StoreError> {
419        let conn = self.conn.lock().unwrap();
420        Ok(conn.execute("DELETE FROM db_vault_grants WHERE entry_id = ?1 AND origin = ?2", params![entry_id, origin])? > 0)
421    }
422
423    pub fn vault_grant_check(&self, entry_id: &str, origin: &str) -> Result<bool, StoreError> {
424        let conn = self.conn.lock().unwrap();
425        let n: i64 = conn.query_row("SELECT COUNT(*) FROM db_vault_grants WHERE entry_id = ?1 AND origin = ?2", params![entry_id, origin], |r| r.get(0))?;
426        Ok(n > 0)
427    }
428
429    /// Every grant as `(entry id, origin, granted at)`.
430    pub fn vault_grant_rows(&self) -> Result<Vec<(String, String, i64)>, StoreError> {
431        let conn = self.conn.lock().unwrap();
432        let mut stmt = conn.prepare("SELECT entry_id, origin, granted_at FROM db_vault_grants ORDER BY entry_id, origin")?;
433        let rows = stmt.query_map([], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)))?;
434        Ok(rows.collect::<Result<_, _>>()?)
435    }
436
437    /// Every entry's grants: entry id to its origins, oldest first.
438    pub fn vault_grants(&self) -> Result<std::collections::HashMap<String, Vec<String>>, StoreError> {
439        let conn = self.conn.lock().unwrap();
440        let mut stmt = conn.prepare("SELECT entry_id, origin FROM db_vault_grants ORDER BY granted_at, origin")?;
441        let rows = stmt.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))?;
442        let mut out: std::collections::HashMap<String, Vec<String>> = std::collections::HashMap::new();
443        for row in rows {
444            let (id, origin) = row?;
445            out.entry(id).or_default().push(origin);
446        }
447        Ok(out)
448    }
449
450    pub fn vault_get(&self, id: &str) -> Result<Option<VaultRow>, StoreError> {
451        let conn = self.conn.lock().unwrap();
452        Ok(conn
453            .query_row(&format!("SELECT {COLUMNS} FROM db_vault_entries WHERE id = ?1"), params![id], row_of)
454            .optional()?)
455    }
456
457    /// Every entry, by label.
458    pub fn vault_list(&self) -> Result<Vec<VaultRow>, StoreError> {
459        let conn = self.conn.lock().unwrap();
460        let mut stmt = conn.prepare(&format!("SELECT {COLUMNS} FROM db_vault_entries ORDER BY label COLLATE NOCASE, id"))?;
461        let rows = stmt.query_map([], row_of)?;
462        Ok(rows.collect::<Result<_, _>>()?)
463    }
464
465    /// The person's Vaults, in their order.
466    pub fn vaults(&self) -> Result<Vec<VaultInfoRow>, StoreError> {
467        let conn = self.conn.lock().unwrap();
468        let mut stmt = conn.prepare("SELECT id, name, agents, agent_ids, position, created_at FROM db_vaults ORDER BY position, created_at, id")?;
469        let rows = stmt.query_map([], vault_of)?;
470        Ok(rows.collect::<Result<_, _>>()?)
471    }
472
473    pub fn vault_info(&self, id: &str) -> Result<Option<VaultInfoRow>, StoreError> {
474        let conn = self.conn.lock().unwrap();
475        Ok(conn
476            .query_row("SELECT id, name, agents, agent_ids, position, created_at FROM db_vaults WHERE id = ?1", params![id], vault_of)
477            .optional()?)
478    }
479
480    /// Adds a Vault after the others.
481    pub fn vault_add(&self, v: &VaultInfoRow) -> Result<(), StoreError> {
482        let conn = self.conn.lock().unwrap();
483        conn.execute(
484            "INSERT INTO db_vaults (id, name, agents, agent_ids, position, created_at) \
485             VALUES (?1, ?2, ?3, ?4, COALESCE((SELECT MAX(position) + 1 FROM db_vaults), 0), ?5)",
486            params![v.id, v.name, v.agents, v.agent_ids, v.created_at],
487        )?;
488        Ok(())
489    }
490
491    /// Renames a Vault and sets who may use it. False if there is no such Vault.
492    pub fn vault_set(&self, id: &str, name: &str, agents: &str, agent_ids: &str) -> Result<bool, StoreError> {
493        let conn = self.conn.lock().unwrap();
494        Ok(conn.execute("UPDATE db_vaults SET name = ?2, agents = ?3, agent_ids = ?4 WHERE id = ?1", params![id, name, agents, agent_ids])? > 0)
495    }
496
497    /// Removes an empty Vault. False if it still holds entries or there is no such Vault.
498    pub fn vault_remove(&self, id: &str) -> Result<bool, StoreError> {
499        let conn = self.conn.lock().unwrap();
500        let tx = conn.unchecked_transaction()?;
501        let held: i64 = tx.query_row("SELECT COUNT(*) FROM db_vault_entries WHERE vault_id = ?1", params![id], |r| r.get(0))?;
502        if held > 0 {
503            return Ok(false);
504        }
505        let n = tx.execute("DELETE FROM db_vaults WHERE id = ?1", params![id])?;
506        // A profile that saved its sign-ins there goes back to Personal.
507        tx.execute("DELETE FROM db_vault_signin_vaults WHERE vault_id = ?1", params![id])?;
508        tx.commit()?;
509        Ok(n > 0)
510    }
511
512    /// Each browser profile's sign-in Vault, for the profiles that have one other than Personal.
513    pub fn signin_vaults(&self) -> Result<Vec<(String, String)>, StoreError> {
514        let conn = self.conn.lock().unwrap();
515        let mut stmt = conn.prepare("SELECT profile, vault_id FROM db_vault_signin_vaults ORDER BY profile")?;
516        let rows = stmt.query_map([], |r| Ok((r.get(0)?, r.get(1)?)))?;
517        Ok(rows.collect::<Result<_, _>>()?)
518    }
519
520    /// The Vault `profile` keeps its sign-ins in, if it is not Personal.
521    pub fn signin_vault(&self, profile: &str) -> Result<Option<String>, StoreError> {
522        let conn = self.conn.lock().unwrap();
523        Ok(conn.query_row("SELECT vault_id FROM db_vault_signin_vaults WHERE profile = ?1", params![profile], |r| r.get(0)).optional()?)
524    }
525
526    /// Sets the Vault `profile` keeps its sign-ins in; Personal clears the row.
527    pub fn signin_vault_set(&self, profile: &str, vault_id: &str) -> Result<(), StoreError> {
528        let conn = self.conn.lock().unwrap();
529        if vault_id == PERSONAL_VAULT {
530            conn.execute("DELETE FROM db_vault_signin_vaults WHERE profile = ?1", params![profile])?;
531        } else {
532            conn.execute(
533                "INSERT INTO db_vault_signin_vaults (profile, vault_id) VALUES (?1, ?2) ON CONFLICT(profile) DO UPDATE SET vault_id = ?2",
534                params![profile, vault_id],
535            )?;
536        }
537        Ok(())
538    }
539
540    /// Puts an entry in another Vault, keeping its id, versions and grants. False if there is no such entry.
541    pub fn vault_move_entry(&self, entry_id: &str, vault_id: &str) -> Result<bool, StoreError> {
542        let conn = self.conn.lock().unwrap();
543        Ok(conn.execute("UPDATE db_vault_entries SET vault_id = ?2 WHERE id = ?1", params![entry_id, vault_id])? > 0)
544    }
545
546    pub fn vault_count(&self) -> Result<i64, StoreError> {
547        let conn = self.conn.lock().unwrap();
548        Ok(conn.query_row("SELECT COUNT(*) FROM db_vault_entries", [], |r| r.get(0))?)
549    }
550
551    /// Notes that an entry was used at `at_ms`.
552    pub fn vault_touch(&self, id: &str, at_ms: i64) -> Result<(), StoreError> {
553        let conn = self.conn.lock().unwrap();
554        conn.execute("UPDATE db_vault_entries SET last_used_at = ?2 WHERE id = ?1", params![id, at_ms])?;
555        Ok(())
556    }
557
558    /// Inserts and updates many entries in one transaction: all of them or none.
559    /// An update replaces the row's kind, label, fields, tags and sealed parts.
560    pub fn vault_write_many(&self, inserts: &[VaultRow], updates: &[VaultRow]) -> Result<(), StoreError> {
561        let conn = self.conn.lock().unwrap();
562        let tx = conn.unchecked_transaction()?;
563        for row in inserts {
564            tx.execute(
565                &format!("INSERT INTO db_vault_entries ({COLUMNS}) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)"),
566                params![row.id, row.kind, row.label, row.fields, row.tags, row.sealed, row.created_at, row.updated_at, row.last_used_at, row.vault_id],
567            )?;
568        }
569        for row in updates {
570            let n = tx.execute(
571                "UPDATE db_vault_entries SET kind = ?2, label = ?3, fields = ?4, tags = ?5, sealed = ?6, updated_at = ?7 WHERE id = ?1",
572                params![row.id, row.kind, row.label, row.fields, row.tags, row.sealed, row.updated_at],
573            )?;
574            if n == 0 {
575                return Err(StoreError::NotFound);
576            }
577        }
578        tx.commit()?;
579        Ok(())
580    }
581
582    /// Whether a MuxBus sign-in is kept, and whose, read from its row alone:
583    /// its tokens are in the keychain, and reading them could ask the person.
584    pub fn vault_kept_muxbus_user(&self) -> Result<Option<String>, StoreError> {
585        let conn = self.conn.lock().unwrap();
586        Ok(conn
587            .query_row("SELECT user_email FROM db_muxbus_credentials WHERE id = 'global'", [], |r| r.get(0))
588            .optional()?)
589    }
590
591    /// Notes that `instance` shows a Vault pane until `until_ms`, or (0)
592    /// that it no longer does. Notes expired by `now_ms` go too: a pane in a
593    /// window that crashed never clears its own.
594    pub fn vault_on_screen_set(&self, instance: &str, until_ms: i64, now_ms: i64) -> Result<(), StoreError> {
595        let conn = self.conn.lock().unwrap();
596        conn.execute("DELETE FROM db_vault_on_screen WHERE until_ms <= ?1", params![now_ms])?;
597        if until_ms <= 0 {
598            conn.execute("DELETE FROM db_vault_on_screen WHERE instance = ?1", params![instance])?;
599        } else {
600            conn.execute(
601                "INSERT OR REPLACE INTO db_vault_on_screen (instance, until_ms) VALUES (?1, ?2)",
602                params![instance, until_ms],
603            )?;
604        }
605        Ok(())
606    }
607
608    /// Every entry's link id that has one: entry id to link id.
609    pub fn vault_link_ids(&self) -> Result<std::collections::HashMap<String, String>, StoreError> {
610        let conn = self.conn.lock().unwrap();
611        let mut stmt = conn.prepare("SELECT entry_id, link_id FROM db_vault_link_ids")?;
612        let rows = stmt.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))?;
613        Ok(rows.collect::<Result<_, _>>()?)
614    }
615
616    /// Gives `entry_id` the link id `link_id` unless it has one: the one it keeps. `None` when `link_id` is taken by
617    /// another entry (the caller draws again).
618    pub fn vault_link_id_assign(&self, entry_id: &str, link_id: &str) -> Result<Option<String>, StoreError> {
619        let conn = self.conn.lock().unwrap();
620        let kept: Option<String> = conn
621            .query_row("SELECT link_id FROM db_vault_link_ids WHERE entry_id = ?1", params![entry_id], |r| r.get(0))
622            .optional()?;
623        if kept.is_some() {
624            return Ok(kept);
625        }
626        let n = conn.execute("INSERT OR IGNORE INTO db_vault_link_ids (entry_id, link_id) VALUES (?1, ?2)", params![entry_id, link_id])?;
627        Ok((n > 0).then(|| link_id.to_string()))
628    }
629
630    /// The entry a link id names, if it still exists.
631    pub fn vault_entry_of_link(&self, link_id: &str) -> Result<Option<String>, StoreError> {
632        let conn = self.conn.lock().unwrap();
633        Ok(conn
634            .query_row(
635                "SELECT l.entry_id FROM (SELECT entry_id, link_id FROM db_vault_link_ids UNION ALL SELECT entry_id, link_id FROM db_vault_link_aliases) l JOIN db_vault_entries e ON e.id = l.entry_id WHERE l.link_id = ?1",
636                params![link_id],
637                |r| r.get(0),
638            )
639            .optional()?)
640    }
641
642    /// Whether any AgentMux instance shows a Vault pane at `now_ms`.
643    pub fn vault_on_screen(&self, now_ms: i64) -> Result<bool, StoreError> {
644        let conn = self.conn.lock().unwrap();
645        let n: i64 = conn.query_row("SELECT COUNT(*) FROM db_vault_on_screen WHERE until_ms > ?1", params![now_ms], |r| r.get(0))?;
646        Ok(n > 0)
647    }
648
649    /// Appends a line to the activity log and chains it: the store gives it its `seq`, its `version` (the entry's
650    /// count of value-setting lines that went through, plus this one if it is one) and its place in the hash
651    /// chain, all in one transaction. Returns the line as stored.
652    pub fn vault_activity_add(&self, row: &VaultActivityRow) -> Result<VaultActivityRow, StoreError> {
653        let mut conn = self.conn.lock().unwrap();
654        // Immediate: the store is shared by every AgentMux process on the computer, and the chain's tip is read and then
655        // written, so a second process must wait (busy_timeout) rather than read the same tip and lose its line.
656        let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
657        let mut row = row.clone();
658        row.seq = tx
659            .query_row("SELECT seq FROM sqlite_sequence WHERE name = 'db_vault_activity'", [], |r| r.get::<_, i64>(0))
660            .optional()?
661            .unwrap_or(0)
662            + 1;
663        row.version = if row.entry_id.is_empty() { 0 } else { activity_version(&tx, &row)? };
664        row.prev_hash = tx
665            .query_row("SELECT hash FROM db_vault_activity WHERE hash != '' ORDER BY seq DESC LIMIT 1", [], |r| r.get::<_, String>(0))
666            .optional()?
667            .unwrap_or_default();
668        row.hash = activity_hash(&row.prev_hash, &row);
669        tx.execute(
670            "INSERT INTO db_vault_activity (seq, at, entry_id, entry_label, actor, action, target, outcome, version, actor_kind, host, reason, refs, prev_hash, hash) \
671             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15)",
672            params![
673                row.seq, row.at, row.entry_id, row.entry_label, row.actor, row.action, row.target, row.outcome, row.version, row.actor_kind, row.host,
674                row.reason, row.refs, row.prev_hash, row.hash
675            ],
676        )?;
677        tx.commit()?;
678        Ok(row)
679    }
680
681    /// The latest `limit` activity rows, newest first.
682    pub fn vault_activity_list(&self, limit: i64) -> Result<Vec<VaultActivityRow>, StoreError> {
683        let conn = self.conn.lock().unwrap();
684        let mut stmt = conn.prepare(&format!("SELECT {ACTIVITY_COLUMNS} FROM db_vault_activity ORDER BY seq DESC LIMIT ?1"))?;
685        let rows = stmt.query_map(params![limit], activity_of)?;
686        Ok(rows.collect::<Result<_, _>>()?)
687    }
688
689    /// The activity rows after number `seq`, oldest first: the lines this machine has made since a sync last looked.
690    pub fn vault_activity_after(&self, seq: i64) -> Result<Vec<VaultActivityRow>, StoreError> {
691        let conn = self.conn.lock().unwrap();
692        let mut stmt = conn.prepare(&format!("SELECT {ACTIVITY_COLUMNS} FROM db_vault_activity WHERE seq > ?1 ORDER BY seq"))?;
693        let rows = stmt.query_map(params![seq], activity_of)?;
694        Ok(rows.collect::<Result<_, _>>()?)
695    }
696
697    /// Every activity row, oldest first: what the hash chain is checked over.
698    pub fn vault_activity_all(&self) -> Result<Vec<VaultActivityRow>, StoreError> {
699        let conn = self.conn.lock().unwrap();
700        let mut stmt = conn.prepare(&format!("SELECT {ACTIVITY_COLUMNS} FROM db_vault_activity ORDER BY seq"))?;
701        let rows = stmt.query_map([], activity_of)?;
702        Ok(rows.collect::<Result<_, _>>()?)
703    }
704
705    /// One entry's latest `limit` activity rows of every action, from `since_ms` on (so a deleted entry whose id was
706    /// reused lends the new one none of its lines), newest first.
707    pub fn vault_activity_history(&self, entry_id: &str, since_ms: i64, limit: i64) -> Result<Vec<VaultActivityRow>, StoreError> {
708        let conn = self.conn.lock().unwrap();
709        let mut stmt = conn.prepare(&format!("SELECT {ACTIVITY_COLUMNS} FROM db_vault_activity WHERE entry_id = ?1 AND at >= ?2 ORDER BY seq DESC LIMIT ?3"))?;
710        let rows = stmt.query_map(params![entry_id, since_ms, limit], activity_of)?;
711        Ok(rows.collect::<Result<_, _>>()?)
712    }
713
714    /// One history line by its number.
715    pub fn vault_activity_get(&self, seq: i64) -> Result<Option<VaultActivityRow>, StoreError> {
716        let conn = self.conn.lock().unwrap();
717        Ok(conn.query_row(&format!("SELECT {ACTIVITY_COLUMNS} FROM db_vault_activity WHERE seq = ?1"), params![seq], activity_of).optional()?)
718    }
719
720    /// The lines agents wrote that are changes to look at (`actions`), from `since_ms` on, newest first.
721    pub fn vault_activity_agent_changes(&self, since_ms: i64, actions: &[&str], entry: Option<&str>, include_seen: bool, limit: i64) -> Result<Vec<VaultActivityRow>, StoreError> {
722        let conn = self.conn.lock().unwrap();
723        let marks = vec!["?"; actions.len()].join(", ");
724        let mut args: Vec<rusqlite::types::Value> = vec![since_ms.into()];
725        args.extend(actions.iter().map(|a| rusqlite::types::Value::from(a.to_string())));
726        let mut filters = String::new();
727        if let Some(entry) = entry {
728            filters.push_str(" AND entry_id = ?");
729            args.push(entry.to_string().into());
730        }
731        if !include_seen {
732            filters.push_str(" AND seq > COALESCE((SELECT through_seq FROM db_vault_changes_seen_all WHERE id = 1), 0) AND NOT EXISTS (SELECT 1 FROM db_vault_changes_seen WHERE db_vault_changes_seen.seq = db_vault_activity.seq)");
733        }
734        args.push(limit.into());
735        let mut stmt = conn.prepare(&format!(
736            "SELECT {ACTIVITY_COLUMNS} FROM db_vault_activity WHERE actor_kind = 'agent' AND at >= ? AND action IN ({marks}) AND (outcome = 'done' OR outcome = 'waiting for the person') AND entry_id != ''{filters} ORDER BY seq DESC LIMIT ?"
737        ))?;
738        let rows = stmt.query_map(rusqlite::params_from_iter(args), activity_of)?;
739        Ok(rows.collect::<Result<_, _>>()?)
740    }
741
742    /// The first line of the entry's history from `since_ms` on (its `created_at`): who made it.
743    pub fn vault_activity_first(&self, entry_id: &str, since_ms: i64) -> Result<Option<VaultActivityRow>, StoreError> {
744        let conn = self.conn.lock().unwrap();
745        let mut stmt = conn.prepare(&format!("SELECT {ACTIVITY_COLUMNS} FROM db_vault_activity WHERE entry_id = ?1 AND at >= ?2 ORDER BY seq ASC LIMIT 1"))?;
746        let mut rows = stmt.query_map(params![entry_id, since_ms], activity_of)?;
747        Ok(rows.next().transpose()?)
748    }
749
750    /// One entry's latest `limit` activity rows with one of `actions`, from
751    /// `since_ms` on, newest first. Filtered by action, so its many uses never
752    /// push these out; bounded by time, so a deleted entry whose id was reused
753    /// lends the new one none of its lines.
754    pub fn vault_activity_for_entry(&self, entry_id: &str, actions: &[&str], since_ms: i64, limit: i64) -> Result<Vec<VaultActivityRow>, StoreError> {
755        let conn = self.conn.lock().unwrap();
756        let marks = vec!["?"; actions.len()].join(", ");
757        let mut stmt = conn.prepare(&format!(
758            "SELECT {ACTIVITY_COLUMNS} FROM db_vault_activity WHERE entry_id = ? AND action IN ({marks}) AND at >= ? ORDER BY seq DESC LIMIT ?"
759        ))?;
760        let mut args: Vec<rusqlite::types::Value> = vec![entry_id.to_string().into()];
761        args.extend(actions.iter().map(|a| rusqlite::types::Value::from(a.to_string())));
762        args.push(since_ms.into());
763        args.push(limit.into());
764        let rows = stmt.query_map(rusqlite::params_from_iter(args), activity_of)?;
765        Ok(rows.collect::<Result<_, _>>()?)
766    }
767}
768
769/// The version `row` is made under: the number of the entry's value-setting lines that went through, one more when this
770/// is one. A line that touches no value is 0. Counts the lines since the entry was last deleted, so one whose id came
771/// round again starts at 1.
772fn activity_version(tx: &rusqlite::Transaction<'_>, row: &VaultActivityRow) -> Result<i64, StoreError> {
773    let sets = VALUE_SETTING.contains(&row.action.as_str());
774    if !sets && !VALUE_USES.contains(&row.action.as_str()) {
775        return Ok(0);
776    }
777    let since: i64 =
778        tx.query_row("SELECT COALESCE(MAX(seq), 0) FROM db_vault_activity WHERE entry_id = ?1 AND action = 'deleted'", params![row.entry_id], |r| r.get(0))?;
779    let marks = vec!["?"; VALUE_SETTING.len()].join(", ");
780    let mut args: Vec<rusqlite::types::Value> = vec![row.entry_id.clone().into(), since.into()];
781    args.extend(VALUE_SETTING.iter().map(|a| rusqlite::types::Value::from(a.to_string())));
782    let made: i64 = tx.query_row(
783        &format!("SELECT COUNT(*) FROM db_vault_activity WHERE entry_id = ? AND seq > ? AND outcome = 'done' AND action IN ({marks})"),
784        rusqlite::params_from_iter(args),
785        |r| r.get(0),
786    )?;
787    Ok(if sets && row.outcome == "done" { made + 1 } else { made })
788}
789
790#[cfg(test)]
791mod tests {
792    use super::*;
793
794    fn store() -> Store {
795        let s = Store::open_in_memory().unwrap();
796        s.apply_identity_schema_for_tests().unwrap();
797        s
798    }
799
800    fn row(id: &str, label: &str) -> VaultRow {
801        VaultRow {
802            id: id.into(),
803            kind: "ssn".into(),
804            label: label.into(),
805            fields: "{}".into(),
806            tags: "[]".into(),
807            sealed: vec![1, 2, 3],
808            created_at: 1,
809            updated_at: 1,
810            last_used_at: 0,
811            vault_id: PERSONAL_VAULT.into(),
812        }
813    }
814
815    #[test]
816    fn a_saved_browser_sign_in_is_listed_without_a_password_and_forgotten_when_deleted() {
817        let s = store();
818        s.browser_signin_note("id-a", "https://intranet.example.com", "Admin", false, "ab***", 10).unwrap();
819        s.browser_signin_note("id-a", "https://proxy.example.com:8080", "", true, "*", 20).unwrap();
820        // The same site saved again replaces its row, not adds one.
821        s.browser_signin_note("id-a", "https://intranet.example.com", "Admin", false, "cd***", 30).unwrap();
822        assert_eq!(
823            s.browser_signins().unwrap(),
824            vec![("https://intranet.example.com".to_string(), "Admin".to_string(), false, "cd***".to_string()), ("https://proxy.example.com:8080".to_string(), String::new(), true, "*".to_string())],
825            "newest first"
826        );
827        // Another identity's sign-in for the same site is its own row, and deleting one leaves the other.
828        s.browser_signin_note("id-b", "https://intranet.example.com", "Admin", false, "ef***", 40).unwrap();
829        s.browser_signin_forget("id-a", "https://intranet.example.com", "Admin", false).unwrap();
830        let left: Vec<String> = s.browser_signins().unwrap().into_iter().map(|r| r.3).collect();
831        assert_eq!(left, vec!["ef***".to_string(), "*".to_string()]);
832        // Forgetting one that isn't there is fine.
833        s.browser_signin_forget("id-z", "https://nowhere.example", "", false).unwrap();
834    }
835
836    #[test]
837    fn entries_insert_update_list_and_delete() {
838        let s = store();
839        s.vault_insert(&row("b", "beta")).unwrap();
840        s.vault_insert(&row("a", "Alpha")).unwrap();
841        assert_eq!(s.vault_list().unwrap().iter().map(|r| r.id.as_str()).collect::<Vec<_>>(), ["a", "b"], "by label");
842        let mut changed = row("a", "Alpha 2");
843        changed.sealed = vec![9];
844        changed.updated_at = 5;
845        assert!(s.vault_update(&changed).unwrap());
846        let got = s.vault_get("a").unwrap().unwrap();
847        assert_eq!((got.label.as_str(), got.sealed.clone(), got.created_at, got.updated_at), ("Alpha 2", vec![9], 1, 5));
848        assert!(!s.vault_update(&row("missing", "x")).unwrap());
849        assert!(s.vault_delete("a").unwrap());
850        assert!(!s.vault_delete("a").unwrap());
851        assert_eq!(s.vault_count().unwrap(), 1);
852    }
853
854    #[test]
855    fn a_grant_is_for_one_entry_and_one_site_and_goes_with_the_entry() {
856        let s = store();
857        s.vault_insert(&row("a", "A")).unwrap();
858        s.vault_insert(&row("b", "B")).unwrap();
859        // An entry deleted while its prompt was open: the late "Always" writes nothing.
860        s.vault_grant_add("gone", "https://irs.gov", 1, 1).unwrap();
861        assert!(s.vault_grants().unwrap().is_empty());
862        s.vault_grant_add("a", "https://irs.gov", 1, 1).unwrap();
863        s.vault_grant_add("a", "https://irs.gov", 2, 1).unwrap();
864        s.vault_grant_add("a", "https://ssa.gov", 3, 1).unwrap();
865        // The same id with another `created_at` is a different entry.
866        s.vault_grant_add("b", "https://irs.gov", 4, 99).unwrap();
867        assert!(!s.vault_grant_check("b", "https://irs.gov").unwrap());
868        assert!(s.vault_grant_check("a", "https://irs.gov").unwrap());
869        assert!(!s.vault_grant_check("a", "https://evil.example").unwrap(), "another site");
870        assert!(!s.vault_grant_check("b", "https://irs.gov").unwrap(), "another entry");
871        assert_eq!(s.vault_grants().unwrap()["a"], ["https://irs.gov", "https://ssa.gov"]);
872        assert!(s.vault_grant_revoke("a", "https://irs.gov").unwrap());
873        assert!(!s.vault_grant_revoke("a", "https://irs.gov").unwrap());
874        assert!(!s.vault_grant_check("a", "https://irs.gov").unwrap(), "a revoked grant asks again");
875        s.vault_delete("a").unwrap();
876        assert!(s.vault_grants().unwrap().is_empty(), "deleting an entry deletes its grants");
877    }
878
879    #[test]
880    fn on_screen_lasts_until_it_expires_or_is_cleared() {
881        let s = store();
882        assert!(!s.vault_on_screen(100).unwrap());
883        s.vault_on_screen_set("a", 200, 100).unwrap();
884        assert!(s.vault_on_screen(100).unwrap());
885        assert!(!s.vault_on_screen(200).unwrap(), "expired");
886        s.vault_on_screen_set("a", 300, 100).unwrap();
887        s.vault_on_screen_set("a", 0, 100).unwrap();
888        assert!(!s.vault_on_screen(100).unwrap(), "cleared");
889        // A note that expired is deleted by the next write, not only ignored.
890        s.vault_on_screen_set("crashed", 200, 100).unwrap();
891        s.vault_on_screen_set("b", 900, 500).unwrap();
892        let rows: i64 = s.conn.lock().unwrap().query_row("SELECT COUNT(*) FROM db_vault_on_screen", [], |r| r.get(0)).unwrap();
893        assert_eq!(rows, 1);
894    }
895
896    #[test]
897    fn activity_lists_newest_first() {
898        let s = store();
899        for (i, action) in ["created", "changed", "deleted"].iter().enumerate() {
900            s.vault_activity_add(&VaultActivityRow {
901                at: i as i64,
902                entry_id: "a".into(),
903                entry_label: "Alpha".into(),
904                actor: "you".into(),
905                action: action.to_string(),
906                target: String::new(),
907                outcome: "done".into(),
908                ..Default::default()
909            })
910            .unwrap();
911        }
912        let got = s.vault_activity_list(2).unwrap();
913        assert_eq!(got.iter().map(|r| r.action.as_str()).collect::<Vec<_>>(), ["deleted", "changed"]);
914    }
915}
916
917impl Store {
918    /// Runs `sql` on the identity store: how a test stands in for someone editing the database by hand.
919    #[cfg(test)]
920    pub fn vault_run_sql_for_tests(&self, sql: &str) {
921        self.conn.lock().unwrap().execute_batch(sql).unwrap();
922    }
923}