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