Cotton code
587 lines · 27.7 KB · RustRaw
//! A LOCAL VAULT KEY IS LET GO ONLY ON POSITIVE EVIDENCE (KEPT FOUR 2, review of 26955e4ba5, 27 Nov 2026; KEPT FOUR 3://! the key in a file of its own, let go only on what the server holds).//!//! A database started on this phone before sign-in founds a vault of its own (`founding::personal`): a vault master//! key (VMK), wrapped to this device's vault key in a `cotton_vault_keys` row of that local copy. That wrap is the ONLY//! place the key exists. A row sealed under it opens only while the wrap is held.//!//! When the local database leaves into the signed-in one, either the key founded the account (a first-ever sign-in://! its wrap was carried up and the account holds it), or the account had a vault of its own, and every row sealed//! under the local key is opened with it and sealed again under the account's key (`cotton-ffi`'s `vault_carry`).//! Until one of those is shown, the copy holding the wrap is never removed: this module answers how many rows still//! depend on it, from what the two copies hold, never from a table's name.//!//! The rows that can depend on it ([`SEALED`]): every kit table that seals a column under the VMK and travels, each//! with why; a lint test reads the kits so a new one cannot be missed. The person key (`cotton_person_keys`) is sealed//! under it too, but it is the local database's own identity (`founding::FOUNDING_TABLES`) and never travels: it goes//! with the copy that holds the key, and nothing outside depends on it. The data key (`seal_key` `dk_enc`) is carried//! by its own rule (`cotton-ffi`'s `seal::ensure`: the account keeps its own, or takes the local one wrapped under the//! account's VMK), never posted under the local key.use std::collections::BTreeMap;use std::path::{Path, PathBuf};/// Every travelling table that seals a column under the vault master key: its store table, the sealed columns, and why.pub const SEALED: &[(&str, &[&str], &str)] = &[    ("cotton_secrets", &["value_enc", "history_enc"], "a password or secret, and its earlier values (`keys::password_row`, `keys::history`)"),    ("cotton_passkey", &["private_key_enc"], "a passkey's private key (`keys::passkey_row`)"),];/// The kit tables that hold a `vmk_version` and are NOT in [`SEALED`], each with why (the lint's other half).pub const NOT_SEALED_HERE: &[(&str, &str)] = &[    ("person_key", "the local database's own identity: it never travels (`founding::FOUNDING_TABLES`), and goes with the key"),    ("vault_key", "the wraps of the key itself, to each device: the key's own rows, never sealed under it"),    ("seal_key", "the data key, carried by its own rule (`seal::ensure`), never posted under the local key"),    ("thread", "names a vault key's version in a view; it seals nothing"),];/// A vault key a copy holds: a wrap of its VMK to one device's vault key.#[derive(Debug, Clone, PartialEq, Eq)]pub struct LocalKey {    pub id: String,    pub device_id: String,    pub public_key: String,    pub wrapped_vmk: String,    pub vmk_version: i64,}fn open_read_only(path: &Path) -> Result<rusqlite::Connection, String> {    rusqlite::Connection::open_with_flags(path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX).map_err(|error| format!("{} does not open ({error})", path.display()))}fn has_table(db: &rusqlite::Connection, table: &str) -> Result<bool, String> {    db.query_row("SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = ?", [table], |row| row.get::<_, i64>(0)).map(|n| n > 0).map_err(|error| error.to_string())}fn columns_of(db: &rusqlite::Connection, table: &str) -> Result<Vec<String>, String> {    let mut statement = db.prepare(&format!("PRAGMA table_info(\"{table}\")")).map_err(|error| error.to_string())?;    let names = statement.query_map([], |row| row.get::<_, String>(1)).map_err(|error| error.to_string())?.collect::<Result<Vec<_>, _>>().map_err(|error| error.to_string());    names}/// The vault keys the copy at `path` holds: every wrapped `cotton_vault_keys` row.pub fn local_keys(path: &Path) -> Result<Vec<LocalKey>, String> {    let db = open_read_only(path)?;    if !has_table(&db, "cotton_vault_keys")? {        return Ok(Vec::new());    }    let mut statement = db        .prepare("SELECT id, device_id, public_key, wrapped_vmk, COALESCE(vmk_version, 0) FROM cotton_vault_keys WHERE wrapped_vmk IS NOT NULL AND wrapped_vmk <> ''")        .map_err(|error| error.to_string())?;    let keys = statement        .query_map([], |row| Ok(LocalKey { id: row.get(0)?, device_id: row.get::<_, Option<String>>(1)?.unwrap_or_default(), public_key: row.get::<_, Option<String>>(2)?.unwrap_or_default(), wrapped_vmk: row.get(3)?, vmk_version: row.get(4)? }))        .map_err(|error| error.to_string())?        .collect::<Result<Vec<_>, _>>()        .map_err(|error| error.to_string());    keys}/// A row sealed under a key, by its table and id, with its sealed columns' values.#[derive(Debug, Clone, PartialEq, Eq)]pub struct SealedRow {    pub table: &'static str,    pub id: String,    pub sealed: BTreeMap<String, String>,}/// Every row of [`SEALED`] the copy at `path` holds, live or binned, with its sealed values.pub fn sealed_rows(path: &Path) -> Result<Vec<SealedRow>, String> {    let db = open_read_only(path)?;    let mut rows = Vec::new();    for (table, columns, _) in SEALED {        if !has_table(&db, table)? {            continue;        }        let present = columns_of(&db, table)?;        let held: Vec<&str> = columns.iter().copied().filter(|column| present.iter().any(|name| name == column)).collect();        if held.is_empty() {            continue;        }        let select = held.iter().map(|column| format!("\"{column}\"")).collect::<Vec<_>>().join(", ");        let mut statement = db.prepare(&format!("SELECT id, {select} FROM \"{table}\"")).map_err(|error| error.to_string())?;        let found = statement            .query_map([], |row| {                let mut sealed = BTreeMap::new();                for (n, column) in held.iter().enumerate() {                    if let Some(value) = row.get::<_, Option<String>>(n + 1)? {                        if !value.is_empty() {                            sealed.insert((*column).to_string(), value);                        }                    }                }                Ok(SealedRow { table, id: row.get(0)?, sealed })            })            .map_err(|error| error.to_string())?            .collect::<Result<Vec<_>, _>>()            .map_err(|error| error.to_string())?;        rows.extend(found.into_iter().filter(|row| !row.sealed.is_empty()));    }    Ok(rows)}/// KEPT FOUR 3 LOW: of `candidates` (store table, id), the rows the copy at `copy` holds that name one of `ids` in a/// column (a link to a row sealed under the local key, held back with it: it waits with it, quietly, and goes after/// it). A table or row the copy does not hold names nothing.pub fn rows_naming(copy: &Path, ids: &std::collections::BTreeSet<String>, candidates: &[(String, String)]) -> Result<std::collections::BTreeSet<(String, String)>, String> {    let mut naming = std::collections::BTreeSet::new();    if ids.is_empty() || candidates.is_empty() {        return Ok(naming);    }    let db = open_read_only(copy)?;    for (table, id) in candidates {        if ids.contains(id) || !table.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') || !has_table(&db, table)? {            continue;        }        let columns = columns_of(&db, table)?;        if !columns.iter().any(|column| column == "id") {            continue;        }        let select = columns.iter().map(|column| format!("\"{column}\"")).collect::<Vec<_>>().join(", ");        let found = db.query_row(&format!("SELECT {select} FROM \"{table}\" WHERE id = ?"), [id], |row| {            Ok((0..columns.len()).any(|n| matches!(row.get_ref(n), Ok(rusqlite::types::ValueRef::Text(text)) if ids.contains(String::from_utf8_lossy(text).as_ref()))))        });        match found {            Ok(true) => {                naming.insert((table.clone(), id.clone()));            }            Ok(false) | Err(rusqlite::Error::QueryReturnedNoRows) => {}            Err(error) => return Err(error.to_string()),        }    }    Ok(naming)}// ── THE LOCAL KEY'S OWN FILE (KEPT FOUR 3 B, C, D) ───────────────────────────────────────────────────────────────//// The wrap of a local vault key lives in a file of its own, `<root>/vault-keys/<local database>.json`, written the// moment the local vault is founded (`cotton-ffi`'s `founding::local_personal`), again before the local database// leaves (the adopt, `copy_keep::retire`), and at every open for a phone an older build left with a key only in a// copy. Its lifetime is its own: no copy, folder or kept-rows list holds the only wrap, so no removal anywhere (inside// `copy_keep` or outside it) can take the key. The file goes by ONE function, [`let_go`], which takes a [`Settled`]:// a proof only [`evidence`] makes, and only from what the SERVER holds.//// The file also records the rows sealed under the key, as the local database held them when it was secured (from// its own copy only, never a `.before-update` one: a password deleted before sign-in is in no row the local copy// holds, so it is never recorded, never carried and never asked of the server), and, per row, the server's version// once the server holds its re-sealed form ([`KeyFile::carried`]), written durably./// The folder the key files live in, beside every database's folder.const KEYS_DIR: &str = "vault-keys";/// The wraps let go of, by hash: a kept folder holding one of them may go ([`copies_may_go`]).const SETTLED_FILE: &str = "settled.json";/// One wrap of a local vault key, as the key file keeps it.#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]pub struct HeldKey {    pub id: String,    #[serde(rename = "deviceId")]    pub device_id: String,    #[serde(rename = "publicKey")]    pub public_key: String,    #[serde(rename = "wrappedVmk")]    pub wrapped_vmk: String,    #[serde(rename = "vmkVersion")]    pub vmk_version: i64,}impl From<LocalKey> for HeldKey {    fn from(key: LocalKey) -> Self {        HeldKey { id: key.id, device_id: key.device_id, public_key: key.public_key, wrapped_vmk: key.wrapped_vmk, vmk_version: key.vmk_version }    }}/// A row sealed under the local key, as the local copy held it.#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]pub struct RecordedRow {    pub table: String,    pub id: String,    pub sealed: BTreeMap<String, String>,}/// What `<root>/vault-keys/<local database>.json` holds.#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]pub struct KeyFile {    #[serde(rename = "localDatabase")]    pub local_database: String,    /// The database the local one left into, once it did.    #[serde(default)]    pub account: Option<String>,    #[serde(default)]    pub keys: Vec<HeldKey>,    #[serde(default)]    pub sealed: Vec<RecordedRow>,    /// `<store table>/<id>` → the server's version of the row once the server holds it sealed under another key.    #[serde(default)]    pub carried: BTreeMap<String, i64>,    /// The server took this key's founding wrap: the account's key IS this key.    #[serde(default)]    pub founded: bool,    /// The rows sealed under the key were read from the local database's own copy ([`secure`]). A file made from a    /// wrap alone ([`secure_wrap`]) knows no rows: it goes only when the server holds that very wrap.    #[serde(default, rename = "rowsKnown")]    pub rows_known: bool,}fn keys_dir(layout: &crate::layout::Layout) -> PathBuf {    layout.root().join(KEYS_DIR)}/// A database id as a file name: anything but a letter, digit, `-` or `_` is spelled out, so no id reaches outside.fn file_name(local_database: &str) -> String {    let mut name = String::new();    for c in local_database.chars() {        if c.is_ascii_alphanumeric() || c == '-' || c == '_' {            name.push(c);        } else {            name.push_str(&format!("~{:x}", c as u32));        }    }    format!("{name}.json")}fn key_path(layout: &crate::layout::Layout, local_database: &str) -> PathBuf {    keys_dir(layout).join(file_name(local_database))}/// Written whole and durably: to a file of its own, synced, renamed over, and the folder synced.fn write_durably(path: &Path, bytes: &[u8]) -> Result<(), String> {    let dir = path.parent().ok_or("a key file has a folder")?;    std::fs::create_dir_all(dir).map_err(|error| error.to_string())?;    let next = path.with_extension("json.next");    // not a copy: the local vault key's own file, written whole first.    std::fs::write(&next, bytes).map_err(|error| error.to_string())?;    std::fs::File::open(&next).and_then(|file| file.sync_all()).map_err(|error| error.to_string())?;    // not a copy: put in place in one step.    std::fs::rename(&next, path).map_err(|error| error.to_string())?;    std::fs::File::open(dir).and_then(|folder| folder.sync_all()).map_err(|error| error.to_string())}fn read_file(path: &Path) -> Result<Option<KeyFile>, String> {    match std::fs::read(path) {        Ok(bytes) => serde_json::from_slice(&bytes).map(Some).map_err(|error| format!("{} does not read ({error})", path.display())),        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),        Err(error) => Err(error.to_string()),    }}fn write_file(layout: &crate::layout::Layout, file: &KeyFile) -> Result<(), String> {    write_durably(&key_path(layout, &file.local_database), &serde_json::to_vec_pretty(file).map_err(|error| error.to_string())?)}/// The key file of `local_database`, if any.pub fn key_file(layout: &crate::layout::Layout, local_database: &str) -> Result<Option<KeyFile>, String> {    read_file(&key_path(layout, local_database))}/// Every key file this phone holds. One that does not read is an error: the caller keeps everything.pub fn key_files(layout: &crate::layout::Layout) -> Result<Vec<KeyFile>, String> {    let dir = keys_dir(layout);    let mut files = Vec::new();    let entries = match std::fs::read_dir(&dir) {        Ok(entries) => entries,        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(files),        Err(error) => return Err(error.to_string()),    };    for entry in entries.flatten() {        let path = entry.path();        if path.extension().is_some_and(|ext| ext == "json") && path.file_name().is_some_and(|name| name != SETTLED_FILE) {            if let Some(file) = read_file(&path)? {                files.push(file);            }        }    }    files.sort_by(|a, b| a.local_database.cmp(&b.local_database));    Ok(files)}/// Whether `copy` is a `.before-update` copy (kept by an upgrade): read for its keys, never for its rows.fn before_update(copy: &Path) -> bool {    copy.file_name().and_then(|name| name.to_str()).is_some_and(|name| name.ends_with(".before-update"))}/// SECURE THE KEY: every vault key wrap `copies` hold goes into `local_database`'s key file (kept with any already/// there: a wrap is never dropped), and the rows sealed under it are recorded as the local database's own copy holds/// them now (never a `.before-update` copy's). `account` names the database it leaves into, when it does. Answers how/// many wraps the file holds; with none in the copies and no file, nothing is written.pub fn secure(layout: &crate::layout::Layout, local_database: &str, copies: &[PathBuf], account: Option<&str>) -> Result<usize, String> {    let mut keys = Vec::new();    for copy in copies {        keys.extend(local_keys(copy)?);    }    // A wrap already let go (`let_go`, on the evidence) never comes back as a key file: a kept copy still holds it, and    // the adopt and the kept folder secure from that copy again (the real-Worker race walk, 28 Nov 2026).    if !keys.is_empty() {        let settled = settled_hashes(layout)?;        keys.retain(|key| !settled.contains(&hash_of(&key.wrapped_vmk)));    }    let existing = key_file(layout, local_database)?;    if keys.is_empty() && existing.is_none() {        return Ok(0);    }    let mut file = existing.unwrap_or_else(|| KeyFile { local_database: local_database.to_string(), ..KeyFile::default() });    let before = file.clone();    for key in keys {        if !file.keys.iter().any(|held| held.wrapped_vmk == key.wrapped_vmk) {            file.keys.push(key.into());        }    }    if let Some(own) = copies.iter().find(|copy| !before_update(copy)) {        if !file.keys.is_empty() {            let mut sealed: Vec<RecordedRow> = sealed_rows(own)?.into_iter().map(|row| RecordedRow { table: row.table.to_string(), id: row.id, sealed: row.sealed }).collect();            sealed.sort_by(|a, b| (&a.table, &a.id).cmp(&(&b.table, &b.id)));            file.sealed = sealed;            file.rows_known = true;        }    }    if let Some(account) = account {        file.account = Some(account.to_string());    }    if file != before {        write_file(layout, &file)?;    }    Ok(file.keys.len())}/// Secure one wrap given as a row (an older build's `kept-rows.json` kept a refused founding row): into the key file.pub fn secure_wrap(layout: &crate::layout::Layout, local_database: &str, key: HeldKey) -> Result<(), String> {    if settled_hashes(layout)?.contains(&hash_of(&key.wrapped_vmk)) {        return Ok(());    }    let mut file = key_file(layout, local_database)?.unwrap_or_else(|| KeyFile { local_database: local_database.to_string(), ..KeyFile::default() });    if file.keys.iter().any(|held| held.wrapped_vmk == key.wrapped_vmk) {        return Ok(());    }    file.keys.push(key);    write_file(layout, &file)}/// The server took this key's founding wrap (a first-ever sign-in): the account's key is this key.pub fn note_founded(layout: &crate::layout::Layout, local_database: &str, account: &str) -> Result<(), String> {    let Some(mut file) = key_file(layout, local_database)? else { return Ok(()) };    file.founded = true;    file.account = Some(account.to_string());    write_file(layout, &file)}/// The person let go of a row sealed under the key (its change let go of in a kept copy): nothing waits for it.pub fn forget_row(layout: &crate::layout::Layout, local_database: &str, table: &str, id: &str) -> Result<(), String> {    let Some(mut file) = key_file(layout, local_database)? else { return Ok(()) };    let before = file.sealed.len();    file.sealed.retain(|row| !(row.table == table && row.id == id));    if file.sealed.len() != before {        write_file(layout, &file)?;    }    Ok(())}/// One row as the server answered it in a complete read.#[derive(Debug, Clone, PartialEq, Eq)]pub struct ServerRow {    pub version: i64,    pub deleted: bool,    /// Its sealed columns, by the store's column names.    pub sealed: BTreeMap<String, String>,}/// A COMPLETE read of the server's rows sealed under the vault, and its vault key wraps: made only by/// [`ServerReading::finish`] on a reading whose last page said there was no next one.#[derive(Debug, Clone, PartialEq, Eq)]pub struct ServerRead {    rows: BTreeMap<(String, String), ServerRow>,    wraps: std::collections::BTreeSet<String>,}/// A read of the server under way, page by page.#[derive(Debug, Default)]pub struct ServerReading {    rows: BTreeMap<(String, String), ServerRow>,    wraps: std::collections::BTreeSet<String>,}impl ServerReading {    /// One row of a page: `table` a store table, `sealed` its sealed columns by store names.    pub fn row(&mut self, table: &str, id: &str, row: ServerRow) {        self.rows.insert((table.to_string(), id.to_string()), row);    }    /// A live vault key wrap the server holds.    pub fn wrap(&mut self, wrapped_vmk: &str) {        self.wraps.insert(wrapped_vmk.to_string());    }    /// The read, only when the last page said there was none after it.    #[must_use]    pub fn finish(self, last_page_said_no_next: bool) -> Option<ServerRead> {        last_page_said_no_next.then_some(ServerRead { rows: self.rows, wraps: self.wraps })    }}/// THE PROOF a local key may go: made only here, by [`evidence`]; [`let_go`] takes it.#[derive(Debug, Clone, PartialEq, Eq)]pub struct Settled {    local_database: String,    wraps: Vec<String>,}/// What the evidence says of a key file.#[derive(Debug, Clone, PartialEq, Eq)]pub enum Evidence {    /// The key may go: the server took its founding, or holds every row sealed under it sealed again (or removed).    Settled(Settled),    /// Rows the server still holds under the local key, or does not hold at all yet: the key stays.    Depends(Vec<(String, String)>),    /// No complete server read: the key stays.    NotRead,}/// THE ONE QUESTION of a local vault key (KEPT FOUR 3 C): may it go? Judged from the key file (what was recorded,/// what the server was seen to hold) and a COMPLETE server read, never from what a live copy holds:/// - the server took its founding: settled;/// - else, with no complete read: not settled;/// - else every recorded row must be held by the server, removed there, or held live with no sealed column the local///   key sealed (sealed again: by this phone's carry, or changed by another device since). A row the server does not///   hold (the push not yet accepted, or refused) and a row still holding a value the local key sealed (a history///   only half sealed again too) keep it./// Answers the evidence and the rows to note as carried (each with the server's version).#[must_use]pub fn evidence(file: &KeyFile, read: Option<&ServerRead>) -> (Evidence, Vec<(String, i64)>) {    let settled = || Evidence::Settled(Settled { local_database: file.local_database.clone(), wraps: file.keys.iter().map(|key| key.wrapped_vmk.clone()).collect() });    if file.founded {        return (settled(), Vec::new());    }    let Some(read) = read else { return (Evidence::NotRead, Vec::new()) };    if file.keys.iter().any(|key| read.wraps.contains(&key.wrapped_vmk)) {        // The server holds this very wrap live: the key founded the account (its founding taken by an older build).        return (settled(), Vec::new());    }    if !file.rows_known {        return (Evidence::NotRead, Vec::new());    }    let mut depends = Vec::new();    let mut carried = Vec::new();    for row in &file.sealed {        match read.rows.get(&(row.table.clone(), row.id.clone())) {            None => depends.push((row.table.clone(), row.id.clone())),            Some(held) if held.deleted => {}            Some(held) => {                let local_left = row.sealed.iter().any(|(column, value)| held.sealed.get(column) == Some(value));                if local_left {                    depends.push((row.table.clone(), row.id.clone()));                } else {                    carried.push((format!("{}/{}", row.table, row.id), held.version));                }            }        }    }    if depends.is_empty() { (settled(), carried) } else { (Evidence::Depends(depends), carried) }}/// Judge `local_database`'s key against a complete server read (or none), note durably what the server holds/// carried, and let the key go when settled. Answers the evidence.pub fn settle(layout: &crate::layout::Layout, local_database: &str, read: Option<&ServerRead>) -> Result<Evidence, String> {    let Some(mut file) = key_file(layout, local_database)? else { return Ok(Evidence::NotRead) };    let (said, carried) = evidence(&file, read);    let mut changed = false;    for (row, version) in carried {        if file.carried.get(&row) != Some(&version) {            file.carried.insert(row, version);            changed = true;        }    }    if changed {        write_file(layout, &file)?;    }    if let Evidence::Settled(proof) = &said {        let_go(layout, proof.clone())?;    }    Ok(said)}fn hash_of(wrapped_vmk: &str) -> String {    use sha2::Digest as _;    hex::encode(sha2::Sha256::digest(wrapped_vmk.as_bytes()))}fn settled_hashes(layout: &crate::layout::Layout) -> Result<std::collections::BTreeSet<String>, String> {    match std::fs::read(keys_dir(layout).join(SETTLED_FILE)) {        Ok(bytes) => serde_json::from_slice(&bytes).map_err(|error| format!("the settled keys do not read ({error})")),        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Default::default()),        Err(error) => Err(error.to_string()),    }}/// THE ONE FUNCTION a local vault key's file goes by (KEPT FOUR 3 D): only with a [`Settled`], which only/// [`evidence`] makes. The wraps it held are written down as let go first (by hash), so a kept folder holding a copy/// of one may go too ([`copies_may_go`]).pub fn let_go(layout: &crate::layout::Layout, proof: Settled) -> Result<(), String> {    let mut hashes = settled_hashes(layout)?;    hashes.extend(proof.wraps.iter().map(|wrap| hash_of(wrap)));    write_durably(&keys_dir(layout).join(SETTLED_FILE), &serde_json::to_vec(&hashes).map_err(|error| error.to_string())?)?;    // not a copy: the local vault key's own file, its key proven no longer needed.    match std::fs::remove_file(key_path(layout, &proof.local_database)) {        Ok(()) => Ok(()),        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),        Err(error) => Err(error.to_string()),    }}/// Whether copies holding vault key wraps may go, as far as the vault goes: every wrap they hold was let go of by/// [`let_go`]. A copy that does not read is an error: the caller keeps it.pub fn copies_may_go(layout: &crate::layout::Layout, copies: &[PathBuf]) -> Result<bool, String> {    let mut keys = Vec::new();    for copy in copies {        keys.extend(local_keys(copy)?);    }    if keys.is_empty() {        return Ok(true);    }    let settled = settled_hashes(layout)?;    Ok(keys.iter().all(|key| settled.contains(&hash_of(&key.wrapped_vmk))))}/// How many wraps the copies hold that were not let go of (what keeps a kept folder, counted).pub fn held_open(layout: &crate::layout::Layout, copies: &[PathBuf]) -> Result<usize, String> {    let mut keys = Vec::new();    for copy in copies {        keys.extend(local_keys(copy)?);    }    let settled = if keys.is_empty() { Default::default() } else { settled_hashes(layout)? };    let mut open: Vec<&str> = keys.iter().filter(|key| !settled.contains(&hash_of(&key.wrapped_vmk))).map(|key| key.wrapped_vmk.as_str()).collect();    open.sort_unstable();    open.dedup();    Ok(open.len())}/// Whether the row `(table, id)` of a copy's [`SEALED`] tables is sealed again in the live copy: held there, with/// every sealed value different from the copy's (what a re-seal writes). A change of such a row, kept in an adopted/// copy, is carried.pub fn sealed_again(copy_row: &SealedRow, live: &Path) -> Result<bool, String> {    if !live.exists() {        return Ok(false);    }    let held = open_read_only(live)?;    if !has_table(&held, copy_row.table)? {        return Ok(false);    }    let present = columns_of(&held, copy_row.table)?;    let mut select = Vec::new();    for column in copy_row.sealed.keys() {        if present.iter().any(|name| name == column) {            select.push(column.clone());        }    }    if select.is_empty() {        return Ok(false);    }    let sql = format!("SELECT {} FROM \"{}\" WHERE id = ?", select.iter().map(|column| format!("\"{column}\"")).collect::<Vec<_>>().join(", "), copy_row.table);    let found = held.query_row(&sql, [&copy_row.id], |row| (0..select.len()).map(|n| row.get::<_, Option<String>>(n)).collect::<Result<Vec<_>, _>>());    match found {        Ok(values) => Ok(values.iter().zip(&select).all(|(value, column)| value.as_ref().is_some_and(|value| Some(value) != copy_row.sealed.get(column)))),        Err(rusqlite::Error::QueryReturnedNoRows) => Ok(false),        Err(error) => Err(error.to_string()),    }}#[cfg(test)]#[path = "vault_keep_tests.rs"]mod tests;