Implement voelin-identity's KeyStore on the SQLite identities table

SqliteKeyStore is the identities table as a KeyStore: every kind (TeamSpeak,
a Voelin key, the account record, an unknown kind that passes through) with
the account binding of the columns that ADD_ACCOUNT_COLUMNS added. It owns a
Store behind a mutex, because a KeyStore is Sync and a connection is not;
with_store runs the TeamSpeak methods on the same connection. The trait's
provided methods (bound_to, account_record, put_account_record, sign_out)
are used as they are.

- put is one upsert; a replaced row keeps its name, origin, default flag and
  creation time, and a blob without a binding unbinds the row. The uid is
  UNIQUE across kinds, so a uid another kind holds is a backend error that
  replaces nothing; get and remove are addressed by kind and uid.
- The TeamSpeak level stays computed from the key and counter, as before; the
  level of a blob that is put is not stored. A TeamSpeak row whose JSON was
  damaged outside this crate lists and reads with level 0.
- A TeamSpeak blob is stored only if its JSON is a tsproto identity and its
  key has the uid the blob names. Without the first one bad row breaks the
  list of TeamSpeak identities; without the second a blob could replace, by
  its uid, the key of a different identity.

Tests copy the exercise() cases of voelin-identity's tests/storage.rs into
the client (with the two deviations of a SQLite store, marked), round-trip
bound and synced entries through the table and a reopen with their raw
columns, and load a client.db migrated from schema versions 5 and 6 through
the key store: kind teamspeak, no binding, JSON byte for byte, origin and
default flag kept.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Sonnet 5.5 committed 2026-10-20 05:48:51 +03:00
1 parent 0137d03d5b
commit 2898281d35
4 files changed
+936

No files matched your search

+250
View File
@@ -0,0 +1,250 @@
//! The `identities` table as a [`voelin_identity::KeyStore`].
//!
//! The table holds identities of more than one kind: the TeamSpeak identities
//! the client has always had (`kind` `teamspeak`, `data` the JSON of a
//! `tsproto::Identity`), a Voelin key (`voelin`), the record of the account the
//! installation is signed in to (`account`) and whatever kind a later version
//! adds, which passes through untouched. A row is addressed by its
//! `(kind, uid)`, and `uid` stays `UNIQUE` across kinds: the uid forms of the
//! kinds do not overlap (a TeamSpeak uid is base64, a Voelin uid 52 characters
//! of `a-z2-7`, an account uid is written `account:<uid>`).
//!
//! Besides the blob a row carries the columns of the TeamSpeak-only world,
//! which a [`KeyStore`] does not see and keeps when it replaces a row: `name`,
//! `origin`, `is_default` and `created`. A blob of a new `(kind, uid)` becomes a
//! row named after its uid, of origin `user` and not the default.
//!
//! The TeamSpeak security level is not stored: it is computed from the key and
//! counter in `data`, as [`Store::identities`] always did, and the level of a
//! blob a caller puts is ignored. A TeamSpeak row whose JSON cannot be read
//! (it could only have been damaged outside this crate) lists and reads with
//! level 0 instead of failing the whole list, so that signing out is never
//! blocked by it.
use std::path::Path;
use std::sync::{Mutex, MutexGuard, PoisonError};
use rusqlite::params;
use tsclientlib::Identity;
use voelin_identity::migrate::SELECT_ACCOUNT_COLUMNS;
use voelin_identity::{
AccountBinding, BlobError, IdentityBlob, IdentityInfo, KIND_TEAMSPEAK, KeyStore, KeyStoreError,
};
use crate::{Error, Result, Store};
/// A result of the key store seam.
type KsResult<T> = std::result::Result<T, KeyStoreError>;
/// The rows of [`KeyStore::list`]. The secret of a kind this crate does not
/// interpret is never read; a TeamSpeak row's `data` is, for its level.
const LIST: &str = "SELECT kind, uid, CASE WHEN kind = 'teamspeak' THEN data END,
account, integration, integration_rev, synced
FROM identities ORDER BY kind, uid";
/// Insert the blob, or replace the row of the same uid if it is of the same
/// kind. A row of another kind is left alone: the statement then changes
/// nothing, which `put` reports.
const PUT: &str = "INSERT INTO identities
(name, uid, data, kind, account, integration, integration_rev, synced)
VALUES (?1, ?1, ?2, ?3, ?4, ?5, ?6, ?7)
ON CONFLICT (uid) DO UPDATE SET
data = excluded.data, account = excluded.account,
integration = excluded.integration, integration_rev = excluded.integration_rev,
synced = excluded.synced
WHERE identities.kind = excluded.kind";
/// The identities of a client database as a [`KeyStore`]: every kind, with its
/// account binding.
///
/// It owns a [`Store`] behind a mutex, because a [`KeyStore`] is `Sync` and a
/// SQLite connection is not. Open it on the database file next to the
/// other connections of the app (the settings writer and the chat history do
/// the same): SQLite lets them share the file. [`Self::with_store`] gives
/// access to the TeamSpeak methods of the same connection.
///
/// [`KeyStore::sign_out`] and the rest of the trait's provided methods work as
/// `voelin-identity` defines them; each call here is one statement.
pub struct SqliteKeyStore {
store: Mutex<Store>,
}
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<Self> {
Ok(Self::new(Store::open(path)?))
}
/// A key store in memory: for tests.
pub fn open_in_memory() -> Result<Self> {
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<R>(&self, f: impl FnOnce(&Store) -> R) -> R {
f(&self.lock())
}
fn lock(&self) -> MutexGuard<'_, Store> {
// A panic in another thread cannot leave the table half-updated: every
// method here is one statement.
self.store.lock().unwrap_or_else(PoisonError::into_inner)
}
}
impl KeyStore for SqliteKeyStore {
fn list(&self) -> KsResult<Vec<IdentityInfo>> {
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<Option<IdentityBlob>> {
let store = self.lock();
let sql =
format!("SELECT {SELECT_ACCOUNT_COLUMNS} FROM identities WHERE kind = ?1 AND uid = ?2");
let mut statement = store.db.prepare_cached(&sql).map_err(backend)?;
let mut rows = statement.query_map(params![kind, uid], Columns::read).map_err(backend)?;
rows.next().transpose().map_err(backend)?.map(Columns::into_blob).transpose()
}
fn put(&self, blob: &IdentityBlob) -> KsResult<()> {
if blob.kind == KIND_TEAMSPEAK {
check_teamspeak(blob)?;
}
let columns = blob.binding_columns()?;
let store = self.lock();
let changed = store
.db
.prepare_cached(PUT)
.map_err(backend)?
.execute(params![
blob.uid,
blob.json,
blob.kind,
columns.account,
columns.integration,
columns.rev,
columns.synced,
])
.map_err(backend)?;
if changed == 0 {
let held_by: String = store
.db
.query_row("SELECT kind FROM identities WHERE uid = ?1", [&blob.uid], |r| r.get(0))
.map_err(backend)?;
return Err(KeyStoreError::backend(Refused::UidHeld {
uid: blob.uid.clone(),
kind: held_by,
}));
}
Ok(())
}
fn remove(&self, kind: &str, uid: &str) -> KsResult<bool> {
let store = self.lock();
let removed = store
.db
.prepare_cached("DELETE FROM identities WHERE kind = ?1 AND uid = ?2")
.map_err(backend)?
.execute(params![kind, uid])
.map_err(backend)?;
Ok(removed > 0)
}
}
/// A TeamSpeak blob is stored only if it is what its kind says: the JSON of a
/// `tsproto::Identity` whose key has the uid the blob names.
///
/// The first keeps one bad row, which a service or a damaged file could hand
/// over, from failing the list of TeamSpeak identities for everyone. The
/// second keeps a blob from overwriting, by its uid, the key of a different
/// identity that is stored under that uid.
fn check_teamspeak(blob: &IdentityBlob) -> KsResult<()> {
let identity: Identity =
serde_json::from_str(&blob.json).map_err(|e| backend(Error::Json(e)))?;
if identity.key().to_pub().get_uid() != blob.uid {
return Err(KeyStoreError::Blob(BlobError::UidMismatch));
}
Ok(())
}
/// A database error as the store's backend error.
fn backend(error: impl Into<Error>) -> KeyStoreError {
KeyStoreError::backend(error.into())
}
/// A [`KeyStore::put`] this store refuses.
#[derive(Debug, thiserror::Error)]
enum Refused {
/// `uid` is unique across kinds in this table.
#[error("the uid {uid:?} is already stored as an identity of kind {kind:?}")]
UidHeld { uid: String, kind: String },
}
/// One row of the table as `LIST` and `SELECT_ACCOUNT_COLUMNS` select it.
struct Columns {
kind: String,
uid: String,
/// The identity itself. `LIST` leaves it out for kinds with no level.
data: Option<String>,
account: Option<String>,
integration: Option<String>,
rev: i64,
synced: i64,
}
impl Columns {
fn read(row: &rusqlite::Row<'_>) -> rusqlite::Result<Self> {
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<Option<AccountBinding>> {
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::<Identity>(json).map_or(0, |identity| identity.level())
}
_ => 0,
}
}
fn into_info(self) -> KsResult<IdentityInfo> {
let binding = self.binding()?;
let level = self.level();
Ok(IdentityInfo { kind: self.kind, uid: self.uid, level, binding })
}
fn into_blob(self) -> KsResult<IdentityBlob> {
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))
}
}
+8
View File
@@ -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};
+72
View File
@@ -799,6 +799,78 @@ mod tests {
std::fs::remove_dir_all(dir).unwrap();
}
/// The acceptance of the migration for the key store: a `client.db` at the
/// version before the identity migrations (5), and at the one between them
/// (6), opens, and every identity loads through the key store unchanged:
/// kind `teamspeak`, no binding, its JSON byte for byte, the level computed
/// as before, and the origin and default flag the old API reports kept.
#[test]
fn a_migrated_database_loads_every_identity_unchanged_through_the_key_store() {
use crate::SqliteKeyStore;
use voelin_identity::{IdentityBlob, IdentityInfo, KIND_TEAMSPEAK, KeyStore};
for version in [5, 6] {
let dir = scratch_dir(&format!("keys-v{version}"));
let path = dir.join("client.db");
let other = Identity::create();
let other_json = serde_json::to_string(&other).unwrap();
let other_uid = other.key().to_pub().get_uid();
database_at(&path, version);
{
let db = rusqlite::Connection::open(&path).unwrap();
for (name, uid, json, origin, default) in [
("Main", TEAMSPEAK_UID, TEAMSPEAK_JSON, "imported", 1),
("Other", other_uid.as_str(), other_json.as_str(), "created", 0),
] {
db.execute(
"INSERT INTO identities (name, uid, data, origin, is_default)
VALUES (?1, ?2, ?3, ?4, ?5)",
params![name, uid, json, origin, default],
)
.unwrap();
}
}
let keys = SqliteKeyStore::open(&path).unwrap();
assert_eq!(keys.with_store(|s| s.schema_version().unwrap()), 7);
let want = [
(TEAMSPEAK_UID.to_owned(), TEAMSPEAK_JSON.to_owned(), TEAMSPEAK_LEVEL),
(other_uid.clone(), other_json.clone(), other.level()),
];
let mut infos: Vec<_> = want
.iter()
.map(|(uid, _, level)| IdentityInfo {
kind: KIND_TEAMSPEAK.into(),
uid: uid.clone(),
level: *level,
binding: None,
})
.collect();
infos.sort_by(|a, b| a.uid.cmp(&b.uid));
assert_eq!(keys.list().unwrap(), infos, "version {version}");
for (uid, json, level) in want {
let blob = keys.get(KIND_TEAMSPEAK, &uid).unwrap().unwrap();
assert_eq!(blob, IdentityBlob::teamspeak(&uid, level, &json), "version {version}");
assert_eq!(blob.json, json, "byte for byte");
assert_eq!(blob.binding, None);
}
// What the TeamSpeak methods report is kept as well.
let entries = keys.with_store(|s| s.identities().unwrap());
let origin = |uid: &str| entries.iter().find(|e| e.uid == uid).unwrap();
assert_eq!(
(origin(TEAMSPEAK_UID).origin, origin(TEAMSPEAK_UID).is_default),
(IdentityOrigin::Imported, true)
);
assert_eq!(
(origin(&other_uid).origin, origin(&other_uid).is_default),
(IdentityOrigin::Created, false)
);
drop(keys);
std::fs::remove_dir_all(dir).unwrap();
}
}
/// A database of version 6 (the `kind` column, no account columns yet) takes
/// the second step alone, and its rows of other kinds stay what they are.
#[test]