diff --git a/.dockerignore b/.dockerignore index c202dcf..3ee2e78 100644 --- a/.dockerignore +++ b/.dockerignore @@ -2,6 +2,10 @@ # the sources only. Builds keep target/ in cache mounts, never in the context. .git .claude +# The per-developer .cargo/config.toml (docs/building.md, a [patch] to a sibling +# VoelinProtocol checkout): never part of a build. Only the root one; the +# committed third_party/dimpl/.cargo stays. +.cargo target dist fuzz/target diff --git a/.gitignore b/.gitignore index e586912..004fc92 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ /target/ /dev/.state/ /dist/ +/.cargo/ diff --git a/CHANGELOG.md b/CHANGELOG.md index 0255379..e79177b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -69,6 +69,14 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows ### Changed +- The identity store keeps identities of more than one kind (TeamSpeak, a Voelin + key, the signed-in account) with the account each belongs to, as a + `voelin-identity` key store, in two database migrations. Existing + databases migrate on first start and every identity stays what it was (kind + TeamSpeak, no account, same key, name, origin and default); nothing changes + on screen yet. The build now fetches `voelin-identity` from the private + VoelinProtocol repository, so a fresh checkout needs read access to it + (see docs/building.md). - Selecting a server observes it through its gateway at once; the Observe button is gone. The server dialog asks only for the address, password, name and nickname: the gateway is found from the address. diff --git a/Cargo.lock b/Cargo.lock index dff23d9..48fd03b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1996,7 +1996,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" dependencies = [ "const-oid 0.9.6", - "der_derive", + "der_derive 0.7.3", "flagset", "pem-rfc7468 0.7.0", "zeroize", @@ -2009,6 +2009,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a878c850e9e421b20262e9b41f9c860e4785fa07541c266b62ff9d1ef998a80a" dependencies = [ "const-oid 0.10.2", + "der_derive 0.8.0", + "flagset", "pem-rfc7468 1.0.0", "zeroize", ] @@ -2038,6 +2040,17 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "der_derive" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59600e2c2d636fde9b65e99cc6445ac770c63d3628195ff39932b8d6d7409903" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "deranged" version = "0.5.8" @@ -2134,7 +2147,7 @@ dependencies = [ "spki 0.7.3", "subtle", "time", - "x509-cert", + "x509-cert 0.2.5", ] [[package]] @@ -9560,6 +9573,23 @@ dependencies = [ "voelin-model", ] +[[package]] +name = "voelin-identity" +version = "0.2.0" +source = "git+ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git?rev=64808ccbb1e3aa10213392724f2f436bc25fd36f#64808ccbb1e3aa10213392724f2f436bc25fd36f" +dependencies = [ + "aws-lc-rs", + "base64 0.23.1", + "prost", + "rcgen", + "serde", + "serde_json", + "thiserror 2.0.21", + "voelin-proto", + "x509-cert 0.3.0", + "zeroize", +] + [[package]] name = "voelin-media" version = "0.1.0" @@ -9639,6 +9669,17 @@ dependencies = [ "zbus", ] +[[package]] +name = "voelin-proto" +version = "0.2.0" +source = "git+ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git?rev=64808ccbb1e3aa10213392724f2f436bc25fd36f#64808ccbb1e3aa10213392724f2f436bc25fd36f" +dependencies = [ + "bytes", + "prost", + "thiserror 2.0.21", + "tokio", +] + [[package]] name = "voelin-query" version = "0.1.0" @@ -9663,6 +9704,7 @@ dependencies = [ "serde_json", "thiserror 2.0.21", "tsclientlib", + "voelin-identity", ] [[package]] @@ -10850,6 +10892,17 @@ dependencies = [ "spki 0.7.3", ] +[[package]] +name = "x509-cert" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "105ef4642d9cb137ef83d623d0e4bf08b8adf69e9918ca904a174adb6d3d038b" +dependencies = [ + "const-oid 0.10.2", + "der 0.8.2", + "spki 0.8.0", +] + [[package]] name = "x509-parser" version = "0.18.1" diff --git a/Cargo.toml b/Cargo.toml index db62918..8fcb1d3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -53,6 +53,14 @@ license = "MIT OR Apache-2.0" repository = "https://github.com/Faumaray/Voelin" publish = false +[workspace.dependencies] +# The protocol repository is private (VoelinProtocol). This is the SSH URL its +# docs/development.md names, so that a per-developer .cargo/config.toml [patch] +# can point it at a sibling checkout (docs/building.md, "Working with a sibling +# VoelinProtocol checkout"). Pinned by commit until the protocol tags a release +# that has the account-bound KeyStore (its Phase 2 task 28). +voelin-identity = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", rev = "64808ccbb1e3aa10213392724f2f436bc25fd36f" } + [workspace.lints.rust] # deny, not forbid: generated code (Slint) needs a local allow. unsafe_code = "deny" diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index d3c2aef..c005bf3 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -175,7 +175,7 @@ the crate's authors are listed as its copyright holders. | License | Crates | |---|---| -| MIT License | 658 | +| MIT License | 660 | | Apache License 2.0 | 31 | | Unicode License v3 | 26 | | BSD 3-Clause "New" or "Revised" License | 22 | @@ -6994,7 +6994,7 @@ DEALINGS IN THE SOFTWARE. ```` -Used by: cpufeatures 0.2.17 +Used by: cpufeatures 0.2.17, der_derive 0.8.0 ````text Copyright (c) 2020-2025 The RustCrypto Project Developers @@ -7246,7 +7246,7 @@ DEALINGS IN THE SOFTWARE. ```` -Used by: pem-rfc7468 1.0.0, pkcs1 0.8.0-rc.4 +Used by: pem-rfc7468 1.0.0, pkcs1 0.8.0-rc.4, x509-cert 0.3.0 ````text Copyright (c) 2021-2025 The RustCrypto Project Developers diff --git a/crates/voelin-store/Cargo.toml b/crates/voelin-store/Cargo.toml index 94f9b2b..b20313f 100644 --- a/crates/voelin-store/Cargo.toml +++ b/crates/voelin-store/Cargo.toml @@ -20,6 +20,7 @@ serde = { version = "1.0.229", features = ["derive"] } serde_json = "1.0.151" thiserror = "2.0.21" tsclientlib = { path = "../proto/tsclientlib" } +voelin-identity = { workspace = true } [lints] workspace = true diff --git a/crates/voelin-store/src/keystore.rs b/crates/voelin-store/src/keystore.rs new file mode 100644 index 0000000..8e0f2ef --- /dev/null +++ b/crates/voelin-store/src/keystore.rs @@ -0,0 +1,292 @@ +//! 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 +//! 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 +//! lines. + +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"; + +/// 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. +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. +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)?; + 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<()> { + 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 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. +/// +/// 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(()) +} + +/// 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 }, +} + +/// 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 a1aa46d..fe21b09 100644 --- a/crates/voelin-store/src/store.rs +++ b/crates/voelin-store/src/store.rs @@ -18,12 +18,21 @@ enum Migration { /// Schema migrations; entry `i` upgrades from version `i` to `i + 1` /// (`PRAGMA user_version`). Add new ones at the end; never change one that /// shipped. +/// +/// Versions 6 and 7 are the identity migrations of `voelin-identity` (the +/// protocol's Phase 2 tasks 7 and 28), run in this order: a `kind` column +/// (every row that exists is a `teamspeak` identity) and then the four +/// account-binding columns (every row that exists is unbound). Their SQL is +/// the protocol's; `the_identity_migrations_are_pinned` keeps it from changing +/// under a shipped version. const MIGRATIONS: &[Migration] = &[ Migration::Sql(SCHEMA_1), Migration::Code(crate::chat::migrate_2), Migration::Sql(crate::contacts::SCHEMA_3), Migration::Sql(SCHEMA_4), Migration::Sql(crate::chat::SCHEMA_5), + Migration::Sql(voelin_identity::migrate::ADD_KIND_COLUMN), + Migration::Sql(voelin_identity::migrate::ADD_ACCOUNT_COLUMNS), ]; /// Version 4: where each identity came from ([`IdentityOrigin`]) and which @@ -287,6 +296,10 @@ impl Store { pub const SCHEMA_VERSION: i64 = MIGRATIONS.len() as i64; // Identities + // + // These methods are the TeamSpeak identities (kind `teamspeak`) the client + // has always had, and act on those rows only: the other kinds of the + // `identities` table (a Voelin key, the signed-in account) are not theirs. /// Store an identity; it is the default when no other one is. pub fn add_identity( @@ -306,7 +319,8 @@ impl Store { pub fn identities(&self) -> Result> { let mut stmt = self.db.prepare( - "SELECT id, name, uid, data, origin, is_default FROM identities ORDER BY id", + "SELECT id, name, uid, data, origin, is_default FROM identities + WHERE kind = 'teamspeak' ORDER BY id", )?; let rows = stmt.query_map([], |r| { Ok(( @@ -339,7 +353,11 @@ impl Store { /// and is never replaced by an import again. pub fn set_default_identity(&self, id: i64, by_user: bool) -> Result<()> { let tx = self.db.unchecked_transaction()?; - if tx.execute("UPDATE identities SET is_default = 1 WHERE id = ?1", [id])? == 0 { + if tx.execute( + "UPDATE identities SET is_default = 1 WHERE id = ?1 AND kind = 'teamspeak'", + [id], + )? == 0 + { return Err(Error::NotFound("identity", id)); } tx.execute("UPDATE identities SET is_default = 0 WHERE id <> ?1", [id])?; @@ -356,7 +374,11 @@ impl Store { pub fn identity(&self, id: i64) -> Result { let data: Option = self .db - .query_row("SELECT data FROM identities WHERE id = ?1", [id], |r| r.get(0)) + .query_row( + "SELECT data FROM identities WHERE id = ?1 AND kind = 'teamspeak'", + [id], + |r| r.get(0), + ) .optional()?; let data = data.ok_or(Error::NotFound("identity", id))?; Ok(serde_json::from_str(&data)?) @@ -365,20 +387,22 @@ impl Store { /// Store an identity again, e.g. after its security level was improved. pub fn update_identity(&self, id: i64, identity: &Identity) -> Result<()> { let n = self.db.execute( - "UPDATE identities SET data = ?2 WHERE id = ?1", + "UPDATE identities SET data = ?2 WHERE id = ?1 AND kind = 'teamspeak'", params![id, serde_json::to_string(identity)?], )?; if n == 0 { Err(Error::NotFound("identity", id)) } else { Ok(()) } } pub fn rename_identity(&self, id: i64, name: &str) -> Result<()> { - let n = - self.db.execute("UPDATE identities SET name = ?2 WHERE id = ?1", params![id, name])?; + let n = self.db.execute( + "UPDATE identities SET name = ?2 WHERE id = ?1 AND kind = 'teamspeak'", + params![id, name], + )?; if n == 0 { Err(Error::NotFound("identity", id)) } else { Ok(()) } } pub fn delete_identity(&self, id: i64) -> Result<()> { - self.db.execute("DELETE FROM identities WHERE id = ?1", [id])?; + self.db.execute("DELETE FROM identities WHERE id = ?1 AND kind = 'teamspeak'", [id])?; Ok(()) } @@ -595,7 +619,7 @@ mod tests { .unwrap(); } let store = Store::open(&path).unwrap(); - assert_eq!(Store::SCHEMA_VERSION, 5); + assert_eq!(Store::SCHEMA_VERSION, 7); assert_eq!(store.schema_version().unwrap(), Store::SCHEMA_VERSION); let channel = ChatTarget::Channel(1); let rows = store.messages("srv", &channel, PageQuery::default()).unwrap(); @@ -611,6 +635,350 @@ mod tests { std::fs::remove_dir_all(dir).unwrap(); } + /// What `serde_json::to_string(&tsproto::Identity)` writes for the test + /// identity of tsproto's own `identity_tests` (the fixture row of + /// `voelin-identity`'s `tests/storage.rs`): its unique id and security + /// level are checked against the real tsproto below. + const TEAMSPEAK_JSON: &str = r#"{"key":"YTyJofmztcTBjq3KZcDdxu+G4RPVwE5vg8VaN2jbQao=","counter":2792354,"max_counter":2792354}"#; + const TEAMSPEAK_UID: &str = "test/9PZ9vww/Bpf5vJxtJhpz80="; + const TEAMSPEAK_LEVEL: u8 = 21; + + /// A `client.db` as it was at schema `version`: the migrations below + /// `version` applied by the code that runs them, nothing else. + fn database_at(path: &Path, version: usize) { + let mut db = rusqlite::Connection::open(path).unwrap(); + for migration in &MIGRATIONS[..version] { + match migration { + Migration::Sql(sql) => db.execute_batch(sql).unwrap(), + Migration::Code(migrate) => { + let tx = db.transaction().unwrap(); + migrate(&tx).unwrap(); + tx.commit().unwrap(); + } + } + } + db.pragma_update(None, "user_version", version as i64).unwrap(); + } + + fn scratch_dir(name: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("voelin-store-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir + } + + #[test] + fn the_teamspeak_fixture_is_what_tsproto_writes() { + let identity: Identity = serde_json::from_str(TEAMSPEAK_JSON).unwrap(); + assert_eq!(identity.key().to_pub().get_uid(), TEAMSPEAK_UID); + assert_eq!(identity.level(), TEAMSPEAK_LEVEL); + assert_eq!(serde_json::to_string(&identity).unwrap(), TEAMSPEAK_JSON); + } + + /// The identity migrations are `voelin-identity`'s SQL, and a shipped + /// version never changes: a newer revision of the protocol repository + /// that touched either string would fail here instead of changing what + /// version 6 or 7 does to an installed database. + #[test] + fn the_identity_migrations_are_pinned() { + let sql = |index: usize| match &MIGRATIONS[index] { + Migration::Sql(sql) => *sql, + Migration::Code(_) => panic!("migration {index} is code"), + }; + assert_eq!(MIGRATIONS.len(), 7); + assert_eq!( + sql(5), + "ALTER TABLE identities ADD COLUMN kind TEXT NOT NULL DEFAULT 'teamspeak';" + ); + assert_eq!( + sql(6), + "ALTER TABLE identities ADD COLUMN account TEXT;\n\ + ALTER TABLE identities ADD COLUMN integration TEXT;\n\ + ALTER TABLE identities ADD COLUMN integration_rev INTEGER NOT NULL DEFAULT 0;\n\ + ALTER TABLE identities ADD COLUMN synced INTEGER NOT NULL DEFAULT 0;" + ); + } + + /// A database of version 5 (what 0.1 ships) gets the `kind` column and + /// then the account columns in one open; every identity stays as it was: + /// kind `teamspeak`, unbound, its JSON byte for byte, its origin and + /// default flag, and the level computed from the key as before. + #[test] + fn migrates_version_5_identities_through_both_steps() { + use voelin_identity::migrate::SELECT_ACCOUNT_COLUMNS; + use voelin_identity::{AccountBinding, IdentityBlob, KIND_TEAMSPEAK}; + + let dir = scratch_dir("v5"); + 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, 5); + { + let db = rusqlite::Connection::open(&path).unwrap(); + assert_eq!( + db.pragma_query_value(None, "user_version", |r| r.get::<_, i64>(0)).unwrap(), + 5 + ); + for (name, uid, json, origin, default) in [ + ("Main", TEAMSPEAK_UID, TEAMSPEAK_JSON, "imported", 1), + ("Other", other_uid.as_str(), other_json.as_str(), "user", 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 store = Store::open(&path).unwrap(); + assert_eq!(Store::SCHEMA_VERSION, 7); + assert_eq!(store.schema_version().unwrap(), 7); + + // Read as the key store reads a row of the migrated table. + let rows: Vec<_> = store + .db + .prepare(&format!("SELECT {SELECT_ACCOUNT_COLUMNS} FROM identities ORDER BY id")) + .unwrap() + .query_map([], |r| { + Ok(( + r.get::<_, String>(0)?, + r.get::<_, String>(1)?, + r.get::<_, String>(2)?, + r.get::<_, Option>(3)?, + r.get::<_, Option>(4)?, + r.get::<_, i64>(5)?, + r.get::<_, i64>(6)?, + )) + }) + .unwrap() + .collect::>() + .unwrap(); + assert_eq!(rows.len(), 2); + for ((kind, uid, data, account, integration, rev, synced), (want_uid, want_json)) in + rows.into_iter().zip([(TEAMSPEAK_UID, TEAMSPEAK_JSON), (&*other_uid, &*other_json)]) + { + assert_eq!(kind, KIND_TEAMSPEAK); + let binding = AccountBinding::from_columns( + account.as_deref(), + integration.as_deref(), + rev, + synced, + ) + .unwrap(); + assert_eq!(binding, None, "an old row is unbound"); + assert_eq!((uid.as_str(), data.as_str()), (want_uid, want_json), "byte for byte"); + let blob = IdentityBlob::from_row(&kind, uid, 0, data); + assert!(blob.is_teamspeak()); + } + + // The old API sees what it saw before, origin and default included. + let list = store.identities().unwrap(); + assert_eq!(list.len(), 2); + assert_eq!((list[0].name.as_str(), list[0].uid.as_str()), ("Main", TEAMSPEAK_UID)); + assert_eq!( + (list[0].level, list[0].origin, list[0].is_default), + (21, IdentityOrigin::Imported, true) + ); + assert_eq!((list[1].name.as_str(), list[1].uid.as_str()), ("Other", &*other_uid)); + assert_eq!( + (list[1].level, list[1].origin, list[1].is_default), + (other.level(), IdentityOrigin::User, false) + ); + assert_eq!(store.default_identity().unwrap().unwrap().id, list[0].id); + assert_eq!(store.identity(list[1].id).unwrap().counter(), other.counter()); + drop(store); + + // Opened again, nothing runs twice. + let store = Store::open(&path).unwrap(); + assert_eq!(store.schema_version().unwrap(), 7); + assert_eq!(store.identities().unwrap(), list); + drop(store); + 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] + fn migrates_version_6_identities_to_accounts() { + let dir = scratch_dir("v6"); + let path = dir.join("client.db"); + database_at(&path, 6); + { + let db = rusqlite::Connection::open(&path).unwrap(); + db.execute( + "INSERT INTO identities (name, uid, data, origin, is_default) + VALUES ('Main', ?1, ?2, 'created', 1)", + params![TEAMSPEAK_UID, TEAMSPEAK_JSON], + ) + .unwrap(); + db.execute( + "INSERT INTO identities (name, uid, data, kind) + VALUES ('key', 'abc', '{\"v\":1}', 'voelin')", + [], + ) + .unwrap(); + } + let store = Store::open(&path).unwrap(); + assert_eq!(store.schema_version().unwrap(), 7); + let (kind, account, integration, rev, synced): ( + String, + Option, + Option, + i64, + i64, + ) = store + .db + .query_row( + "SELECT kind, account, integration, integration_rev, synced FROM identities + WHERE uid = 'abc'", + [], + |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?)), + ) + .unwrap(); + assert_eq!( + (kind.as_str(), account, integration, rev, synced), + ("voelin", None, None, 0, 0) + ); + let list = store.identities().unwrap(); + assert_eq!(list.len(), 1, "the Voelin row is not a TeamSpeak identity"); + assert_eq!( + (list[0].origin, list[0].is_default, list[0].level), + (IdentityOrigin::Created, true, 21) + ); + drop(store); + std::fs::remove_dir_all(dir).unwrap(); + } + + /// Rows of other kinds share the table with the TeamSpeak identities and + /// are none of the TeamSpeak methods' business: they are not listed, not + /// read as an identity, not renamed, changed, made the default or deleted + /// (the JSON of a Voelin key is not a `tsproto::Identity`, and listing + /// would fail on it). + #[test] + fn the_teamspeak_methods_leave_other_kinds_alone() { + let store = Store::open_in_memory().unwrap(); + let mine = Identity::create(); + let id = store.add_identity("mine", &mine, IdentityOrigin::User).unwrap(); + let other_id = |kind: &str, uid: &str| { + store + .db + .execute( + "INSERT INTO identities (name, uid, data, kind) VALUES (?1, ?2, '{\"v\":1}', ?1)", + params![kind, uid], + ) + .unwrap(); + store.db.last_insert_rowid() + }; + let voelin = other_id("voelin", "v1"); + let account = other_id("account", "account:a1"); + + let list = store.identities().unwrap(); + assert_eq!(list.iter().map(|e| e.id).collect::>(), [id]); + assert_eq!(store.default_identity().unwrap().unwrap().id, id); + for other in [voelin, account] { + assert!(matches!(store.identity(other), Err(Error::NotFound(..)))); + assert!(matches!(store.rename_identity(other, "x"), Err(Error::NotFound(..)))); + assert!(matches!(store.update_identity(other, &mine), Err(Error::NotFound(..)))); + assert!(matches!(store.set_default_identity(other, true), Err(Error::NotFound(..)))); + store.delete_identity(other).unwrap(); + } + let rows: i64 = + store.db.query_row("SELECT count(*) FROM identities", [], |r| r.get(0)).unwrap(); + assert_eq!(rows, 3, "nothing of another kind was deleted"); + let names: Vec = store + .db + .prepare("SELECT name FROM identities ORDER BY id") + .unwrap() + .query_map([], |r| r.get(0)) + .unwrap() + .collect::>() + .unwrap(); + assert_eq!(names, ["mine", "voelin", "account"]); + let defaults: i64 = store + .db + .query_row("SELECT count(*) FROM identities WHERE is_default", [], |r| r.get(0)) + .unwrap(); + assert_eq!(defaults, 1); + // A TeamSpeak identity is deleted as before. + store.delete_identity(id).unwrap(); + assert!(store.identities().unwrap().is_empty()); + } + #[test] fn bookmarks_keep_order_and_fields() { let store = Store::open_in_memory().unwrap(); diff --git a/crates/voelin-store/tests/keystore.rs b/crates/voelin-store/tests/keystore.rs new file mode 100644 index 0000000..2d5a396 --- /dev/null +++ b/crates/voelin-store/tests/keystore.rs @@ -0,0 +1,1170 @@ +//! 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. +//! +//! The sign-out cases (`voelin-identity`'s `tests/accounts.rs`, protocol +//! section 13.6) run the trait's own `sign_out` on the SQLite store, in the +//! last section. + +use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; + +use rusqlite::{Connection, params}; +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, +}; +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 { + /// 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}-{}-{n}", 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 a_refused_teamspeak_blob_does_not_quote_its_key_in_the_error() { + // The JSON of a TeamSpeak identity holds the private key. serde's account of + // a key it cannot read quotes the string it was given, so the store must not + // forward it: the error reaches Display and Debug, and so any log line. + const KEY_TEXT: &str = "PRIVATE-KEY-TEXT-0123456789"; + let json = format!(r#"{{"key":"{KEY_TEXT}","counter":1,"max_counter":1}}"#); + let parse_error = serde_json::from_str::(&json).unwrap_err(); + assert!( + parse_error.to_string().contains(KEY_TEXT), + "the case proves nothing if serde does not quote the key: {parse_error}" + ); + + let store = SqliteKeyStore::open_in_memory().unwrap(); + let error = store.put(&IdentityBlob::teamspeak("some/uid=", 0, json.as_str())).unwrap_err(); + assert!(matches!(error, KeyStoreError::Backend(_)), "{error:?}"); + let mut texts = vec![format!("{error}"), format!("{error:?}"), format!("{error:#?}")]; + let mut source = std::error::Error::source(&error); + while let Some(cause) = source { + texts.extend([format!("{cause}"), format!("{cause:?}"), format!("{cause:#?}")]); + source = cause.source(); + } + for text in &texts { + assert!(!text.contains(KEY_TEXT), "the error repeats the key: {text}"); + } + assert!(store.list().unwrap().is_empty(), "nothing was stored"); + + // The same holds when the JSON parses and only the uid is wrong: that error + // is a fixed text as well. + let stranger = Identity::create(); + let json = serde_json::to_string(&stranger).unwrap(); + let key_text = json.split('"').nth(3).unwrap().to_owned(); + let error = store.put(&IdentityBlob::teamspeak("some/uid=", 0, json)).unwrap_err(); + for text in [format!("{error}"), format!("{error:?}")] { + assert!(!text.contains(&key_text), "the error repeats the key: {text}"); + } +} + +#[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)); +} + +// ------------------------------------------------------------- sign-out +// +// `KeyStore::sign_out` is `voelin-identity`'s: it is generic over the trait, so +// the store here does not re-implement it, and these cases run it on SQLite +// (protocol section 13.6, "Signing out", and `voelin-identity`'s +// `tests/accounts.rs`). A TeamSpeak identity needs a key that has its uid for +// this store to accept it, so the identities of these cases are fresh ones. + +/// The record `record()` writes, as JSON. +const RECORD_JSON: &str = concat!( + r#"{"v":1,"service":"https://accounts.example.org","#, + r#""issuer":"eh7ddx5bksrgcytl7bkai36se4nxx3klnk7elksyq57pi74xeg4q","#, + r#""account_id":"aaaqeayeaudaocajbifqydiob4","#, + r#""device":"eh7ddx5bksrgcytl7bkai36se4nxx3klnk7elksyq57pi74xeg4q","#, + r#""bound_existing_key":false,"login":"alice","cert":"CgNib2T/"}"#, +); + +/// An install signed in to the account: the device key, the record with the +/// given key flag, a synced copy, a device-only secret and a local identity. +struct Install { + store: SqliteKeyStore, + synced: IdentityBlob, + device_only: IdentityBlob, + local: IdentityBlob, +} + +fn signed_in_install(bound_existing_key: bool) -> Install { + let store = SqliteKeyStore::open_in_memory().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(); + } + Install { store, synced, device_only, local } +} + +fn device_key_info() -> IdentityInfo { + IdentityInfo { kind: KIND_VOELIN.into(), uid: key().uid().to_base32(), level: 0, binding: None } +} + +fn info_of(blob: &IdentityBlob) -> IdentityInfo { + IdentityInfo { + kind: blob.kind.clone(), + uid: blob.uid.clone(), + level: blob.level, + binding: blob.binding, + } +} + +fn sorted(mut infos: Vec) -> Vec<(String, String)> { + infos.sort(); + infos.into_iter().map(|info| (info.kind, info.uid)).collect() +} + +fn pair(blob: &IdentityBlob) -> (String, String) { + (blob.kind.clone(), blob.uid.clone()) +} + +/// The record of the install replaced by damaged JSON. +fn damage_the_record(store: &SqliteKeyStore, json: &str) { + let mut damaged = store.get(KIND_ACCOUNT, &record().blob_uid()).unwrap().unwrap(); + damaged.json = json.to_owned(); + store.put(&damaged).unwrap(); +} + +#[test] +fn the_record_fixture_is_what_the_protocol_writes() { + assert_eq!(IdentityBlob::account(&record()).unwrap().json, RECORD_JSON); + assert_eq!(record().device, issuer(), "the RFC 8032 key is both the issuer and the device"); +} + +#[test] +fn signing_out_deletes_the_copies_and_keeps_the_device_secrets() { + // The device key was made for the account: signing out deletes it. + let Install { store, synced, device_only, local } = signed_in_install(false); + let mine = binding().account; + let theirs = account_uid(&issuer(), &AccountId::from_bytes([9; 16])); + let theirs_blob = fresh_teamspeak(AccountBinding { account: theirs, ..binding() }); + store.put(&theirs_blob).unwrap(); + // Another Voelin key that is not the device key stays. + let other_key = IdentityKey::generate().unwrap(); + store.put_voelin_key(&other_key).unwrap(); + + let done = store.sign_out(&mine, DeviceKeyChoice::Auto).unwrap(); + let mut expected_removed = vec![ + (KIND_ACCOUNT.to_owned(), record().blob_uid()), + pair(&synced), + (KIND_VOELIN.to_owned(), key().uid().to_base32()), + ]; + expected_removed.sort(); + assert_eq!(sorted(done.removed.clone()), expected_removed, "{done:?}"); + assert_eq!(done.unbound, vec![info_of(&device_only.clone().with_binding(None))]); + + // What is left: the device secret unbound and byte for byte as it was, the + // local and the other account's identities as they were, the other key. + assert!(store.get(KIND_TEAMSPEAK, &synced.uid).unwrap().is_none()); + assert!(store.voelin_key(&key().uid()).unwrap().is_none()); + assert_eq!(store.account_record().unwrap(), None); + let kept = store.get(KIND_TEAMSPEAK, &device_only.uid).unwrap().unwrap(); + assert_eq!(kept, device_only.clone().with_binding(None)); + assert_eq!(kept.json, device_only.json); + assert_eq!(store.get(KIND_TEAMSPEAK, &local.uid).unwrap().unwrap(), local); + assert_eq!(store.get(KIND_TEAMSPEAK, &theirs_blob.uid).unwrap().unwrap(), theirs_blob); + assert!(store.voelin_key(&other_key.uid()).unwrap().is_some()); + assert_eq!(store.list().unwrap().len(), 4); + + // Signing out again finds nothing to do. + assert_eq!(store.sign_out(&mine, DeviceKeyChoice::Auto).unwrap(), SignOut::default()); + assert_eq!(store.list().unwrap().len(), 4); + // Another account's sign-out acts on that account's identities only. + assert_eq!( + store.sign_out(&theirs, DeviceKeyChoice::Auto).unwrap().removed, + vec![info_of(&theirs_blob)] + ); + assert_eq!(store.get(KIND_TEAMSPEAK, &device_only.uid).unwrap().unwrap(), kept); +} + +#[test] +fn signing_out_keeps_a_device_key_that_predates_the_account() { + // The install's own Voelin identity became the device key at the first + // sign-in. On a host that verifies no accounts it is still the user's + // identity, so signing out must not destroy it. + let Install { store, synced, device_only, local } = signed_in_install(true); + let key_before = store.get(KIND_VOELIN, &key().uid().to_base32()).unwrap().unwrap(); + let signature = key().sign(b"the same key, signed before and after"); + + let done = store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap(); + let mut removed = vec![(KIND_ACCOUNT.to_owned(), record().blob_uid()), pair(&synced)]; + removed.sort(); + assert_eq!(sorted(done.removed.clone()), removed, "{done:?}"); + // The key is reported as kept and unbound, next to the device secret. + assert_eq!( + sorted(done.unbound.clone()), + sorted(vec![device_key_info(), info_of(&device_only.clone().with_binding(None))]), + "{done:?}" + ); + assert!(done.unbound.contains(&device_key_info())); + + // It is the same key, byte for byte, with no binding, and the record that + // named it as the device key is gone. + let kept = store.voelin_key(&key().uid()).unwrap().expect("the key stays"); + assert_eq!(kept.uid(), key().uid()); + assert_eq!(kept.sign(b"the same key, signed before and after"), signature); + assert_eq!(&kept.to_pkcs8().unwrap()[..], &key().to_pkcs8().unwrap()[..]); + let key_after = store.get(KIND_VOELIN, &key().uid().to_base32()).unwrap().unwrap(); + assert_eq!(key_after, key_before, "the stored blob is untouched"); + assert_eq!(key_after.json, key_before.json); + assert_eq!(key_after.binding, None); + assert_eq!(store.account_record().unwrap(), None); + assert_eq!(store.list().unwrap().len(), 3, "the key, the device secret and the local one"); + assert!(store.get(KIND_TEAMSPEAK, &local.uid).unwrap().is_some()); + + // Signing out again finds nothing to do, and the key is still there. + assert_eq!( + store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap(), + SignOut::default() + ); + assert!(store.voelin_key(&key().uid()).unwrap().is_some()); +} + +#[test] +fn signing_out_deletes_a_device_key_the_client_made_for_the_account() { + let Install { store, device_only, local, .. } = signed_in_install(false); + let done = store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap(); + assert!(done.removed.contains(&device_key_info()), "{done:?}"); + assert!(!done.unbound.contains(&device_key_info()), "{done:?}"); + assert!(store.voelin_key(&key().uid()).unwrap().is_none()); + let mut left = sorted(store.list().unwrap()); + left.sort(); + let mut expected = vec![pair(&device_only), pair(&local)]; + expected.sort(); + assert_eq!(left, expected, "the device secret and the local one"); +} + +#[test] +fn a_record_without_the_key_flag_keeps_the_key() { + // A record written before the flag existed. Deleting a key is the + // irreversible choice, so the missing flag must not read as "delete". + let Install { store, .. } = signed_in_install(false); + let old = RECORD_JSON.replace("\"bound_existing_key\":false,", ""); + assert!(!old.contains("bound_existing_key")); + damage_the_record(&store, &old); + assert!(store.account_record().unwrap().unwrap().bound_existing_key); + + let done = store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap(); + assert!(done.unbound.contains(&device_key_info()), "{done:?}"); + assert!(!done.removed.contains(&device_key_info()), "{done:?}"); + assert!(store.voelin_key(&key().uid()).unwrap().is_some()); + assert_eq!(store.account_record().unwrap(), None, "the record itself is gone"); + + // The explicit choice still deletes it. + let Install { store, .. } = signed_in_install(false); + damage_the_record(&store, &old); + 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()); +} + +#[test] +fn forgetting_the_identity_deletes_the_device_key_whatever_the_record_says() { + for predates_the_account in [true, false] { + let Install { store, synced, device_only, local } = signed_in_install(predates_the_account); + let forget = DeviceKeyChoice::Forget(key().uid()); + let done = store.sign_out(&binding().account, forget).unwrap(); + assert!(done.removed.contains(&device_key_info()), "{predates_the_account}: {done:?}"); + assert!(!done.unbound.contains(&device_key_info()), "{predates_the_account}: {done:?}"); + assert!(store.voelin_key(&key().uid()).unwrap().is_none()); + assert_eq!(store.account_record().unwrap(), None); + // The rest is what any sign-out does. + assert!(store.get(KIND_TEAMSPEAK, &synced.uid).unwrap().is_none()); + assert_eq!(store.get(KIND_TEAMSPEAK, &device_only.uid).unwrap().unwrap().binding, None); + assert!(store.get(KIND_TEAMSPEAK, &local.uid).unwrap().is_some()); + // And another Voelin key stays. + let other = IdentityKey::generate().unwrap(); + store.put_voelin_key(&other).unwrap(); + assert!(store.voelin_key(&other.uid()).unwrap().is_some()); + } +} + +#[test] +fn a_sign_out_that_stopped_half_way_can_be_run_again() { + // The device key is gone already (a crash after it) but the record is + // still there: the second run deletes the record and the rest. A key that + // is not there is not reported as kept either. + for (predates_the_account, choice) in [ + (false, DeviceKeyChoice::Auto), + (true, DeviceKeyChoice::Auto), + (true, DeviceKeyChoice::Forget(key().uid())), + ] { + let store = SqliteKeyStore::open_in_memory().unwrap(); + store + .put_account_record(&AccountRecord { + bound_existing_key: predates_the_account, + ..record() + }) + .unwrap(); + store.put(&fresh_teamspeak(binding())).unwrap(); + let done = store.sign_out(&binding().account, choice).unwrap(); + assert_eq!(done.removed.len(), 2, "{predates_the_account}, {choice:?}: {done:?}"); + assert!(done.unbound.is_empty(), "{predates_the_account}, {choice:?}: {done:?}"); + assert!(store.list().unwrap().is_empty()); + } +} + +/// The three ways a record cannot be read. +fn unreadable_records() -> [(String, &'static str); 3] { + [ + (RECORD_JSON.replace("\"v\":1", "\"v\":2"), "AccountVersion(2)"), + ("not json".to_owned(), "AccountJson"), + ("{}".to_owned(), "AccountJson"), + ] +} + +#[test] +fn an_unreadable_record_is_deleted_before_the_error_is_reported() { + // After a downgrade or damage, the record cannot be read. The first call + // must not leave it behind to fail the same way for ever. + for (json, expected) in unreadable_records() { + let Install { store, synced, device_only, local } = signed_in_install(true); + damage_the_record(&store, &json); + + let error = store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap_err(); + assert!( + matches!(&error, KeyStoreError::Blob(blob) if format!("{blob:?}") == expected), + "{expected}: {error:?}" + ); + // The record is gone and so is the synced copy; the secret that only + // this device holds is unbound; the key the record named cannot be + // found from it and stays, which is the safe reading. + assert!(store.get(KIND_ACCOUNT, &record().blob_uid()).unwrap().is_none()); + assert!(store.get(KIND_TEAMSPEAK, &synced.uid).unwrap().is_none()); + assert_eq!(store.get(KIND_TEAMSPEAK, &device_only.uid).unwrap().unwrap().binding, None); + assert!(store.voelin_key(&key().uid()).unwrap().is_some()); + + // The second call completes instead of failing again. + assert_eq!( + store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap(), + SignOut::default() + ); + assert_eq!(store.list().unwrap().len(), 3); + assert!(store.get(KIND_TEAMSPEAK, &local.uid).unwrap().is_some()); + } +} + +#[test] +fn forgetting_the_identity_with_an_unreadable_record_still_deletes_the_named_key() { + // The user chose "Forget this device's identity". The record that names + // the device key cannot be read (a version from a newer client, damage), + // so the call reports the error; it must not leave the key behind and + // look done on the retry, when nothing names the key any more. + for (json, expected) in unreadable_records() { + let Install { store, synced, device_only, .. } = signed_in_install(true); + damage_the_record(&store, &json); + let other = IdentityKey::generate().unwrap(); + store.put_voelin_key(&other).unwrap(); + + let forget = DeviceKeyChoice::Forget(key().uid()); + let error = store.sign_out(&binding().account, forget).unwrap_err(); + assert!( + matches!(&error, KeyStoreError::Blob(blob) if format!("{blob:?}") == expected), + "{expected}: {error:?}" + ); + // The key the caller named is gone, with the record and the synced + // copy; the device-only secret is unbound; another key stays. + assert!(store.voelin_key(&key().uid()).unwrap().is_none(), "{expected}"); + assert!(store.get(KIND_ACCOUNT, &record().blob_uid()).unwrap().is_none()); + assert!(store.get(KIND_TEAMSPEAK, &synced.uid).unwrap().is_none()); + assert_eq!(store.get(KIND_TEAMSPEAK, &device_only.uid).unwrap().unwrap().binding, None); + assert!(store.voelin_key(&other.uid()).unwrap().is_some()); + + // The retry has nothing left to do, and the key is not back. + assert_eq!(store.sign_out(&binding().account, forget).unwrap(), SignOut::default()); + assert!(store.voelin_key(&key().uid()).unwrap().is_none()); + assert_eq!( + store.list().unwrap().len(), + 3, + "the other key, the device secret, the local one" + ); + } +} + +/// 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. + let Install { store, .. } = signed_in_install(false); + let other = IdentityKey::generate().unwrap(); + store.put_voelin_key(&other).unwrap(); + let done = store.sign_out(&binding().account, DeviceKeyChoice::Forget(other.uid())).unwrap(); + assert!(store.voelin_key(&other.uid()).unwrap().is_none()); + assert!( + done.removed + .iter() + .any(|info| info.kind == KIND_VOELIN && info.uid == other.uid().to_base32()) + ); + // The record's key is not touched, and is not reported either way. + assert!(store.voelin_key(&key().uid()).unwrap().is_some()); + assert!( + !done.removed.contains(&device_key_info()) && !done.unbound.contains(&device_key_info()) + ); + assert_eq!(store.account_record().unwrap(), None); + + // A uid that is not stored deletes nothing and is not reported. + let Install { store, .. } = signed_in_install(true); + let done = store.sign_out(&binding().account, DeviceKeyChoice::Forget(other.uid())).unwrap(); + assert!(store.voelin_key(&key().uid()).unwrap().is_some()); + assert!(!done.removed.iter().any(|info| info.kind == KIND_VOELIN), "{done:?}"); +} + +#[test] +fn a_sign_out_is_durable_in_the_file() { + // What the sign-out did is in the database, not in the connection: a new + // connection finds the key unbound, the copies and the record gone, and a + // second sign-out has nothing to do. + let scratch = Scratch::new("signout"); + let synced = fresh_teamspeak(binding()); + let device_only = fresh_teamspeak(AccountBinding { synced: false, ..binding() }); + { + let store = SqliteKeyStore::open(&scratch.db()).unwrap(); + store.put_voelin_key(&key()).unwrap(); + store.put_account_record(&AccountRecord { bound_existing_key: true, ..record() }).unwrap(); + store.put(&synced).unwrap(); + store.put(&device_only).unwrap(); + let done = store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap(); + assert_eq!(done.removed.len(), 2, "{done:?}"); + assert_eq!(done.unbound.len(), 2, "{done:?}"); + } + let store = SqliteKeyStore::open(&scratch.db()).unwrap(); + assert_eq!(store.account_record().unwrap(), None); + assert!(store.get(KIND_TEAMSPEAK, &synced.uid).unwrap().is_none()); + assert_eq!(store.get(KIND_TEAMSPEAK, &device_only.uid).unwrap().unwrap().binding, None); + let kept = store.get(KIND_VOELIN, &key().uid().to_base32()).unwrap().unwrap(); + assert_eq!(kept, IdentityBlob::voelin(&key()).unwrap()); + assert!(store.bound_to(&binding().account).unwrap().is_empty()); + assert_eq!( + store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap(), + SignOut::default() + ); + // And the raw row of the kept key has no account column set. + let db = Connection::open(scratch.db()).unwrap(); + let account: Option = db + .query_row("SELECT account FROM identities WHERE kind = 'voelin'", [], |r| r.get(0)) + .unwrap(); + assert_eq!(account, None); +} diff --git a/deny.toml b/deny.toml index b121807..13bc519 100644 --- a/deny.toml +++ b/deny.toml @@ -48,3 +48,6 @@ allow-wildcard-paths = true [sources] unknown-registry = "deny" unknown-git = "deny" +# The private protocol repository (voelin-identity and its voelin-proto); +# docs/building.md, "Depending on VoelinProtocol". +allow-git = ["ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git"] diff --git a/docs/architecture.md b/docs/architecture.md index 58daaef..2b60763 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -69,7 +69,7 @@ fuzz/ cargo-fuzz targets | `voelin-query` | ServerQuery codec and transports: raw TCP, SSH (russh), HTTP WebQuery | done | | `voelin-observer` | Presence tracker + chat relay pool over `voelin-query` | done | | `voelin-gateway-proto`, `voelin-gateway` (`tsgw`) | Companion service for server admins: identity-challenge auth, permission-mirroring authorization, presence stream, chat relay, SQLite history, WebSocket + JSON (`tsgw.v1+json`) | done | -| `voelin-store` | Identities, bookmarks, settings, chat history (dedupe, paging, sync cursors, where each chat was read), contacts, secrets (keyring / Android Keystore); versioned schema | done | +| `voelin-store` | Identities (TeamSpeak, a Voelin key, the signed-in account, each with its account binding, as a `voelin-identity` `KeyStore`; see Identities), bookmarks, settings, chat history (dedupe, paging, sync cursors, where each chat was read), contacts, secrets (keyring / Android Keystore); versioned schema | done | | `voelin-audio` | Capture/playback, Opus, echo cancellation, resampling, jitter buffer, mixer, VAD/push-to-talk; the voice packet types (`TalkerId`, `VoicePacket`, `EncodedVoice`), so it depends on no voice transport | v0 (no AEC yet) | | `voelin-stream` | TS6 stream commands, JSON signalling, str0m peer connections, host/STUN candidates, streamer/viewer sessions, frame-source seam; its frame and simulcast layer types are `voelin-media`'s | sessions + transport | | `voelin-core` | Engine: runtime, per-server sessions, merge of voice/gateway/query sources, the `ServerLink` seam the voice source sits behind (`link.rs`; `TsLink` is the TeamSpeak implementation, for now in this crate), event bus, command API, chat history, the gateway's features, audio settings and volumes, streams on TS6, files, avatar and icon cache, pokes, offline messages, contacts; `media` module (capture → encoder → stream, stream → decoder); the stream types of its API are its own (`stream_types`, see Streams) | done | @@ -323,6 +323,42 @@ their private messages and pokes are dropped or flagged per `stream.permissions = friends` lets friends watch our stream without asking and asks for everyone else. +## Identities + +The `identities` table of `voelin-store` holds identities of more than one kind. +A row is a `voelin_identity::IdentityBlob` { `kind`, `uid`, `level`, `json` } +with an optional account binding: a `teamspeak` row is the JSON of a +`tsproto::Identity`, exactly as the client has always stored it; a `voelin` row +is an Ed25519 key; the `account` row (`account:`) says which +account the installation is signed in to and which key is its device key; a +kind this version does not know passes through untouched. `uid` is unique +across kinds, and the uid forms of the kinds do not overlap. The table got its +new columns from two schema versions, 6 (`kind`, defaulting to `teamspeak`) and +7 (`account`, `integration`, `integration_rev`, `synced`), the SQL of which is +`voelin-identity`'s (`migrate::ADD_KIND_COLUMN` and `ADD_ACCOUNT_COLUMNS`); +every identity that existed stays what it was: kind `teamspeak`, unbound, its +JSON untouched, its origin and default flag kept. + +`Store` keeps the TeamSpeak identity methods (`identities`, `identity`, +`add_identity`, ...), which act on `teamspeak` rows only, so nothing above the +store changed. `SqliteKeyStore` is the same table as a `KeyStore`, with the +binding: `put` replaces a row of the same `(kind, uid)` and keeps its name, +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. +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 +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. + +`voelin-identity` comes from the private VoelinProtocol repository as a git +dependency pinned by commit ([building.md](building.md#depending-on-voelinprotocol)). + ## Streams `voelin-stream::Streams` holds the stream state of one TS6 connection without diff --git a/docs/building.md b/docs/building.md index 576a31b..9810b5c 100644 --- a/docs/building.md +++ b/docs/building.md @@ -124,3 +124,60 @@ the proxy is on localhost. If the proxy inspects TLS, set `scripts/flatpak-build.sh` writes `dist/flatpak/voelin.flatpak` using the release builder image. It requires a privileged container for Flatpak's nested sandbox; do not use it on an untrusted build host. + +## Depending on VoelinProtocol + +`voelin-store` uses `voelin-identity` (the identity blobs, the account-bound +`KeyStore` and the sign-out rules) from the **private** VoelinProtocol +repository, as a Cargo git dependency in the workspace `Cargo.toml`: + +```toml +[workspace.dependencies] +voelin-identity = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", rev = "…" } +``` + +It is pinned by commit until the protocol tags a release that has it; moving +to a newer protocol means changing the `rev` (later a `tag`) and committing +the resulting `Cargo.lock` together with `THIRD_PARTY_NOTICES.md`, which +`scripts/notices.sh` regenerates (the CI notices job fails on a stale one). +Cargo fetches it over SSH, so the machine needs an SSH key that can read +VoelinProtocol (an `ssh-agent` or a `~/.ssh/config` entry for +`git.faumaray.com`); if Cargo's built-in git client cannot use your SSH setup, +set `net.git-fetch-with-cli = true` in `~/.cargo/config.toml`. +`voelin-identity` builds AWS-LC from source (`aws-lc-sys`), which needs a C +compiler (gcc or clang) and cmake. +`deny.toml` allows this one git source. + +**CI and the Docker builds need read access to that repository too**: an SSH +deploy key (a repository secret written to `~/.ssh`, with the server's host key +in `known_hosts`) or an access token (rewrite the SSH URL to HTTPS with +`git config --global url."https://@git.faumaray.com/".insteadOf ssh://gitea@git.faumaray.com/` +and set `CARGO_NET_GIT_FETCH_WITH_CLI=true`). Without it `cargo` cannot fetch +the dependency and a fresh checkout does not build; the details are in +VoelinProtocol's `docs/development.md` ("Depending on VoelinProtocol"). + +### Working with a sibling VoelinProtocol checkout + +To change the protocol and this client together, check VoelinProtocol out next +to this repository (`Projects/Voelin/VoelinProtocol` beside +`Projects/Voelin/VoelinClient`) and redirect the git dependency to it with a +per-developer `.cargo/config.toml` in the root of this repository: + +```toml +# VoelinClient/.cargo/config.toml (per developer, never committed) +[patch."ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git"] +voelin-identity = { path = "../VoelinProtocol/crates/voelin-identity" } +# voelin-proto is a dependency of voelin-identity from the same repository: +voelin-proto = { path = "../VoelinProtocol/crates/voelin-proto" } +``` + +- Relative paths in a Cargo config file resolve from the directory that + contains `.cargo`, so `../VoelinProtocol` is the sibling checkout. (A git + worktree of this repository, such as `.wt/`, uses the matching number + of `../` or an absolute path.) +- The URL must be spelled exactly as in the workspace `Cargo.toml`. +- `/.cargo/` is in `.gitignore`: the file is yours and is never committed. +- With the patch active Cargo rewrites `Cargo.lock` (the patched crates lose + their git `source`). Do not commit that: run `git checkout Cargo.lock` before + committing, or remove the file and run `cargo update -p voelin-identity` + after changing the `rev`. CI builds with `--locked` and has no patch. diff --git a/docs/ci.md b/docs/ci.md index 44b844c..64678b7 100644 --- a/docs/ci.md +++ b/docs/ci.md @@ -55,7 +55,12 @@ the separate `release.yml` workflow below. 3. Allow network access from the runner and job container to the Gitea instance, GitHub (checkout action, dependencies and RustSec advisories), GHCR (runner image), Ubuntu apt mirrors, rustup distribution servers, - crates.io and dependency/license sources used by cargo-about. + crates.io and dependency/license sources used by cargo-about. The + workspace also depends on the **private** VoelinProtocol repository + (`voelin-identity`, over SSH), so the job needs read access to it: an SSH + deploy key or an access token, set up as in + [building.md](building.md#depending-on-voelinprotocol). Until a runner has + it, a fresh checkout does not build there. 4. Provision enough RAM, swap and free disk for a full Slint workspace build plus cargo-deny/cargo-about compilation. These are large builds; monitor the first run and size the runner accordingly. The workflow limits Cargo