From 0137d03d5b16960b16975077bf15599598cd6726 Mon Sep 17 00:00:00 2001 From: faumaray Date: Tue, 20 Oct 2026 05:43:52 +0300 Subject: [PATCH] Run the identity migrations of voelin-identity as schema versions 6 and 7 ADD_KIND_COLUMN and then ADD_ACCOUNT_COLUMNS are the next two entries of the user_version list, in the order the protocol's Phase 2 tasks 7 and 28 give. Every identity that exists stays what it was: kind teamspeak, unbound, its JSON untouched, its origin and default flag kept, and the level still computed from the key. The TeamSpeak methods of Store (identities, identity, update, rename, delete, set_default) now act on rows of kind teamspeak only, so that a Voelin key or the account record in the same table can never be listed as a tsproto identity (listing would fail on its JSON) or renamed, changed or deleted by the old API. Their signatures are unchanged. Tests build a client.db at the current schema (version 5) and at version 6 from the migration list itself, open it, and check both steps: the fixture row (the real tsproto serialization, its uid and level checked against tsproto), a second generated identity, the raw columns, the old API, and a reopen that runs nothing twice. A test pins the SQL of both migrations against the protocol's strings so that a newer protocol revision cannot change a shipped version. Co-Authored-By: Claude Sonnet 5.5 --- crates/voelin-store/src/store.rs | 312 ++++++++++++++++++++++++++++++- 1 file changed, 304 insertions(+), 8 deletions(-) diff --git a/crates/voelin-store/src/store.rs b/crates/voelin-store/src/store.rs index a1aa46d..092429d 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,278 @@ 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(); + } + + /// 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();