diff --git a/crates/voelin-store/src/keystore.rs b/crates/voelin-store/src/keystore.rs index a7d53b2..8e0f2ef 100644 --- a/crates/voelin-store/src/keystore.rs +++ b/crates/voelin-store/src/keystore.rs @@ -18,8 +18,11 @@ //! counter in `data`, as [`Store::identities`] always did, and the level of a //! blob a caller puts is ignored. A TeamSpeak row whose JSON cannot be read //! (it could only have been damaged outside this crate) lists and reads with -//! level 0 instead of failing the whole list, so that signing out is never -//! blocked by it. +//! 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. //! //! 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 @@ -46,6 +49,12 @@ const LIST: &str = "SELECT kind, uid, CASE WHEN kind = 'teamspeak' THEN data END account, integration, integration_rev, synced FROM identities ORDER BY kind, uid"; +/// Replace the binding of the row of this `(kind, uid)` if its `data` is +/// exactly the blob's: nothing else of the row is written. +const REBIND: &str = "UPDATE identities + SET account = ?4, integration = ?5, integration_rev = ?6, synced = ?7 + WHERE kind = ?1 AND uid = ?2 AND data = ?3"; + /// 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. @@ -68,7 +77,7 @@ 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; each call here is one statement. +/// `voelin-identity` defines them, on top of the five methods here. pub struct SqliteKeyStore { store: Mutex, } @@ -98,7 +107,8 @@ impl SqliteKeyStore { fn lock(&self) -> MutexGuard<'_, Store> { // A panic in another thread cannot leave the table half-updated: every - // method here is one statement. + // write here is one statement, and `put` tries a second one only when + // the first changed nothing. self.store.lock().unwrap_or_else(PoisonError::into_inner) } } @@ -121,11 +131,31 @@ impl KeyStore for SqliteKeyStore { } fn put(&self, blob: &IdentityBlob) -> KsResult<()> { + let columns = blob.binding_columns()?; + let store = self.lock(); + // 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. + let rebound = store + .db + .prepare_cached(REBIND) + .map_err(backend)? + .execute(params![ + blob.kind, + blob.uid, + blob.json, + columns.account, + columns.integration, + columns.rev, + columns.synced, + ]) + .map_err(backend)?; + if rebound > 0 { + return Ok(()); + } if blob.kind == KIND_TEAMSPEAK { check_teamspeak(blob)?; } - let columns = blob.binding_columns()?; - let store = self.lock(); let changed = store .db .prepare_cached(PUT) diff --git a/crates/voelin-store/tests/keystore.rs b/crates/voelin-store/tests/keystore.rs index eed3e05..2d5a396 100644 --- a/crates/voelin-store/tests/keystore.rs +++ b/crates/voelin-store/tests/keystore.rs @@ -19,6 +19,7 @@ //! last section. use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; use rusqlite::{Connection, params}; use tsclientlib::Identity; @@ -51,9 +52,13 @@ const ACCOUNT_ID_BYTES: [u8; 16] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 struct Scratch(std::path::PathBuf); impl Scratch { + /// A directory of its own for each call, also for two tests that pass the + /// same name and run side by side. fn new(name: &str) -> Self { + static NEXT: AtomicUsize = AtomicUsize::new(0); + let n = NEXT.fetch_add(1, Ordering::Relaxed); let dir = - std::env::temp_dir().join(format!("voelin-keystore-{name}-{}", std::process::id())); + std::env::temp_dir().join(format!("voelin-keystore-{name}-{}-{n}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); Self(dir) @@ -972,6 +977,134 @@ fn forgetting_the_identity_with_an_unreadable_record_still_deletes_the_named_key } } +/// A signed-in install on a file, with the device-only secret's `data` +/// replaced by `damage` through a second connection, as something outside this +/// crate could damage it. +struct Damaged { + _scratch: Scratch, + store: SqliteKeyStore, + synced: IdentityBlob, + device_only: IdentityBlob, +} + +fn install_with_a_damaged_device_secret(bound_existing_key: bool, damage: &str) -> Damaged { + let scratch = Scratch::new("damaged-row"); + let store = SqliteKeyStore::open(&scratch.db()).unwrap(); + let synced = fresh_teamspeak(binding()); + let device_only = fresh_teamspeak(AccountBinding { synced: false, ..binding() }); + store.put_voelin_key(&key()).unwrap(); + store.put_account_record(&AccountRecord { bound_existing_key, ..record() }).unwrap(); + store.put(&synced).unwrap(); + store.put(&device_only).unwrap(); + let db = Connection::open(scratch.db()).unwrap(); + let changed = db + .execute("UPDATE identities SET data = ?1 WHERE uid = ?2", params![damage, device_only.uid]) + .unwrap(); + assert_eq!(changed, 1); + Damaged { _scratch: scratch, store, synced, device_only } +} + +#[test] +fn a_damaged_device_secret_does_not_block_a_sign_out() { + // The row is bound, device-only, and its JSON is no identity (it could only + // have been damaged outside this crate). Signing out unbinds it without + // reading the JSON again, deletes the record, and leaves the row as it is. + for damage in ["damaged", "", "{}", r#"{"key":"AAAA","counter":1,"max_counter":1}"#] { + let Damaged { _scratch, store, synced, device_only } = + install_with_a_damaged_device_secret(true, damage); + let listed = store.bound_to(&binding().account).unwrap(); + assert_eq!(sorted(listed), sorted(vec![info_of(&synced), info_of(&device_only)])); + + let done = store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap(); + assert_eq!(done.removed.len(), 2, "{damage:?}: {done:?}"); + assert!(done.removed.contains(&info_of(&synced))); + assert!( + done.removed.iter().any(|i| i.kind == KIND_ACCOUNT && i.uid == record().blob_uid()) + ); + let unbound: Vec<_> = + done.unbound.iter().map(|i| (i.kind.clone(), i.uid.clone())).collect(); + assert!(unbound.contains(&pair(&device_only)), "{damage:?}: {done:?}"); + assert!(unbound.contains(&pair(&IdentityBlob::voelin(&key()).unwrap())), "{done:?}"); + + // The record is gone, so the sign-out is complete and a retry has + // nothing to do; the row keeps its damaged JSON, unbound; the device key + // predates the account and stays. + assert!(store.get(KIND_ACCOUNT, &record().blob_uid()).unwrap().is_none(), "{damage:?}"); + assert!(store.get(KIND_TEAMSPEAK, &synced.uid).unwrap().is_none()); + let row = store.get(KIND_TEAMSPEAK, &device_only.uid).unwrap().unwrap(); + assert_eq!((row.binding, row.json.as_str(), row.level), (None, damage, 0)); + assert!(store.voelin_key(&key().uid()).unwrap().is_some()); + assert!(store.bound_to(&binding().account).unwrap().is_empty()); + assert_eq!( + store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap(), + SignOut::default() + ); + } +} + +#[test] +fn forgetting_the_identity_with_a_damaged_device_secret_still_deletes_the_named_key() { + // The user chose "Forget this device's identity" while a device-only secret + // is damaged: the named key is deleted, the record goes, and the secret is + // unbound, not left to fail every retry. + for bound_existing_key in [true, false] { + let Damaged { _scratch, store, synced, device_only } = + install_with_a_damaged_device_secret(bound_existing_key, "damaged"); + let other = IdentityKey::generate().unwrap(); + store.put_voelin_key(&other).unwrap(); + + let forget = DeviceKeyChoice::Forget(key().uid()); + let done = store.sign_out(&binding().account, forget).unwrap(); + assert!(done.removed.contains(&device_key_info()), "{done:?}"); + assert!(store.voelin_key(&key().uid()).unwrap().is_none(), "{bound_existing_key}"); + assert!(store.get(KIND_ACCOUNT, &record().blob_uid()).unwrap().is_none()); + assert!(store.get(KIND_TEAMSPEAK, &synced.uid).unwrap().is_none()); + let row = store.get(KIND_TEAMSPEAK, &device_only.uid).unwrap().unwrap(); + assert_eq!((row.binding, row.json.as_str()), (None, "damaged")); + assert!(store.voelin_key(&other.uid()).unwrap().is_some()); + assert_eq!(store.sign_out(&binding().account, forget).unwrap(), SignOut::default()); + assert!(store.voelin_key(&key().uid()).unwrap().is_none()); + } +} + +#[test] +fn a_put_that_changes_only_the_binding_writes_the_binding_and_nothing_else() { + let Damaged { _scratch, store, device_only, .. } = + install_with_a_damaged_device_secret(true, "damaged"); + let uid = &device_only.uid; + + // The same data with another binding is accepted, however the data reads. + let moved = AccountBinding { rev: 9, ..binding() }; + let rebound = IdentityBlob::from_row(KIND_TEAMSPEAK, uid.clone(), 0, "damaged".to_owned()) + .with_binding(moved); + store.put(&rebound).unwrap(); + let row = store.get(KIND_TEAMSPEAK, uid).unwrap().unwrap(); + assert_eq!((row.binding, row.json.as_str()), (Some(moved), "damaged")); + let unbound = rebound.clone().with_binding(None); + store.put(&unbound).unwrap(); + assert_eq!(store.get(KIND_TEAMSPEAK, uid).unwrap().unwrap().binding, None); + + // Other data is a new identity for that uid and is checked as ever: damage + // is not replaced by more damage, nor by the key of a stranger. + let worse = IdentityBlob::from_row(KIND_TEAMSPEAK, uid.clone(), 0, "worse".to_owned()); + assert!(matches!(store.put(&worse), Err(KeyStoreError::Backend(_)))); + let stranger = Identity::create(); + let hijack = IdentityBlob::teamspeak( + uid.clone(), + stranger.level(), + serde_json::to_string(&stranger).unwrap(), + ); + assert!(matches!(store.put(&hijack), Err(KeyStoreError::Blob(BlobError::UidMismatch)))); + let row = store.get(KIND_TEAMSPEAK, uid).unwrap().unwrap(); + assert_eq!((row.binding, row.json.as_str()), (None, "damaged")); + + // The fast path is for a row of the same kind: another kind's put of this + // uid is still refused, and replaces nothing. + let other_kind = IdentityBlob::new("other", uid.as_str(), 0, "damaged"); + assert!(matches!(store.put(&other_kind), Err(KeyStoreError::Backend(_)))); + assert!(store.get("other", uid).unwrap().is_none()); +} + #[test] fn forgetting_deletes_the_key_the_caller_names_and_no_other() { // `Forget` acts on the uid it carries, not on what the record says.