Files
VoelinClient/crates/voelin-store/src/keystore.rs
T
faumarayandClaude Sonnet 5.5 71edc7cc2f Unbind a bound TeamSpeak row without reading its JSON again
KeyStore::sign_out unbinds a device-only secret by get() and put() of the
same blob with the binding cleared. put() ran check_teamspeak on the data
first, so a bound row whose JSON had been damaged outside this crate made the
put fail on every call: the account record was never reached, and with
DeviceKeyChoice::Forget the order of the sign-out kept the named key from
being deleted by the retry loop the module doc promised was unnecessary.

put() now first tries a statement that rewrites only the four binding columns
of the row of the same (kind, uid) whose data equals the blob's, and returns
if it changed a row. Anything else, a new row or other data, goes through the
check and the upsert as before: damage is not replaced by more damage, a
stranger's key still cannot take over a uid, and another kind's put of a held
uid is still refused. Nothing but the binding of the row is written, so the
name, origin, default flag and creation time stay as they were.

Tests: sign_out (Auto, and Forget with and without bound_existing_key)
completes on a damaged bound row, deletes the record, unbinds the row and
leaves its data as it was; the put cases above; each fails on the previous
commit. The scratch directories of the test file are unique per call now, as
two tests that pass the same name run side by side.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 06:21:10 +03:00

293 lines
10 KiB
Rust

//! 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, 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<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";
/// 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<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
// 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<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<()> {
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<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.
///
/// 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::<Identity>(&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<Error>) -> 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<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))
}
}