Let a sign-out finish when a row's binding columns cannot be read

SqliteKeyStore::list() failed on the first row whose binding columns were
damaged outside this crate (synced = 2 on the account record, say), and
KeyStore::sign_out starts with list() through bound_to(): it never reached the
record, so it could never finish, and DeviceKeyChoice::Forget did not delete
the key it was given either. get() failed the same way where sign_out reads
the record and the device key.

A row whose binding columns cannot be read (refused by
AccountBinding::from_columns, or a value of the wrong type) is now listed and
read as unbound, with a tracing warning that names the row and the reason and
quotes no content. Unbound is the reading that never deletes on a guess: such
a row is not deleted as a synced copy, and a put of it writes four good
columns. A data column that is not text is read as text with the odd bytes
replaced, so a record that cannot be read is deleted by the trait's sign_out
instead of its read failing; a row whose kind or uid is not text cannot be
addressed and the list leaves it out with a warning. list() now fails only
when the database does.

Tests: the gate's probe (UPDATE identities SET synced = 2 WHERE kind =
'account', then sign_out with Auto and with Forget on a store with
bound_existing_key true and false), more damage to the record row, the device
key row and a synced copy, and the unreadable data and kind/uid cases; the
test that asserted the old precise errors of get() and list() now asserts the
unbound reading. The six new tests fail on the previous keystore.rs.

voelin-store gets the tracing dependency (already in the lock); Cargo.lock
changes, THIRD_PARTY_NOTICES.md is unchanged by it.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Sonnet 5.5 committed 2026-10-20 08:23:55 +03:00
1 parent 7c6d149f78
commit 4944a0694b
5 files changed
+382 -59

No files matched your search

+91 -35
View File
@@ -24,6 +24,23 @@
//! `data` again. That is how [`KeyStore::sign_out`] unbinds a device-only
//! secret, so a damaged row never blocks it.
//!
//! 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 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 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 row whose
//! `kind` or `uid` is not text cannot be addressed, and the list leaves it out
//! with a warning.
//!
//! 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.
@@ -32,6 +49,7 @@ use std::path::Path;
use std::sync::{Mutex, MutexGuard, PoisonError};
use rusqlite::params;
use rusqlite::types::ValueRef;
use tsclientlib::Identity;
use voelin_identity::migrate::SELECT_ACCOUNT_COLUMNS;
use voelin_identity::{
@@ -46,7 +64,7 @@ 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
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
@@ -118,16 +136,21 @@ impl KeyStore for SqliteKeyStore {
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()
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} FROM identities WHERE kind = ?1 AND uid = ?2");
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)?;
rows.next().transpose().map_err(backend)?.map(Columns::into_blob).transpose()
Ok(rows.next().transpose().map_err(backend)?.flatten().map(Columns::into_blob))
}
fn put(&self, blob: &IdentityBlob) -> KsResult<()> {
@@ -232,38 +255,48 @@ enum Refused {
UidHeld { uid: String, kind: String },
}
/// One row of the table as `LIST` and `SELECT_ACCOUNT_COLUMNS` select it.
/// 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>,
account: Option<String>,
integration: Option<String>,
rev: i64,
synced: i64,
/// `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 {
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 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
@@ -277,16 +310,39 @@ impl Columns {
}
}
fn into_info(self) -> KsResult<IdentityInfo> {
let binding = self.binding()?;
fn into_info(self) -> IdentityInfo {
let level = self.level();
Ok(IdentityInfo { kind: self.kind, uid: self.uid, level, binding })
IdentityInfo { kind: self.kind, uid: self.uid, level, binding: self.binding }
}
fn into_blob(self) -> KsResult<IdentityBlob> {
let binding = self.binding()?;
fn into_blob(self) -> IdentityBlob {
let level = self.level();
let data = self.data.unwrap_or_default();
Ok(IdentityBlob::from_row(&self.kind, self.uid, level, data).with_binding(binding))
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())
}
}
}