Refuse to store the device key as a synced copy

KeyStore::sign_out deletes every identity bound with synced = true in its
first step, before it reads the account record that says which Voelin key is
the device key and whether it predates the account. A device key stored with
synced = true was therefore deleted even where the record says to keep it.
Nothing in this crate stored such a key, but the store accepted it.

SqliteKeyStore::put now refuses, with an error that names the key and the
record and says why, a voelin blob with synced = true while an account record
names its uid as the device key, and also while an account record cannot be
read (it may name the key, and the sign-out would delete it on that guess).
The state is also reached from the other side, so a put of an account record
whose device key is already stored as a synced copy is refused as well. A
binding with synced = false is accepted: a sign-out unbinds it and then follows
the record. The check runs before the binding-only fast path, so a put of the
key's own data cannot rebind it as synced.

Documented in keystore.rs and docs/architecture.md. Tests cover the refusal
for records that keep and that delete the key (the error text, the row left
untouched, the sign-out still following the record), another key that may be
synced, no record or a record naming another key, a record put naming a synced
copy, and unreadable records; the three refusal tests fail without the check.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Sonnet 5.5 committed 2026-10-20 08:31:36 +03:00
1 parent 248955b85c
commit 3c59f24608
3 files changed
+244 -1

No files matched your search

+104 -1
View File
@@ -50,6 +50,19 @@
//! succeeds and a warning says that the bytes stay in the log until the next
//! checkpoint (`Store::truncate_wal`).
//!
//! The device key is never a synced copy. The account record names the Voelin key
//! that is the installation's device key, and [`KeyStore::sign_out`] deletes
//! every identity bound with `synced = true` in its first step, before it reads
//! the record, so a key stored that way would be deleted whatever the record
//! says (a key that predates the account is to be kept). 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 then
//! follows the record. 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.
@@ -62,7 +75,8 @@ use rusqlite::types::ValueRef;
use tsclientlib::Identity;
use voelin_identity::migrate::SELECT_ACCOUNT_COLUMNS;
use voelin_identity::{
AccountBinding, BlobError, IdentityBlob, IdentityInfo, KIND_TEAMSPEAK, KeyStore, KeyStoreError,
AccountBinding, BlobError, IdentityBlob, IdentityInfo, KIND_ACCOUNT, KIND_TEAMSPEAK,
KIND_VOELIN, KeyStore, KeyStoreError,
};
use crate::{Error, Result, Store};
@@ -165,6 +179,13 @@ impl KeyStore for SqliteKeyStore {
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.
@@ -252,6 +273,66 @@ fn check_teamspeak(blob: &IdentityBlob) -> KsResult<()> {
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())
@@ -267,6 +348,28 @@ 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 },
/// The Voelin key is the device key of an account record. A sign-out
/// deletes a synced copy without reading the record, so the key the record
/// says to keep would be deleted.
#[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 would delete it whatever the record says"
)]
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"
)]
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 would delete it whatever the record \
says"
)]
RecordNamesSyncedKey { record: String, device: String },
}
/// One row of the table as `LIST` and `SELECT_ACCOUNT_COLUMNS` select it (with
+128
View File
@@ -1541,3 +1541,131 @@ fn removing_through_the_key_store_leaves_no_key_behind_either() {
// Removing what is not there is not an error and changes nothing.
assert!(!store.remove(KIND_VOELIN, &device.uid).unwrap());
}
// -------------------------------------- the device key is never a synced copy
//
// `KeyStore::sign_out` deletes everything bound with `synced = true` in its
// first step, before it reads the record that says which key to keep. A store
// that let the record's device key be such a copy would lose a key the record
// says to keep, so it refuses (`SqliteKeyStore::put`, and the record's put).
/// The Voelin key as a synced copy of the account's material.
fn synced_voelin(key: &IdentityKey) -> IdentityBlob {
IdentityBlob::voelin(key).unwrap().with_binding(binding())
}
/// Why a put was refused: the backend error's text.
fn refusal(result: Result<(), KeyStoreError>) -> String {
match result {
Err(KeyStoreError::Backend(source)) => source.to_string(),
other => panic!("the put was not refused by the backend: {other:?}"),
}
}
#[test]
fn a_synced_binding_on_the_device_key_is_refused_with_a_precise_error() {
for bound_existing_key in [true, false] {
let store = SqliteKeyStore::open_in_memory().unwrap();
store.put_voelin_key(&key()).unwrap();
store.put_account_record(&AccountRecord { bound_existing_key, ..record() }).unwrap();
let uid = key().uid().to_base32();
let before = store.get(KIND_VOELIN, &uid).unwrap().unwrap();
// The row holds this data already, so the put would only rebind it; it is
// refused all the same, and the error names the key and the record and
// says why, without the key.
let shown = refusal(store.put(&synced_voelin(&key())));
assert!(shown.contains(&uid) && shown.contains(&record().blob_uid()), "{shown}");
assert!(shown.contains("device key") && shown.contains("synced = true"), "{shown}");
assert!(!shown.contains(&key_text(&before.json, "pkcs8")), "{shown}");
assert_eq!(store.get(KIND_VOELIN, &uid).unwrap().unwrap(), before, "nothing was written");
assert_eq!(store.list().unwrap().iter().filter(|i| i.binding.is_some()).count(), 0);
// A binding that is not synced is a device-only secret: accepted, and a
// sign-out unbinds it and keeps it (or deletes it, as the record says).
let device_only = AccountBinding { synced: false, ..binding() };
store.put(&IdentityBlob::voelin(&key()).unwrap().with_binding(device_only)).unwrap();
store.put(&before).unwrap();
// So the sign-out still does what the record says with the key.
let done = store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap();
assert_eq!(done.unbound.contains(&device_key_info()), bound_existing_key, "{done:?}");
assert_eq!(store.voelin_key(&key().uid()).unwrap().is_some(), bound_existing_key);
}
}
#[test]
fn a_key_the_record_does_not_name_may_be_a_synced_copy() {
let store = SqliteKeyStore::open_in_memory().unwrap();
store.put_voelin_key(&key()).unwrap();
store.put_account_record(&AccountRecord { bound_existing_key: true, ..record() }).unwrap();
let other = IdentityKey::generate().unwrap();
store.put(&synced_voelin(&other)).unwrap();
assert_eq!(store.bound_to(&binding().account).unwrap().len(), 1);
let done = store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap();
assert!(done.removed.iter().any(|i| i.kind == KIND_VOELIN && i.uid == other.uid().to_base32()));
assert!(store.voelin_key(&other.uid()).unwrap().is_none(), "the copy is deleted");
assert!(store.voelin_key(&key().uid()).unwrap().is_some(), "the device key is kept");
}
#[test]
fn a_synced_key_is_accepted_while_no_record_names_it() {
let store = SqliteKeyStore::open_in_memory().unwrap();
// Without a record there is no device key to protect.
store.put(&synced_voelin(&key())).unwrap();
// A record that names another key does not protect this one either.
let other_device = AccountRecord { device: Uid::from_bytes([5; 32]), ..record() };
store.put_account_record(&other_device).unwrap();
store.put(&synced_voelin(&key())).unwrap();
assert_eq!(
store.get(KIND_VOELIN, &key().uid().to_base32()).unwrap().unwrap().binding,
Some(binding())
);
}
#[test]
fn a_record_that_names_a_synced_copy_as_the_device_key_is_refused() {
// The same state reached from the other side: the key is stored as a synced
// copy first, and then a record names it as the device key.
let store = SqliteKeyStore::open_in_memory().unwrap();
store.put(&synced_voelin(&key())).unwrap();
let shown = refusal(store.put_account_record(&record()));
assert!(
shown.contains(&key().uid().to_base32()) && shown.contains(&record().blob_uid()),
"{shown}"
);
assert!(shown.contains("device key") && shown.contains("synced = true"), "{shown}");
assert_eq!(store.account_record().unwrap(), None, "the record was not stored");
assert_eq!(store.list().unwrap().len(), 1);
// Once the key is not a synced copy the record is accepted.
store.put(&IdentityBlob::voelin(&key()).unwrap()).unwrap();
store.put_account_record(&record()).unwrap();
assert_eq!(store.account_record().unwrap(), Some(record()));
// A record that is no record is kept as ever; a sign-out deletes it.
damage_the_record(&store, "not json");
}
#[test]
fn a_synced_key_is_refused_while_a_record_cannot_be_read() {
// The record may name the key, and the store cannot tell; a sign-out would
// delete the key on that guess, so it is not stored that way.
for (json, _) in unreadable_records() {
let store = SqliteKeyStore::open_in_memory().unwrap();
store.put_account_record(&record()).unwrap();
damage_the_record(&store, &json);
let other = IdentityKey::generate().unwrap();
let shown = refusal(store.put(&synced_voelin(&other)));
assert!(
shown.contains("cannot be read") && shown.contains(&record().blob_uid()),
"{shown}"
);
assert!(shown.contains(&other.uid().to_base32()), "{shown}");
assert!(store.voelin_key(&other.uid()).unwrap().is_none());
// A sign-out deletes the unreadable record; then the key is accepted.
let _ = store.sign_out(&binding().account, DeviceKeyChoice::Auto);
store.put(&synced_voelin(&other)).unwrap();
}
}
+12
View File
@@ -360,6 +360,18 @@ record says it predates the account, and deletes it when it does not or when
the caller asks to forget it. The engine and the UI do not use the key store
yet; accounts, sign-in and the integrations page are later steps.
The device key is never a synced copy. The trait's `sign_out` deletes every
identity bound with `synced = true` in its first step, before it reads the
record, so a device key stored that way would be deleted even where the record
says to keep it. `SqliteKeyStore` therefore refuses, with an error that names
the key and the record, a `put` of a `voelin` blob with `synced = true` while an
account record names its uid as the device key, or while an account record
cannot be read (it may name the key); and a `put` of an account record whose
device key is stored as a synced copy. A key bound with `synced = false` is
accepted: a sign-out unbinds it and then follows the record. The check is made
under the store's lock; it is defence in depth against the code that signs in,
which does not exist yet.
The rows are private keys, so a deleted key must not stay in the file. Every
connection to the database sets `secure_delete`, which makes SQLite overwrite
what it deletes, and deleting a key (`Store::delete_identity`, and the