//! The `identities` table as a [`voelin_identity::KeyStore`]. //! //! The table holds identities of more than one kind: the TeamSpeak identities //! the client has always had (`kind` `teamspeak`, `data` the JSON of a //! `tsproto::Identity`), a Voelin key (`voelin`), the record of the account the //! installation is signed in to (`account`) and whatever kind a later version //! adds, which passes through untouched. A row is addressed by its //! `(kind, uid)`, and `uid` stays `UNIQUE` across kinds: the uid forms of the //! kinds do not overlap (a TeamSpeak uid is base64, a Voelin uid 52 characters //! of `a-z2-7`, an account uid is written `account:`). //! //! Besides the blob a row carries the columns of the TeamSpeak-only world, //! which a [`KeyStore`] does not see and keeps when it replaces a row: `name`, //! `origin`, `is_default` and `created`. A blob of a new `(kind, uid)` becomes a //! row named after its uid, of origin `user` and not the default. //! //! The TeamSpeak security level is not stored: it is computed from the key and //! 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, and a [`KeyStore::put`] that only //! changes the binding of a row (the row of that `(kind, uid)` already holds //! 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 //! 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 (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 //! 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 //! 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. use std::path::Path; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Mutex, MutexGuard, PoisonError}; use rusqlite::types::ValueRef; use rusqlite::{OptionalExtension, params}; use tsclientlib::Identity; use voelin_identity::migrate::SELECT_ACCOUNT_COLUMNS; use voelin_identity::{ AccountBinding, BindingColumns, BlobError, DeviceKeyChoice, IdentityBlob, IdentityInfo, KIND_ACCOUNT, KIND_TEAMSPEAK, KIND_VOELIN, KeyStore, KeyStoreError, SignOut, Uid, }; use crate::{Error, Result, Store}; /// A result of the key store seam. 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, id 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"; /// [`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. const PUT: &str = "INSERT INTO identities (name, uid, data, kind, account, integration, integration_rev, synced) VALUES (?1, ?1, ?2, ?3, ?4, ?5, ?6, ?7) ON CONFLICT (uid) DO UPDATE SET data = excluded.data, account = excluded.account, integration = excluded.integration, integration_rev = excluded.integration_rev, synced = excluded.synced WHERE identities.kind = excluded.kind"; /// The identities of a client database as a [`KeyStore`]: every kind, with its /// account binding. /// /// It owns a [`Store`] behind a mutex, because a [`KeyStore`] is `Sync` and a /// SQLite connection is not. Open it on the database file next to the /// other connections of the app (the settings writer and the chat history do /// the same): SQLite lets them share the file. [`Self::with_store`] gives /// 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; the /// sign-out only truncates the write-ahead log once, at its end. pub struct SqliteKeyStore { store: Mutex, } impl SqliteKeyStore { /// The identities of an open [`Store`]. pub fn new(store: Store) -> Self { Self { store: Mutex::new(store) } } /// Open or create the database at `path`, migrating it. pub fn open(path: &Path) -> Result { Ok(Self::new(Store::open(path)?)) } /// A key store in memory: for tests. pub fn open_in_memory() -> Result { Ok(Self::new(Store::open_in_memory()?)) } /// Run `f` on the [`Store`] behind this key store, holding its lock: the /// TeamSpeak identity methods (`identities`, `default_identity`, ...) see /// the same rows on the same connection. pub fn with_store(&self, f: impl FnOnce(&Store) -> R) -> R { f(&self.lock()) } fn lock(&self) -> MutexGuard<'_, Store> { // A panic in another thread cannot leave the table half-updated: every // 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) } } impl KeyStore for SqliteKeyStore { fn list(&self) -> KsResult> { 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)?; 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}, 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)?; Ok(rows.next().transpose().map_err(backend)?.flatten().map(Columns::into_blob)) } 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. "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) .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 || rebind_stored_bytes(&store, blob, &columns)? { return Ok(()); } if blob.kind == KIND_TEAMSPEAK { check_teamspeak(blob)?; } let changed = store .db .prepare_cached(PUT) .map_err(backend)? .execute(params![ blob.uid, blob.json, blob.kind, columns.account, columns.integration, columns.rev, columns.synced, ]) .map_err(backend)?; if changed == 0 { let held_by: String = store .db .query_row("SELECT kind FROM identities WHERE uid = ?1", [&blob.uid], |r| r.get(0)) .map_err(backend)?; return Err(KeyStoreError::backend(Refused::UidHeld { uid: blob.uid.clone(), kind: held_by, })); } Ok(()) } fn remove(&self, kind: &str, uid: &str) -> KsResult { let store = self.lock(); 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) } /// 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) } } /// 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. /// /// The first keeps one bad row, which a service or a damaged file could hand /// over, from failing the list of TeamSpeak identities for everyone. The /// second keeps a blob from overwriting, by its uid, the key of a different /// identity that is stored under that uid. /// /// The parse error of serde is dropped, not forwarded: it can quote the text /// it choked on, which is a private key, into a log line. fn check_teamspeak(blob: &IdentityBlob) -> KsResult<()> { let Ok(identity) = serde_json::from_str::(&blob.json) else { return Err(KeyStoreError::backend(Refused::NotATeamSpeakIdentity)); }; if identity.key().to_pub().get_uid() != blob.uid { return Err(KeyStoreError::Blob(BlobError::UidMismatch)); } 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()) } /// A [`KeyStore::put`] this store refuses. #[derive(Debug, thiserror::Error)] enum Refused { /// The JSON is not that of a `tsproto::Identity`. The text is a private /// key, so the error does not repeat it, nor serde's account of it. #[error("the TeamSpeak identity JSON is not that of an identity")] NotATeamSpeakIdentity, /// `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 /// 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, /// `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 { /// 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 /// that is no identity. fn level(&self) -> u8 { match &self.data { Some(json) if self.kind == KIND_TEAMSPEAK => { serde_json::from_str::(json).map_or(0, |identity| identity.level()) } _ => 0, } } fn into_info(self) -> IdentityInfo { let level = self.level(); IdentityInfo { kind: self.kind, uid: self.uid, level, binding: self.binding } } fn into_blob(self) -> IdentityBlob { let level = self.level(); let data = self.data.unwrap_or_default(); 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()) } } }