diff --git a/crates/voelin-store/src/keystore.rs b/crates/voelin-store/src/keystore.rs new file mode 100644 index 0000000..8603b2c --- /dev/null +++ b/crates/voelin-store/src/keystore.rs @@ -0,0 +1,250 @@ +//! 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, so that signing out is never +//! blocked by it. + +use std::path::Path; +use std::sync::{Mutex, MutexGuard, PoisonError}; + +use rusqlite::params; +use tsclientlib::Identity; +use voelin_identity::migrate::SELECT_ACCOUNT_COLUMNS; +use voelin_identity::{ + AccountBinding, BlobError, IdentityBlob, IdentityInfo, KIND_TEAMSPEAK, KeyStore, KeyStoreError, +}; + +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 + FROM identities ORDER BY kind, uid"; + +/// 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; each call here is one statement. +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 + // method here is one statement. + 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)?; + rows.map(|row| row.map_err(backend)?.into_info()).collect() + } + + 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 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() + } + + fn put(&self, blob: &IdentityBlob) -> KsResult<()> { + if blob.kind == KIND_TEAMSPEAK { + check_teamspeak(blob)?; + } + let columns = blob.binding_columns()?; + let store = self.lock(); + 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 = 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 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. +fn check_teamspeak(blob: &IdentityBlob) -> KsResult<()> { + let identity: Identity = + serde_json::from_str(&blob.json).map_err(|e| backend(Error::Json(e)))?; + if identity.key().to_pub().get_uid() != blob.uid { + return Err(KeyStoreError::Blob(BlobError::UidMismatch)); + } + 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 { + /// `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 }, +} + +/// One row of the table as `LIST` and `SELECT_ACCOUNT_COLUMNS` select it. +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, +} + +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 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) -> KsResult { + let binding = self.binding()?; + let level = self.level(); + Ok(IdentityInfo { kind: self.kind, uid: self.uid, level, binding }) + } + + fn into_blob(self) -> KsResult { + let binding = self.binding()?; + let level = self.level(); + let data = self.data.unwrap_or_default(); + Ok(IdentityBlob::from_row(&self.kind, self.uid, level, data).with_binding(binding)) + } +} diff --git a/crates/voelin-store/src/lib.rs b/crates/voelin-store/src/lib.rs index d420d5d..696290a 100644 --- a/crates/voelin-store/src/lib.rs +++ b/crates/voelin-store/src/lib.rs @@ -7,9 +7,16 @@ //! //! The schema is versioned (`PRAGMA user_version`): opening a database runs //! the migrations it has not seen, each in one transaction, keeping the data. +//! +//! The `identities` table keeps identities of more than one kind. [`Store`] +//! has the TeamSpeak identities the client has always had; [`SqliteKeyStore`] +//! is the table as a `voelin_identity::KeyStore`: every kind (TeamSpeak, a +//! Voelin key, the record of the signed-in account), each with the binding that +//! says whether it belongs to an account, and the sign-out of that account. pub mod chat; pub mod contacts; +mod keystore; mod secrets; mod store; @@ -18,6 +25,7 @@ pub use chat::{ StoredMessage, SyncState, WriteOutcome, Written, }; pub use contacts::{Contact, ContactSeen, Relation}; +pub use keystore::SqliteKeyStore; #[cfg(feature = "keyring")] pub use secrets::KeyringSecrets; pub use secrets::{MemorySecrets, Secrets}; diff --git a/crates/voelin-store/src/store.rs b/crates/voelin-store/src/store.rs index 092429d..fe21b09 100644 --- a/crates/voelin-store/src/store.rs +++ b/crates/voelin-store/src/store.rs @@ -799,6 +799,78 @@ mod tests { std::fs::remove_dir_all(dir).unwrap(); } + /// The acceptance of the migration for the key store: a `client.db` at the + /// version before the identity migrations (5), and at the one between them + /// (6), opens, and every identity loads through the key store unchanged: + /// kind `teamspeak`, no binding, its JSON byte for byte, the level computed + /// as before, and the origin and default flag the old API reports kept. + #[test] + fn a_migrated_database_loads_every_identity_unchanged_through_the_key_store() { + use crate::SqliteKeyStore; + use voelin_identity::{IdentityBlob, IdentityInfo, KIND_TEAMSPEAK, KeyStore}; + + for version in [5, 6] { + let dir = scratch_dir(&format!("keys-v{version}")); + let path = dir.join("client.db"); + let other = Identity::create(); + let other_json = serde_json::to_string(&other).unwrap(); + let other_uid = other.key().to_pub().get_uid(); + database_at(&path, version); + { + let db = rusqlite::Connection::open(&path).unwrap(); + for (name, uid, json, origin, default) in [ + ("Main", TEAMSPEAK_UID, TEAMSPEAK_JSON, "imported", 1), + ("Other", other_uid.as_str(), other_json.as_str(), "created", 0), + ] { + db.execute( + "INSERT INTO identities (name, uid, data, origin, is_default) + VALUES (?1, ?2, ?3, ?4, ?5)", + params![name, uid, json, origin, default], + ) + .unwrap(); + } + } + + let keys = SqliteKeyStore::open(&path).unwrap(); + assert_eq!(keys.with_store(|s| s.schema_version().unwrap()), 7); + let want = [ + (TEAMSPEAK_UID.to_owned(), TEAMSPEAK_JSON.to_owned(), TEAMSPEAK_LEVEL), + (other_uid.clone(), other_json.clone(), other.level()), + ]; + let mut infos: Vec<_> = want + .iter() + .map(|(uid, _, level)| IdentityInfo { + kind: KIND_TEAMSPEAK.into(), + uid: uid.clone(), + level: *level, + binding: None, + }) + .collect(); + infos.sort_by(|a, b| a.uid.cmp(&b.uid)); + assert_eq!(keys.list().unwrap(), infos, "version {version}"); + for (uid, json, level) in want { + let blob = keys.get(KIND_TEAMSPEAK, &uid).unwrap().unwrap(); + assert_eq!(blob, IdentityBlob::teamspeak(&uid, level, &json), "version {version}"); + assert_eq!(blob.json, json, "byte for byte"); + assert_eq!(blob.binding, None); + } + + // What the TeamSpeak methods report is kept as well. + let entries = keys.with_store(|s| s.identities().unwrap()); + let origin = |uid: &str| entries.iter().find(|e| e.uid == uid).unwrap(); + assert_eq!( + (origin(TEAMSPEAK_UID).origin, origin(TEAMSPEAK_UID).is_default), + (IdentityOrigin::Imported, true) + ); + assert_eq!( + (origin(&other_uid).origin, origin(&other_uid).is_default), + (IdentityOrigin::Created, false) + ); + drop(keys); + std::fs::remove_dir_all(dir).unwrap(); + } + } + /// A database of version 6 (the `kind` column, no account columns yet) takes /// the second step alone, and its rows of other kinds stay what they are. #[test] diff --git a/crates/voelin-store/tests/keystore.rs b/crates/voelin-store/tests/keystore.rs new file mode 100644 index 0000000..edaad7b --- /dev/null +++ b/crates/voelin-store/tests/keystore.rs @@ -0,0 +1,606 @@ +//! The `identities` table as a `voelin_identity::KeyStore` (`SqliteKeyStore`): +//! the behaviour every key store has, bound and synced entries, and the rows +//! the TeamSpeak methods of `Store` share with it. +//! +//! The behaviour cases are the `exercise` of `voelin-identity`'s +//! `tests/storage.rs` (a private function of that test crate, which the client +//! copies, as the protocol's Phase 2 task for this crate says), with the two +//! deviations a SQLite store has and the memory store does not; each is marked +//! `DEVIATION` where it happens: +//! +//! - `identities.uid` is `UNIQUE` across kinds, so the same uid under another +//! kind is refused (the trait allows this, see `KeyStore::put`). +//! - The TeamSpeak level is computed from the key and counter, as the store +//! always did; the level of a blob that is put is not stored. The case that +//! raised the level with an invented one raises it with a real counter. + +use std::sync::Arc; + +use rusqlite::{Connection, params}; +use tsclientlib::Identity; +use voelin_identity::{ + AccountBinding, AccountId, AccountRecord, BlobError, IdentityBlob, IdentityInfo, IdentityKey, + IntegrationId, KIND_ACCOUNT, KIND_TEAMSPEAK, KIND_VOELIN, KeyStore, KeyStoreError, Uid, + UidParseError, account_uid, +}; +use voelin_store::{IdentityOrigin, SqliteKeyStore, Store}; + +/// What `serde_json::to_string(&tsproto::Identity)` writes for the test +/// identity of tsproto's own `identity_tests`. +const TEAMSPEAK_JSON: &str = r#"{"key":"YTyJofmztcTBjq3KZcDdxu+G4RPVwE5vg8VaN2jbQao=","counter":2792354,"max_counter":2792354}"#; +/// `Identity::key().to_pub().get_uid()` of that identity. +const TEAMSPEAK_UID: &str = "test/9PZ9vww/Bpf5vJxtJhpz80="; +const TEAMSPEAK_LEVEL: u8 = 21; +/// The same key with another counter. +const RAISED_JSON: &str = r#"{"key":"YTyJofmztcTBjq3KZcDdxu+G4RPVwE5vg8VaN2jbQao=","counter":9000000,"max_counter":9000000}"#; + +const SEED: [u8; 32] = [ + 0x9d, 0x61, 0xb1, 0x9d, 0xef, 0xfd, 0x5a, 0x60, 0xba, 0x84, 0x4a, 0xf4, 0x92, 0xec, 0x2c, 0xc4, + 0x44, 0x49, 0xc5, 0x69, 0x7b, 0x32, 0x69, 0x19, 0x70, 0x3b, 0xac, 0x03, 0x1c, 0xae, 0x7f, 0x60, +]; +const RFC8032_UID: &str = "eh7ddx5bksrgcytl7bkai36se4nxx3klnk7elksyq57pi74xeg4q"; +/// The issuer id of an account service whose root key is the RFC 8032 test key. +const ISSUER: &str = RFC8032_UID; +const ACCOUNT_ID_BYTES: [u8; 16] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]; + +/// A scratch directory that is removed again. +struct Scratch(std::path::PathBuf); + +impl Scratch { + fn new(name: &str) -> Self { + let dir = + std::env::temp_dir().join(format!("voelin-keystore-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + Self(dir) + } + + fn db(&self) -> std::path::PathBuf { + self.0.join("client.db") + } +} + +impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn teamspeak_blob() -> IdentityBlob { + IdentityBlob::teamspeak(TEAMSPEAK_UID, TEAMSPEAK_LEVEL, TEAMSPEAK_JSON) +} + +fn key() -> IdentityKey { + IdentityKey::from_seed(&SEED).unwrap() +} + +fn issuer() -> Uid { + Uid::from_base32(ISSUER).unwrap() +} + +fn account_id() -> AccountId { + AccountId::from_bytes(ACCOUNT_ID_BYTES) +} + +/// A fresh TeamSpeak identity as a blob, with its real uid and level, bound as +/// given. +fn fresh_teamspeak(binding: impl Into>) -> IdentityBlob { + let identity = Identity::create(); + IdentityBlob::teamspeak( + identity.key().to_pub().get_uid(), + identity.level(), + serde_json::to_string(&identity).unwrap(), + ) + .with_binding(binding) +} + +/// The record of an install whose device key was made for the account. +fn record() -> AccountRecord { + AccountRecord { + service: "https://accounts.example.org".into(), + issuer: issuer(), + account_id: account_id(), + device: key().uid(), + bound_existing_key: false, + login: "alice".into(), + cert: vec![0x0a, 0x03, 0x62, 0x6f, 0x64, 0xff], + } +} + +fn binding() -> AccountBinding { + AccountBinding { + account: account_uid(&issuer(), &account_id()), + integration: Some(IntegrationId::from_bytes([7; 16])), + rev: 3, + synced: true, + } +} + +fn binding_for(seed: u8) -> Uid { + account_uid(&Uid::from_bytes([seed; 32]), &AccountId::from_bytes([seed; 16])) +} + +// ------------------------------------------------------------ key stores + +/// What every `KeyStore` must do (`voelin-identity`'s `tests/storage.rs`). +fn exercise(store: &dyn KeyStore) { + assert!(store.list().unwrap().is_empty()); + assert!(store.get(KIND_TEAMSPEAK, TEAMSPEAK_UID).unwrap().is_none()); + assert!(!store.remove(KIND_TEAMSPEAK, TEAMSPEAK_UID).unwrap()); + + // A TeamSpeak identity goes in and comes out byte for byte. + store.put(&teamspeak_blob()).unwrap(); + let ts = store.get(KIND_TEAMSPEAK, TEAMSPEAK_UID).unwrap().unwrap(); + assert_eq!(ts, teamspeak_blob()); + assert_eq!(ts.json, TEAMSPEAK_JSON); + + // A Voelin key. + let key = key(); + store.put_voelin_key(&key).unwrap(); + let back = store.voelin_key(&key.uid()).unwrap().unwrap(); + assert_eq!(back.public_key(), key.public_key()); + assert!(store.voelin_key(&IdentityKey::generate().unwrap().uid()).unwrap().is_none()); + + // A kind this crate has never heard of passes through untouched. + let discord = IdentityBlob::new("discord", "1234", 0, r#"{"token":"opaque"}"#); + store.put(&discord).unwrap(); + assert_eq!(store.get("discord", "1234").unwrap().unwrap(), discord); + + // DEVIATION: the same uid in another kind. The memory store keeps it as + // another identity; `identities.uid` is UNIQUE across kinds, which the + // trait allows for a backend: the put is a backend error and replaces + // nothing. + let same_uid = IdentityBlob::new("other", RFC8032_UID, 0, "{}"); + assert!(matches!(store.put(&same_uid), Err(KeyStoreError::Backend(_)))); + assert!(store.get("other", RFC8032_UID).unwrap().is_none()); + assert!(store.get(KIND_VOELIN, RFC8032_UID).unwrap().is_some()); + assert_eq!(store.voelin_key(&key.uid()).unwrap().unwrap().public_key(), key.public_key()); + + let mut listed = store.list().unwrap(); + listed.sort(); + assert_eq!( + listed, + vec![ + IdentityInfo { kind: "discord".into(), uid: "1234".into(), level: 0, binding: None }, + IdentityInfo { + kind: KIND_TEAMSPEAK.into(), + uid: TEAMSPEAK_UID.into(), + level: TEAMSPEAK_LEVEL, + binding: None + }, + IdentityInfo { + kind: KIND_VOELIN.into(), + uid: RFC8032_UID.into(), + level: 0, + binding: None + }, + ] + ); + + // Putting again replaces (the security level was raised). DEVIATION: the + // level is computed from the key and counter, so the new blob carries the + // level its counter really has instead of an invented one. + let raised_level = serde_json::from_str::(RAISED_JSON).unwrap().level(); + assert_ne!(raised_level, TEAMSPEAK_LEVEL, "the replacement must be visible"); + let raised = IdentityBlob::teamspeak(TEAMSPEAK_UID, raised_level, RAISED_JSON); + store.put(&raised).unwrap(); + assert_eq!(store.get(KIND_TEAMSPEAK, TEAMSPEAK_UID).unwrap().unwrap(), raised); + assert_eq!(store.list().unwrap().len(), 3); + + // Removing. + assert!(store.remove(KIND_TEAMSPEAK, TEAMSPEAK_UID).unwrap()); + assert!(!store.remove(KIND_TEAMSPEAK, TEAMSPEAK_UID).unwrap()); + assert!(store.get(KIND_TEAMSPEAK, TEAMSPEAK_UID).unwrap().is_none()); + assert_eq!(store.list().unwrap().len(), 2); + + // A stored Voelin blob that does not hold the key it names is an error + // to the caller, not a wrong key. + let mut tampered = IdentityBlob::voelin(&key).unwrap(); + tampered.json = r#"{"v":1,"pkcs8":"AAAAAAAA"}"#.into(); + store.put(&tampered).unwrap(); + assert!(matches!(store.voelin_key(&key.uid()), Err(KeyStoreError::Blob(BlobError::Key(_))))); +} + +#[test] +fn the_sqlite_store_behaves() { + exercise(&SqliteKeyStore::open_in_memory().unwrap()); +} + +#[test] +fn the_sqlite_store_behaves_on_a_file_and_after_a_reopen() { + let scratch = Scratch::new("exercise"); + exercise(&SqliteKeyStore::open(&scratch.db()).unwrap()); + // What `exercise` left is still there in a new connection. + let store = SqliteKeyStore::open(&scratch.db()).unwrap(); + assert_eq!(store.list().unwrap().len(), 2); + assert!(store.get(KIND_VOELIN, RFC8032_UID).unwrap().is_some()); + assert!(store.get("discord", "1234").unwrap().is_some()); +} + +#[test] +fn the_trait_is_object_safe_and_shareable() { + let store: Arc = Arc::new(SqliteKeyStore::open_in_memory().unwrap()); + let other = Arc::clone(&store); + std::thread::spawn(move || other.put(&teamspeak_blob()).unwrap()).join().unwrap(); + assert_eq!(store.list().unwrap().len(), 1); +} + +#[test] +fn a_put_of_a_uid_another_kind_holds_is_refused_and_replaces_nothing() { + let store = SqliteKeyStore::open_in_memory().unwrap(); + let ts = teamspeak_blob(); + store.put(&ts).unwrap(); + // The Voelin kind with a TeamSpeak uid, and an unknown kind with it. + for kind in [KIND_VOELIN, "discord"] { + let error = store.put(&IdentityBlob::new(kind, TEAMSPEAK_UID, 0, "{}")).unwrap_err(); + let KeyStoreError::Backend(source) = &error else { panic!("{error:?}") }; + let shown = source.to_string(); + assert!(shown.contains(TEAMSPEAK_UID) && shown.contains(KIND_TEAMSPEAK), "{shown}"); + } + assert_eq!(store.get(KIND_TEAMSPEAK, TEAMSPEAK_UID).unwrap().unwrap(), ts); + assert_eq!(store.list().unwrap().len(), 1); + + // A uid is addressed with its kind: another kind finds and removes nothing, + // although `uid` alone is unique in the table. + assert!(store.get(KIND_VOELIN, TEAMSPEAK_UID).unwrap().is_none()); + assert!(!store.remove(KIND_VOELIN, TEAMSPEAK_UID).unwrap()); + assert!(!store.remove("discord", TEAMSPEAK_UID).unwrap()); + assert_eq!(store.get(KIND_TEAMSPEAK, TEAMSPEAK_UID).unwrap().unwrap(), ts); +} + +// ------------------------------------------------------------ the rows + +#[test] +fn bound_and_synced_entries_round_trip_and_survive_a_reopen() { + let scratch = Scratch::new("bound"); + let account = binding_for(7); + let synced = fresh_teamspeak(AccountBinding { + account, + integration: Some(IntegrationId::from_bytes([7; 16])), + rev: 4, + synced: true, + }); + let device_only = fresh_teamspeak(AccountBinding { + account, + integration: Some(IntegrationId::from_bytes([8; 16])), + rev: 0, + synced: false, + }); + let without_integration = + fresh_teamspeak(AccountBinding { account, integration: None, rev: 0, synced: false }); + let large_rev = fresh_teamspeak(AccountBinding { + account, + integration: None, + rev: i64::MAX as u64, + synced: true, + }); + let unbound = fresh_teamspeak(None); + let voelin = IdentityBlob::voelin(&key()).unwrap(); + let record_blob = IdentityBlob::account(&record()).unwrap(); + let blobs = + [&synced, &device_only, &without_integration, &large_rev, &unbound, &voelin, &record_blob]; + + let store = SqliteKeyStore::open(&scratch.db()).unwrap(); + for blob in blobs { + store.put(blob).unwrap(); + } + for blob in blobs { + assert_eq!(&store.get(&blob.kind, &blob.uid).unwrap().unwrap(), blob); + } + // The binding is part of what a list shows. + let listed = store.list().unwrap(); + assert_eq!(listed.len(), blobs.len()); + for blob in blobs { + let info = listed.iter().find(|i| i.kind == blob.kind && i.uid == blob.uid).unwrap(); + assert_eq!((info.binding, info.level), (blob.binding, blob.level), "{}", blob.uid); + } + assert_eq!(store.account_record().unwrap(), Some(record())); + drop(store); + + // The same in a new connection, and the raw columns of the rows. + let store = SqliteKeyStore::open(&scratch.db()).unwrap(); + for blob in blobs { + assert_eq!(&store.get(&blob.kind, &blob.uid).unwrap().unwrap(), blob); + } + let db = Connection::open(scratch.db()).unwrap(); + let columns = |uid: &str| -> (Option, Option, i64, i64) { + db.query_row( + "SELECT account, integration, integration_rev, synced FROM identities WHERE uid = ?1", + [uid], + |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)), + ) + .unwrap() + }; + assert_eq!( + columns(&synced.uid), + (Some(account.to_base32()), Some(IntegrationId::from_bytes([7; 16]).to_base32()), 4, 1) + ); + assert_eq!( + columns(&device_only.uid), + (Some(account.to_base32()), Some(IntegrationId::from_bytes([8; 16]).to_base32()), 0, 0) + ); + assert_eq!(columns(&without_integration.uid), (Some(account.to_base32()), None, 0, 0)); + assert_eq!(columns(&large_rev.uid).2, i64::MAX); + assert_eq!(columns(&unbound.uid), (None, None, 0, 0)); + assert_eq!(columns(&voelin.uid), (None, None, 0, 0)); + assert_eq!(columns(&record_blob.uid), (None, None, 0, 0)); +} + +#[test] +fn a_revision_sqlite_cannot_hold_is_a_precise_error_and_stores_nothing() { + let store = SqliteKeyStore::open_in_memory().unwrap(); + let too_large = fresh_teamspeak(AccountBinding { rev: u64::MAX, ..binding() }); + assert!(matches!(store.put(&too_large), Err(KeyStoreError::Blob(BlobError::BindingRevision)))); + assert!(store.list().unwrap().is_empty()); +} + +#[test] +fn putting_a_blob_without_a_binding_unbinds_it() { + let store = SqliteKeyStore::open_in_memory().unwrap(); + let bound = fresh_teamspeak(binding()); + store.put(&bound).unwrap(); + assert_eq!(store.get(KIND_TEAMSPEAK, &bound.uid).unwrap().unwrap().binding, Some(binding())); + + let unbound = bound.clone().with_binding(None); + store.put(&unbound).unwrap(); + let back = store.get(KIND_TEAMSPEAK, &bound.uid).unwrap().unwrap(); + assert_eq!(back.binding, None); + assert_eq!(back, unbound); + assert_eq!(store.list().unwrap()[0].binding, None); +} + +#[test] +fn bound_to_lists_exactly_the_identities_of_one_account() { + let store = SqliteKeyStore::open_in_memory().unwrap(); + let mine = binding().account; + let theirs = account_uid(&issuer(), &AccountId::from_bytes([9; 16])); + let (a, b, c, d) = ( + fresh_teamspeak(binding()), + fresh_teamspeak(AccountBinding { synced: false, ..binding() }), + fresh_teamspeak(AccountBinding { account: theirs, ..binding() }), + fresh_teamspeak(None), + ); + for blob in [&a, &b, &c, &d] { + store.put(blob).unwrap(); + } + store.put_voelin_key(&key()).unwrap(); + store.put_account_record(&record()).unwrap(); + + let mut bound: Vec<_> = store.bound_to(&mine).unwrap().into_iter().map(|i| i.uid).collect(); + bound.sort(); + let mut expected = vec![a.uid.clone(), b.uid.clone()]; + expected.sort(); + assert_eq!(bound, expected, "not the other account's, the unbound, the key or the record"); + let other: Vec<_> = store.bound_to(&theirs).unwrap().into_iter().map(|i| i.uid).collect(); + assert_eq!(other, [c.uid.as_str()]); + assert!(store.bound_to(&Uid::from_bytes([0; 32])).unwrap().is_empty()); +} + +#[test] +fn the_account_record_goes_through_the_stores_own_accessors() { + let store = SqliteKeyStore::open_in_memory().unwrap(); + assert_eq!(store.account_record().unwrap(), None); + store.put_account_record(&record()).unwrap(); + assert_eq!(store.account_record().unwrap(), Some(record())); + let blob = store.get(KIND_ACCOUNT, &record().blob_uid()).unwrap().unwrap(); + assert_eq!(blob.uid, format!("account:{}", record().account_uid().to_base32())); + assert_eq!(blob.binding, None); + + // Putting it again replaces it (a renewed certificate). + let renewed = AccountRecord { cert: vec![1, 2, 3], ..record() }; + store.put_account_record(&renewed).unwrap(); + assert_eq!(store.account_record().unwrap(), Some(renewed)); + assert_eq!(store.list().unwrap().len(), 1); + + // A stored record that is not one is an error to the caller. + let mut bad = blob; + bad.json = "{}".into(); + store.put(&bad).unwrap(); + assert!(matches!(store.account_record(), Err(KeyStoreError::Blob(BlobError::AccountJson)))); +} + +#[test] +fn damaged_binding_columns_are_precise_errors_when_read() { + let scratch = Scratch::new("damaged"); + let store = SqliteKeyStore::open(&scratch.db()).unwrap(); + store.put(&teamspeak_blob()).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 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(_))))); + + set(&format!("account = '{}'", binding_for(1).to_base32())); + assert_eq!(read().unwrap().unwrap().binding.unwrap().account, binding_for(1)); + + 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)))); +} + +// ------------------------------------- what the TeamSpeak methods share + +#[test] +fn a_replaced_row_keeps_its_name_origin_default_flag_and_creation() { + let scratch = Scratch::new("replaced"); + let store = SqliteKeyStore::open(&scratch.db()).unwrap(); + let identity: Identity = serde_json::from_str(TEAMSPEAK_JSON).unwrap(); + let id = + store.with_store(|s| s.add_identity("Main", &identity, IdentityOrigin::Imported).unwrap()); + let db = Connection::open(scratch.db()).unwrap(); + // Age the row, so that a row written again would show a later `created`. + db.execute("UPDATE identities SET created = 1000", []).unwrap(); + + // The synced copy of the same identity arrives, with the counter raised. + let mut synced = IdentityBlob::teamspeak(TEAMSPEAK_UID, 0, RAISED_JSON); + synced.binding = Some(binding()); + store.put(&synced).unwrap(); + + let (rows, row_id, name, origin, is_default, created): (i64, i64, String, String, i64, i64) = + db.query_row( + "SELECT count(*), id, name, origin, is_default, created FROM identities", + [], + |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?, r.get(5)?)), + ) + .unwrap(); + assert_eq!((rows, row_id), (1, id), "the same row, replaced in place"); + assert_eq!( + (name.as_str(), origin.as_str(), is_default, created), + ("Main", "imported", 1, 1000) + ); + + let listed = store.with_store(|s| s.identities().unwrap()); + let entry = &listed[0]; + assert_eq!((entry.id, entry.name.as_str()), (id, "Main")); + assert_eq!((entry.origin, entry.is_default), (IdentityOrigin::Imported, true)); + // The level is the one of the new counter, computed. + let level = serde_json::from_str::(RAISED_JSON).unwrap().level(); + assert_eq!(entry.level, level); + assert_eq!(store.with_store(|s| s.identity(id).unwrap().counter()), 9_000_000); + let blob = store.get(KIND_TEAMSPEAK, TEAMSPEAK_UID).unwrap().unwrap(); + assert_eq!((blob.binding, blob.level), (Some(binding()), level)); + assert_eq!(blob.json, RAISED_JSON); +} + +#[test] +fn a_new_teamspeak_blob_is_a_row_the_teamspeak_methods_list() { + let store = SqliteKeyStore::open_in_memory().unwrap(); + let main = Identity::create(); + let main_id = + store.with_store(|s| s.add_identity("Main", &main, IdentityOrigin::User).unwrap()); + let synced = fresh_teamspeak(binding()); + store.put(&synced).unwrap(); + // A Voelin key and the account record share the table and are not listed. + store.put_voelin_key(&key()).unwrap(); + store.put_account_record(&record()).unwrap(); + + let listed = store.with_store(|s| s.identities().unwrap()); + assert_eq!(listed.len(), 2, "{listed:?}"); + let entry = &listed[1]; + assert_eq!( + (entry.name.as_str(), entry.uid.as_str()), + (synced.uid.as_str(), synced.uid.as_str()) + ); + assert_eq!( + (entry.origin, entry.is_default, entry.level), + (IdentityOrigin::User, false, synced.level) + ); + // The default stays the identity that was the default. + assert_eq!(store.with_store(|s| s.default_identity().unwrap().unwrap().id), main_id); + // The identity loads through the old API, the key unchanged. + let loaded = store.with_store(|s| s.identity(entry.id).unwrap()); + assert_eq!(serde_json::to_string(&loaded).unwrap(), synced.json); + // And the old API's delete is the same row as the key store's remove. + store.with_store(|s| s.delete_identity(entry.id).unwrap()); + assert!(store.get(KIND_TEAMSPEAK, &synced.uid).unwrap().is_none()); + assert!(store.get(KIND_VOELIN, &key().uid().to_base32()).unwrap().is_some()); +} + +#[test] +fn an_identity_added_the_old_way_is_an_unbound_teamspeak_blob() { + let store = SqliteKeyStore::open_in_memory().unwrap(); + let identity: Identity = serde_json::from_str(TEAMSPEAK_JSON).unwrap(); + store.with_store(|s| s.add_identity("Main", &identity, IdentityOrigin::Imported).unwrap()); + assert_eq!(store.get(KIND_TEAMSPEAK, TEAMSPEAK_UID).unwrap().unwrap(), teamspeak_blob()); + assert_eq!( + store.list().unwrap(), + [IdentityInfo { + kind: KIND_TEAMSPEAK.into(), + uid: TEAMSPEAK_UID.into(), + level: TEAMSPEAK_LEVEL, + binding: None + }] + ); + // The old API's rename leaves the blob alone. + let id = store.with_store(|s| s.identities().unwrap()[0].id); + store.with_store(|s| s.rename_identity(id, "Renamed").unwrap()); + assert_eq!(store.get(KIND_TEAMSPEAK, TEAMSPEAK_UID).unwrap().unwrap(), teamspeak_blob()); +} + +#[test] +fn a_teamspeak_blob_that_is_no_identity_is_refused() { + let store = SqliteKeyStore::open_in_memory().unwrap(); + store.put(&teamspeak_blob()).unwrap(); + + // Not the JSON of a tsproto identity: refused, so that it cannot break the + // list of TeamSpeak identities. + for json in ["", "not json", "{}", r#"{"key":"AAAA","counter":1,"max_counter":1}"#] { + let bad = IdentityBlob::teamspeak("some/uid=", 0, json); + assert!(matches!(store.put(&bad), Err(KeyStoreError::Backend(_))), "{json:?}"); + } + // An identity that names another identity's uid: refused, so that it cannot + // replace that identity's key. + let stranger = Identity::create(); + let hijack = IdentityBlob::teamspeak( + TEAMSPEAK_UID, + stranger.level(), + serde_json::to_string(&stranger).unwrap(), + ); + assert!(matches!(store.put(&hijack), Err(KeyStoreError::Blob(BlobError::UidMismatch)))); + // Nothing was stored or replaced. + assert_eq!(store.list().unwrap().len(), 1); + assert_eq!(store.get(KIND_TEAMSPEAK, TEAMSPEAK_UID).unwrap().unwrap(), teamspeak_blob()); + assert_eq!(store.with_store(|s| s.identities().unwrap().len()), 1); +} + +#[test] +fn the_level_is_computed_from_the_key_never_stored_and_never_blocks_a_read() { + let scratch = Scratch::new("level"); + let store = SqliteKeyStore::open(&scratch.db()).unwrap(); + // A blob that claims another level is stored with the level its key has. + store.put(&IdentityBlob::teamspeak(TEAMSPEAK_UID, 99, TEAMSPEAK_JSON)).unwrap(); + assert_eq!(store.get(KIND_TEAMSPEAK, TEAMSPEAK_UID).unwrap().unwrap().level, TEAMSPEAK_LEVEL); + assert_eq!(store.list().unwrap()[0].level, TEAMSPEAK_LEVEL); + // Kinds without a level read back with 0, whatever was put. + store.put(&IdentityBlob::new("discord", "1", 7, "{}")).unwrap(); + assert_eq!(store.get("discord", "1").unwrap().unwrap().level, 0); + + // A TeamSpeak row damaged outside this crate lists and reads with level 0 + // and its JSON as it is, instead of failing the list (and a sign-out). + let db = Connection::open(scratch.db()).unwrap(); + db.execute("UPDATE identities SET data = 'damaged' WHERE uid = ?1", params![TEAMSPEAK_UID]) + .unwrap(); + let listed = store.list().unwrap(); + assert_eq!(listed.iter().find(|i| i.uid == TEAMSPEAK_UID).unwrap().level, 0); + let blob = store.get(KIND_TEAMSPEAK, TEAMSPEAK_UID).unwrap().unwrap(); + assert_eq!((blob.level, blob.json.as_str()), (0, "damaged")); +} + +#[test] +fn unknown_kinds_are_kept_and_the_teamspeak_methods_do_not_see_them() { + let store = SqliteKeyStore::open_in_memory().unwrap(); + let discord = IdentityBlob::new("discord", "1234", 0, r#"{"token":"opaque"}"#); + store.put(&discord).unwrap(); + assert!(store.with_store(|s| s.identities().unwrap()).is_empty()); + assert!(store.with_store(|s| s.default_identity().unwrap()).is_none()); + assert_eq!(store.get("discord", "1234").unwrap().unwrap(), discord); +} + +#[test] +fn the_sqlite_store_is_the_store_the_client_already_has() { + // A `Store` opened the old way is a key store without a migration or a copy. + let scratch = Scratch::new("shared"); + let store = Store::open(&scratch.db()).unwrap(); + let identity = Identity::create(); + store.add_identity("Main", &identity, IdentityOrigin::Created).unwrap(); + drop(store); + let keys = SqliteKeyStore::open(&scratch.db()).unwrap(); + let listed = keys.list().unwrap(); + assert_eq!(listed.len(), 1); + assert_eq!(listed[0].uid, identity.key().to_pub().get_uid()); + assert_eq!((listed[0].kind.as_str(), listed[0].binding), (KIND_TEAMSPEAK, None)); +}