AccountClient::release (voelin-account-client at c5bb6b9) asks the service to release the key and then runs KeyStore::sign_out with DeviceKeyChoice::Auto, so the unbind of one key that keeps its data is the sign-out's own step (and a put of the blob without its binding for a single key). Open question 10 and protocol 13.6 ask the client to remember nothing: the service holds the registration of the key, and the client learns that a key is still registered with an account it signed out of from the service's answer to a sign-in or a sign-up (CONFLICT, field device). So there is no "released" record and no new store call; keystore.rs says so, and says the same of the deletion of an account, whose local half is this sign-out. Two tests pin what the client relies on after a release: the key is kept byte for byte and unbound, then is the device key of a record of another account, and a sign-out of that account keeps it again (its copies go); and a release whose local half was cut short is finished by a sign-out with Auto, and a second one finds nothing to do. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
673 lines
28 KiB
Rust
673 lines
28 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
|
|
//! that `data`, as [`KeyStore::get`] reads it) writes the four binding columns,
|
|
//! does not look at `data` again and does not rewrite it. That is how
|
|
//! [`KeyStore::sign_out`] unbinds a device-only secret: a row whose `data` was
|
|
//! damaged outside this crate (JSON that is no identity, a BLOB, bytes that are
|
|
//! no UTF-8) does not keep the sign-out from unbinding it, and its `data` is
|
|
//! kept byte for byte.
|
|
//!
|
|
//! A row that is damaged elsewhere never fails a call that is not about it. A
|
|
//! row whose binding columns cannot be read (`synced = 2`, an `account` that is
|
|
//! no uid, a revision that is no integer; only something outside this crate
|
|
//! writes them) is listed and read as unbound, and a warning names the row and
|
|
//! the reason. [`KeyStore::list`] fails only when the database does, because
|
|
//! the trait's [`KeyStore::sign_out`] starts with it and then reads the account
|
|
//! record and the device key with [`KeyStore::get`]: one damaged row, the
|
|
//! record's own included, would otherwise keep a sign-out from ever finishing,
|
|
//! and with it the deletion of the synced copies and of the record, and the
|
|
//! forgetting of the key the user asked to forget. Unbound is the reading that
|
|
//! never deletes on a guess: a sign-out neither deletes such a row as a synced
|
|
//! copy nor writes it, it stays as it is until a `put` of it writes four good
|
|
//! binding columns. A `data` column that is not text (a BLOB, or text of bytes
|
|
//! that are no UTF-8) is read as text with the odd bytes replaced, so that a
|
|
//! record that cannot be read is deleted by the sign-out, as the trait says,
|
|
//! instead of its read failing. A [`KeyStore::put`] of the text that
|
|
//! [`KeyStore::get`] returned for such a row is taken for the data that is
|
|
//! there: it changes the binding and keeps the stored bytes, where any other
|
|
//! text replaces them (a TeamSpeak blob still has to be an identity). A row
|
|
//! whose `kind` or `uid` is not text cannot be addressed, and the list leaves it
|
|
//! out with a warning.
|
|
//!
|
|
//! # Signing out keeps every key
|
|
//!
|
|
//! [`KeyStore::sign_out`] is the trait's own, run on this table, and since
|
|
//! Phase 2 task 34 of the protocol repository (open question 10 of its accounts
|
|
//! design, answered by the owner on 2026-10-24) it keeps every key of the
|
|
//! device. The device key stays, unbound and byte for byte, whether it was in
|
|
//! use before the account existed or the client made it for the account:
|
|
//! `AccountRecord::bound_existing_key` only records which, for the client's
|
|
//! wording, and no rule reads it. At every host without accounts that the user
|
|
//! reached with it, either key is the user's identity, and deleting it would
|
|
//! lose their servers, roles and memberships there. The identities that only
|
|
//! this device holds (a TeamSpeak identity of custody `DEVICE`, one the user
|
|
//! kept local) are unbound and kept as well.
|
|
//!
|
|
//! What a sign-out deletes is not a key of the device: the synced copies of
|
|
//! integration secrets, which the account service holds and every device can
|
|
//! fetch again (a copy of a TeamSpeak identity is a private key, and is deleted
|
|
//! like one, see below), and the account record, which holds no secret. A
|
|
//! sign-out does not release the device key at the account service either: the
|
|
//! key stays registered with the account there. The release is its own
|
|
//! operation, see below.
|
|
//!
|
|
//! # Releasing a device key
|
|
//!
|
|
//! The release of the device key from its account (part 2 of open question 10)
|
|
//! is the account service's operation followed by a local unbind, and the unbind
|
|
//! is a sign-out: `AccountClient::release` of `voelin-account-client` calls
|
|
//! `POST /v1/devices/<own>/release` after a password check, and then runs
|
|
//! [`KeyStore::sign_out`] with [`DeviceKeyChoice::Auto`], which keeps the key,
|
|
//! unbound. So the store needs nothing of its own for it: no call that unbinds
|
|
//! one key (a [`KeyStore::put`] of the blob without its binding does that, and
|
|
//! keeps the data, as the sign-out does), and no record that the key was
|
|
//! released. The accounts design asks the client to remember nothing of the
|
|
//! kind: the service holds the registration of the key (after a release it is
|
|
//! registered with no account, after a sign-out with the account that was
|
|
//! signed out of), and the client learns which at the next sign-in or sign-up,
|
|
//! from the service's answer (`CONFLICT`, field `device`), not from a note kept
|
|
//! here. The deletion of the account (`AccountClient::delete_account`) is the
|
|
//! same: the service writes a DEVICE and a RELEASED entry for every device key
|
|
//! of the account, and the local half is this sign-out, which keeps this
|
|
//! device's key.
|
|
//!
|
|
//! # Forgetting the device's identity
|
|
//!
|
|
//! "Forget this device's identity" is the user's explicit choice and the only
|
|
//! deletion of a key of the device; the UI offers to export the key first and
|
|
//! asks before it deletes.
|
|
//!
|
|
//! - Signed in, it is a sign-out with [`DeviceKeyChoice::Forget`] and the uid of
|
|
//! the device key. The caller names the key, because the key goes before the
|
|
//! record is read: a record that cannot be read does not keep it.
|
|
//! - Signed out, or with a key that no account ever bound, it is
|
|
//! [`KeyStore::remove`] of `(KIND_VOELIN, uid)`; a TeamSpeak identity is
|
|
//! [`Store::delete_identity`]. Neither looks at an account record, so a UI
|
|
//! that forgets the device key of the account it is signed in to does it
|
|
//! through the sign-out, not through `remove`.
|
|
//!
|
|
//! The store has no call that exports, because it would only wrap what the
|
|
//! caller can read before it deletes: a Voelin key is
|
|
//! `KeyStore::voelin_key(uid)` followed by `IdentityKey::to_pkcs8` (the DER that
|
|
//! `voelin_identity::FileSigner` reads back; the buffer is zeroized when it is
|
|
//! dropped), and a TeamSpeak identity is `Store::identity(id)` followed by
|
|
//! `voelin_core::ts::identity::export` or `write_export`. The same two calls,
|
|
//! with [`KeyStore::list`] for the `voelin` rows, serve the dialog that deletes
|
|
//! the account: it offers an export of the device keys before the service is
|
|
//! asked.
|
|
//!
|
|
//! # Deleted keys leave no trace
|
|
//!
|
|
//! The rows are private keys, so a removed row is not left behind in the file:
|
|
//! every connection sets `secure_delete`, which makes SQLite overwrite what it
|
|
//! deletes, and [`KeyStore::remove`] truncates the write-ahead log after it, as
|
|
//! [`Store::delete_identity`] does, so that the frame of the log that held the
|
|
//! page with the key is gone too. A forgotten key needs exactly that. So does
|
|
//! the one deletion a sign-out still makes of a key: a synced copy of a
|
|
//! TeamSpeak identity, and with `Forget` the device key itself. The sign-out
|
|
//! deletes with `remove` on a `SignOutPass` and truncates the log once, after
|
|
//! its last step, not after each removal; one that deletes nothing (the record
|
|
//! was gone, no copies) truncates nothing. The checkpoint waits for another
|
|
//! connection for a moment at most (`Store::truncate_wal`): one that keeps
|
|
//! reading an old snapshot blocks it, and then the removal still succeeds and a
|
|
//! warning says that the deleted bytes may stay in the log file, until a later
|
|
//! checkpoint truncates the log, later writes overwrite those frames, or the
|
|
//! last connection to the database closes and the log is deleted.
|
|
//!
|
|
//! # The device key is never a synced copy
|
|
//!
|
|
//! A sign-out keeps the device key, but its first step deletes every identity
|
|
//! bound with `synced = true`, before it reads the account record that names
|
|
//! the device key. A device key stored that way would be deleted by that step,
|
|
//! whether it predates the account or not, which is what the rule that a
|
|
//! sign-out keeps every device key forbids. The store therefore refuses, with an
|
|
//! error that says why, a [`KeyStore::put`] of a `voelin` blob with
|
|
//! `synced = true` while an account record names its uid as the device, or while
|
|
//! a record cannot be read, because then it cannot tell; and a put of an
|
|
//! account record that names a key which is stored as a synced copy. A binding
|
|
//! with `synced = false` is accepted: a sign-out unbinds such a key and keeps
|
|
//! it. The check and the write are done under the store's lock; a second
|
|
//! process writing the same file at the same moment is not covered.
|
|
//!
|
|
//! 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::atomic::{AtomicBool, Ordering};
|
|
use std::sync::{Mutex, MutexGuard, PoisonError};
|
|
|
|
use rusqlite::types::ValueRef;
|
|
use rusqlite::{OptionalExtension, params};
|
|
use tsclientlib::Identity;
|
|
use voelin_identity::migrate::SELECT_ACCOUNT_COLUMNS;
|
|
use voelin_identity::{
|
|
AccountBinding, BindingColumns, BlobError, DeviceKeyChoice, IdentityBlob, IdentityInfo,
|
|
KIND_ACCOUNT, KIND_TEAMSPEAK, KIND_VOELIN, KeyStore, KeyStoreError, SignOut, Uid,
|
|
};
|
|
|
|
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, id
|
|
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";
|
|
|
|
/// [`REBIND`] for a row whose `data` is not text and reads, as [`lossy_text`]
|
|
/// reads it, as the blob's: the same four columns, and the stored bytes stay.
|
|
const REBIND_BYTES: &str = "UPDATE identities
|
|
SET account = ?3, integration = ?4, integration_rev = ?5, synced = ?6
|
|
WHERE kind = ?1 AND uid = ?2";
|
|
|
|
/// 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: a sign-out
|
|
/// keeps every key of the device (only [`DeviceKeyChoice::Forget`] deletes the
|
|
/// device key), and only truncates the write-ahead log once, at its end, when
|
|
/// it deleted something.
|
|
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)?;
|
|
let mut infos = Vec::new();
|
|
for row in rows {
|
|
infos.extend(row.map_err(backend)?.map(Columns::into_info));
|
|
}
|
|
Ok(infos)
|
|
}
|
|
|
|
fn get(&self, kind: &str, uid: &str) -> KsResult<Option<IdentityBlob>> {
|
|
let store = self.lock();
|
|
let sql = format!(
|
|
"SELECT {SELECT_ACCOUNT_COLUMNS}, id 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)?;
|
|
Ok(rows.next().transpose().map_err(backend)?.flatten().map(Columns::into_blob))
|
|
}
|
|
|
|
fn put(&self, blob: &IdentityBlob) -> KsResult<()> {
|
|
let columns = blob.binding_columns()?;
|
|
let store = self.lock();
|
|
match blob.kind.as_str() {
|
|
KIND_VOELIN if blob.binding.is_some_and(|binding| binding.synced) => {
|
|
refuse_synced_device_key(&store, &blob.uid)?;
|
|
}
|
|
KIND_ACCOUNT => refuse_record_of_synced_key(&store, blob)?,
|
|
_ => {}
|
|
}
|
|
// 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. "Holds this data" is
|
|
// meant as `get` reads it: for a `data` that is not text, `get` hands out
|
|
// the text with the odd bytes replaced, `REBIND` cannot match that, and
|
|
// the second statement takes the blob for the data that is there.
|
|
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 || rebind_stored_bytes(&store, blob, &columns)? {
|
|
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 = delete_row(&store, kind, uid)?;
|
|
if removed {
|
|
// The row may be a key: leave nothing of it in the log either.
|
|
store.truncate_wal();
|
|
}
|
|
Ok(removed)
|
|
}
|
|
|
|
/// The trait's sign-out, with the log truncated once after its last step
|
|
/// instead of after each of its removals: it removes up to a handful of
|
|
/// rows (the synced copies, the account record and, with
|
|
/// [`DeviceKeyChoice::Forget`], the device key; every other key stays), and
|
|
/// a checkpoint that another connection blocks costs a moment
|
|
/// (`Store::truncate_wal`) each time. The steps are the trait's own; they
|
|
/// run on a `SignOutPass`, which deletes like [`Self::remove`] and leaves
|
|
/// the checkpoint to this method. A sign-out that deleted nothing does not
|
|
/// checkpoint.
|
|
fn sign_out(&self, account: &Uid, device_key: DeviceKeyChoice) -> KsResult<SignOut> {
|
|
let pass = SignOutPass { store: self, deleted: AtomicBool::new(false) };
|
|
let outcome = KeyStore::sign_out(&pass, account, device_key);
|
|
// Also after a failure: the removals before it have happened.
|
|
if pass.deleted.load(Ordering::Relaxed) {
|
|
self.lock().truncate_wal();
|
|
}
|
|
outcome
|
|
}
|
|
}
|
|
|
|
/// Delete the row of this `(kind, uid)`: whether there was one. The rows are
|
|
/// overwritten (`secure_delete`); the log is the caller's to truncate.
|
|
fn delete_row(store: &Store, kind: &str, uid: &str) -> KsResult<bool> {
|
|
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 [`SqliteKeyStore`] for the length of one [`KeyStore::sign_out`]: the same
|
|
/// rows, but `remove` only notes that it deleted something, so that the sign-out
|
|
/// truncates the log once at its end. What a sign-out removes is the synced
|
|
/// copies of integration secrets, the account record and, when the user chose
|
|
/// to forget it, the device key; unbinding goes through `put`, which deletes
|
|
/// nothing.
|
|
struct SignOutPass<'a> {
|
|
store: &'a SqliteKeyStore,
|
|
/// Whether a row was deleted.
|
|
deleted: AtomicBool,
|
|
}
|
|
|
|
impl KeyStore for SignOutPass<'_> {
|
|
fn list(&self) -> KsResult<Vec<IdentityInfo>> {
|
|
self.store.list()
|
|
}
|
|
|
|
fn get(&self, kind: &str, uid: &str) -> KsResult<Option<IdentityBlob>> {
|
|
self.store.get(kind, uid)
|
|
}
|
|
|
|
fn put(&self, blob: &IdentityBlob) -> KsResult<()> {
|
|
self.store.put(blob)
|
|
}
|
|
|
|
fn remove(&self, kind: &str, uid: &str) -> KsResult<bool> {
|
|
let removed = delete_row(&self.store.lock(), kind, uid)?;
|
|
if removed {
|
|
self.deleted.store(true, Ordering::Relaxed);
|
|
}
|
|
Ok(removed)
|
|
}
|
|
}
|
|
|
|
/// Change only the binding of the row of the blob's `(kind, uid)` if its `data`
|
|
/// is not text but reads as exactly the blob's JSON, and say whether it did.
|
|
///
|
|
/// [`KeyStore::get`] reads a `data` that is a BLOB, or TEXT of bytes that are no
|
|
/// UTF-8, as text with the odd bytes replaced ([`lossy_text`]). The blob that a
|
|
/// sign-out puts back to unbind such a row carries that text, so `REBIND` finds
|
|
/// nothing, and writing the blob would replace the stored bytes with the
|
|
/// replaced text (and refuse a TeamSpeak row, whose replaced text is no
|
|
/// identity, for ever). The text `get` handed out is taken for the data that is
|
|
/// there, and the bytes are kept.
|
|
///
|
|
/// It is called after `REBIND` changed nothing, which is why the stored value is
|
|
/// known not to be exactly the blob's text. Any other JSON does not match, and
|
|
/// is a new identity for the uid as ever.
|
|
fn rebind_stored_bytes(
|
|
store: &Store,
|
|
blob: &IdentityBlob,
|
|
columns: &BindingColumns,
|
|
) -> KsResult<bool> {
|
|
let reads_as_blob = store
|
|
.db
|
|
.prepare_cached("SELECT data FROM identities WHERE kind = ?1 AND uid = ?2")
|
|
.map_err(backend)?
|
|
.query_row(params![blob.kind, blob.uid], |row| {
|
|
Ok(lossy_text(row.get_ref(0)?).is_some_and(|text| text == blob.json))
|
|
})
|
|
.optional()
|
|
.map_err(backend)?;
|
|
if reads_as_blob != Some(true) {
|
|
return Ok(false);
|
|
}
|
|
store
|
|
.db
|
|
.prepare_cached(REBIND_BYTES)
|
|
.map_err(backend)?
|
|
.execute(params![
|
|
blob.kind,
|
|
blob.uid,
|
|
columns.account,
|
|
columns.integration,
|
|
columns.rev,
|
|
columns.synced,
|
|
])
|
|
.map_err(backend)?;
|
|
Ok(true)
|
|
}
|
|
|
|
/// 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(())
|
|
}
|
|
|
|
/// Refuse to store the Voelin key `uid` as a synced copy while the device key
|
|
/// of the installation, as an account record names it, is this key.
|
|
///
|
|
/// A record that cannot be read could name it: it is refused then too, because
|
|
/// the sign-out that follows would delete the key on that guess.
|
|
fn refuse_synced_device_key(store: &Store, uid: &str) -> KsResult<()> {
|
|
let mut statement = store
|
|
.db
|
|
.prepare_cached("SELECT uid, data FROM identities WHERE kind = 'account'")
|
|
.map_err(backend)?;
|
|
let mut rows = statement.query([]).map_err(backend)?;
|
|
while let Some(row) = rows.next().map_err(backend)? {
|
|
// A record whose uid is not text cannot be addressed; it is not read.
|
|
let Ok(record_uid) = row.get_ref(0).map_err(backend)?.as_str() else { continue };
|
|
let data = lossy_text(row.get_ref(1).map_err(backend)?).unwrap_or_default();
|
|
match IdentityBlob::new(KIND_ACCOUNT, record_uid, 0, data).account_record() {
|
|
Ok(record) if record.device.to_base32() == uid => {
|
|
return Err(KeyStoreError::backend(Refused::SyncedDeviceKey {
|
|
uid: uid.to_owned(),
|
|
record: record_uid.to_owned(),
|
|
}));
|
|
}
|
|
Ok(_) => {}
|
|
Err(_) => {
|
|
return Err(KeyStoreError::backend(Refused::UnreadableRecord {
|
|
uid: uid.to_owned(),
|
|
record: record_uid.to_owned(),
|
|
}));
|
|
}
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
/// Refuse to store an account record whose device key is stored as a synced
|
|
/// copy: the same state as [`refuse_synced_device_key`] guards, reached from
|
|
/// the other side. A blob that is no readable record is not checked here; the
|
|
/// store has always kept what it is given for that kind, and a sign-out
|
|
/// deletes it.
|
|
fn refuse_record_of_synced_key(store: &Store, blob: &IdentityBlob) -> KsResult<()> {
|
|
let Ok(record) = blob.account_record() else { return Ok(()) };
|
|
let device = record.device.to_base32();
|
|
let synced: bool = store
|
|
.db
|
|
.prepare_cached(
|
|
"SELECT EXISTS (SELECT 1 FROM identities
|
|
WHERE kind = 'voelin' AND uid = ?1 AND synced = 1)",
|
|
)
|
|
.map_err(backend)?
|
|
.query_row([&device], |row| row.get(0))
|
|
.map_err(backend)?;
|
|
if synced {
|
|
return Err(KeyStoreError::backend(Refused::RecordNamesSyncedKey {
|
|
record: blob.uid.clone(),
|
|
device,
|
|
}));
|
|
}
|
|
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 },
|
|
/// The Voelin key is the device key of an account record. A sign-out keeps
|
|
/// the device key, but it deletes a synced copy without reading the record,
|
|
/// so a device key stored as one would be deleted all the same.
|
|
#[error(
|
|
"the Voelin key {uid:?} is the device key of the account record {record:?} and cannot be \
|
|
stored as a synced copy (synced = true): a sign-out deletes every synced copy before it \
|
|
reads the record, so it would delete the device key that it keeps"
|
|
)]
|
|
SyncedDeviceKey { uid: String, record: String },
|
|
/// An account record cannot be read, so the store cannot tell whether the
|
|
/// Voelin key is its device key.
|
|
#[error(
|
|
"the Voelin key {uid:?} cannot be stored as a synced copy (synced = true): the account \
|
|
record {record:?} cannot be read, so it may name this key as the device key, which a \
|
|
sign-out keeps but would delete as a synced copy"
|
|
)]
|
|
UnreadableRecord { uid: String, record: String },
|
|
/// The device key of the record is stored as a synced copy already.
|
|
#[error(
|
|
"the account record {record:?} names the Voelin key {device:?} as the device key, which is \
|
|
stored as a synced copy (synced = true): a sign-out deletes every synced copy before it \
|
|
reads the record, so it would delete the device key that it keeps"
|
|
)]
|
|
RecordNamesSyncedKey { record: String, device: String },
|
|
}
|
|
|
|
/// One row of the table as `LIST` and `SELECT_ACCOUNT_COLUMNS` select it (with
|
|
/// the row id last), its binding already read.
|
|
struct Columns {
|
|
kind: String,
|
|
uid: String,
|
|
/// The identity itself. `LIST` leaves it out for kinds with no level.
|
|
data: Option<String>,
|
|
/// `None` for an unbound row and for one whose binding columns are damaged.
|
|
binding: Option<AccountBinding>,
|
|
}
|
|
|
|
/// Why binding columns cannot be read.
|
|
#[derive(Debug, thiserror::Error)]
|
|
enum Damage {
|
|
#[error(transparent)]
|
|
Binding(#[from] BlobError),
|
|
#[error("a binding column holds a value of the wrong type")]
|
|
WrongType,
|
|
}
|
|
|
|
impl Columns {
|
|
/// The row, or `None` for a row that cannot be addressed (its `kind` or
|
|
/// `uid` is not text) and is left out with a warning.
|
|
fn read(row: &rusqlite::Row<'_>) -> rusqlite::Result<Option<Self>> {
|
|
let id: i64 = row.get(7)?;
|
|
let (Ok(kind), Ok(uid)) = (row.get_ref(0)?.as_str(), row.get_ref(1)?.as_str()) else {
|
|
tracing::warn!(id, "an identities row whose kind or uid is not text is left out");
|
|
return Ok(None);
|
|
};
|
|
let binding = read_binding(row).unwrap_or_else(|damage| {
|
|
tracing::warn!(
|
|
id, kind, uid, %damage,
|
|
"the binding columns of an identity cannot be read: it is treated as unbound",
|
|
);
|
|
None
|
|
});
|
|
Ok(Some(Self {
|
|
kind: kind.to_owned(),
|
|
uid: uid.to_owned(),
|
|
data: lossy_text(row.get_ref(2)?),
|
|
binding,
|
|
}))
|
|
}
|
|
|
|
/// 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) -> IdentityInfo {
|
|
let level = self.level();
|
|
IdentityInfo { kind: self.kind, uid: self.uid, level, binding: self.binding }
|
|
}
|
|
|
|
fn into_blob(self) -> IdentityBlob {
|
|
let level = self.level();
|
|
let data = self.data.unwrap_or_default();
|
|
IdentityBlob::from_row(&self.kind, self.uid, level, data).with_binding(self.binding)
|
|
}
|
|
}
|
|
|
|
/// The binding of a row from its four columns (3 to 6 of both selects).
|
|
fn read_binding(row: &rusqlite::Row<'_>) -> std::result::Result<Option<AccountBinding>, Damage> {
|
|
let column = |index| row.get_ref(index).map_err(|_| Damage::WrongType);
|
|
let account = column(3)?.as_str_or_null().map_err(|_| Damage::WrongType)?;
|
|
let integration = column(4)?.as_str_or_null().map_err(|_| Damage::WrongType)?;
|
|
let rev = column(5)?.as_i64().map_err(|_| Damage::WrongType)?;
|
|
let synced = column(6)?.as_i64().map_err(|_| Damage::WrongType)?;
|
|
Ok(AccountBinding::from_columns(account, integration, rev, synced)?)
|
|
}
|
|
|
|
/// A `data` column as text, whatever it holds. Bytes that are no UTF-8 and
|
|
/// values of another type are damage; read as text they fail where the
|
|
/// blob's kind is checked, with that kind's own error, instead of failing the
|
|
/// read of the row.
|
|
fn lossy_text(value: ValueRef<'_>) -> Option<String> {
|
|
match value {
|
|
ValueRef::Null => None,
|
|
ValueRef::Integer(n) => Some(n.to_string()),
|
|
ValueRef::Real(x) => Some(x.to_string()),
|
|
ValueRef::Text(bytes) | ValueRef::Blob(bytes) => {
|
|
Some(String::from_utf8_lossy(bytes).into_owned())
|
|
}
|
|
}
|
|
}
|