From 4944a0694bdb4f1733801ecb95b444062ac396c2 Mon Sep 17 00:00:00 2001 From: faumaray Date: Tue, 20 Oct 2026 08:23:55 +0300 Subject: [PATCH 1/6] Let a sign-out finish when a row's binding columns cannot be read SqliteKeyStore::list() failed on the first row whose binding columns were damaged outside this crate (synced = 2 on the account record, say), and KeyStore::sign_out starts with list() through bound_to(): it never reached the record, so it could never finish, and DeviceKeyChoice::Forget did not delete the key it was given either. get() failed the same way where sign_out reads the record and the device key. A row whose binding columns cannot be read (refused by AccountBinding::from_columns, or a value of the wrong type) is now listed and read as unbound, with a tracing warning that names the row and the reason and quotes no content. Unbound is the reading that never deletes on a guess: such a row is not deleted as a synced copy, and a put of it writes four good columns. A data column that is not text is read as text with the odd bytes replaced, so a record that cannot be read is deleted by the trait's sign_out instead of its read failing; a row whose kind or uid is not text cannot be addressed and the list leaves it out with a warning. list() now fails only when the database does. Tests: the gate's probe (UPDATE identities SET synced = 2 WHERE kind = 'account', then sign_out with Auto and with Forget on a store with bound_existing_key true and false), more damage to the record row, the device key row and a synced copy, and the unreadable data and kind/uid cases; the test that asserted the old precise errors of get() and list() now asserts the unbound reading. The six new tests fail on the previous keystore.rs. voelin-store gets the tracing dependency (already in the lock); Cargo.lock changes, THIRD_PARTY_NOTICES.md is unchanged by it. Co-Authored-By: Claude Sonnet 5.5 --- Cargo.lock | 1 + crates/voelin-store/Cargo.toml | 1 + crates/voelin-store/src/keystore.rs | 126 ++++++++--- crates/voelin-store/tests/keystore.rs | 309 ++++++++++++++++++++++++-- docs/architecture.md | 4 + 5 files changed, 382 insertions(+), 59 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 48fd03b..aea5df7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9703,6 +9703,7 @@ dependencies = [ "serde", "serde_json", "thiserror 2.0.21", + "tracing", "tsclientlib", "voelin-identity", ] diff --git a/crates/voelin-store/Cargo.toml b/crates/voelin-store/Cargo.toml index b20313f..56cb5ba 100644 --- a/crates/voelin-store/Cargo.toml +++ b/crates/voelin-store/Cargo.toml @@ -19,6 +19,7 @@ rusqlite = { version = "0.40.2", features = ["bundled"] } serde = { version = "1.0.229", features = ["derive"] } serde_json = "1.0.151" thiserror = "2.0.21" +tracing = "0.1.44" tsclientlib = { path = "../proto/tsclientlib" } voelin-identity = { workspace = true } diff --git a/crates/voelin-store/src/keystore.rs b/crates/voelin-store/src/keystore.rs index 8e0f2ef..f1fb940 100644 --- a/crates/voelin-store/src/keystore.rs +++ b/crates/voelin-store/src/keystore.rs @@ -24,6 +24,23 @@ //! `data` again. That is how [`KeyStore::sign_out`] unbinds a device-only //! secret, so a damaged row never blocks it. //! +//! A row that is damaged elsewhere never fails a call that is not about it. A +//! row whose binding columns cannot be read (`synced = 2`, an `account` that is +//! no uid, a revision that is no integer; only something outside this crate +//! writes them) is listed and read as unbound, and a warning names the row and +//! the reason. [`KeyStore::list`] fails only when the database does, because +//! the trait's [`KeyStore::sign_out`] starts with it and then reads the account +//! record and the device key with [`KeyStore::get`]: one damaged row, the +//! record's own included, would otherwise keep a sign-out from ever finishing, +//! and with it the deletion of the key the user asked to forget. Unbound is the +//! reading that never deletes on a guess: a sign-out neither deletes such a row +//! as a synced copy nor writes it, it stays as it is until a `put` of it writes +//! four good binding columns. A `data` column that is not text is read as text +//! with the odd bytes replaced, so that a record that cannot be read is deleted +//! by the sign-out, as the trait says, instead of its read failing; a row whose +//! `kind` or `uid` is not text cannot be addressed, and the list leaves it out +//! with a warning. +//! //! A TeamSpeak blob that is refused says why in words that carry none of its //! input: its `data` is the identity's private key, and an error reaches log //! lines. @@ -32,6 +49,7 @@ use std::path::Path; use std::sync::{Mutex, MutexGuard, PoisonError}; use rusqlite::params; +use rusqlite::types::ValueRef; use tsclientlib::Identity; use voelin_identity::migrate::SELECT_ACCOUNT_COLUMNS; use voelin_identity::{ @@ -46,7 +64,7 @@ type KsResult = std::result::Result; /// The rows of [`KeyStore::list`]. The secret of a kind this crate does not /// interpret is never read; a TeamSpeak row's `data` is, for its level. const LIST: &str = "SELECT kind, uid, CASE WHEN kind = 'teamspeak' THEN data END, - account, integration, integration_rev, synced + account, integration, integration_rev, synced, id FROM identities ORDER BY kind, uid"; /// Replace the binding of the row of this `(kind, uid)` if its `data` is @@ -118,16 +136,21 @@ impl KeyStore for SqliteKeyStore { let store = self.lock(); let mut statement = store.db.prepare_cached(LIST).map_err(backend)?; let rows = statement.query_map([], Columns::read).map_err(backend)?; - rows.map(|row| row.map_err(backend)?.into_info()).collect() + let mut infos = Vec::new(); + for row in rows { + infos.extend(row.map_err(backend)?.map(Columns::into_info)); + } + Ok(infos) } fn get(&self, kind: &str, uid: &str) -> KsResult> { let store = self.lock(); - let sql = - format!("SELECT {SELECT_ACCOUNT_COLUMNS} FROM identities WHERE kind = ?1 AND uid = ?2"); + let sql = format!( + "SELECT {SELECT_ACCOUNT_COLUMNS}, id FROM identities WHERE kind = ?1 AND uid = ?2" + ); let mut statement = store.db.prepare_cached(&sql).map_err(backend)?; let mut rows = statement.query_map(params![kind, uid], Columns::read).map_err(backend)?; - rows.next().transpose().map_err(backend)?.map(Columns::into_blob).transpose() + Ok(rows.next().transpose().map_err(backend)?.flatten().map(Columns::into_blob)) } fn put(&self, blob: &IdentityBlob) -> KsResult<()> { @@ -232,38 +255,48 @@ enum Refused { UidHeld { uid: String, kind: String }, } -/// One row of the table as `LIST` and `SELECT_ACCOUNT_COLUMNS` select it. +/// One row of the table as `LIST` and `SELECT_ACCOUNT_COLUMNS` select it (with +/// the row id last), its binding already read. struct Columns { kind: String, uid: String, /// The identity itself. `LIST` leaves it out for kinds with no level. data: Option, - account: Option, - integration: Option, - rev: i64, - synced: i64, + /// `None` for an unbound row and for one whose binding columns are damaged. + binding: Option, +} + +/// Why binding columns cannot be read. +#[derive(Debug, thiserror::Error)] +enum Damage { + #[error(transparent)] + Binding(#[from] BlobError), + #[error("a binding column holds a value of the wrong type")] + WrongType, } impl Columns { - fn read(row: &rusqlite::Row<'_>) -> rusqlite::Result { - Ok(Self { - kind: row.get(0)?, - uid: row.get(1)?, - data: row.get(2)?, - account: row.get(3)?, - integration: row.get(4)?, - rev: row.get(5)?, - synced: row.get(6)?, - }) - } - - fn binding(&self) -> KsResult> { - Ok(AccountBinding::from_columns( - self.account.as_deref(), - self.integration.as_deref(), - self.rev, - self.synced, - )?) + /// The row, or `None` for a row that cannot be addressed (its `kind` or + /// `uid` is not text) and is left out with a warning. + fn read(row: &rusqlite::Row<'_>) -> rusqlite::Result> { + let id: i64 = row.get(7)?; + let (Ok(kind), Ok(uid)) = (row.get_ref(0)?.as_str(), row.get_ref(1)?.as_str()) else { + tracing::warn!(id, "an identities row whose kind or uid is not text is left out"); + return Ok(None); + }; + let binding = read_binding(row).unwrap_or_else(|damage| { + tracing::warn!( + id, kind, uid, %damage, + "the binding columns of an identity cannot be read: it is treated as unbound", + ); + None + }); + Ok(Some(Self { + kind: kind.to_owned(), + uid: uid.to_owned(), + data: lossy_text(row.get_ref(2)?), + binding, + })) } /// The security level of a TeamSpeak row, 0 for any other kind and for JSON @@ -277,16 +310,39 @@ impl Columns { } } - fn into_info(self) -> KsResult { - let binding = self.binding()?; + fn into_info(self) -> IdentityInfo { let level = self.level(); - Ok(IdentityInfo { kind: self.kind, uid: self.uid, level, binding }) + IdentityInfo { kind: self.kind, uid: self.uid, level, binding: self.binding } } - fn into_blob(self) -> KsResult { - let binding = self.binding()?; + fn into_blob(self) -> IdentityBlob { let level = self.level(); let data = self.data.unwrap_or_default(); - Ok(IdentityBlob::from_row(&self.kind, self.uid, level, data).with_binding(binding)) + IdentityBlob::from_row(&self.kind, self.uid, level, data).with_binding(self.binding) + } +} + +/// The binding of a row from its four columns (3 to 6 of both selects). +fn read_binding(row: &rusqlite::Row<'_>) -> std::result::Result, Damage> { + let column = |index| row.get_ref(index).map_err(|_| Damage::WrongType); + let account = column(3)?.as_str_or_null().map_err(|_| Damage::WrongType)?; + let integration = column(4)?.as_str_or_null().map_err(|_| Damage::WrongType)?; + let rev = column(5)?.as_i64().map_err(|_| Damage::WrongType)?; + let synced = column(6)?.as_i64().map_err(|_| Damage::WrongType)?; + Ok(AccountBinding::from_columns(account, integration, rev, synced)?) +} + +/// A `data` column as text, whatever it holds. Bytes that are no UTF-8 and +/// values of another type are damage; read as text they fail where the +/// blob's kind is checked, with that kind's own error, instead of failing the +/// read of the row. +fn lossy_text(value: ValueRef<'_>) -> Option { + match value { + ValueRef::Null => None, + ValueRef::Integer(n) => Some(n.to_string()), + ValueRef::Real(x) => Some(x.to_string()), + ValueRef::Text(bytes) | ValueRef::Blob(bytes) => { + Some(String::from_utf8_lossy(bytes).into_owned()) + } } } diff --git a/crates/voelin-store/tests/keystore.rs b/crates/voelin-store/tests/keystore.rs index 2d5a396..8e4fdf5 100644 --- a/crates/voelin-store/tests/keystore.rs +++ b/crates/voelin-store/tests/keystore.rs @@ -26,7 +26,7 @@ use tsclientlib::Identity; use voelin_identity::{ AccountBinding, AccountId, AccountRecord, BlobError, DeviceKeyChoice, IdentityBlob, IdentityInfo, IdentityKey, IntegrationId, KIND_ACCOUNT, KIND_TEAMSPEAK, KIND_VOELIN, KeyStore, - KeyStoreError, SignOut, Uid, UidParseError, account_uid, + KeyStoreError, SignOut, Uid, account_uid, }; use voelin_store::{IdentityOrigin, SqliteKeyStore, Store}; @@ -408,37 +408,112 @@ fn the_account_record_goes_through_the_stores_own_accessors() { assert!(matches!(store.account_record(), Err(KeyStoreError::Blob(BlobError::AccountJson)))); } +/// The ways the binding columns of a row can be damaged outside this crate: +/// what `AccountBinding::from_columns` refuses, and values of the wrong type. +/// Each is applied to a row that has a good account. +const BINDING_DAMAGE: [&str; 11] = [ + "account = 'junk'", + "synced = 2", + "synced = -1", + "integration_rev = -3", + "integration = 'nope'", + // An integration, a revision or a flag without an account. + "account = NULL, integration = 'aaaqeayeaudaocajbifqydiob4'", + "account = NULL, integration_rev = 5", + "account = NULL, synced = 2", + // Values of another type than the column's. + "synced = 'yes'", + "integration_rev = 'many'", + "account = x'0102'", +]; + #[test] -fn damaged_binding_columns_are_precise_errors_when_read() { +fn a_row_whose_binding_columns_cannot_be_read_is_listed_and_read_as_unbound() { + // A listing that fails on one damaged row would keep a sign-out from ever + // finishing (it starts with the list), so the row reads as unbound, with a + // warning, and everything else about it is as stored. let scratch = Scratch::new("damaged"); let store = SqliteKeyStore::open(&scratch.db()).unwrap(); - store.put(&teamspeak_blob()).unwrap(); + let ts = teamspeak_blob(); + store.put(&ts).unwrap(); + let neighbour = fresh_teamspeak(binding()); + store.put(&neighbour).unwrap(); let db = Connection::open(scratch.db()).unwrap(); - let set = |sql: &str| { - db.execute(&format!("UPDATE identities SET {sql} WHERE uid = ?1"), [TEAMSPEAK_UID]).unwrap() + let account = binding_for(1); + let reset = || { + db.execute( + "UPDATE identities SET account = ?2, integration = NULL, integration_rev = 0, + synced = 0 WHERE uid = ?1", + [TEAMSPEAK_UID, &account.to_base32()], + ) + .unwrap(); }; - let read = || store.get(KIND_TEAMSPEAK, TEAMSPEAK_UID); - set("account = 'junk'"); - assert!(matches!( - read(), - Err(KeyStoreError::Blob(BlobError::BindingAccount(UidParseError::Length(4)))) - )); - // A listing fails the same way: a damaged row is reported, not skipped. - assert!(matches!(store.list(), Err(KeyStoreError::Blob(BlobError::BindingAccount(_))))); + reset(); + let bound = store.get(KIND_TEAMSPEAK, TEAMSPEAK_UID).unwrap().unwrap(); + assert_eq!(bound.binding.map(|b| b.account), Some(account)); + assert_eq!(store.bound_to(&account).unwrap().len(), 1); - set(&format!("account = '{}'", binding_for(1).to_base32())); - assert_eq!(read().unwrap().unwrap().binding.unwrap().account, binding_for(1)); + for damage in BINDING_DAMAGE { + reset(); + db.execute(&format!("UPDATE identities SET {damage} WHERE uid = ?1"), [TEAMSPEAK_UID]) + .unwrap(); + // Read: the identity, unbound, its JSON and level as stored. + let read = store.get(KIND_TEAMSPEAK, TEAMSPEAK_UID).unwrap().expect(damage); + assert_eq!(read, ts, "{damage}"); + assert_eq!(read.json, TEAMSPEAK_JSON, "{damage}"); + // Listed: still there, unbound, and its neighbour is untouched. + let listed = store.list().unwrap(); + assert_eq!(listed.len(), 2, "{damage}"); + let row = listed.iter().find(|i| i.uid == TEAMSPEAK_UID).expect(damage); + assert_eq!((row.binding, row.level), (None, TEAMSPEAK_LEVEL), "{damage}"); + let next = listed.iter().find(|i| i.uid == neighbour.uid).unwrap(); + assert_eq!(next.binding, neighbour.binding, "{damage}"); + // It belongs to no account as far as a sign-out can tell: not a guess. + assert!(store.bound_to(&account).unwrap().is_empty(), "{damage}"); + assert_eq!(store.bound_to(&binding().account).unwrap().len(), 1, "{damage}"); + } - set("synced = 2"); - assert!(matches!(read(), Err(KeyStoreError::Blob(BlobError::BindingSynced(2))))); - set("synced = 0, integration_rev = -3"); - assert!(matches!(read(), Err(KeyStoreError::Blob(BlobError::BindingRevision)))); - set("integration_rev = 0, integration = 'nope'"); - assert!(matches!(read(), Err(KeyStoreError::Blob(BlobError::BindingIntegration(_))))); - // An integration without an account. - set("account = NULL, integration = 'aaaqeayeaudaocajbifqydiob4'"); - assert!(matches!(read(), Err(KeyStoreError::Blob(BlobError::BindingOrphan)))); + // A put of the row writes four good columns, however it was damaged. + let rebound = ts.clone().with_binding(binding()); + store.put(&rebound).unwrap(); + assert_eq!(store.get(KIND_TEAMSPEAK, TEAMSPEAK_UID).unwrap().unwrap(), rebound); + let (synced, rev): (i64, i64) = db + .query_row( + "SELECT synced, integration_rev FROM identities WHERE uid = ?1", + [TEAMSPEAK_UID], + |r| Ok((r.get(0)?, r.get(1)?)), + ) + .unwrap(); + assert_eq!((synced, rev), (1, 3)); +} + +#[test] +fn a_row_that_cannot_be_addressed_is_left_out_of_the_list() { + // A `kind` or `uid` that is not text cannot be named in `get` or `remove`, + // so the list has nothing to show for it; it must not fail the others. + let scratch = Scratch::new("unaddressable"); + let store = SqliteKeyStore::open(&scratch.db()).unwrap(); + store.put(&teamspeak_blob()).unwrap(); + store.put_voelin_key(&key()).unwrap(); + let db = Connection::open(scratch.db()).unwrap(); + let id: i64 = db + .query_row("SELECT id FROM identities WHERE uid = ?1", [TEAMSPEAK_UID], |r| r.get(0)) + .unwrap(); + for (column, original) in [("uid", TEAMSPEAK_UID), ("kind", KIND_TEAMSPEAK)] { + db.execute(&format!("UPDATE identities SET {column} = x'0102' WHERE id = ?1"), [id]) + .unwrap(); + let listed = store.list().unwrap(); + assert_eq!(sorted(listed), [(KIND_VOELIN.to_owned(), RFC8032_UID.to_owned())], "{column}"); + assert!(store.get(KIND_TEAMSPEAK, TEAMSPEAK_UID).unwrap().is_none(), "{column}"); + db.execute( + &format!("UPDATE identities SET {column} = ?2 WHERE id = ?1"), + params![id, original], + ) + .unwrap(); + assert_eq!(store.list().unwrap().len(), 2, "{column}"); + } + assert_eq!(store.get(KIND_TEAMSPEAK, TEAMSPEAK_UID).unwrap().unwrap(), teamspeak_blob()); } // ------------------------------------- what the TeamSpeak methods share @@ -1168,3 +1243,189 @@ fn a_sign_out_is_durable_in_the_file() { .unwrap(); assert_eq!(account, None); } + +// ------------------------------- sign-out with damaged rows (the gate's probe) + +/// A signed-in install on a file, to damage through a second connection (as +/// something outside this crate could): the device key, the record with the +/// given key flag, a synced copy, a device-only secret and a local identity. +struct OnFile { + scratch: Scratch, + store: SqliteKeyStore, + synced: IdentityBlob, + device_only: IdentityBlob, + local: IdentityBlob, +} + +fn signed_in_install_on_file(bound_existing_key: bool) -> OnFile { + let scratch = Scratch::new("signed-in"); + let store = SqliteKeyStore::open(&scratch.db()).unwrap(); + let synced = fresh_teamspeak(binding()); + let device_only = fresh_teamspeak(AccountBinding { synced: false, ..binding() }); + let local = fresh_teamspeak(None); + store.put_voelin_key(&key()).unwrap(); + store.put_account_record(&AccountRecord { bound_existing_key, ..record() }).unwrap(); + for blob in [&synced, &device_only, &local] { + store.put(blob).unwrap(); + } + OnFile { scratch, store, synced, device_only, local } +} + +impl OnFile { + /// Run one statement on the file, which must change a row. + fn damage(&self, sql: &str) { + let db = Connection::open(self.scratch.db()).unwrap(); + assert_eq!(db.execute(sql, []).unwrap(), 1, "{sql}"); + } + + /// What a sign-out of `choice` must have done, whatever else was damaged: + /// the record and the synced copy are gone, the device-only secret is + /// unbound and the local identity is as it was; the device key is deleted + /// when the user forgot it or the client made it for the account, and + /// reported as kept and unbound otherwise. + fn assert_signed_out( + &self, + done: &SignOut, + bound_existing_key: bool, + choice: DeviceKeyChoice, + label: &str, + ) { + let key_goes = matches!(choice, DeviceKeyChoice::Forget(_)) || !bound_existing_key; + let mut removed = vec![(KIND_ACCOUNT.to_owned(), record().blob_uid()), pair(&self.synced)]; + let mut unbound = vec![pair(&self.device_only)]; + let device_key = (KIND_VOELIN.to_owned(), key().uid().to_base32()); + if key_goes { + removed.push(device_key) + } else { + unbound.push(device_key) + } + removed.sort(); + unbound.sort(); + assert_eq!(sorted(done.removed.clone()), removed, "{label}: {done:?}"); + assert_eq!(sorted(done.unbound.clone()), unbound, "{label}: {done:?}"); + + let store = &self.store; + assert!(store.get(KIND_ACCOUNT, &record().blob_uid()).unwrap().is_none(), "{label}"); + assert!(store.get(KIND_TEAMSPEAK, &self.synced.uid).unwrap().is_none(), "{label}"); + let secret = store.get(KIND_TEAMSPEAK, &self.device_only.uid).unwrap().unwrap(); + assert_eq!(secret, self.device_only.clone().with_binding(None), "{label}"); + assert_eq!(store.get(KIND_TEAMSPEAK, &self.local.uid).unwrap().unwrap(), self.local); + assert_eq!(store.voelin_key(&key().uid()).unwrap().is_none(), key_goes, "{label}"); + // A retry has nothing left to do. + assert_eq!( + store.sign_out(&binding().account, choice).unwrap(), + SignOut::default(), + "{label}" + ); + } +} + +/// The ways the row of the account record can be damaged in its binding +/// columns, the first being the gate's probe. +const RECORD_ROW_DAMAGE: [&str; 5] = [ + "UPDATE identities SET synced = 2 WHERE kind = 'account'", + "UPDATE identities SET account = 'junk' WHERE kind = 'account'", + "UPDATE identities SET integration = 'aaaqeayeaudaocajbifqydiob4' WHERE kind = 'account'", + "UPDATE identities SET integration_rev = 'many' WHERE kind = 'account'", + "UPDATE identities SET account = x'0102' WHERE kind = 'account'", +]; + +#[test] +fn a_damaged_account_record_row_does_not_keep_a_sign_out_from_finishing() { + // The record carries no binding, so damage in those columns says nothing + // about the record: it is read, and the sign-out does what it always does. + // `Forget` deletes the key it names; `Auto` follows the record. + for bound_existing_key in [true, false] { + for damage in RECORD_ROW_DAMAGE { + for choice in [DeviceKeyChoice::Auto, DeviceKeyChoice::Forget(key().uid())] { + let label = format!("{bound_existing_key}, {choice:?}, {damage}"); + let install = signed_in_install_on_file(bound_existing_key); + install.damage(damage); + let done = install + .store + .sign_out(&binding().account, choice) + .unwrap_or_else(|error| panic!("{label}: {error}")); + install.assert_signed_out(&done, bound_existing_key, choice, &label); + } + } + } +} + +#[test] +fn a_damaged_device_key_row_does_not_keep_a_sign_out_from_finishing() { + // With `Auto` and a key that predates the account, the trait reads the key + // to report it as kept. Damage in its binding columns must not fail that. + for bound_existing_key in [true, false] { + for damage in [ + "UPDATE identities SET synced = 2 WHERE kind = 'voelin'", + "UPDATE identities SET account = 'junk' WHERE kind = 'voelin'", + "UPDATE identities SET integration_rev = 'many' WHERE kind = 'voelin'", + ] { + let label = format!("{bound_existing_key}, {damage}"); + let install = signed_in_install_on_file(bound_existing_key); + install.damage(damage); + let done = install + .store + .sign_out(&binding().account, DeviceKeyChoice::Auto) + .unwrap_or_else(|error| panic!("{label}: {error}")); + install.assert_signed_out(&done, bound_existing_key, DeviceKeyChoice::Auto, &label); + if bound_existing_key { + // The key was kept, as it was stored. + let kept = install.store.voelin_key(&key().uid()).unwrap().unwrap(); + assert_eq!(&kept.to_pkcs8().unwrap()[..], &key().to_pkcs8().unwrap()[..]); + } + } + } +} + +#[test] +fn a_damaged_synced_copy_is_not_deleted_on_a_guess() { + // Its binding cannot be read, so a sign-out cannot know it is a copy of what + // the service holds: it stays, unbound as far as the store can tell, and the + // rest of the sign-out is done. + let install = signed_in_install_on_file(true); + install + .damage(&format!("UPDATE identities SET synced = 2 WHERE uid = '{}'", install.synced.uid)); + let done = install.store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap(); + assert_eq!(done.removed.len(), 1, "only the record: {done:?}"); + assert!(done.removed.iter().all(|i| i.kind == KIND_ACCOUNT), "{done:?}"); + let kept = install.store.get(KIND_TEAMSPEAK, &install.synced.uid).unwrap().unwrap(); + assert_eq!((kept.binding, kept.json.as_str()), (None, install.synced.json.as_str())); + assert_eq!(install.store.account_record().unwrap(), None); + let again = install.store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap(); + assert_eq!(again, SignOut::default()); +} + +#[test] +fn an_account_row_whose_data_is_not_text_is_deleted_like_an_unreadable_record() { + // A `data` column that holds bytes or a number reads as text that is no + // record: the trait deletes the record before it reports the error, so the + // sign-out finishes on the second call at the latest instead of failing the + // read for ever. `Forget` deletes the key it names first. + for damage in [ + "UPDATE identities SET data = x'ff00fe' WHERE kind = 'account'", + "UPDATE identities SET data = 5 WHERE kind = 'account'", + "UPDATE identities SET data = 1.5 WHERE kind = 'account'", + ] { + for choice in [DeviceKeyChoice::Auto, DeviceKeyChoice::Forget(key().uid())] { + let label = format!("{choice:?}, {damage}"); + let install = signed_in_install_on_file(true); + install.damage(damage); + let error = install.store.sign_out(&binding().account, choice).unwrap_err(); + assert!( + matches!(error, KeyStoreError::Blob(BlobError::AccountJson)), + "{label}: {error:?}" + ); + + let store = &install.store; + assert!(store.get(KIND_ACCOUNT, &record().blob_uid()).unwrap().is_none(), "{label}"); + assert!(store.get(KIND_TEAMSPEAK, &install.synced.uid).unwrap().is_none(), "{label}"); + let secret = store.get(KIND_TEAMSPEAK, &install.device_only.uid).unwrap().unwrap(); + assert_eq!(secret.binding, None, "{label}"); + // `Auto` cannot find the key the record named, and keeps it. + let forgot = matches!(choice, DeviceKeyChoice::Forget(_)); + assert_eq!(store.voelin_key(&key().uid()).unwrap().is_none(), forgot, "{label}"); + assert_eq!(store.sign_out(&binding().account, choice).unwrap(), SignOut::default()); + } + } +} diff --git a/docs/architecture.md b/docs/architecture.md index 2b60763..5a0b51a 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -349,6 +349,10 @@ names (the error says only that, never the JSON: it is a private key), and the TeamSpeak security level is still computed from the key, never stored. A `put` that changes only the binding of a row does not read its JSON again, so a row damaged outside the client cannot keep a sign-out from unbinding it. +A row whose binding columns cannot be read is listed and read as unbound, with a +warning, instead of failing the list; so no damaged row, the account record's +included, keeps a sign-out from finishing, and `Forget` still deletes the key +it names. Signing out of an account is the trait's `sign_out`, run on this table: it removes the account record and the synced copies, unbinds the identities only this device holds, keeps the device key (unbound, byte for byte) when the From 248955b85c96ef6ca05292b21cbd3a8db54cc7c0 Mon Sep 17 00:00:00 2001 From: faumaray Date: Tue, 20 Oct 2026 08:27:56 +0300 Subject: [PATCH 2/6] Overwrite a deleted key and truncate the log after it SQLite's secure_delete was off: a deleted row stayed in the free space of its page, and the frame of the write-ahead log that held that page kept the key until the log was reset. Every connection (Store::init) now sets secure_delete = ON next to foreign_keys, and Store::delete_identity and KeyStore::remove (how a sign-out deletes the device key, the synced copies and the account record) run PRAGMA wal_checkpoint(TRUNCATE) after a row was deleted, so the page with the overwritten row is copied into client.db and the log is empty. The truncate is best effort: the delete has happened and a sign-out must still finish, so a checkpoint that another connection blocks, or that fails, only logs a warning that the bytes stay in the log until the next checkpoint. Keys deleted before this change stay in the free pages until a VACUUM; the architecture notes say so. Tests read client.db and client.db-wal as bytes: the PKCS#8 text of a Voelin device key (sign-out with Auto, and with Forget), a synced TeamSpeak copy's key, a TeamSpeak identity deleted by Store::delete_identity and a key removed through KeyStore::remove are present before and in neither file after, another key is still stored and the log is empty; and secure_delete reads 1 on every connection. Each raw-file test fails with either measure taken out. Co-Authored-By: Claude Sonnet 5.5 --- CHANGELOG.md | 3 + crates/voelin-store/src/keystore.rs | 14 ++++ crates/voelin-store/src/store.rs | 60 +++++++++++++- crates/voelin-store/tests/keystore.rs | 112 ++++++++++++++++++++++++++ docs/architecture.md | 11 +++ 5 files changed, 199 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e79177b..8f76932 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -188,6 +188,9 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows ### Fixed +- A deleted identity key no longer stays in the database file: SQLite overwrites + what it deletes, and the log is truncated after a key is deleted (an identity + you delete, a key a sign-out deletes). - Hover help in the Stream Studio (a source's error, the status details) shows each time and closes when the pointer leaves; it showed only once, and stayed open until a click. diff --git a/crates/voelin-store/src/keystore.rs b/crates/voelin-store/src/keystore.rs index f1fb940..23d035f 100644 --- a/crates/voelin-store/src/keystore.rs +++ b/crates/voelin-store/src/keystore.rs @@ -41,6 +41,15 @@ //! `kind` or `uid` is not text cannot be addressed, and the list leaves it out //! with a warning. //! +//! The rows are private keys, so a removed row is not left behind in the file: +//! every connection sets `secure_delete`, which makes SQLite overwrite what it +//! deletes, and [`KeyStore::remove`] (which is how a sign-out deletes a key) +//! truncates the write-ahead log after it, as [`Store::delete_identity`] does, +//! so that the frame of the log that held the page with the key is gone too. A +//! checkpoint that another connection blocks cannot truncate; the removal still +//! succeeds and a warning says that the bytes stay in the log until the next +//! checkpoint (`Store::truncate_wal`). +//! //! A TeamSpeak blob that is refused says why in words that carry none of its //! input: its `data` is the identity's private key, and an error reaches log //! lines. @@ -214,6 +223,11 @@ impl KeyStore for SqliteKeyStore { .map_err(backend)? .execute(params![kind, uid]) .map_err(backend)?; + if removed > 0 { + // The row may be a key (a sign-out removes them one by one through + // this method): leave nothing of it in the log either. + store.truncate_wal(); + } Ok(removed > 0) } } diff --git a/crates/voelin-store/src/store.rs b/crates/voelin-store/src/store.rs index fe21b09..8aacd6b 100644 --- a/crates/voelin-store/src/store.rs +++ b/crates/voelin-store/src/store.rs @@ -270,6 +270,13 @@ impl Store { // Statements run through `prepare_cached` are parsed once per connection. db.set_prepared_statement_cache_capacity(64); db.pragma_update(None, "foreign_keys", true)?; + // Identities hold private keys. By default a delete only unlinks the + // row: its bytes stay in the free space of the page, and in earlier + // frames of the write-ahead log. With this SQLite overwrites what it + // deletes with zeros, and `truncate_wal` then folds the log into the + // file after a key is removed. It is a setting of the connection, so + // every connection that opens the file sets it here. + db.pragma_update(None, "secure_delete", true)?; // Each migration with its version bump in one write transaction: a // second connection that opens the file at the same time (the // settings writer, the chat history) waits, then sees the new version. @@ -401,11 +408,48 @@ impl Store { if n == 0 { Err(Error::NotFound("identity", id)) } else { Ok(()) } } + /// Delete the identity, key included: SQLite overwrites the row + /// (`secure_delete`) and the write-ahead log is truncated, so the key is + /// in neither the database file nor its log afterwards + /// (`truncate_wal` says when it cannot be). pub fn delete_identity(&self, id: i64) -> Result<()> { - self.db.execute("DELETE FROM identities WHERE id = ?1 AND kind = 'teamspeak'", [id])?; + let deleted = + self.db.execute("DELETE FROM identities WHERE id = ?1 AND kind = 'teamspeak'", [id])?; + if deleted > 0 { + self.truncate_wal(); + } Ok(()) } + /// Fold the write-ahead log into the database file and truncate it to + /// nothing. The delete of a key has overwritten its bytes in the page + /// (`secure_delete`), but the frame of the log that held the page when the + /// key was stored still has them until the log is reset, and a plain + /// checkpoint only copies the frames. Call it after the rows of a key were + /// deleted. + /// + /// It is best effort, because the delete it follows has happened and a + /// sign-out must still finish: a checkpoint that cannot complete (another + /// connection keeps reading an old snapshot for as long as the busy timeout) + /// or fails leaves the bytes in the log until the next checkpoint, and a + /// warning says so. It does nothing to a database that is not in WAL mode + /// and does not overwrite what was deleted before `secure_delete` was on + /// (`VACUUM` does). + pub(crate) fn truncate_wal(&self) { + let blocked = + self.db.query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |r| r.get::<_, i64>(0)); + match blocked { + Ok(0) => {} + Ok(_) => tracing::warn!( + "a deleted key may stay in the write-ahead log: another connection blocked the checkpoint" + ), + Err(error) => tracing::warn!( + %error, + "a deleted key may stay in the write-ahead log: the checkpoint failed" + ), + } + } + // Bookmarks pub fn add_bookmark(&self, bookmark: &Bookmark) -> Result { @@ -530,6 +574,20 @@ mod tests { assert!(matches!(store.identity(id), Err(Error::NotFound(..)))); } + #[test] + fn every_connection_overwrites_what_it_deletes() { + let secure_delete = |store: &Store| -> i64 { + store.db.pragma_query_value(None, "secure_delete", |r| r.get(0)).unwrap() + }; + assert_eq!(secure_delete(&Store::open_in_memory().unwrap()), 1); + let dir = scratch_dir("secure-delete"); + let path = dir.join("client.db"); + assert_eq!(secure_delete(&Store::open(&path).unwrap()), 1); + // A second connection to the same file sets it for itself. + assert_eq!(secure_delete(&Store::open(&path).unwrap()), 1); + std::fs::remove_dir_all(dir).unwrap(); + } + #[test] fn the_default_identity() { let store = Store::open_in_memory().unwrap(); diff --git a/crates/voelin-store/tests/keystore.rs b/crates/voelin-store/tests/keystore.rs index 8e4fdf5..003bf04 100644 --- a/crates/voelin-store/tests/keystore.rs +++ b/crates/voelin-store/tests/keystore.rs @@ -1429,3 +1429,115 @@ fn an_account_row_whose_data_is_not_text_is_deleted_like_an_unreadable_record() } } } + +// ------------------------------------------- a deleted key is gone from the file + +/// The database file and its write-ahead log, as the bytes on disk. +struct RawFiles { + db: Vec, + wal: Vec, +} + +impl RawFiles { + fn read(scratch: &Scratch) -> Self { + let wal = format!("{}-wal", scratch.db().display()); + Self { + db: std::fs::read(scratch.db()).unwrap(), + wal: std::fs::read(wal).unwrap_or_default(), + } + } + + fn holds(&self, text: &str) -> bool { + let contains = |bytes: &[u8]| bytes.windows(text.len()).any(|w| w == text.as_bytes()); + contains(&self.db) || contains(&self.wal) + } + + /// Where the text is, for a failure message. + fn where_is(&self, text: &str) -> (bool, bool) { + let contains = |bytes: &[u8]| bytes.windows(text.len()).any(|w| w == text.as_bytes()); + (contains(&self.db), contains(&self.wal)) + } +} + +/// The text of the private key in a stored blob: `pkcs8` of a Voelin key, +/// `key` of a TeamSpeak identity. +fn key_text(json: &str, field: &str) -> String { + let json: serde_json::Value = serde_json::from_str(json).unwrap(); + let text = json[field].as_str().unwrap().to_owned(); + assert!(text.len() >= 40, "{field}: a short text would match anything"); + text +} + +#[test] +fn a_key_deleted_by_a_sign_out_is_in_neither_the_database_file_nor_its_log() { + // The device key the client made for the account goes with `Auto`, and a + // key that predates the account goes when the user forgets it. Either way + // its PKCS#8 text, and a synced TeamSpeak copy's key, must not stay in the + // free pages of `client.db` or in a frame of `client.db-wal`. + for (bound_existing_key, choice) in + [(false, DeviceKeyChoice::Auto), (true, DeviceKeyChoice::Forget(key().uid()))] + { + let scratch = Scratch::new("scrub-signout"); + let store = SqliteKeyStore::open(&scratch.db()).unwrap(); + let device = IdentityBlob::voelin(&key()).unwrap(); + let other = IdentityBlob::voelin(&IdentityKey::generate().unwrap()).unwrap(); + let synced = fresh_teamspeak(binding()); + let (device_text, other_text) = + (key_text(&device.json, "pkcs8"), key_text(&other.json, "pkcs8")); + let synced_text = key_text(&synced.json, "key"); + store.put(&device).unwrap(); + store.put(&other).unwrap(); + store.put(&synced).unwrap(); + store.put_account_record(&AccountRecord { bound_existing_key, ..record() }).unwrap(); + // Another connection to the file (the settings writer, the chat history), + // idle, as the app has them. + let neighbour = Store::open(&scratch.db()).unwrap(); + assert_eq!(neighbour.schema_version().unwrap(), Store::SCHEMA_VERSION); + + // The keys are on disk before: the test proves nothing otherwise. + let before = RawFiles::read(&scratch); + assert!(before.holds(&device_text) && before.holds(&synced_text)); + + store.sign_out(&binding().account, choice).unwrap(); + assert!(store.voelin_key(&key().uid()).unwrap().is_none(), "{choice:?}"); + let after = RawFiles::read(&scratch); + assert_eq!(after.where_is(&device_text), (false, false), "{choice:?}: the device key"); + assert_eq!(after.where_is(&synced_text), (false, false), "{choice:?}: the synced copy"); + assert!(after.holds(&other_text), "{choice:?}: a key that stays is still stored"); + assert!(after.wal.is_empty(), "{choice:?}: the log is truncated"); + drop(neighbour); + } +} + +#[test] +fn a_teamspeak_identity_deleted_by_the_store_is_in_neither_the_database_file_nor_its_log() { + let scratch = Scratch::new("scrub-delete"); + let store = Store::open(&scratch.db()).unwrap(); + let (doomed, kept) = (Identity::create(), Identity::create()); + let doomed_text = key_text(&serde_json::to_string(&doomed).unwrap(), "key"); + let kept_text = key_text(&serde_json::to_string(&kept).unwrap(), "key"); + let doomed_id = store.add_identity("doomed", &doomed, IdentityOrigin::User).unwrap(); + store.add_identity("kept", &kept, IdentityOrigin::User).unwrap(); + assert!(RawFiles::read(&scratch).holds(&doomed_text), "the test proves nothing otherwise"); + + store.delete_identity(doomed_id).unwrap(); + let after = RawFiles::read(&scratch); + assert_eq!(after.where_is(&doomed_text), (false, false)); + assert!(after.holds(&kept_text)); + assert!(after.wal.is_empty(), "the log is truncated"); +} + +#[test] +fn removing_through_the_key_store_leaves_no_key_behind_either() { + // `remove` is how a sign-out deletes, and it is public on its own. + let scratch = Scratch::new("scrub-remove"); + let store = SqliteKeyStore::open(&scratch.db()).unwrap(); + let device = IdentityBlob::voelin(&key()).unwrap(); + let text = key_text(&device.json, "pkcs8"); + store.put(&device).unwrap(); + assert!(RawFiles::read(&scratch).holds(&text)); + assert!(store.remove(KIND_VOELIN, &device.uid).unwrap()); + assert_eq!(RawFiles::read(&scratch).where_is(&text), (false, false)); + // Removing what is not there is not an error and changes nothing. + assert!(!store.remove(KIND_VOELIN, &device.uid).unwrap()); +} diff --git a/docs/architecture.md b/docs/architecture.md index 5a0b51a..00409fb 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -360,6 +360,17 @@ record says it predates the account, and deletes it when it does not or when the caller asks to forget it. The engine and the UI do not use the key store yet; accounts, sign-in and the integrations page are later steps. +The rows are private keys, so a deleted key must not stay in the file. Every +connection to the database sets `secure_delete`, which makes SQLite overwrite +what it deletes, and deleting a key (`Store::delete_identity`, and the +`KeyStore::remove` a sign-out deletes with) is followed by a +`PRAGMA wal_checkpoint(TRUNCATE)`, so that the frame of the write-ahead log that +held the key's page goes too: neither `client.db` nor `client.db-wal` has the +key's text afterwards. If another connection blocks the checkpoint the delete +stands, a warning is logged, and the bytes stay in the log until the next +checkpoint. Keys deleted before `secure_delete` was on stay in the free pages +until the database is vacuumed. + `voelin-identity` comes from the private VoelinProtocol repository as a git dependency pinned by commit ([building.md](building.md#depending-on-voelinprotocol)). From 3c59f2460881873210c29f47825e09d97f662f5a Mon Sep 17 00:00:00 2001 From: faumaray Date: Tue, 20 Oct 2026 08:31:36 +0300 Subject: [PATCH 3/6] Refuse to store the device key as a synced copy KeyStore::sign_out deletes every identity bound with synced = true in its first step, before it reads the account record that says which Voelin key is the device key and whether it predates the account. A device key stored with synced = true was therefore deleted even where the record says to keep it. Nothing in this crate stored such a key, but the store accepted it. SqliteKeyStore::put now refuses, with an error that names the key and the record and says why, a voelin blob with synced = true while an account record names its uid as the device key, and also while an account record cannot be read (it may name the key, and the sign-out would delete it on that guess). The state is also reached from the other side, so a put of an account record whose device key is already stored as a synced copy is refused as well. A binding with synced = false is accepted: a sign-out unbinds it and then follows the record. The check runs before the binding-only fast path, so a put of the key's own data cannot rebind it as synced. Documented in keystore.rs and docs/architecture.md. Tests cover the refusal for records that keep and that delete the key (the error text, the row left untouched, the sign-out still following the record), another key that may be synced, no record or a record naming another key, a record put naming a synced copy, and unreadable records; the three refusal tests fail without the check. Co-Authored-By: Claude Sonnet 5.5 --- crates/voelin-store/src/keystore.rs | 105 ++++++++++++++++++++- crates/voelin-store/tests/keystore.rs | 128 ++++++++++++++++++++++++++ docs/architecture.md | 12 +++ 3 files changed, 244 insertions(+), 1 deletion(-) diff --git a/crates/voelin-store/src/keystore.rs b/crates/voelin-store/src/keystore.rs index 23d035f..4822fd1 100644 --- a/crates/voelin-store/src/keystore.rs +++ b/crates/voelin-store/src/keystore.rs @@ -50,6 +50,19 @@ //! succeeds and a warning says that the bytes stay in the log until the next //! checkpoint (`Store::truncate_wal`). //! +//! The device key is never a synced copy. The account record names the Voelin key +//! that is the installation's device key, and [`KeyStore::sign_out`] deletes +//! every identity bound with `synced = true` in its first step, before it reads +//! the record, so a key stored that way would be deleted whatever the record +//! says (a key that predates the account is to be kept). The store therefore +//! refuses, with an error that says why, a [`KeyStore::put`] of a `voelin` blob +//! with `synced = true` while an account record names its uid as the device, or +//! while a record cannot be read, because then it cannot tell; and a put of an +//! account record that names a key which is stored as a synced copy. A binding +//! with `synced = false` is accepted: a sign-out unbinds such a key and then +//! follows the record. The check and the write are done under the store's lock; +//! a second process writing the same file at the same moment is not covered. +//! //! A TeamSpeak blob that is refused says why in words that carry none of its //! input: its `data` is the identity's private key, and an error reaches log //! lines. @@ -62,7 +75,8 @@ use rusqlite::types::ValueRef; use tsclientlib::Identity; use voelin_identity::migrate::SELECT_ACCOUNT_COLUMNS; use voelin_identity::{ - AccountBinding, BlobError, IdentityBlob, IdentityInfo, KIND_TEAMSPEAK, KeyStore, KeyStoreError, + AccountBinding, BlobError, IdentityBlob, IdentityInfo, KIND_ACCOUNT, KIND_TEAMSPEAK, + KIND_VOELIN, KeyStore, KeyStoreError, }; use crate::{Error, Result, Store}; @@ -165,6 +179,13 @@ impl KeyStore for SqliteKeyStore { fn put(&self, blob: &IdentityBlob) -> KsResult<()> { let columns = blob.binding_columns()?; let store = self.lock(); + match blob.kind.as_str() { + KIND_VOELIN if blob.binding.is_some_and(|binding| binding.synced) => { + refuse_synced_device_key(&store, &blob.uid)?; + } + KIND_ACCOUNT => refuse_record_of_synced_key(&store, blob)?, + _ => {} + } // A row that already holds this data changes its binding and nothing // else, and is not checked again: it may have been damaged outside this // crate, and a sign-out still has to unbind it. @@ -252,6 +273,66 @@ fn check_teamspeak(blob: &IdentityBlob) -> KsResult<()> { Ok(()) } +/// Refuse to store the Voelin key `uid` as a synced copy while the device key +/// of the installation, as an account record names it, is this key. +/// +/// A record that cannot be read could name it: it is refused then too, because +/// the sign-out that follows would delete the key on that guess. +fn refuse_synced_device_key(store: &Store, uid: &str) -> KsResult<()> { + let mut statement = store + .db + .prepare_cached("SELECT uid, data FROM identities WHERE kind = 'account'") + .map_err(backend)?; + let mut rows = statement.query([]).map_err(backend)?; + while let Some(row) = rows.next().map_err(backend)? { + // A record whose uid is not text cannot be addressed; it is not read. + let Ok(record_uid) = row.get_ref(0).map_err(backend)?.as_str() else { continue }; + let data = lossy_text(row.get_ref(1).map_err(backend)?).unwrap_or_default(); + match IdentityBlob::new(KIND_ACCOUNT, record_uid, 0, data).account_record() { + Ok(record) if record.device.to_base32() == uid => { + return Err(KeyStoreError::backend(Refused::SyncedDeviceKey { + uid: uid.to_owned(), + record: record_uid.to_owned(), + })); + } + Ok(_) => {} + Err(_) => { + return Err(KeyStoreError::backend(Refused::UnreadableRecord { + uid: uid.to_owned(), + record: record_uid.to_owned(), + })); + } + } + } + Ok(()) +} + +/// Refuse to store an account record whose device key is stored as a synced +/// copy: the same state as [`refuse_synced_device_key`] guards, reached from +/// the other side. A blob that is no readable record is not checked here; the +/// store has always kept what it is given for that kind, and a sign-out +/// deletes it. +fn refuse_record_of_synced_key(store: &Store, blob: &IdentityBlob) -> KsResult<()> { + let Ok(record) = blob.account_record() else { return Ok(()) }; + let device = record.device.to_base32(); + let synced: bool = store + .db + .prepare_cached( + "SELECT EXISTS (SELECT 1 FROM identities + WHERE kind = 'voelin' AND uid = ?1 AND synced = 1)", + ) + .map_err(backend)? + .query_row([&device], |row| row.get(0)) + .map_err(backend)?; + if synced { + return Err(KeyStoreError::backend(Refused::RecordNamesSyncedKey { + record: blob.uid.clone(), + device, + })); + } + Ok(()) +} + /// A database error as the store's backend error. fn backend(error: impl Into) -> KeyStoreError { KeyStoreError::backend(error.into()) @@ -267,6 +348,28 @@ enum Refused { /// `uid` is unique across kinds in this table. #[error("the uid {uid:?} is already stored as an identity of kind {kind:?}")] UidHeld { uid: String, kind: String }, + /// The Voelin key is the device key of an account record. A sign-out + /// deletes a synced copy without reading the record, so the key the record + /// says to keep would be deleted. + #[error( + "the Voelin key {uid:?} is the device key of the account record {record:?} and cannot be \ + stored as a synced copy (synced = true): a sign-out would delete it whatever the record says" + )] + SyncedDeviceKey { uid: String, record: String }, + /// An account record cannot be read, so the store cannot tell whether the + /// Voelin key is its device key. + #[error( + "the Voelin key {uid:?} cannot be stored as a synced copy (synced = true): the account \ + record {record:?} cannot be read, so it may name this key as the device key" + )] + UnreadableRecord { uid: String, record: String }, + /// The device key of the record is stored as a synced copy already. + #[error( + "the account record {record:?} names the Voelin key {device:?} as the device key, which is \ + stored as a synced copy (synced = true): a sign-out would delete it whatever the record \ + says" + )] + RecordNamesSyncedKey { record: String, device: String }, } /// One row of the table as `LIST` and `SELECT_ACCOUNT_COLUMNS` select it (with diff --git a/crates/voelin-store/tests/keystore.rs b/crates/voelin-store/tests/keystore.rs index 003bf04..8e62f16 100644 --- a/crates/voelin-store/tests/keystore.rs +++ b/crates/voelin-store/tests/keystore.rs @@ -1541,3 +1541,131 @@ fn removing_through_the_key_store_leaves_no_key_behind_either() { // Removing what is not there is not an error and changes nothing. assert!(!store.remove(KIND_VOELIN, &device.uid).unwrap()); } + +// -------------------------------------- the device key is never a synced copy +// +// `KeyStore::sign_out` deletes everything bound with `synced = true` in its +// first step, before it reads the record that says which key to keep. A store +// that let the record's device key be such a copy would lose a key the record +// says to keep, so it refuses (`SqliteKeyStore::put`, and the record's put). + +/// The Voelin key as a synced copy of the account's material. +fn synced_voelin(key: &IdentityKey) -> IdentityBlob { + IdentityBlob::voelin(key).unwrap().with_binding(binding()) +} + +/// Why a put was refused: the backend error's text. +fn refusal(result: Result<(), KeyStoreError>) -> String { + match result { + Err(KeyStoreError::Backend(source)) => source.to_string(), + other => panic!("the put was not refused by the backend: {other:?}"), + } +} + +#[test] +fn a_synced_binding_on_the_device_key_is_refused_with_a_precise_error() { + for bound_existing_key in [true, false] { + let store = SqliteKeyStore::open_in_memory().unwrap(); + store.put_voelin_key(&key()).unwrap(); + store.put_account_record(&AccountRecord { bound_existing_key, ..record() }).unwrap(); + let uid = key().uid().to_base32(); + let before = store.get(KIND_VOELIN, &uid).unwrap().unwrap(); + + // The row holds this data already, so the put would only rebind it; it is + // refused all the same, and the error names the key and the record and + // says why, without the key. + let shown = refusal(store.put(&synced_voelin(&key()))); + assert!(shown.contains(&uid) && shown.contains(&record().blob_uid()), "{shown}"); + assert!(shown.contains("device key") && shown.contains("synced = true"), "{shown}"); + assert!(!shown.contains(&key_text(&before.json, "pkcs8")), "{shown}"); + assert_eq!(store.get(KIND_VOELIN, &uid).unwrap().unwrap(), before, "nothing was written"); + assert_eq!(store.list().unwrap().iter().filter(|i| i.binding.is_some()).count(), 0); + + // A binding that is not synced is a device-only secret: accepted, and a + // sign-out unbinds it and keeps it (or deletes it, as the record says). + let device_only = AccountBinding { synced: false, ..binding() }; + store.put(&IdentityBlob::voelin(&key()).unwrap().with_binding(device_only)).unwrap(); + store.put(&before).unwrap(); + + // So the sign-out still does what the record says with the key. + let done = store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap(); + assert_eq!(done.unbound.contains(&device_key_info()), bound_existing_key, "{done:?}"); + assert_eq!(store.voelin_key(&key().uid()).unwrap().is_some(), bound_existing_key); + } +} + +#[test] +fn a_key_the_record_does_not_name_may_be_a_synced_copy() { + let store = SqliteKeyStore::open_in_memory().unwrap(); + store.put_voelin_key(&key()).unwrap(); + store.put_account_record(&AccountRecord { bound_existing_key: true, ..record() }).unwrap(); + let other = IdentityKey::generate().unwrap(); + store.put(&synced_voelin(&other)).unwrap(); + assert_eq!(store.bound_to(&binding().account).unwrap().len(), 1); + + let done = store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap(); + assert!(done.removed.iter().any(|i| i.kind == KIND_VOELIN && i.uid == other.uid().to_base32())); + assert!(store.voelin_key(&other.uid()).unwrap().is_none(), "the copy is deleted"); + assert!(store.voelin_key(&key().uid()).unwrap().is_some(), "the device key is kept"); +} + +#[test] +fn a_synced_key_is_accepted_while_no_record_names_it() { + let store = SqliteKeyStore::open_in_memory().unwrap(); + // Without a record there is no device key to protect. + store.put(&synced_voelin(&key())).unwrap(); + // A record that names another key does not protect this one either. + let other_device = AccountRecord { device: Uid::from_bytes([5; 32]), ..record() }; + store.put_account_record(&other_device).unwrap(); + store.put(&synced_voelin(&key())).unwrap(); + assert_eq!( + store.get(KIND_VOELIN, &key().uid().to_base32()).unwrap().unwrap().binding, + Some(binding()) + ); +} + +#[test] +fn a_record_that_names_a_synced_copy_as_the_device_key_is_refused() { + // The same state reached from the other side: the key is stored as a synced + // copy first, and then a record names it as the device key. + let store = SqliteKeyStore::open_in_memory().unwrap(); + store.put(&synced_voelin(&key())).unwrap(); + let shown = refusal(store.put_account_record(&record())); + assert!( + shown.contains(&key().uid().to_base32()) && shown.contains(&record().blob_uid()), + "{shown}" + ); + assert!(shown.contains("device key") && shown.contains("synced = true"), "{shown}"); + assert_eq!(store.account_record().unwrap(), None, "the record was not stored"); + assert_eq!(store.list().unwrap().len(), 1); + + // Once the key is not a synced copy the record is accepted. + store.put(&IdentityBlob::voelin(&key()).unwrap()).unwrap(); + store.put_account_record(&record()).unwrap(); + assert_eq!(store.account_record().unwrap(), Some(record())); + // A record that is no record is kept as ever; a sign-out deletes it. + damage_the_record(&store, "not json"); +} + +#[test] +fn a_synced_key_is_refused_while_a_record_cannot_be_read() { + // The record may name the key, and the store cannot tell; a sign-out would + // delete the key on that guess, so it is not stored that way. + for (json, _) in unreadable_records() { + let store = SqliteKeyStore::open_in_memory().unwrap(); + store.put_account_record(&record()).unwrap(); + damage_the_record(&store, &json); + let other = IdentityKey::generate().unwrap(); + let shown = refusal(store.put(&synced_voelin(&other))); + assert!( + shown.contains("cannot be read") && shown.contains(&record().blob_uid()), + "{shown}" + ); + assert!(shown.contains(&other.uid().to_base32()), "{shown}"); + assert!(store.voelin_key(&other.uid()).unwrap().is_none()); + + // A sign-out deletes the unreadable record; then the key is accepted. + let _ = store.sign_out(&binding().account, DeviceKeyChoice::Auto); + store.put(&synced_voelin(&other)).unwrap(); + } +} diff --git a/docs/architecture.md b/docs/architecture.md index 00409fb..b6d69e8 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -360,6 +360,18 @@ record says it predates the account, and deletes it when it does not or when the caller asks to forget it. The engine and the UI do not use the key store yet; accounts, sign-in and the integrations page are later steps. +The device key is never a synced copy. The trait's `sign_out` deletes every +identity bound with `synced = true` in its first step, before it reads the +record, so a device key stored that way would be deleted even where the record +says to keep it. `SqliteKeyStore` therefore refuses, with an error that names +the key and the record, a `put` of a `voelin` blob with `synced = true` while an +account record names its uid as the device key, or while an account record +cannot be read (it may name the key); and a `put` of an account record whose +device key is stored as a synced copy. A key bound with `synced = false` is +accepted: a sign-out unbinds it and then follows the record. The check is made +under the store's lock; it is defence in depth against the code that signs in, +which does not exist yet. + The rows are private keys, so a deleted key must not stay in the file. Every connection to the database sets `secure_delete`, which makes SQLite overwrite what it deletes, and deleting a key (`Store::delete_identity`, and the From 2e026a043c85177b2d3cb6483e833644f23ec406 Mon Sep 17 00:00:00 2001 From: faumaray Date: Tue, 20 Oct 2026 08:46:58 +0300 Subject: [PATCH 4/6] Update rustls and yoke-derive for cargo deny, ignore wasapi until 0.25 cargo deny check failed on the advisories of the base lock: - rustls 0.23.45 (RUSTSEC-2026-0346 to 0349: Debug output of client session values, buffered data after ECH rejection, unbounded brotli certificate decompression, ServerHello downgrade): cargo update -p rustls --precise 0.23.46, which the advisories name as the fix. - yoke-derive 0.8.3 was yanked: cargo update -p yoke-derive --precise 0.8.4. - wasapi 0.24.0 (RUSTSEC-2026-0332, unsound WaveFormat::parse): the fix is wasapi 0.25.0, a breaking release of a Windows-only dependency of voelin-media, which the Linux CI can neither build nor test, so it is not a semver update. voelin-media never calls WaveFormat::parse (it only builds formats with WaveFormat::new). deny.toml ignores the advisory with that reason and a date: remove by 2026-12-20, by upgrading wasapi on a Windows machine. cargo-deny cannot enforce the date; the comment and the reason say it. Cargo.lock changes only those two packages (cargo's re-resolution also moved tempfile to getrandom 0.3.4; that is put back to 0.4.3 by hand so the diff is the advisories' and nothing else; cargo metadata --locked accepts it). THIRD_PARTY_NOTICES.md is regenerated (scripts/notices.sh, cargo-about 0.9.2) for the two version numbers. cargo deny --locked --workspace check: advisories, bans, licenses and sources ok. Co-Authored-By: Claude Sonnet 5.5 --- Cargo.lock | 8 ++++---- THIRD_PARTY_NOTICES.md | 4 ++-- deny.toml | 9 +++++++++ 3 files changed, 15 insertions(+), 6 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index aea5df7..c0e06a3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7149,9 +7149,9 @@ dependencies = [ [[package]] name = "rustls" -version = "0.23.45" +version = "0.23.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" dependencies = [ "aws-lc-rs", "once_cell", @@ -11020,9 +11020,9 @@ dependencies = [ [[package]] name = "yoke-derive" -version = "0.8.3" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33811428bee40dbceb6d545e95754741d17a6aef9a4849f0fd62e2ba4f412a78" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" dependencies = [ "proc-macro2", "quote", diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index c005bf3..7aa38c6 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -4150,7 +4150,7 @@ DEALINGS IN THE SOFTWARE. ```` -Used by: hyper-rustls 0.27.10, rustls-native-certs 0.8.4, rustls 0.23.45 +Used by: hyper-rustls 0.27.10, rustls-native-certs 0.8.4, rustls 0.23.46 ````text Copyright (c) 2016 Joseph Birr-Pixton @@ -11796,7 +11796,7 @@ authorization of the copyright holder. ```` -Used by: fixed_decimal 0.7.2, icu_collections 2.3.0, icu_decimal 2.3.0, icu_decimal_data 2.3.0, icu_locale_core 2.3.0, icu_locale_fallback 2.3.0, icu_locale_fallback_data 2.3.0, icu_normalizer 2.3.0, icu_normalizer_data 2.3.0, icu_properties 2.3.0, icu_properties_data 2.3.0, icu_provider 2.3.1, icu_segmenter 2.3.0, icu_segmenter_data 2.3.0, litemap 0.8.3, potential_utf 0.1.6, tinystr 0.8.4, writeable 0.6.4, yoke-derive 0.8.3, yoke 0.8.3, zerofrom-derive 0.1.8, zerofrom 0.1.8, zerotrie 0.2.5, zerovec-derive 0.11.6, zerovec 0.11.8 +Used by: fixed_decimal 0.7.2, icu_collections 2.3.0, icu_decimal 2.3.0, icu_decimal_data 2.3.0, icu_locale_core 2.3.0, icu_locale_fallback 2.3.0, icu_locale_fallback_data 2.3.0, icu_normalizer 2.3.0, icu_normalizer_data 2.3.0, icu_properties 2.3.0, icu_properties_data 2.3.0, icu_provider 2.3.1, icu_segmenter 2.3.0, icu_segmenter_data 2.3.0, litemap 0.8.3, potential_utf 0.1.6, tinystr 0.8.4, writeable 0.6.4, yoke-derive 0.8.4, yoke 0.8.3, zerofrom-derive 0.1.8, zerofrom 0.1.8, zerotrie 0.2.5, zerovec-derive 0.11.6, zerovec 0.11.8 ````text UNICODE LICENSE V3 diff --git a/deny.toml b/deny.toml index 13bc519..5c6cba3 100644 --- a/deny.toml +++ b/deny.toml @@ -12,6 +12,15 @@ ignore = [ # keys, so russh needs RSA to verify the server's signature (a public-key # operation). We never hold an RSA private key: query logins use passwords. { id = "RUSTSEC-2023-0071", reason = "only RSA signature verification is used (SSH host keys)" }, + # TIME-LIMITED, remove by 2026-12-20 (entered 2026-10-20). `wasapi` 0.24.0: + # `WaveFormat::parse` is a safe fn that reads past the end of the + # `&WAVEFORMATEX` it is given. The fix is `wasapi` 0.25.0, a breaking + # release (the fn became `unsafe`) of a Windows-only dependency of + # voelin-media that the Linux CI can neither build nor test, so it is not + # a semver update. voelin-media never calls `WaveFormat::parse` (it only + # builds formats with `WaveFormat::new`); upgrade `wasapi` to 0.25 on a + # Windows machine, then delete this entry. + { id = "RUSTSEC-2026-0332", reason = "voelin-media does not call wasapi's WaveFormat::parse; the fix is the breaking wasapi 0.25 (Windows-only), upgrade by 2026-12-20" }, ] [licenses] From 0ac409514355635b35bcfd0736d7407ff9a69e2b Mon Sep 17 00:00:00 2001 From: faumaray Date: Tue, 20 Oct 2026 10:21:49 +0300 Subject: [PATCH 5/6] Bound the checkpoint after a removed key to a short wait, once per sign-out Store::truncate_wal ran PRAGMA wal_checkpoint(TRUNCATE) with the connection's busy timeout of five seconds. A checkpoint that truncates holds the writer lock of the log while it waits for readers, so a reader that kept a snapshot made every removed row cost the whole timeout with the store's mutex held, and other writers failed with "database is locked" meanwhile. KeyStore::sign_out removes up to four rows (the synced copies, the device key, the record) and ran the checkpoint after each: 20 s and failing writers in the gate's probe. - truncate_wal now sets a busy timeout of 150 ms (CHECKPOINT_WAIT) around the pragma and restores the timeout the connection had (read back with PRAGMA busy_timeout, so a value set by a caller survives) whatever the checkpoint returned. A blocked checkpoint still leaves the delete standing and warns. - SqliteKeyStore overrides sign_out: the trait's own steps run on a private SignOutPass whose remove deletes the row and notes it, and the sign-out truncates the log once after its last step (also when a step failed, the removals before it have happened). KeyStore::remove on its own still truncates after the row it removed. - The three sentences that said the bytes "stay in the log until the next checkpoint" (keystore.rs, Store::truncate_wal, docs/architecture.md) are corrected: they go when a later checkpoint truncates the log, later writes overwrite those frames, or the last connection closes and the log is deleted. Tests: with a raw connection holding a read snapshot, a sign-out with four removals returns in about 170 ms (it took 20 s) while a writer on another connection with a one-second busy timeout writes throughout without an error (it got "database is locked" nineteen times), and the next removal after the reader is gone truncates the log again; a unit test shows a blocked truncate_wal returns in under a second, leaves the log, and restores a non-default busy timeout, and that the same call truncates once the reader is gone. Both tests fail on the previous code. Co-Authored-By: Claude Sonnet 5.5 --- crates/voelin-store/src/keystore.rs | 97 +++++++++++++++++++++------ crates/voelin-store/src/store.rs | 82 +++++++++++++++++++--- crates/voelin-store/tests/keystore.rs | 65 +++++++++++++++++- docs/architecture.md | 14 ++-- 4 files changed, 225 insertions(+), 33 deletions(-) diff --git a/crates/voelin-store/src/keystore.rs b/crates/voelin-store/src/keystore.rs index 4822fd1..ff34e2a 100644 --- a/crates/voelin-store/src/keystore.rs +++ b/crates/voelin-store/src/keystore.rs @@ -43,12 +43,16 @@ //! //! The rows are private keys, so a removed row is not left behind in the file: //! every connection sets `secure_delete`, which makes SQLite overwrite what it -//! deletes, and [`KeyStore::remove`] (which is how a sign-out deletes a key) -//! truncates the write-ahead log after it, as [`Store::delete_identity`] does, -//! so that the frame of the log that held the page with the key is gone too. A -//! checkpoint that another connection blocks cannot truncate; the removal still -//! succeeds and a warning says that the bytes stay in the log until the next -//! checkpoint (`Store::truncate_wal`). +//! deletes, and [`KeyStore::remove`] truncates the write-ahead log after it, as +//! [`Store::delete_identity`] does, so that the frame of the log that held the +//! page with the key is gone too. [`KeyStore::sign_out`], which deletes with +//! `remove`, truncates the log once, after its last step, not after each +//! removal. The checkpoint waits for another connection for a moment at most +//! (`Store::truncate_wal`): one that keeps reading an old snapshot blocks it, +//! and then the removal still succeeds and a warning says that the deleted +//! bytes may stay in the log file, until a later checkpoint truncates the log, +//! later writes overwrite those frames, or the last connection to the database +//! closes and the log is deleted. //! //! The device key is never a synced copy. The account record names the Voelin key //! that is the installation's device key, and [`KeyStore::sign_out`] deletes @@ -68,6 +72,7 @@ //! lines. use std::path::Path; +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Mutex, MutexGuard, PoisonError}; use rusqlite::params; @@ -75,8 +80,8 @@ use rusqlite::types::ValueRef; use tsclientlib::Identity; use voelin_identity::migrate::SELECT_ACCOUNT_COLUMNS; use voelin_identity::{ - AccountBinding, BlobError, IdentityBlob, IdentityInfo, KIND_ACCOUNT, KIND_TEAMSPEAK, - KIND_VOELIN, KeyStore, KeyStoreError, + AccountBinding, BlobError, DeviceKeyChoice, IdentityBlob, IdentityInfo, KIND_ACCOUNT, + KIND_TEAMSPEAK, KIND_VOELIN, KeyStore, KeyStoreError, SignOut, Uid, }; use crate::{Error, Result, Store}; @@ -118,7 +123,8 @@ const PUT: &str = "INSERT INTO identities /// access to the TeamSpeak methods of the same connection. /// /// [`KeyStore::sign_out`] and the rest of the trait's provided methods work as -/// `voelin-identity` defines them, on top of the five methods here. +/// `voelin-identity` defines them, on top of the five methods here; the +/// sign-out only truncates the write-ahead log once, at its end. pub struct SqliteKeyStore { store: Mutex, } @@ -238,18 +244,71 @@ impl KeyStore for SqliteKeyStore { fn remove(&self, kind: &str, uid: &str) -> KsResult { let store = self.lock(); - let removed = store - .db - .prepare_cached("DELETE FROM identities WHERE kind = ?1 AND uid = ?2") - .map_err(backend)? - .execute(params![kind, uid]) - .map_err(backend)?; - if removed > 0 { - // The row may be a key (a sign-out removes them one by one through - // this method): leave nothing of it in the log either. + let removed = delete_row(&store, kind, uid)?; + if removed { + // The row may be a key: leave nothing of it in the log either. store.truncate_wal(); } - Ok(removed > 0) + Ok(removed) + } + + /// The trait's sign-out, with the log truncated once after its last step + /// instead of after each of its removals: it removes up to a handful of + /// rows, and a checkpoint that another connection blocks costs a moment + /// (`Store::truncate_wal`) each time. The steps are the trait's own; they + /// run on a `SignOutPass`, which deletes like [`Self::remove`] and leaves + /// the checkpoint to this method. + fn sign_out(&self, account: &Uid, device_key: DeviceKeyChoice) -> KsResult { + let pass = SignOutPass { store: self, deleted: AtomicBool::new(false) }; + let outcome = KeyStore::sign_out(&pass, account, device_key); + // Also after a failure: the removals before it have happened. + if pass.deleted.load(Ordering::Relaxed) { + self.lock().truncate_wal(); + } + outcome + } +} + +/// Delete the row of this `(kind, uid)`: whether there was one. The rows are +/// overwritten (`secure_delete`); the log is the caller's to truncate. +fn delete_row(store: &Store, kind: &str, uid: &str) -> KsResult { + let removed = store + .db + .prepare_cached("DELETE FROM identities WHERE kind = ?1 AND uid = ?2") + .map_err(backend)? + .execute(params![kind, uid]) + .map_err(backend)?; + Ok(removed > 0) +} + +/// A [`SqliteKeyStore`] for the length of one [`KeyStore::sign_out`]: the same +/// rows, but `remove` only notes that it deleted something, so that the sign-out +/// truncates the log once at its end. +struct SignOutPass<'a> { + store: &'a SqliteKeyStore, + /// Whether a row was deleted. + deleted: AtomicBool, +} + +impl KeyStore for SignOutPass<'_> { + fn list(&self) -> KsResult> { + self.store.list() + } + + fn get(&self, kind: &str, uid: &str) -> KsResult> { + self.store.get(kind, uid) + } + + fn put(&self, blob: &IdentityBlob) -> KsResult<()> { + self.store.put(blob) + } + + fn remove(&self, kind: &str, uid: &str) -> KsResult { + let removed = delete_row(&self.store.lock(), kind, uid)?; + if removed { + self.deleted.store(true, Ordering::Relaxed); + } + Ok(removed) } } diff --git a/crates/voelin-store/src/store.rs b/crates/voelin-store/src/store.rs index 8aacd6b..4b4a1dc 100644 --- a/crates/voelin-store/src/store.rs +++ b/crates/voelin-store/src/store.rs @@ -1,6 +1,7 @@ //! The SQLite database. use std::path::Path; +use std::time::Duration; use rusqlite::{Connection, OptionalExtension, TransactionBehavior, params}; use serde::de::DeserializeOwned; @@ -237,6 +238,12 @@ impl Bookmark { } } +/// How long the checkpoint that follows the deletion of a key waits for another +/// connection ([`Store::truncate_wal`]). Short on purpose: the connection's own +/// busy timeout is seconds, and the checkpoint holds the writer lock while it +/// waits. +const CHECKPOINT_WAIT: Duration = Duration::from_millis(150); + pub struct Store { pub(crate) db: Connection, } @@ -429,16 +436,22 @@ impl Store { /// deleted. /// /// It is best effort, because the delete it follows has happened and a - /// sign-out must still finish: a checkpoint that cannot complete (another - /// connection keeps reading an old snapshot for as long as the busy timeout) - /// or fails leaves the bytes in the log until the next checkpoint, and a - /// warning says so. It does nothing to a database that is not in WAL mode - /// and does not overwrite what was deleted before `secure_delete` was on - /// (`VACUUM` does). + /// sign-out must still finish. A checkpoint that cannot complete (another + /// connection keeps reading an old snapshot) or fails leaves the bytes in + /// the log file, and a warning says so; they go when a later checkpoint + /// truncates the log, when later writes overwrite those frames, or when the + /// last connection to the database closes and the log is deleted. It does + /// nothing to a database that is not in WAL mode and does not overwrite what + /// was deleted before `secure_delete` was on (`VACUUM` does). + /// + /// It waits for another connection for [`CHECKPOINT_WAIT`] at most, not for + /// the busy timeout of the connection: while a checkpoint that truncates + /// waits for readers it holds the writer lock of the log, so every other + /// writer would wait with it, and fail with "database is locked" when its + /// own timeout is shorter than the wait. The timeout the connection had is + /// restored before this returns. pub(crate) fn truncate_wal(&self) { - let blocked = - self.db.query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |r| r.get::<_, i64>(0)); - match blocked { + match self.checkpoint_truncate() { Ok(0) => {} Ok(_) => tracing::warn!( "a deleted key may stay in the write-ahead log: another connection blocked the checkpoint" @@ -450,6 +463,20 @@ impl Store { } } + /// `PRAGMA wal_checkpoint(TRUNCATE)` under [`CHECKPOINT_WAIT`]: whether + /// another connection blocked it (`1`) or not (`0`). + fn checkpoint_truncate(&self) -> rusqlite::Result { + let previous: i64 = self.db.pragma_query_value(None, "busy_timeout", |r| r.get(0))?; + let previous = Duration::from_millis(u64::try_from(previous).unwrap_or_default()); + self.db.busy_timeout(CHECKPOINT_WAIT)?; + let blocked = + self.db.query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |r| r.get::<_, i64>(0)); + if let Err(error) = self.db.busy_timeout(previous) { + tracing::warn!(%error, "the busy timeout of the connection could not be restored"); + } + blocked + } + // Bookmarks pub fn add_bookmark(&self, bookmark: &Bookmark) -> Result { @@ -588,6 +615,43 @@ mod tests { std::fs::remove_dir_all(dir).unwrap(); } + #[test] + fn a_blocked_checkpoint_waits_briefly_and_leaves_the_busy_timeout_as_it_was() { + let dir = scratch_dir("blocked-checkpoint"); + let path = dir.join("client.db"); + let wal = dir.join("client.db-wal"); + let store = Store::open(&path).unwrap(); + store.add_identity("first", &Identity::create(), IdentityOrigin::User).unwrap(); + + // A reader whose snapshot is older than the last write keeps the log + // from being reset. + let reader = Connection::open(&path).unwrap(); + reader.execute_batch("BEGIN").unwrap(); + reader.query_row("SELECT count(*) FROM identities", [], |r| r.get::<_, i64>(0)).unwrap(); + store.add_identity("second", &Identity::create(), IdentityOrigin::User).unwrap(); + + // A value that is not the default, so that restoring a constant would show. + let timeout = |store: &Store| -> i64 { + store.db.pragma_query_value(None, "busy_timeout", |r| r.get(0)).unwrap() + }; + store.db.busy_timeout(Duration::from_millis(2345)).unwrap(); + let started = std::time::Instant::now(); + store.truncate_wal(); + let elapsed = started.elapsed(); + assert!(elapsed < Duration::from_secs(1), "the checkpoint waited {elapsed:?}"); + assert!(std::fs::metadata(&wal).unwrap().len() > 0, "the reader should block the reset"); + assert_eq!(timeout(&store), 2345); + + // Without the reader the same call resets the log. + reader.execute_batch("COMMIT").unwrap(); + store.truncate_wal(); + assert_eq!(std::fs::metadata(&wal).unwrap().len(), 0); + assert_eq!(timeout(&store), 2345); + drop(reader); + drop(store); + std::fs::remove_dir_all(dir).unwrap(); + } + #[test] fn the_default_identity() { let store = Store::open_in_memory().unwrap(); diff --git a/crates/voelin-store/tests/keystore.rs b/crates/voelin-store/tests/keystore.rs index 8e62f16..a4b46fb 100644 --- a/crates/voelin-store/tests/keystore.rs +++ b/crates/voelin-store/tests/keystore.rs @@ -19,7 +19,8 @@ //! last section. use std::sync::Arc; -use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::time::{Duration, Instant}; use rusqlite::{Connection, params}; use tsclientlib::Identity; @@ -1542,6 +1543,68 @@ fn removing_through_the_key_store_leaves_no_key_behind_either() { assert!(!store.remove(KIND_VOELIN, &device.uid).unwrap()); } +#[test] +fn a_reader_that_blocks_the_checkpoint_costs_milliseconds_and_starves_no_writer() { + // A connection that keeps a read snapshot (a long query of the UI, a backup) + // keeps the checkpoint that truncates the log from finishing. The sign-out + // still deletes and warns that the bytes may stay in the log, and it waits + // for the checkpoint a moment, not for the busy timeout of five seconds once + // per removed row. While the checkpoint waits it holds the writer lock of the + // log, so a second connection that writes meanwhile must get through. + let scratch = Scratch::new("blocked-checkpoint"); + let store = SqliteKeyStore::open(&scratch.db()).unwrap(); + store.put_voelin_key(&key()).unwrap(); + store.put_account_record(&AccountRecord { bound_existing_key: false, ..record() }).unwrap(); + for copy in [fresh_teamspeak(binding()), fresh_teamspeak(binding())] { + store.put(©).unwrap(); + } + + // The snapshot is older than every removal below. + let reader = Connection::open(scratch.db()).unwrap(); + reader.execute_batch("BEGIN").unwrap(); + let rows: i64 = reader.query_row("SELECT count(*) FROM identities", [], |r| r.get(0)).unwrap(); + assert_eq!(rows, 4); + + let stop = AtomicBool::new(false); + let (done, elapsed, writes, errors) = std::thread::scope(|scope| { + let writer = scope.spawn(|| { + // Its own connection, which gives up on a lock after one second. + let db = Connection::open(scratch.db()).unwrap(); + db.busy_timeout(Duration::from_secs(1)).unwrap(); + let sql = "INSERT OR REPLACE INTO settings (key, value) VALUES ('probe', ?1)"; + let (mut writes, mut errors) = (0, Vec::new()); + while !stop.load(Ordering::Relaxed) { + match db.execute(sql, [writes.to_string()]) { + Ok(_) => writes += 1, + Err(error) => errors.push(error.to_string()), + } + std::thread::sleep(Duration::from_millis(5)); + } + (writes, errors) + }); + let started = Instant::now(); + let done = store.sign_out(&binding().account, DeviceKeyChoice::Auto); + let elapsed = started.elapsed(); + stop.store(true, Ordering::Relaxed); + let (writes, errors) = writer.join().unwrap(); + (done.unwrap(), elapsed, writes, errors) + }); + + // Four removals: the two copies, the device key the client made, the record. + assert_eq!(done.removed.len(), 4, "{done:?}"); + assert!(store.list().unwrap().is_empty()); + assert!(writes > 0, "the writer never ran"); + assert!(errors.is_empty(), "a concurrent writer failed: {errors:?}"); + assert!(elapsed < Duration::from_secs(1), "the sign-out took {elapsed:?}"); + + // Nothing is lost by the wait: once the reader is gone, the next removal + // truncates the log. + reader.execute_batch("COMMIT").unwrap(); + store.put_voelin_key(&key()).unwrap(); + assert!(store.remove(KIND_VOELIN, &key().uid().to_base32()).unwrap()); + assert!(RawFiles::read(&scratch).wal.is_empty(), "the log is truncated again"); +} + // -------------------------------------- the device key is never a synced copy // // `KeyStore::sign_out` deletes everything bound with `synced = true` in its diff --git a/docs/architecture.md b/docs/architecture.md index b6d69e8..7f87069 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -378,10 +378,16 @@ what it deletes, and deleting a key (`Store::delete_identity`, and the `KeyStore::remove` a sign-out deletes with) is followed by a `PRAGMA wal_checkpoint(TRUNCATE)`, so that the frame of the write-ahead log that held the key's page goes too: neither `client.db` nor `client.db-wal` has the -key's text afterwards. If another connection blocks the checkpoint the delete -stands, a warning is logged, and the bytes stay in the log until the next -checkpoint. Keys deleted before `secure_delete` was on stay in the free pages -until the database is vacuumed. +key's text afterwards. A sign-out runs the checkpoint once, after its last step, +not after each row it removes. The checkpoint waits for another connection for +150 ms at most (the connection's own busy timeout is restored after it), because +while it waits for a reader it holds the writer lock of the log and every other +writer waits with it. If another connection blocks it (one that keeps reading an +old snapshot) the delete stands, a warning is logged, and the bytes stay in the +log file until a later checkpoint truncates the log, later writes overwrite +those frames, or the last connection to the database closes and the log is +deleted. Keys deleted before `secure_delete` was on stay in the free pages until +the database is vacuumed. `voelin-identity` comes from the private VoelinProtocol repository as a git dependency pinned by commit ([building.md](building.md#depending-on-voelinprotocol)). From 670ed9f29b2df03ff5d5ef9a84f6e42d91463f2f Mon Sep 17 00:00:00 2001 From: faumaray Date: Tue, 20 Oct 2026 14:35:46 +0300 Subject: [PATCH 6/6] Keep the stored bytes when a sign-out unbinds a row whose data is not text KeyStore::get reads a data column that is a BLOB, or TEXT of bytes that are no UTF-8, as text with the odd bytes replaced. The sign-out's unbind step puts that text back with the binding removed; REBIND (data = ?3) matches nothing for such a row, so put fell through to the full write: the lossy string replaced the original bytes (invalid UTF-8 became U+FFFD, a BLOB became TEXT), and for a TeamSpeak row the replaced text is no identity, so check_teamspeak refused it and the sign-out could never finish for that row. - put() now tries a second statement when REBIND changed nothing: rebind_stored_bytes reads the stored data raw and, if it reads (lossy_text) as exactly the blob's JSON, updates only the four binding columns by (kind, uid) (REBIND_BYTES) and returns without check_teamspeak, so the original bytes are kept and the TeamSpeak case unsticks. Any other JSON is a new identity for the uid, checked and stored as before. - The doc sentences at the top of keystore.rs (what a binding-only put and a non-text data column mean) and docs/architecture.md are narrowed to what holds: the bytes are kept for the text get returned, any other text replaces them. Tests: the gate's probe (a bound voelin row with data x'7b2276223aff317d', two future-kind rows, one a BLOB and one TEXT of no UTF-8, and two TeamSpeak BLOB rows, one of a good identity and one of garbage): sign_out(Auto) and sign_out(Forget) are Ok and every data value is byte-identical afterwards; a put of what get read changes the binding and keeps the bytes; a put of other data is checked and replaces them. The three tests fail on the previous code. Co-Authored-By: Claude Sonnet 5.5 --- crates/voelin-store/src/keystore.rs | 89 ++++++++++++--- crates/voelin-store/tests/keystore.rs | 153 ++++++++++++++++++++++++++ docs/architecture.md | 9 +- 3 files changed, 236 insertions(+), 15 deletions(-) diff --git a/crates/voelin-store/src/keystore.rs b/crates/voelin-store/src/keystore.rs index ff34e2a..185433b 100644 --- a/crates/voelin-store/src/keystore.rs +++ b/crates/voelin-store/src/keystore.rs @@ -20,9 +20,12 @@ //! (it could only have been damaged outside this crate) lists and reads with //! level 0 instead of failing the whole list, and a [`KeyStore::put`] that only //! changes the binding of a row (the row of that `(kind, uid)` already holds -//! exactly that `data`) writes the four binding columns and does not look at -//! `data` again. That is how [`KeyStore::sign_out`] unbinds a device-only -//! secret, so a damaged row never blocks it. +//! that `data`, as [`KeyStore::get`] reads it) writes the four binding columns, +//! does not look at `data` again and does not rewrite it. That is how +//! [`KeyStore::sign_out`] unbinds a device-only secret: a row whose `data` was +//! damaged outside this crate (JSON that is no identity, a BLOB, bytes that are +//! no UTF-8) does not keep the sign-out from unbinding it, and its `data` is +//! kept byte for byte. //! //! A row that is damaged elsewhere never fails a call that is not about it. A //! row whose binding columns cannot be read (`synced = 2`, an `account` that is @@ -35,11 +38,15 @@ //! and with it the deletion of the key the user asked to forget. Unbound is the //! reading that never deletes on a guess: a sign-out neither deletes such a row //! as a synced copy nor writes it, it stays as it is until a `put` of it writes -//! four good binding columns. A `data` column that is not text is read as text -//! with the odd bytes replaced, so that a record that cannot be read is deleted -//! by the sign-out, as the trait says, instead of its read failing; a row whose -//! `kind` or `uid` is not text cannot be addressed, and the list leaves it out -//! with a warning. +//! four good binding columns. A `data` column that is not text (a BLOB, or text +//! of bytes that are no UTF-8) is read as text with the odd bytes replaced, so +//! that a record that cannot be read is deleted by the sign-out, as the trait +//! says, instead of its read failing. A [`KeyStore::put`] of the text that +//! [`KeyStore::get`] returned for such a row is taken for the data that is +//! there: it changes the binding and keeps the stored bytes, where any other +//! text replaces them (a TeamSpeak blob still has to be an identity). A row +//! whose `kind` or `uid` is not text cannot be addressed, and the list leaves it +//! out with a warning. //! //! The rows are private keys, so a removed row is not left behind in the file: //! every connection sets `secure_delete`, which makes SQLite overwrite what it @@ -75,13 +82,13 @@ use std::path::Path; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Mutex, MutexGuard, PoisonError}; -use rusqlite::params; use rusqlite::types::ValueRef; +use rusqlite::{OptionalExtension, params}; use tsclientlib::Identity; use voelin_identity::migrate::SELECT_ACCOUNT_COLUMNS; use voelin_identity::{ - AccountBinding, BlobError, DeviceKeyChoice, IdentityBlob, IdentityInfo, KIND_ACCOUNT, - KIND_TEAMSPEAK, KIND_VOELIN, KeyStore, KeyStoreError, SignOut, Uid, + AccountBinding, BindingColumns, BlobError, DeviceKeyChoice, IdentityBlob, IdentityInfo, + KIND_ACCOUNT, KIND_TEAMSPEAK, KIND_VOELIN, KeyStore, KeyStoreError, SignOut, Uid, }; use crate::{Error, Result, Store}; @@ -101,6 +108,12 @@ const REBIND: &str = "UPDATE identities SET account = ?4, integration = ?5, integration_rev = ?6, synced = ?7 WHERE kind = ?1 AND uid = ?2 AND data = ?3"; +/// [`REBIND`] for a row whose `data` is not text and reads, as [`lossy_text`] +/// reads it, as the blob's: the same four columns, and the stored bytes stay. +const REBIND_BYTES: &str = "UPDATE identities + SET account = ?3, integration = ?4, integration_rev = ?5, synced = ?6 + WHERE kind = ?1 AND uid = ?2"; + /// Insert the blob, or replace the row of the same uid if it is of the same /// kind. A row of another kind is left alone: the statement then changes /// nothing, which `put` reports. @@ -194,7 +207,10 @@ impl KeyStore for SqliteKeyStore { } // A row that already holds this data changes its binding and nothing // else, and is not checked again: it may have been damaged outside this - // crate, and a sign-out still has to unbind it. + // crate, and a sign-out still has to unbind it. "Holds this data" is + // meant as `get` reads it: for a `data` that is not text, `get` hands out + // the text with the odd bytes replaced, `REBIND` cannot match that, and + // the second statement takes the blob for the data that is there. let rebound = store .db .prepare_cached(REBIND) @@ -209,7 +225,7 @@ impl KeyStore for SqliteKeyStore { columns.synced, ]) .map_err(backend)?; - if rebound > 0 { + if rebound > 0 || rebind_stored_bytes(&store, blob, &columns)? { return Ok(()); } if blob.kind == KIND_TEAMSPEAK { @@ -312,6 +328,53 @@ impl KeyStore for SignOutPass<'_> { } } +/// Change only the binding of the row of the blob's `(kind, uid)` if its `data` +/// is not text but reads as exactly the blob's JSON, and say whether it did. +/// +/// [`KeyStore::get`] reads a `data` that is a BLOB, or TEXT of bytes that are no +/// UTF-8, as text with the odd bytes replaced ([`lossy_text`]). The blob that a +/// sign-out puts back to unbind such a row carries that text, so `REBIND` finds +/// nothing, and writing the blob would replace the stored bytes with the +/// replaced text (and refuse a TeamSpeak row, whose replaced text is no +/// identity, for ever). The text `get` handed out is taken for the data that is +/// there, and the bytes are kept. +/// +/// It is called after `REBIND` changed nothing, which is why the stored value is +/// known not to be exactly the blob's text. Any other JSON does not match, and +/// is a new identity for the uid as ever. +fn rebind_stored_bytes( + store: &Store, + blob: &IdentityBlob, + columns: &BindingColumns, +) -> KsResult { + let reads_as_blob = store + .db + .prepare_cached("SELECT data FROM identities WHERE kind = ?1 AND uid = ?2") + .map_err(backend)? + .query_row(params![blob.kind, blob.uid], |row| { + Ok(lossy_text(row.get_ref(0)?).is_some_and(|text| text == blob.json)) + }) + .optional() + .map_err(backend)?; + if reads_as_blob != Some(true) { + return Ok(false); + } + store + .db + .prepare_cached(REBIND_BYTES) + .map_err(backend)? + .execute(params![ + blob.kind, + blob.uid, + columns.account, + columns.integration, + columns.rev, + columns.synced, + ]) + .map_err(backend)?; + Ok(true) +} + /// A TeamSpeak blob is stored only if it is what its kind says: the JSON of a /// `tsproto::Identity` whose key has the uid the blob names. /// diff --git a/crates/voelin-store/tests/keystore.rs b/crates/voelin-store/tests/keystore.rs index a4b46fb..5da0b3e 100644 --- a/crates/voelin-store/tests/keystore.rs +++ b/crates/voelin-store/tests/keystore.rs @@ -1431,6 +1431,159 @@ fn an_account_row_whose_data_is_not_text_is_deleted_like_an_unreadable_record() } } +// ------------------ a `data` column that is not text (the gate's second probe) + +/// `data` of a row as SQLite holds it: its storage class and its bytes. +fn raw_data(db: &Connection, blob: &IdentityBlob) -> (String, Vec) { + db.query_row( + "SELECT typeof(data), CAST(data AS BLOB) FROM identities WHERE kind = ?1 AND uid = ?2", + params![blob.kind, blob.uid], + |row| Ok((row.get(0)?, row.get(1)?)), + ) + .unwrap() +} + +/// Bytes that are no UTF-8: `{"v":"`, 0xff, `1}`. +const NOT_UTF8: &str = "x'7b2276223aff317d'"; + +/// Five bound, device-only rows whose `data` is not text, as something outside +/// this crate could have left them (the identities as they were put, unbound, +/// are returned): +/// +/// 0. a Voelin key whose data is a BLOB of bytes that are no UTF-8; +/// 1. a row of a kind a later version adds, whose data is a BLOB; +/// 2. a row of that kind whose data is TEXT of bytes that are no UTF-8; +/// 3. a TeamSpeak row whose data is a BLOB of bytes that are no identity; +/// 4. a TeamSpeak row whose data is a BLOB of a good identity. +fn rows_without_text(install: &OnFile) -> Vec { + let device_only = AccountBinding { synced: false, ..binding() }; + let blobs = vec![ + IdentityBlob::voelin(&IdentityKey::generate().unwrap()).unwrap(), + IdentityBlob::new("future", "future:one", 0, r#"{"secret":"one"}"#), + IdentityBlob::new("future", "future:two", 0, r#"{"secret":"two"}"#), + fresh_teamspeak(None), + fresh_teamspeak(None), + ]; + let damage = [ + NOT_UTF8, + "CAST(data AS BLOB)", + &format!("CAST({NOT_UTF8} AS TEXT)"), + "x'ff00fe'", + "CAST(data AS BLOB)", + ]; + for (blob, set) in blobs.iter().zip(damage) { + install.store.put(&blob.clone().with_binding(device_only)).unwrap(); + install.damage(&format!( + "UPDATE identities SET data = {set} WHERE kind = '{}' AND uid = '{}'", + blob.kind, blob.uid + )); + } + blobs +} + +#[test] +fn a_sign_out_keeps_the_bytes_of_a_bound_row_whose_data_is_not_text() { + // The gate's probe. A `data` column that is a BLOB, or TEXT that is no + // UTF-8, is read as text with the odd bytes replaced. Unbinding such a row + // must write the binding and leave `data` the bytes it is (a Voelin key, a + // kind that passes through untouched), and a TeamSpeak row of that kind must + // not keep the sign-out from finishing because its replaced text is no + // identity. + for choice in [DeviceKeyChoice::Auto, DeviceKeyChoice::Forget(key().uid())] { + let install = signed_in_install_on_file(true); + let rows = rows_without_text(&install); + let db = Connection::open(install.scratch.db()).unwrap(); + let before: Vec<_> = rows.iter().map(|blob| raw_data(&db, blob)).collect(); + let types: Vec<_> = before.iter().map(|(class, _)| class.as_str()).collect(); + assert_eq!(types, ["blob", "blob", "text", "blob", "blob"], "the setup: {choice:?}"); + + let done = install.store.sign_out(&binding().account, choice).unwrap(); + let unbound = sorted(done.unbound.clone()); + for row in &rows { + assert!( + unbound.contains(&pair(row)), + "{choice:?}: {:?} is unbound: {done:?}", + pair(row) + ); + } + let after: Vec<_> = rows.iter().map(|blob| raw_data(&db, blob)).collect(); + assert_eq!(after, before, "{choice:?}: data is byte for byte what it was"); + for blob in &rows { + let stored = install.store.get(&blob.kind, &blob.uid).unwrap().unwrap(); + assert_eq!(stored.binding, None, "{choice:?}: {:?}", pair(blob)); + let account: Option = db + .query_row( + "SELECT account FROM identities WHERE kind = ?1 AND uid = ?2", + params![blob.kind, blob.uid], + |row| row.get(0), + ) + .unwrap(); + assert_eq!(account, None, "{choice:?}: {:?}", pair(blob)); + } + // The rest of the sign-out happened, and a retry has nothing to do. + let store = &install.store; + assert!(store.get(KIND_ACCOUNT, &record().blob_uid()).unwrap().is_none(), "{choice:?}"); + assert!(store.get(KIND_TEAMSPEAK, &install.synced.uid).unwrap().is_none(), "{choice:?}"); + assert!(store.bound_to(&binding().account).unwrap().is_empty(), "{choice:?}"); + assert_eq!(store.sign_out(&binding().account, choice).unwrap(), SignOut::default()); + } +} + +#[test] +fn a_put_of_what_get_read_changes_the_binding_and_keeps_the_stored_bytes() { + let install = signed_in_install_on_file(true); + let rows = rows_without_text(&install); + let db = Connection::open(install.scratch.db()).unwrap(); + let moved = AccountBinding { rev: 9, ..binding() }; + for blob in &rows { + let before = raw_data(&db, blob); + let read = install.store.get(&blob.kind, &blob.uid).unwrap().unwrap(); + for binding in [Some(moved), None] { + install.store.put(&read.clone().with_binding(binding)).unwrap(); + let label = format!("{:?}, {binding:?}", pair(blob)); + assert_eq!(raw_data(&db, blob), before, "{label}: the bytes are kept"); + let stored = install.store.get(&blob.kind, &blob.uid).unwrap().unwrap(); + assert_eq!(stored.binding, binding, "{label}"); + } + } +} + +#[test] +fn a_put_of_other_data_over_a_row_that_is_not_text_is_checked_and_replaces_it() { + // Only what `get` read is taken for the data that is there. Other data is a + // new identity for that uid: refused when it is not what its kind says, and + // stored (as TEXT) when it is. + let install = signed_in_install_on_file(true); + let rows = rows_without_text(&install); + let db = Connection::open(install.scratch.db()).unwrap(); + let garbage = &rows[3]; + let before = raw_data(&db, garbage); + + let worse = IdentityBlob::from_row(KIND_TEAMSPEAK, garbage.uid.clone(), 0, "worse".to_owned()); + assert!(matches!(install.store.put(&worse), Err(KeyStoreError::Backend(_)))); + let stranger = Identity::create(); + let hijack = IdentityBlob::teamspeak( + garbage.uid.clone(), + stranger.level(), + serde_json::to_string(&stranger).unwrap(), + ); + assert!(matches!(install.store.put(&hijack), Err(KeyStoreError::Blob(BlobError::UidMismatch)))); + assert_eq!(raw_data(&db, garbage), before, "refused, so nothing is written"); + + // The identity the uid names replaces the bytes, and the row is TEXT again. + install.store.put(garbage).unwrap(); + assert_eq!(raw_data(&db, garbage), ("text".to_owned(), garbage.json.clone().into_bytes())); + assert_eq!(install.store.get(&garbage.kind, &garbage.uid).unwrap().unwrap(), *garbage); + + // The same identity over the BLOB that holds it is not data of another + // value: the bytes stay. + let good = &rows[4]; + let before = raw_data(&db, good); + assert_eq!(before.0, "blob"); + install.store.put(good).unwrap(); + assert_eq!(raw_data(&db, good), before); +} + // ------------------------------------------- a deleted key is gone from the file /// The database file and its write-ahead log, as the bytes on disk. diff --git a/docs/architecture.md b/docs/architecture.md index 7f87069..a93bc12 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -347,8 +347,13 @@ origin and default flag, a uid another kind holds is refused, a TeamSpeak blob is stored only when its JSON is a tsproto identity whose key has the uid it names (the error says only that, never the JSON: it is a private key), and the TeamSpeak security level is still computed from the key, never stored. A -`put` that changes only the binding of a row does not read its JSON again, so a -row damaged outside the client cannot keep a sign-out from unbinding it. +`put` that changes only the binding of a row (its data is what `get` read from +the row) neither checks nor rewrites the data, so a row whose data was damaged +outside the client (JSON that is no identity, a BLOB, bytes that are no UTF-8) +cannot keep a sign-out from unbinding it, and keeps its data byte for byte. +`get` hands such data out as text with the odd bytes replaced, and the `put` of +that text is taken for the data that is there; any other text is a new identity +for the uid, checked as ever, and replaces the bytes. A row whose binding columns cannot be read is listed and read as unbound, with a warning, instead of failing the list; so no damaged row, the account record's included, keeps a sign-out from finishing, and `Forget` still deletes the key