//! THE RE-SEAL (KEPT FOUR 2 decision b; KEPT FOUR 3 B, C, LOW): a local database founded its own vault before //! sign-in and was adopted into an account that already had one (or another phone founded it first). Every row sealed //! under the local vault key is opened with it and sealed again under the account's key, on this phone, whenever the //! vault is opened (`vault::opened_vmk`, every path): the one moment the core holds this device's vault private key, //! which opens both wraps (the local key's and the account's are wrapped to the same device key). //! //! The local key comes from its own file (`cotton_client::vault_keep`), never from a kept copy, so no copy's removal //! can take it. The rows: //! - held back by the adopt (never posted): read from the local database's own copy in its kept folder (never a //! `.before-update` copy: a password deleted before sign-in is in no row of the local copy, so it never comes back), //! only rows the key file recorded, written into the signed-in copy sealed under the account's key; //! - held in the signed-in copy with any column still sealed under the local key (an older build carried it up as it //! was, or another phone half re-sealed it: a new value with its history still under the local key): each such //! column sealed again in place, the history too; //! - rows that link to a held-back row (a passkey's, a placement's): written after it, as they stand. //! //! Resumable: each row is judged afresh, one write per row. The key goes only on the SERVER's evidence: after a pass, //! [`settle_after_pass`] reads every page of the server's sealed rows and wraps and lets the key go //! (`vault_keep::settle`) only when the server holds every row sealed again (or removed). use std::collections::{BTreeMap, BTreeSet}; use std::path::{Path, PathBuf}; use base64::engine::general_purpose::URL_SAFE_NO_PAD; use base64::Engine as _; use serde_json::{json, Map, Value}; use cotton_core::vault::Vmk; use crate::shell::client::ClientController; /// What one carry did. #[derive(Debug, Default, Clone, PartialEq, Eq)] pub struct Carried { /// Rows written into the signed-in copy, sealed under the account's key (held back by the adopt). pub written: usize, /// Rows sealed again in place, column by column. pub sealed_again: usize, /// Rows linking to a held-back row, written after it. pub linked: usize, /// Rows that could not be opened with the local key (left as they are; the key stays). pub unopened: usize, } fn read_only(copy: &Path) -> Result { rusqlite::Connection::open_with_flags(copy, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX).map_err(|error| error.to_string()) } fn read_rows(copy: &Path, table: &str, only: Option<&BTreeSet>) -> Result>, String> { if !copy.exists() || !table.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') { return Ok(Vec::new()); } let db = read_only(copy)?; let held: i64 = db.query_row("SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = ?", [table], |row| row.get(0)).map_err(|error| error.to_string())?; if held == 0 { return Ok(Vec::new()); } let mut statement = db.prepare(&format!("SELECT * FROM \"{table}\"")).map_err(|error| error.to_string())?; let names: Vec = statement.column_names().map(str::to_string).collect(); let rows = statement .query_map([], |row| { let mut map = Map::new(); for (n, name) in names.iter().enumerate() { let value = match row.get_ref(n)? { rusqlite::types::ValueRef::Null => Value::Null, rusqlite::types::ValueRef::Integer(i) => Value::from(i), rusqlite::types::ValueRef::Real(f) => Value::from(f), rusqlite::types::ValueRef::Text(text) => Value::from(String::from_utf8_lossy(text).into_owned()), rusqlite::types::ValueRef::Blob(_) => continue, }; map.insert(name.clone(), value); } Ok(map) }) .map_err(|error| error.to_string())? .collect::, _>>() .map_err(|error| error.to_string())?; Ok(rows.into_iter().filter(|row| only.is_none_or(|ids| row.get("id").and_then(Value::as_str).is_some_and(|id| ids.contains(id)))).collect()) } /// The local vault keys this device's private key opens: from every key file this phone holds. fn local_vmks(layout: &cotton_client::layout::Layout, secret: &[u8; 32]) -> Result, String> { let public = URL_SAFE_NO_PAD.encode(cotton_core::vault::wrap::public_of(secret)); let mut vmks = Vec::new(); for file in cotton_client::vault_keep::key_files(layout)? { for key in &file.keys { if key.public_key != public { continue; } let Some(bytes) = cotton_core::vault::unwrap(secret, &key.wrapped_vmk) else { continue }; let Ok(bytes): Result<[u8; 32], _> = bytes.try_into() else { continue }; vmks.push((file.local_database.clone(), Vmk::from_bytes(bytes))); } } Ok(vmks) } /// The columns of `row` that open under one of `locals`, each sealed again under `account` at `version`. `whole`: /// every sealed column must open (a held-back row), else `None`. fn sealed_anew(row: &Map, id: &str, columns: &[&'static str], locals: &[&Vmk], account: &Vmk, version: u32, whole: bool) -> Option> { let mut patch = Map::new(); for column in columns { if row.get(*column).and_then(Value::as_str).is_none_or(str::is_empty) { continue; } let opened = locals.iter().find_map(|local| cotton_core::keys::sealed_row::open(row, id, local, column).ok()); match opened { Some(bytes) => { let sealed = cotton_core::keys::sealed_row::seal(account, id, version, &bytes).ok()?; patch.insert((*column).to_string(), Value::from(sealed)); } None if whole => return None, None => {} } } if patch.is_empty() { return None; } patch.insert("vmk_version".to_string(), Value::from(version)); Some(patch) } /// The local database's own copy in a kept folder: never a `.before-update` one. fn own_copies(kept: &cotton_client::copy_keep::Kept) -> Result, String> { Ok(cotton_client::copy_keep::copies_kept(kept)?.into_iter().filter(|copy| !copy.to_string_lossy().ends_with(".before-update")).collect()) } /// Carry every row sealed under a local vault key into the open database, sealed under `account` (the account's /// key, just opened) at `version`. `secret` is this device's vault private key, held for the length of this call. pub(crate) fn carry(client: &ClientController, secret: &[u8; 32], account: &Vmk, version: u32) -> Result { let mut carried = Carried::default(); if !client.signed_in() { return Ok(carried); } let database = client.current_database()?; let layout = client.layout().clone(); let files: BTreeMap = cotton_client::vault_keep::key_files(&layout)?.into_iter().filter(|file| file.account.as_deref().is_none_or(|into| into == database)).map(|file| (file.local_database.clone(), file)).collect(); if files.is_empty() { return Ok(carried); } let locals = local_vmks(&layout, secret)?; if locals.is_empty() { return Ok(carried); } let all_locals: Vec<&Vmk> = locals.iter().map(|(_, vmk)| vmk).collect(); let live = layout.replica(&database); let gone = tombstoned(&live)?; // (table, id, patch, in place) let mut work: Vec<(String, String, Map, bool)> = Vec::new(); let mut planned: BTreeSet<(String, String)> = BTreeSet::new(); // In place: every row of the signed-in copy with a column still sealed under a local key, the history too. for (table, columns, _) in cotton_client::vault_keep::SEALED { for row in read_rows(&live, table, None)? { let Some(id) = row.get("id").and_then(Value::as_str).map(str::to_string) else { continue }; if let Some(patch) = sealed_anew(&row, &id, columns, &all_locals, account, version, false) { planned.insert((table.to_string(), id.clone())); work.push((table.to_string(), id, patch, true)); carried.sealed_again += 1; } } } // Held back: from each kept folder adopted from a local database whose key waits, its own copy's recorded rows. let mut linked_work: Vec<(String, String, Map)> = Vec::new(); for kept in cotton_client::copy_keep::kept(&layout, Some(&database)) { let Some(local_database) = kept.state.adopted_from.clone() else { continue }; let Some(file) = files.get(&local_database) else { continue }; let mine: Vec<&Vmk> = locals.iter().filter(|(of, _)| *of == local_database).map(|(_, vmk)| vmk).collect(); if mine.is_empty() { continue; } for copy in own_copies(&kept)? { let let_go: BTreeSet<(String, String)> = cotton_client::copy_keep::changes_in(©)?.into_iter().filter(|change| kept.state.let_go.contains(&change.op_id)).map(|change| (change.table, change.row_id)).collect(); let rename = |value: &Value| match value.as_str() { Some(text) if text == local_database => Value::from(database.clone()), _ => value.clone(), }; let mut held_ids: BTreeSet = BTreeSet::new(); for (table, columns, _) in cotton_client::vault_keep::SEALED { let recorded: BTreeSet = file.sealed.iter().filter(|row| row.table == *table).map(|row| row.id.clone()).collect(); for row in read_rows(©, table, Some(&recorded))? { let Some(id) = row.get("id").and_then(Value::as_str).map(str::to_string) else { continue }; let key = (table.to_string(), id.clone()); if let_go.contains(&key) || planned.contains(&key) || gone.contains(&key) || live_holds(&live, table, &id)? { continue; } let Some(mut patch) = sealed_anew(&row, &id, columns, &mine, account, version, true) else { carried.unopened += 1; continue; }; for (column, value) in &row { if column.starts_with('_') || column == "id" || patch.contains_key(column) || value.is_null() { continue; } patch.insert(column.clone(), rename(value)); } planned.insert(key); held_ids.insert(id.clone()); work.push((table.to_string(), id, patch, false)); carried.written += 1; } } // The rows that link to a held-back row, as they stand, after it (KEPT FOUR 3 LOW). if !held_ids.is_empty() { let candidates: Vec<(String, String)> = cotton_client::unsent::unsent_changes(©)?.into_iter().map(|change| (change.table, change.row_id)).filter(|key| !planned.contains(key) && !let_go.contains(key)).collect(); for (table, id) in cotton_client::vault_keep::rows_naming(©, &held_ids, &candidates)? { if gone.contains(&(table.clone(), id.clone())) || live_holds(&live, &table, &id)? { continue; } let only: BTreeSet = [id.clone()].into(); let Some(row) = read_rows(©, &table, Some(&only))?.into_iter().next() else { continue }; let patch: Map = row.iter().filter(|(column, value)| !column.starts_with('_') && *column != "id" && !value.is_null()).map(|(column, value)| (column.clone(), rename(value))).collect(); planned.insert((table.clone(), id.clone())); linked_work.push((table, id, patch)); carried.linked += 1; } } } } if work.is_empty() && linked_work.is_empty() { return Ok(carried); } // One write per row: a stop part way leaves each row done or not, never half. for (table, id, patch, in_place) in work.into_iter().chain(linked_work.into_iter().map(|(table, id, patch)| (table, id, patch, false))) { client .write_rows("vault.carry", &mut |ctx| { let written = if in_place { cotton_tools::mcp::handlers::common::update_row(ctx, &table, &id, patch.clone()) } else { cotton_tools::mcp::handlers::common::insert_row(ctx, &table, &id, patch.clone()) }; written.map_err(|failure| failure.to_string())?; Ok(Value::Null) }) .map_err(|error| format!("{table} {id} was not carried: {error}"))?; } eprintln!("[vault-carry] {} written, {} sealed again, {} linked, {} not opened with the local key", carried.written, carried.sealed_again, carried.linked, carried.unopened); client.nudge_sync(); Ok(carried) } fn live_holds(live: &Path, table: &str, id: &str) -> Result { if !live.exists() || !table.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') { return Ok(false); } let db = read_only(live)?; let held: i64 = db.query_row("SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = ?", [table], |row| row.get(0)).map_err(|error| error.to_string())?; if held == 0 { return Ok(false); } db.query_row(&format!("SELECT COUNT(*) FROM \"{table}\" WHERE id = ?"), [id], |row| row.get::<_, i64>(0)).map(|n| n > 0).map_err(|error| error.to_string()) } /// The rows the copy at `live` holds a removal of, by store table and id. fn tombstoned(live: &Path) -> Result, String> { if !live.exists() { return Ok(Default::default()); } let db = read_only(live)?; let held: i64 = db.query_row("SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = '_tombstones'", [], |row| row.get(0)).map_err(|error| error.to_string())?; if held == 0 { return Ok(Default::default()); } let mut statement = db.prepare("SELECT tbl, row_id FROM _tombstones").map_err(|error| error.to_string())?; let rows = statement.query_map([], |row| Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))).map_err(|error| error.to_string())?.collect::>().map_err(|error| error.to_string()); rows } /// A COMPLETE read of the server's rows sealed under the vault, and its vault key wraps, every page (KEPT FOUR 3 C): /// `None` when any page is not answered or the pages do not end. fn read_server(client: &ClientController) -> Result, String> { let Some(door) = client.object_door() else { return Ok(None) }; let tables = cotton_client::transport::object::ObjectTables::personal(); let mut wanted: Vec = vec!["vault_key".to_string()]; for (store, _, _) in cotton_client::vault_keep::SEALED { if let Some(table) = tables.ours(store) { wanted.push(table.table.clone()); } } let mut reading = cotton_client::vault_keep::ServerReading::default(); let mut path = format!("/v1/sync?since=0&tables={}&limit=1000", wanted.join(",")); for _ in 0..200 { let page = match door.send("GET", &path, None) { Ok(page) => page, Err(refusal) => { eprintln!("[vault-carry] the server's rows were not read ({}): the local key stays", refusal.message); return Ok(None); } }; for row in page["rows"].as_array().into_iter().flatten() { let (Some(name), Some(id)) = (row["table"].as_str(), row["id"].as_str()) else { continue }; let deleted = row["deleted"] == json!(true); if name == "vault_key" { if let Some(wrap) = row["data"]["wrapped_vmk"].as_str().filter(|wrap| !wrap.is_empty() && !deleted) { reading.wrap(wrap); } continue; } let Some(table) = tables.object(name) else { continue }; let Some((_, columns, _)) = cotton_client::vault_keep::SEALED.iter().find(|(store, _, _)| *store == table.store) else { continue }; let mut sealed = BTreeMap::new(); for (object, ours, _) in &table.columns { if columns.contains(&ours.as_str()) { if let Some(value) = row["data"][object.as_str()].as_str().filter(|value| !value.is_empty()) { sealed.insert(ours.clone(), value.to_string()); } } } for column in columns.iter() { if !sealed.contains_key(*column) { if let Some(value) = row["data"][*column].as_str().filter(|value| !value.is_empty()) { sealed.insert((*column).to_string(), value.to_string()); } } } reading.row(&table.store, id, cotton_client::vault_keep::ServerRow { version: row["version"].as_i64().unwrap_or(0), deleted, sealed }); } match page["next"].as_str() { Some(next) => path = format!("/v1/sync?cursor={next}"), None => return Ok(reading.finish(true)), } } Ok(None) } /// After a pass (KEPT FOUR 3 C): every local key adopted into this database is judged against a complete read of the /// server, what the server holds sealed again is noted, and a key whose every row the server holds goes. pub fn settle_after_pass(client: &ClientController) { if !client.signed_in() { return; } let Ok(database) = client.current_database() else { return }; let layout = client.layout().clone(); let files: Vec<_> = cotton_client::vault_keep::key_files(&layout).unwrap_or_default().into_iter().filter(|file| file.account.as_deref() == Some(database.as_str())).collect(); if files.is_empty() { return; } let read = match read_server(client) { Ok(read) => read, Err(reason) => { eprintln!("[vault-carry] the server was not read: {reason}"); None } }; for file in files { match cotton_client::vault_keep::settle(&layout, &file.local_database, read.as_ref()) { Ok(cotton_client::vault_keep::Evidence::Settled(_)) => eprintln!("[vault-carry] a local vault key is let go: the server holds everything sealed under it sealed again"), Ok(cotton_client::vault_keep::Evidence::Depends(rows)) => eprintln!("[vault-carry] a local vault key stays: {} row(s) the server does not yet hold sealed again", rows.len()), Ok(cotton_client::vault_keep::Evidence::NotRead) => {} Err(reason) => eprintln!("[vault-carry] a local vault key was not judged: {reason}"), } } } /// VAULT GUARD 2 item 2b: this device declares the identity of the key it opened (`vmk_check`, re-declaring its own /// row unchanged, which is what the object pins by) only on proof it holds the ACCOUNT's key: it opened, with that /// key, a row of the account sealed under the vault that this device never wrote (a row another device sealed, or /// stored before this sign-in); or, in an account with nothing sealed, its own row is the only wrapped one (its /// founding was the one the object took). A phone holding only its local key never gets here (nothing opens). pub(crate) fn declare(client: &ClientController, secret: &[u8; 32], vmk: &Vmk, version: u32) { use std::sync::{Mutex, OnceLock}; static DECLARED: OnceLock>> = OnceLock::new(); if !client.signed_in() { return; } let Ok(database) = client.current_database() else { return }; let said = DECLARED.get_or_init(|| Mutex::new(BTreeSet::new())); if said.lock().map(|said| said.contains(&(database.clone(), version))).unwrap_or(true) { return; } let Some(device) = client.self_device_id() else { return }; let live = client.layout().replica(&database); let Ok(proof) = proves_the_account_key(&live, &device, vmk) else { return }; if !proof { return; } let public = URL_SAFE_NO_PAD.encode(cotton_core::vault::wrap::public_of(secret)); let Ok(Some((id, wrapped))) = own_row(&live, &device, &public, version) else { return }; let Some(door) = client.object_door() else { return }; let body = json!({ "act": "update", "args": { "table": "vault_key", "id": id, "data": { "wrapped_vmk": wrapped, "vmk_version": version }, "vmk_check": cotton_core::vault::identity::of(vmk, version) } }); match door.send("POST", "/v1/act", Some(&body)) { Ok(_) => { if let Ok(mut said) = said.lock() { said.insert((database, version)); } } Err(refusal) => eprintln!("[vault] this device's key identity was not declared ({}): asked again at the next open", refusal.code), } } /// This device's own non-founder wrapped row at `version`, the oldest: its id and wrap. fn own_row(live: &Path, device: &str, public: &str, version: u32) -> Result, String> { let db = read_only(live)?; let found = db.query_row( "SELECT id, wrapped_vmk FROM cotton_vault_keys WHERE device_id = ? AND public_key = ? AND COALESCE(vmk_version, 0) = ? AND wrapped_vmk IS NOT NULL AND wrapped_vmk <> '' AND id NOT LIKE 'founder:%' ORDER BY created_at, id LIMIT 1", rusqlite::params![device, public, version], |row| Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)), ); match found { Ok(row) => Ok(Some(row)), Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None), Err(error) => Err(error.to_string()), } } /// Whether `vmk` opens a row of the copy sealed under the vault that `device` never wrote; or nothing is sealed and /// this device's rows are the only wrapped ones. fn proves_the_account_key(live: &Path, device: &str, vmk: &Vmk) -> Result { let db = read_only(live)?; let has_writes: i64 = db.query_row("SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = '_writes'", [], |row| row.get(0)).map_err(|error| error.to_string())?; let mut anything_sealed = false; for (table, columns, _) in cotton_client::vault_keep::SEALED { for row in read_rows(live, table, None)? { let Some(id) = row.get("id").and_then(Value::as_str).map(str::to_string) else { continue }; let sealed: Vec<&&str> = columns.iter().filter(|column| row.get(**column).and_then(Value::as_str).is_some_and(|value| !value.is_empty())).collect(); if sealed.is_empty() { continue; } anything_sealed = true; let mine = has_writes > 0 && db.query_row("SELECT COUNT(*) FROM _writes WHERE tbl = ? AND row_id = ? AND author = ?", rusqlite::params![table, id, device], |found| found.get::<_, i64>(0)).map_err(|error| error.to_string())? > 0; if mine { continue; } if sealed.iter().any(|column| cotton_core::keys::sealed_row::open(&row, &id, vmk, column).is_ok()) { return Ok(true); } } } if anything_sealed { return Ok(false); } let others: i64 = db .query_row("SELECT COUNT(*) FROM cotton_vault_keys WHERE wrapped_vmk IS NOT NULL AND wrapped_vmk <> '' AND COALESCE(device_id, '') <> ?", [device], |row| row.get(0)) .map_err(|error| error.to_string())?; Ok(others == 0) } // Tested end to end, two phones through one account: `adopt_tests` (KEPT FOUR 2, 3), and against the real Worker: // `personal_object_e2e` (`two_phones_founding_at_once_read_each_others_passwords`).