Files
VoelinClient/crates/voelin-store/tests/keystore.rs
T
faumarayandClaude Sonnet 5.5 2cbb816686 voelin-store: the two blocked-checkpoint tests no longer decide by the clock
a_reader_that_blocks_the_checkpoint_... and store::tests::a_blocked_checkpoint_...
bounded the wall clock of a checkpoint (1 s) and gave the concurrent writer a
busy timeout of 1 s. A checkpoint ends in two fsyncs, which take seconds under
disk pressure: the review's sequences failed 7 of 8 and 6 of 8 at I/O pressure
of 10 to 30 %, and dd conv=fsync loops beside 32 busy loops made the lib test
wait 6 s and the sign-out 5 s ("database is locked" for the writer,
DatabaseBusy for the sign-out, whose writer neighbour committed with
synchronous = FULL).

The integration test now asserts what it means without a time: the sign-out
finishes, the writer (set up as the app's connections are, synchronous =
NORMAL, a busy timeout of a minute) gets through without an error, and one
checkpoint is made for the four removals. It is renamed from "costs
milliseconds". The lib test sets the connection's busy timeout to an hour, calls
checkpoint_truncate once and requires that it came back while the reader still
held its snapshot (the reader lets go from a watchdog after 30 s, so a
checkpoint that does not give up fails the test instead of hanging it), that the
reader blocked it, and that the timeout is the hour again. With the line that
sets CHECKPOINT_WAIT removed the lib test fails after 30 s.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 09:14:22 +03:00

2161 lines
93 KiB
Rust

//! The `identities` table as a `voelin_identity::KeyStore` (`SqliteKeyStore`):
//! the behaviour every key store has, bound and synced entries, and the rows
//! the TeamSpeak methods of `Store` share with it.
//!
//! The behaviour cases are the `exercise` of `voelin-identity`'s
//! `tests/storage.rs` (a private function of that test crate, which the client
//! copies, as the protocol's Phase 2 task for this crate says), with the two
//! deviations a SQLite store has and the memory store does not; each is marked
//! `DEVIATION` where it happens:
//!
//! - `identities.uid` is `UNIQUE` across kinds, so the same uid under another
//! kind is refused (the trait allows this, see `KeyStore::put`).
//! - The TeamSpeak level is computed from the key and counter, as the store
//! always did; the level of a blob that is put is not stored. The case that
//! raised the level with an invented one raises it with a real counter.
//!
//! The sign-out cases (`voelin-identity`'s `tests/accounts.rs`, protocol
//! section 13.6) run the trait's own `sign_out` on the SQLite store, in the
//! last section.
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::time::{Duration, Instant};
use rusqlite::{Connection, params};
use tsclientlib::Identity;
use voelin_identity::{
AccountBinding, AccountId, AccountRecord, BlobError, DeviceKeyChoice, IdentityBlob,
IdentityInfo, IdentityKey, IntegrationId, KIND_ACCOUNT, KIND_TEAMSPEAK, KIND_VOELIN, KeyStore,
KeyStoreError, SignOut, Uid, account_uid,
};
use voelin_store::{IdentityOrigin, SqliteKeyStore, Store};
mod support;
/// What `serde_json::to_string(&tsproto::Identity)` writes for the test
/// identity of tsproto's own `identity_tests`.
const TEAMSPEAK_JSON: &str = r#"{"key":"YTyJofmztcTBjq3KZcDdxu+G4RPVwE5vg8VaN2jbQao=","counter":2792354,"max_counter":2792354}"#;
/// `Identity::key().to_pub().get_uid()` of that identity.
const TEAMSPEAK_UID: &str = "test/9PZ9vww/Bpf5vJxtJhpz80=";
const TEAMSPEAK_LEVEL: u8 = 21;
/// The same key with another counter.
const RAISED_JSON: &str = r#"{"key":"YTyJofmztcTBjq3KZcDdxu+G4RPVwE5vg8VaN2jbQao=","counter":9000000,"max_counter":9000000}"#;
const SEED: [u8; 32] = [
0x9d, 0x61, 0xb1, 0x9d, 0xef, 0xfd, 0x5a, 0x60, 0xba, 0x84, 0x4a, 0xf4, 0x92, 0xec, 0x2c, 0xc4,
0x44, 0x49, 0xc5, 0x69, 0x7b, 0x32, 0x69, 0x19, 0x70, 0x3b, 0xac, 0x03, 0x1c, 0xae, 0x7f, 0x60,
];
const RFC8032_UID: &str = "eh7ddx5bksrgcytl7bkai36se4nxx3klnk7elksyq57pi74xeg4q";
/// The issuer id of an account service whose root key is the RFC 8032 test key.
const ISSUER: &str = RFC8032_UID;
const ACCOUNT_ID_BYTES: [u8; 16] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
/// A scratch directory that is removed again.
struct Scratch(std::path::PathBuf);
impl Scratch {
/// A directory of its own for each call, also for two tests that pass the
/// same name and run side by side.
fn new(name: &str) -> Self {
static NEXT: AtomicUsize = AtomicUsize::new(0);
let n = NEXT.fetch_add(1, Ordering::Relaxed);
let dir =
std::env::temp_dir().join(format!("voelin-keystore-{name}-{}-{n}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
Self(dir)
}
fn db(&self) -> std::path::PathBuf {
self.0.join("client.db")
}
}
impl Drop for Scratch {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn teamspeak_blob() -> IdentityBlob {
IdentityBlob::teamspeak(TEAMSPEAK_UID, TEAMSPEAK_LEVEL, TEAMSPEAK_JSON)
}
fn key() -> IdentityKey {
IdentityKey::from_seed(&SEED).unwrap()
}
fn issuer() -> Uid {
Uid::from_base32(ISSUER).unwrap()
}
fn account_id() -> AccountId {
AccountId::from_bytes(ACCOUNT_ID_BYTES)
}
/// A fresh TeamSpeak identity as a blob, with its real uid and level, bound as
/// given.
fn fresh_teamspeak(binding: impl Into<Option<AccountBinding>>) -> IdentityBlob {
let identity = Identity::create();
IdentityBlob::teamspeak(
identity.key().to_pub().get_uid(),
identity.level(),
serde_json::to_string(&identity).unwrap(),
)
.with_binding(binding)
}
/// The record of an install whose device key was made for the account.
fn record() -> AccountRecord {
AccountRecord {
service: "https://accounts.example.org".into(),
issuer: issuer(),
account_id: account_id(),
device: key().uid(),
bound_existing_key: false,
login: "alice".into(),
cert: vec![0x0a, 0x03, 0x62, 0x6f, 0x64, 0xff],
}
}
fn binding() -> AccountBinding {
AccountBinding {
account: account_uid(&issuer(), &account_id()),
integration: Some(IntegrationId::from_bytes([7; 16])),
rev: 3,
synced: true,
}
}
fn binding_for(seed: u8) -> Uid {
account_uid(&Uid::from_bytes([seed; 32]), &AccountId::from_bytes([seed; 16]))
}
// ------------------------------------------------------------ key stores
/// What every `KeyStore` must do (`voelin-identity`'s `tests/storage.rs`).
fn exercise(store: &dyn KeyStore) {
assert!(store.list().unwrap().is_empty());
assert!(store.get(KIND_TEAMSPEAK, TEAMSPEAK_UID).unwrap().is_none());
assert!(!store.remove(KIND_TEAMSPEAK, TEAMSPEAK_UID).unwrap());
// A TeamSpeak identity goes in and comes out byte for byte.
store.put(&teamspeak_blob()).unwrap();
let ts = store.get(KIND_TEAMSPEAK, TEAMSPEAK_UID).unwrap().unwrap();
assert_eq!(ts, teamspeak_blob());
assert_eq!(ts.json, TEAMSPEAK_JSON);
// A Voelin key.
let key = key();
store.put_voelin_key(&key).unwrap();
let back = store.voelin_key(&key.uid()).unwrap().unwrap();
assert_eq!(back.public_key(), key.public_key());
assert!(store.voelin_key(&IdentityKey::generate().unwrap().uid()).unwrap().is_none());
// A kind this crate has never heard of passes through untouched.
let discord = IdentityBlob::new("discord", "1234", 0, r#"{"token":"opaque"}"#);
store.put(&discord).unwrap();
assert_eq!(store.get("discord", "1234").unwrap().unwrap(), discord);
// DEVIATION: the same uid in another kind. The memory store keeps it as
// another identity; `identities.uid` is UNIQUE across kinds, which the
// trait allows for a backend: the put is a backend error and replaces
// nothing.
let same_uid = IdentityBlob::new("other", RFC8032_UID, 0, "{}");
assert!(matches!(store.put(&same_uid), Err(KeyStoreError::Backend(_))));
assert!(store.get("other", RFC8032_UID).unwrap().is_none());
assert!(store.get(KIND_VOELIN, RFC8032_UID).unwrap().is_some());
assert_eq!(store.voelin_key(&key.uid()).unwrap().unwrap().public_key(), key.public_key());
let mut listed = store.list().unwrap();
listed.sort();
assert_eq!(
listed,
vec![
IdentityInfo { kind: "discord".into(), uid: "1234".into(), level: 0, binding: None },
IdentityInfo {
kind: KIND_TEAMSPEAK.into(),
uid: TEAMSPEAK_UID.into(),
level: TEAMSPEAK_LEVEL,
binding: None
},
IdentityInfo {
kind: KIND_VOELIN.into(),
uid: RFC8032_UID.into(),
level: 0,
binding: None
},
]
);
// Putting again replaces (the security level was raised). DEVIATION: the
// level is computed from the key and counter, so the new blob carries the
// level its counter really has instead of an invented one.
let raised_level = serde_json::from_str::<Identity>(RAISED_JSON).unwrap().level();
assert_ne!(raised_level, TEAMSPEAK_LEVEL, "the replacement must be visible");
let raised = IdentityBlob::teamspeak(TEAMSPEAK_UID, raised_level, RAISED_JSON);
store.put(&raised).unwrap();
assert_eq!(store.get(KIND_TEAMSPEAK, TEAMSPEAK_UID).unwrap().unwrap(), raised);
assert_eq!(store.list().unwrap().len(), 3);
// Removing.
assert!(store.remove(KIND_TEAMSPEAK, TEAMSPEAK_UID).unwrap());
assert!(!store.remove(KIND_TEAMSPEAK, TEAMSPEAK_UID).unwrap());
assert!(store.get(KIND_TEAMSPEAK, TEAMSPEAK_UID).unwrap().is_none());
assert_eq!(store.list().unwrap().len(), 2);
// A stored Voelin blob that does not hold the key it names is an error
// to the caller, not a wrong key.
let mut tampered = IdentityBlob::voelin(&key).unwrap();
tampered.json = r#"{"v":1,"pkcs8":"AAAAAAAA"}"#.into();
store.put(&tampered).unwrap();
assert!(matches!(store.voelin_key(&key.uid()), Err(KeyStoreError::Blob(BlobError::Key(_)))));
}
#[test]
fn the_sqlite_store_behaves() {
exercise(&SqliteKeyStore::open_in_memory().unwrap());
}
#[test]
fn the_sqlite_store_behaves_on_a_file_and_after_a_reopen() {
let scratch = Scratch::new("exercise");
exercise(&SqliteKeyStore::open(&scratch.db()).unwrap());
// What `exercise` left is still there in a new connection.
let store = SqliteKeyStore::open(&scratch.db()).unwrap();
assert_eq!(store.list().unwrap().len(), 2);
assert!(store.get(KIND_VOELIN, RFC8032_UID).unwrap().is_some());
assert!(store.get("discord", "1234").unwrap().is_some());
}
#[test]
fn the_trait_is_object_safe_and_shareable() {
let store: Arc<dyn KeyStore> = Arc::new(SqliteKeyStore::open_in_memory().unwrap());
let other = Arc::clone(&store);
std::thread::spawn(move || other.put(&teamspeak_blob()).unwrap()).join().unwrap();
assert_eq!(store.list().unwrap().len(), 1);
}
#[test]
fn a_put_of_a_uid_another_kind_holds_is_refused_and_replaces_nothing() {
let store = SqliteKeyStore::open_in_memory().unwrap();
let ts = teamspeak_blob();
store.put(&ts).unwrap();
// The Voelin kind with a TeamSpeak uid, and an unknown kind with it.
for kind in [KIND_VOELIN, "discord"] {
let error = store.put(&IdentityBlob::new(kind, TEAMSPEAK_UID, 0, "{}")).unwrap_err();
let KeyStoreError::Backend(source) = &error else { panic!("{error:?}") };
let shown = source.to_string();
assert!(shown.contains(TEAMSPEAK_UID) && shown.contains(KIND_TEAMSPEAK), "{shown}");
}
assert_eq!(store.get(KIND_TEAMSPEAK, TEAMSPEAK_UID).unwrap().unwrap(), ts);
assert_eq!(store.list().unwrap().len(), 1);
// A uid is addressed with its kind: another kind finds and removes nothing,
// although `uid` alone is unique in the table.
assert!(store.get(KIND_VOELIN, TEAMSPEAK_UID).unwrap().is_none());
assert!(!store.remove(KIND_VOELIN, TEAMSPEAK_UID).unwrap());
assert!(!store.remove("discord", TEAMSPEAK_UID).unwrap());
assert_eq!(store.get(KIND_TEAMSPEAK, TEAMSPEAK_UID).unwrap().unwrap(), ts);
}
// ------------------------------------------------------------ the rows
#[test]
fn bound_and_synced_entries_round_trip_and_survive_a_reopen() {
let scratch = Scratch::new("bound");
let account = binding_for(7);
let synced = fresh_teamspeak(AccountBinding {
account,
integration: Some(IntegrationId::from_bytes([7; 16])),
rev: 4,
synced: true,
});
let device_only = fresh_teamspeak(AccountBinding {
account,
integration: Some(IntegrationId::from_bytes([8; 16])),
rev: 0,
synced: false,
});
let without_integration =
fresh_teamspeak(AccountBinding { account, integration: None, rev: 0, synced: false });
let large_rev = fresh_teamspeak(AccountBinding {
account,
integration: None,
rev: i64::MAX as u64,
synced: true,
});
let unbound = fresh_teamspeak(None);
let voelin = IdentityBlob::voelin(&key()).unwrap();
let record_blob = IdentityBlob::account(&record()).unwrap();
let blobs =
[&synced, &device_only, &without_integration, &large_rev, &unbound, &voelin, &record_blob];
let store = SqliteKeyStore::open(&scratch.db()).unwrap();
for blob in blobs {
store.put(blob).unwrap();
}
for blob in blobs {
assert_eq!(&store.get(&blob.kind, &blob.uid).unwrap().unwrap(), blob);
}
// The binding is part of what a list shows.
let listed = store.list().unwrap();
assert_eq!(listed.len(), blobs.len());
for blob in blobs {
let info = listed.iter().find(|i| i.kind == blob.kind && i.uid == blob.uid).unwrap();
assert_eq!((info.binding, info.level), (blob.binding, blob.level), "{}", blob.uid);
}
assert_eq!(store.account_record().unwrap(), Some(record()));
drop(store);
// The same in a new connection, and the raw columns of the rows.
let store = SqliteKeyStore::open(&scratch.db()).unwrap();
for blob in blobs {
assert_eq!(&store.get(&blob.kind, &blob.uid).unwrap().unwrap(), blob);
}
let db = Connection::open(scratch.db()).unwrap();
let columns = |uid: &str| -> (Option<String>, Option<String>, i64, i64) {
db.query_row(
"SELECT account, integration, integration_rev, synced FROM identities WHERE uid = ?1",
[uid],
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)),
)
.unwrap()
};
assert_eq!(
columns(&synced.uid),
(Some(account.to_base32()), Some(IntegrationId::from_bytes([7; 16]).to_base32()), 4, 1)
);
assert_eq!(
columns(&device_only.uid),
(Some(account.to_base32()), Some(IntegrationId::from_bytes([8; 16]).to_base32()), 0, 0)
);
assert_eq!(columns(&without_integration.uid), (Some(account.to_base32()), None, 0, 0));
assert_eq!(columns(&large_rev.uid).2, i64::MAX);
assert_eq!(columns(&unbound.uid), (None, None, 0, 0));
assert_eq!(columns(&voelin.uid), (None, None, 0, 0));
assert_eq!(columns(&record_blob.uid), (None, None, 0, 0));
}
#[test]
fn a_revision_sqlite_cannot_hold_is_a_precise_error_and_stores_nothing() {
let store = SqliteKeyStore::open_in_memory().unwrap();
let too_large = fresh_teamspeak(AccountBinding { rev: u64::MAX, ..binding() });
assert!(matches!(store.put(&too_large), Err(KeyStoreError::Blob(BlobError::BindingRevision))));
assert!(store.list().unwrap().is_empty());
}
#[test]
fn putting_a_blob_without_a_binding_unbinds_it() {
let store = SqliteKeyStore::open_in_memory().unwrap();
let bound = fresh_teamspeak(binding());
store.put(&bound).unwrap();
assert_eq!(store.get(KIND_TEAMSPEAK, &bound.uid).unwrap().unwrap().binding, Some(binding()));
let unbound = bound.clone().with_binding(None);
store.put(&unbound).unwrap();
let back = store.get(KIND_TEAMSPEAK, &bound.uid).unwrap().unwrap();
assert_eq!(back.binding, None);
assert_eq!(back, unbound);
assert_eq!(store.list().unwrap()[0].binding, None);
}
#[test]
fn bound_to_lists_exactly_the_identities_of_one_account() {
let store = SqliteKeyStore::open_in_memory().unwrap();
let mine = binding().account;
let theirs = account_uid(&issuer(), &AccountId::from_bytes([9; 16]));
let (a, b, c, d) = (
fresh_teamspeak(binding()),
fresh_teamspeak(AccountBinding { synced: false, ..binding() }),
fresh_teamspeak(AccountBinding { account: theirs, ..binding() }),
fresh_teamspeak(None),
);
for blob in [&a, &b, &c, &d] {
store.put(blob).unwrap();
}
store.put_voelin_key(&key()).unwrap();
store.put_account_record(&record()).unwrap();
let mut bound: Vec<_> = store.bound_to(&mine).unwrap().into_iter().map(|i| i.uid).collect();
bound.sort();
let mut expected = vec![a.uid.clone(), b.uid.clone()];
expected.sort();
assert_eq!(bound, expected, "not the other account's, the unbound, the key or the record");
let other: Vec<_> = store.bound_to(&theirs).unwrap().into_iter().map(|i| i.uid).collect();
assert_eq!(other, [c.uid.as_str()]);
assert!(store.bound_to(&Uid::from_bytes([0; 32])).unwrap().is_empty());
}
#[test]
fn the_account_record_goes_through_the_stores_own_accessors() {
let store = SqliteKeyStore::open_in_memory().unwrap();
assert_eq!(store.account_record().unwrap(), None);
store.put_account_record(&record()).unwrap();
assert_eq!(store.account_record().unwrap(), Some(record()));
let blob = store.get(KIND_ACCOUNT, &record().blob_uid()).unwrap().unwrap();
assert_eq!(blob.uid, format!("account:{}", record().account_uid().to_base32()));
assert_eq!(blob.binding, None);
// Putting it again replaces it (a renewed certificate).
let renewed = AccountRecord { cert: vec![1, 2, 3], ..record() };
store.put_account_record(&renewed).unwrap();
assert_eq!(store.account_record().unwrap(), Some(renewed));
assert_eq!(store.list().unwrap().len(), 1);
// A stored record that is not one is an error to the caller.
let mut bad = blob;
bad.json = "{}".into();
store.put(&bad).unwrap();
assert!(matches!(store.account_record(), Err(KeyStoreError::Blob(BlobError::AccountJson))));
}
/// The ways the binding columns of a row can be damaged outside this crate:
/// what `AccountBinding::from_columns` refuses, and values of the wrong type.
/// Each is applied to a row that has a good account.
const BINDING_DAMAGE: [&str; 11] = [
"account = 'junk'",
"synced = 2",
"synced = -1",
"integration_rev = -3",
"integration = 'nope'",
// An integration, a revision or a flag without an account.
"account = NULL, integration = 'aaaqeayeaudaocajbifqydiob4'",
"account = NULL, integration_rev = 5",
"account = NULL, synced = 2",
// Values of another type than the column's.
"synced = 'yes'",
"integration_rev = 'many'",
"account = x'0102'",
];
#[test]
fn a_row_whose_binding_columns_cannot_be_read_is_listed_and_read_as_unbound() {
// A listing that fails on one damaged row would keep a sign-out from ever
// finishing (it starts with the list), so the row reads as unbound, with a
// warning, and everything else about it is as stored.
let scratch = Scratch::new("damaged");
let store = SqliteKeyStore::open(&scratch.db()).unwrap();
let ts = teamspeak_blob();
store.put(&ts).unwrap();
let neighbour = fresh_teamspeak(binding());
store.put(&neighbour).unwrap();
let db = Connection::open(scratch.db()).unwrap();
let account = binding_for(1);
let reset = || {
db.execute(
"UPDATE identities SET account = ?2, integration = NULL, integration_rev = 0,
synced = 0 WHERE uid = ?1",
[TEAMSPEAK_UID, &account.to_base32()],
)
.unwrap();
};
reset();
let bound = store.get(KIND_TEAMSPEAK, TEAMSPEAK_UID).unwrap().unwrap();
assert_eq!(bound.binding.map(|b| b.account), Some(account));
assert_eq!(store.bound_to(&account).unwrap().len(), 1);
for damage in BINDING_DAMAGE {
reset();
db.execute(&format!("UPDATE identities SET {damage} WHERE uid = ?1"), [TEAMSPEAK_UID])
.unwrap();
// Read: the identity, unbound, its JSON and level as stored.
let read = store.get(KIND_TEAMSPEAK, TEAMSPEAK_UID).unwrap().expect(damage);
assert_eq!(read, ts, "{damage}");
assert_eq!(read.json, TEAMSPEAK_JSON, "{damage}");
// Listed: still there, unbound, and its neighbour is untouched.
let listed = store.list().unwrap();
assert_eq!(listed.len(), 2, "{damage}");
let row = listed.iter().find(|i| i.uid == TEAMSPEAK_UID).expect(damage);
assert_eq!((row.binding, row.level), (None, TEAMSPEAK_LEVEL), "{damage}");
let next = listed.iter().find(|i| i.uid == neighbour.uid).unwrap();
assert_eq!(next.binding, neighbour.binding, "{damage}");
// It belongs to no account as far as a sign-out can tell: not a guess.
assert!(store.bound_to(&account).unwrap().is_empty(), "{damage}");
assert_eq!(store.bound_to(&binding().account).unwrap().len(), 1, "{damage}");
}
// A put of the row writes four good columns, however it was damaged.
let rebound = ts.clone().with_binding(binding());
store.put(&rebound).unwrap();
assert_eq!(store.get(KIND_TEAMSPEAK, TEAMSPEAK_UID).unwrap().unwrap(), rebound);
let (synced, rev): (i64, i64) = db
.query_row(
"SELECT synced, integration_rev FROM identities WHERE uid = ?1",
[TEAMSPEAK_UID],
|r| Ok((r.get(0)?, r.get(1)?)),
)
.unwrap();
assert_eq!((synced, rev), (1, 3));
}
#[test]
fn a_row_that_cannot_be_addressed_is_left_out_of_the_list() {
// A `kind` or `uid` that is not text cannot be named in `get` or `remove`,
// so the list has nothing to show for it; it must not fail the others.
let scratch = Scratch::new("unaddressable");
let store = SqliteKeyStore::open(&scratch.db()).unwrap();
store.put(&teamspeak_blob()).unwrap();
store.put_voelin_key(&key()).unwrap();
let db = Connection::open(scratch.db()).unwrap();
let id: i64 = db
.query_row("SELECT id FROM identities WHERE uid = ?1", [TEAMSPEAK_UID], |r| r.get(0))
.unwrap();
for (column, original) in [("uid", TEAMSPEAK_UID), ("kind", KIND_TEAMSPEAK)] {
db.execute(&format!("UPDATE identities SET {column} = x'0102' WHERE id = ?1"), [id])
.unwrap();
let listed = store.list().unwrap();
assert_eq!(sorted(listed), [(KIND_VOELIN.to_owned(), RFC8032_UID.to_owned())], "{column}");
assert!(store.get(KIND_TEAMSPEAK, TEAMSPEAK_UID).unwrap().is_none(), "{column}");
db.execute(
&format!("UPDATE identities SET {column} = ?2 WHERE id = ?1"),
params![id, original],
)
.unwrap();
assert_eq!(store.list().unwrap().len(), 2, "{column}");
}
assert_eq!(store.get(KIND_TEAMSPEAK, TEAMSPEAK_UID).unwrap().unwrap(), teamspeak_blob());
}
// ------------------------------------- what the TeamSpeak methods share
#[test]
fn a_replaced_row_keeps_its_name_origin_default_flag_and_creation() {
let scratch = Scratch::new("replaced");
let store = SqliteKeyStore::open(&scratch.db()).unwrap();
let identity: Identity = serde_json::from_str(TEAMSPEAK_JSON).unwrap();
let id =
store.with_store(|s| s.add_identity("Main", &identity, IdentityOrigin::Imported).unwrap());
let db = Connection::open(scratch.db()).unwrap();
// Age the row, so that a row written again would show a later `created`.
db.execute("UPDATE identities SET created = 1000", []).unwrap();
// The synced copy of the same identity arrives, with the counter raised.
let mut synced = IdentityBlob::teamspeak(TEAMSPEAK_UID, 0, RAISED_JSON);
synced.binding = Some(binding());
store.put(&synced).unwrap();
let (rows, row_id, name, origin, is_default, created): (i64, i64, String, String, i64, i64) =
db.query_row(
"SELECT count(*), id, name, origin, is_default, created FROM identities",
[],
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?, r.get(5)?)),
)
.unwrap();
assert_eq!((rows, row_id), (1, id), "the same row, replaced in place");
assert_eq!(
(name.as_str(), origin.as_str(), is_default, created),
("Main", "imported", 1, 1000)
);
let listed = store.with_store(|s| s.identities().unwrap());
let entry = &listed[0];
assert_eq!((entry.id, entry.name.as_str()), (id, "Main"));
assert_eq!((entry.origin, entry.is_default), (IdentityOrigin::Imported, true));
// The level is the one of the new counter, computed.
let level = serde_json::from_str::<Identity>(RAISED_JSON).unwrap().level();
assert_eq!(entry.level, level);
assert_eq!(store.with_store(|s| s.identity(id).unwrap().counter()), 9_000_000);
let blob = store.get(KIND_TEAMSPEAK, TEAMSPEAK_UID).unwrap().unwrap();
assert_eq!((blob.binding, blob.level), (Some(binding()), level));
assert_eq!(blob.json, RAISED_JSON);
}
#[test]
fn a_new_teamspeak_blob_is_a_row_the_teamspeak_methods_list() {
let store = SqliteKeyStore::open_in_memory().unwrap();
let main = Identity::create();
let main_id =
store.with_store(|s| s.add_identity("Main", &main, IdentityOrigin::User).unwrap());
let synced = fresh_teamspeak(binding());
store.put(&synced).unwrap();
// A Voelin key and the account record share the table and are not listed.
store.put_voelin_key(&key()).unwrap();
store.put_account_record(&record()).unwrap();
let listed = store.with_store(|s| s.identities().unwrap());
assert_eq!(listed.len(), 2, "{listed:?}");
let entry = &listed[1];
assert_eq!(
(entry.name.as_str(), entry.uid.as_str()),
(synced.uid.as_str(), synced.uid.as_str())
);
assert_eq!(
(entry.origin, entry.is_default, entry.level),
(IdentityOrigin::User, false, synced.level)
);
// The default stays the identity that was the default.
assert_eq!(store.with_store(|s| s.default_identity().unwrap().unwrap().id), main_id);
// The identity loads through the old API, the key unchanged.
let loaded = store.with_store(|s| s.identity(entry.id).unwrap());
assert_eq!(serde_json::to_string(&loaded).unwrap(), synced.json);
// And the old API's delete is the same row as the key store's remove.
store.with_store(|s| s.delete_identity(entry.id).unwrap());
assert!(store.get(KIND_TEAMSPEAK, &synced.uid).unwrap().is_none());
assert!(store.get(KIND_VOELIN, &key().uid().to_base32()).unwrap().is_some());
}
#[test]
fn an_identity_added_the_old_way_is_an_unbound_teamspeak_blob() {
let store = SqliteKeyStore::open_in_memory().unwrap();
let identity: Identity = serde_json::from_str(TEAMSPEAK_JSON).unwrap();
store.with_store(|s| s.add_identity("Main", &identity, IdentityOrigin::Imported).unwrap());
assert_eq!(store.get(KIND_TEAMSPEAK, TEAMSPEAK_UID).unwrap().unwrap(), teamspeak_blob());
assert_eq!(
store.list().unwrap(),
[IdentityInfo {
kind: KIND_TEAMSPEAK.into(),
uid: TEAMSPEAK_UID.into(),
level: TEAMSPEAK_LEVEL,
binding: None
}]
);
// The old API's rename leaves the blob alone.
let id = store.with_store(|s| s.identities().unwrap()[0].id);
store.with_store(|s| s.rename_identity(id, "Renamed").unwrap());
assert_eq!(store.get(KIND_TEAMSPEAK, TEAMSPEAK_UID).unwrap().unwrap(), teamspeak_blob());
}
#[test]
fn a_teamspeak_blob_that_is_no_identity_is_refused() {
let store = SqliteKeyStore::open_in_memory().unwrap();
store.put(&teamspeak_blob()).unwrap();
// Not the JSON of a tsproto identity: refused, so that it cannot break the
// list of TeamSpeak identities.
for json in ["", "not json", "{}", r#"{"key":"AAAA","counter":1,"max_counter":1}"#] {
let bad = IdentityBlob::teamspeak("some/uid=", 0, json);
assert!(matches!(store.put(&bad), Err(KeyStoreError::Backend(_))), "{json:?}");
}
// An identity that names another identity's uid: refused, so that it cannot
// replace that identity's key.
let stranger = Identity::create();
let hijack = IdentityBlob::teamspeak(
TEAMSPEAK_UID,
stranger.level(),
serde_json::to_string(&stranger).unwrap(),
);
assert!(matches!(store.put(&hijack), Err(KeyStoreError::Blob(BlobError::UidMismatch))));
// Nothing was stored or replaced.
assert_eq!(store.list().unwrap().len(), 1);
assert_eq!(store.get(KIND_TEAMSPEAK, TEAMSPEAK_UID).unwrap().unwrap(), teamspeak_blob());
assert_eq!(store.with_store(|s| s.identities().unwrap().len()), 1);
}
#[test]
fn a_refused_teamspeak_blob_does_not_quote_its_key_in_the_error() {
// The JSON of a TeamSpeak identity holds the private key. serde's account of
// a key it cannot read quotes the string it was given, so the store must not
// forward it: the error reaches Display and Debug, and so any log line.
const KEY_TEXT: &str = "PRIVATE-KEY-TEXT-0123456789";
let json = format!(r#"{{"key":"{KEY_TEXT}","counter":1,"max_counter":1}}"#);
let parse_error = serde_json::from_str::<Identity>(&json).unwrap_err();
assert!(
parse_error.to_string().contains(KEY_TEXT),
"the case proves nothing if serde does not quote the key: {parse_error}"
);
let store = SqliteKeyStore::open_in_memory().unwrap();
let error = store.put(&IdentityBlob::teamspeak("some/uid=", 0, json.as_str())).unwrap_err();
assert!(matches!(error, KeyStoreError::Backend(_)), "{error:?}");
let mut texts = vec![format!("{error}"), format!("{error:?}"), format!("{error:#?}")];
let mut source = std::error::Error::source(&error);
while let Some(cause) = source {
texts.extend([format!("{cause}"), format!("{cause:?}"), format!("{cause:#?}")]);
source = cause.source();
}
for text in &texts {
assert!(!text.contains(KEY_TEXT), "the error repeats the key: {text}");
}
assert!(store.list().unwrap().is_empty(), "nothing was stored");
// The same holds when the JSON parses and only the uid is wrong: that error
// is a fixed text as well.
let stranger = Identity::create();
let json = serde_json::to_string(&stranger).unwrap();
let key_text = json.split('"').nth(3).unwrap().to_owned();
let error = store.put(&IdentityBlob::teamspeak("some/uid=", 0, json)).unwrap_err();
for text in [format!("{error}"), format!("{error:?}")] {
assert!(!text.contains(&key_text), "the error repeats the key: {text}");
}
}
#[test]
fn the_level_is_computed_from_the_key_never_stored_and_never_blocks_a_read() {
let scratch = Scratch::new("level");
let store = SqliteKeyStore::open(&scratch.db()).unwrap();
// A blob that claims another level is stored with the level its key has.
store.put(&IdentityBlob::teamspeak(TEAMSPEAK_UID, 99, TEAMSPEAK_JSON)).unwrap();
assert_eq!(store.get(KIND_TEAMSPEAK, TEAMSPEAK_UID).unwrap().unwrap().level, TEAMSPEAK_LEVEL);
assert_eq!(store.list().unwrap()[0].level, TEAMSPEAK_LEVEL);
// Kinds without a level read back with 0, whatever was put.
store.put(&IdentityBlob::new("discord", "1", 7, "{}")).unwrap();
assert_eq!(store.get("discord", "1").unwrap().unwrap().level, 0);
// A TeamSpeak row damaged outside this crate lists and reads with level 0
// and its JSON as it is, instead of failing the list (and a sign-out).
let db = Connection::open(scratch.db()).unwrap();
db.execute("UPDATE identities SET data = 'damaged' WHERE uid = ?1", params![TEAMSPEAK_UID])
.unwrap();
let listed = store.list().unwrap();
assert_eq!(listed.iter().find(|i| i.uid == TEAMSPEAK_UID).unwrap().level, 0);
let blob = store.get(KIND_TEAMSPEAK, TEAMSPEAK_UID).unwrap().unwrap();
assert_eq!((blob.level, blob.json.as_str()), (0, "damaged"));
}
#[test]
fn unknown_kinds_are_kept_and_the_teamspeak_methods_do_not_see_them() {
let store = SqliteKeyStore::open_in_memory().unwrap();
let discord = IdentityBlob::new("discord", "1234", 0, r#"{"token":"opaque"}"#);
store.put(&discord).unwrap();
assert!(store.with_store(|s| s.identities().unwrap()).is_empty());
assert!(store.with_store(|s| s.default_identity().unwrap()).is_none());
assert_eq!(store.get("discord", "1234").unwrap().unwrap(), discord);
}
#[test]
fn the_sqlite_store_is_the_store_the_client_already_has() {
// A `Store` opened the old way is a key store without a migration or a copy.
let scratch = Scratch::new("shared");
let store = Store::open(&scratch.db()).unwrap();
let identity = Identity::create();
store.add_identity("Main", &identity, IdentityOrigin::Created).unwrap();
drop(store);
let keys = SqliteKeyStore::open(&scratch.db()).unwrap();
let listed = keys.list().unwrap();
assert_eq!(listed.len(), 1);
assert_eq!(listed[0].uid, identity.key().to_pub().get_uid());
assert_eq!((listed[0].kind.as_str(), listed[0].binding), (KIND_TEAMSPEAK, None));
}
// ------------------------------------------------------------- sign-out
//
// `KeyStore::sign_out` is `voelin-identity`'s: it is generic over the trait, so
// the store here does not re-implement it, and these cases run it on SQLite
// (protocol section 13.6, "Signing out", and `voelin-identity`'s
// `tests/accounts.rs`). A TeamSpeak identity needs a key that has its uid for
// this store to accept it, so the identities of these cases are fresh ones.
/// The record `record()` writes, as JSON.
const RECORD_JSON: &str = concat!(
r#"{"v":1,"service":"https://accounts.example.org","#,
r#""issuer":"eh7ddx5bksrgcytl7bkai36se4nxx3klnk7elksyq57pi74xeg4q","#,
r#""account_id":"aaaqeayeaudaocajbifqydiob4","#,
r#""device":"eh7ddx5bksrgcytl7bkai36se4nxx3klnk7elksyq57pi74xeg4q","#,
r#""bound_existing_key":false,"login":"alice","cert":"CgNib2T/"}"#,
);
/// An install signed in to the account: the device key, the record with the
/// given key flag, a synced copy, a device-only secret and a local identity.
struct Install {
store: SqliteKeyStore,
synced: IdentityBlob,
device_only: IdentityBlob,
local: IdentityBlob,
}
fn signed_in_install(bound_existing_key: bool) -> Install {
let store = SqliteKeyStore::open_in_memory().unwrap();
let synced = fresh_teamspeak(binding());
let device_only = fresh_teamspeak(AccountBinding { synced: false, ..binding() });
let local = fresh_teamspeak(None);
store.put_voelin_key(&key()).unwrap();
store.put_account_record(&AccountRecord { bound_existing_key, ..record() }).unwrap();
for blob in [&synced, &device_only, &local] {
store.put(blob).unwrap();
}
Install { store, synced, device_only, local }
}
fn device_key_info() -> IdentityInfo {
IdentityInfo { kind: KIND_VOELIN.into(), uid: key().uid().to_base32(), level: 0, binding: None }
}
fn info_of(blob: &IdentityBlob) -> IdentityInfo {
IdentityInfo {
kind: blob.kind.clone(),
uid: blob.uid.clone(),
level: blob.level,
binding: blob.binding,
}
}
fn sorted(mut infos: Vec<IdentityInfo>) -> Vec<(String, String)> {
infos.sort();
infos.into_iter().map(|info| (info.kind, info.uid)).collect()
}
fn pair(blob: &IdentityBlob) -> (String, String) {
(blob.kind.clone(), blob.uid.clone())
}
/// The record of the install replaced by damaged JSON.
fn damage_the_record(store: &SqliteKeyStore, json: &str) {
let mut damaged = store.get(KIND_ACCOUNT, &record().blob_uid()).unwrap().unwrap();
damaged.json = json.to_owned();
store.put(&damaged).unwrap();
}
#[test]
fn the_record_fixture_is_what_the_protocol_writes() {
assert_eq!(IdentityBlob::account(&record()).unwrap().json, RECORD_JSON);
assert_eq!(record().device, issuer(), "the RFC 8032 key is both the issuer and the device");
}
#[test]
fn signing_out_deletes_the_copies_and_keeps_the_keys_and_the_device_secrets() {
// The device key was made for the account: signing out keeps it all the
// same, unbound (open question 10 of the accounts design).
let Install { store, synced, device_only, local } = signed_in_install(false);
let mine = binding().account;
let theirs = account_uid(&issuer(), &AccountId::from_bytes([9; 16]));
let theirs_blob = fresh_teamspeak(AccountBinding { account: theirs, ..binding() });
store.put(&theirs_blob).unwrap();
// Another Voelin key that is not the device key stays.
let other_key = IdentityKey::generate().unwrap();
store.put_voelin_key(&other_key).unwrap();
let done = store.sign_out(&mine, DeviceKeyChoice::Auto).unwrap();
let mut expected_removed = vec![(KIND_ACCOUNT.to_owned(), record().blob_uid()), pair(&synced)];
expected_removed.sort();
assert_eq!(sorted(done.removed.clone()), expected_removed, "{done:?}");
assert_eq!(
sorted(done.unbound.clone()),
sorted(vec![device_key_info(), info_of(&device_only.clone().with_binding(None))]),
"{done:?}"
);
// What is left: the device key, the device secret unbound and byte for
// byte as it was, the local and the other account's identities as they
// were, the other key.
assert!(store.get(KIND_TEAMSPEAK, &synced.uid).unwrap().is_none());
assert_eq!(store.voelin_key(&key().uid()).unwrap().unwrap().uid(), key().uid());
assert_eq!(store.account_record().unwrap(), None);
let kept = store.get(KIND_TEAMSPEAK, &device_only.uid).unwrap().unwrap();
assert_eq!(kept, device_only.clone().with_binding(None));
assert_eq!(kept.json, device_only.json);
assert_eq!(store.get(KIND_TEAMSPEAK, &local.uid).unwrap().unwrap(), local);
assert_eq!(store.get(KIND_TEAMSPEAK, &theirs_blob.uid).unwrap().unwrap(), theirs_blob);
assert!(store.voelin_key(&other_key.uid()).unwrap().is_some());
assert_eq!(store.list().unwrap().len(), 5);
// Signing out again finds nothing to do.
assert_eq!(store.sign_out(&mine, DeviceKeyChoice::Auto).unwrap(), SignOut::default());
assert_eq!(store.list().unwrap().len(), 5);
// Another account's sign-out acts on that account's identities only.
assert_eq!(
store.sign_out(&theirs, DeviceKeyChoice::Auto).unwrap().removed,
vec![info_of(&theirs_blob)]
);
assert_eq!(store.get(KIND_TEAMSPEAK, &device_only.uid).unwrap().unwrap(), kept);
}
#[test]
fn signing_out_keeps_a_device_key_that_predates_the_account() {
// The install's own Voelin identity became the device key at the first
// sign-in. On a host that verifies no accounts it is still the user's
// identity, so signing out must not destroy it.
let Install { store, synced, device_only, local } = signed_in_install(true);
let key_before = store.get(KIND_VOELIN, &key().uid().to_base32()).unwrap().unwrap();
let signature = key().sign(b"the same key, signed before and after");
let done = store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap();
let mut removed = vec![(KIND_ACCOUNT.to_owned(), record().blob_uid()), pair(&synced)];
removed.sort();
assert_eq!(sorted(done.removed.clone()), removed, "{done:?}");
// The key is reported as kept and unbound, next to the device secret.
assert_eq!(
sorted(done.unbound.clone()),
sorted(vec![device_key_info(), info_of(&device_only.clone().with_binding(None))]),
"{done:?}"
);
assert!(done.unbound.contains(&device_key_info()));
// It is the same key, byte for byte, with no binding, and the record that
// named it as the device key is gone.
let kept = store.voelin_key(&key().uid()).unwrap().expect("the key stays");
assert_eq!(kept.uid(), key().uid());
assert_eq!(kept.sign(b"the same key, signed before and after"), signature);
assert_eq!(&kept.to_pkcs8().unwrap()[..], &key().to_pkcs8().unwrap()[..]);
let key_after = store.get(KIND_VOELIN, &key().uid().to_base32()).unwrap().unwrap();
assert_eq!(key_after, key_before, "the stored blob is untouched");
assert_eq!(key_after.json, key_before.json);
assert_eq!(key_after.binding, None);
assert_eq!(store.account_record().unwrap(), None);
assert_eq!(store.list().unwrap().len(), 3, "the key, the device secret and the local one");
assert!(store.get(KIND_TEAMSPEAK, &local.uid).unwrap().is_some());
// Signing out again finds nothing to do, and the key is still there.
assert_eq!(
store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap(),
SignOut::default()
);
assert!(store.voelin_key(&key().uid()).unwrap().is_some());
}
#[test]
fn signing_out_keeps_a_device_key_the_client_made_for_the_account_too() {
// Open question 10 of the accounts design (answered 2026-10-24): a key that
// the client made for the account is the user's identity at every host
// without accounts that the user reached with it as well, so `Auto` keeps
// it like a key that predates the account. Only `Forget` deletes it.
let Install { store, device_only, local, .. } = signed_in_install(false);
let key_before = store.get(KIND_VOELIN, &key().uid().to_base32()).unwrap().unwrap();
let signature = key().sign(b"the same key, signed before and after");
let done = store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap();
assert!(!done.removed.contains(&device_key_info()), "{done:?}");
assert!(done.unbound.contains(&device_key_info()), "{done:?}");
let kept = store.voelin_key(&key().uid()).unwrap().expect("the key stays");
assert_eq!(kept.sign(b"the same key, signed before and after"), signature);
let key_after = store.get(KIND_VOELIN, &key().uid().to_base32()).unwrap().unwrap();
assert_eq!(key_after, key_before, "the stored blob is untouched");
assert_eq!(key_after.binding, None);
let mut left = sorted(store.list().unwrap());
left.sort();
let mut expected = vec![pair(&device_only), pair(&local), pair(&key_after)];
expected.sort();
assert_eq!(left, expected, "the key, the device secret and the local one");
// The flag changes nothing: a key that predates the account gets the same
// treatment. (The other identities of the two installs are fresh ones, so
// the reports differ in them.)
let existing = signed_in_install(true);
let again = existing.store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap();
assert!(again.unbound.contains(&device_key_info()), "{again:?}");
assert!(!again.removed.contains(&device_key_info()), "{again:?}");
assert_eq!(again.removed.len(), done.removed.len());
assert_eq!(again.unbound.len(), done.unbound.len());
}
#[test]
fn a_record_without_the_key_flag_keeps_the_key() {
// A record written before the flag existed. Deleting a key is the
// irreversible choice, so the missing flag must not read as "delete".
let Install { store, .. } = signed_in_install(false);
let old = RECORD_JSON.replace("\"bound_existing_key\":false,", "");
assert!(!old.contains("bound_existing_key"));
damage_the_record(&store, &old);
assert!(store.account_record().unwrap().unwrap().bound_existing_key);
let done = store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap();
assert!(done.unbound.contains(&device_key_info()), "{done:?}");
assert!(!done.removed.contains(&device_key_info()), "{done:?}");
assert!(store.voelin_key(&key().uid()).unwrap().is_some());
assert_eq!(store.account_record().unwrap(), None, "the record itself is gone");
// The explicit choice still deletes it.
let Install { store, .. } = signed_in_install(false);
damage_the_record(&store, &old);
let forget = DeviceKeyChoice::Forget(key().uid());
let done = store.sign_out(&binding().account, forget).unwrap();
assert!(done.removed.contains(&device_key_info()), "{done:?}");
assert!(store.voelin_key(&key().uid()).unwrap().is_none());
}
#[test]
fn forgetting_the_identity_deletes_the_device_key_whatever_the_record_says() {
for predates_the_account in [true, false] {
let Install { store, synced, device_only, local } = signed_in_install(predates_the_account);
let forget = DeviceKeyChoice::Forget(key().uid());
let done = store.sign_out(&binding().account, forget).unwrap();
assert!(done.removed.contains(&device_key_info()), "{predates_the_account}: {done:?}");
assert!(!done.unbound.contains(&device_key_info()), "{predates_the_account}: {done:?}");
assert!(store.voelin_key(&key().uid()).unwrap().is_none());
assert_eq!(store.account_record().unwrap(), None);
// The rest is what any sign-out does.
assert!(store.get(KIND_TEAMSPEAK, &synced.uid).unwrap().is_none());
assert_eq!(store.get(KIND_TEAMSPEAK, &device_only.uid).unwrap().unwrap().binding, None);
assert!(store.get(KIND_TEAMSPEAK, &local.uid).unwrap().is_some());
// And another Voelin key stays.
let other = IdentityKey::generate().unwrap();
store.put_voelin_key(&other).unwrap();
assert!(store.voelin_key(&other.uid()).unwrap().is_some());
}
}
#[test]
fn a_sign_out_that_stopped_half_way_can_be_run_again() {
// The device key is gone already (a crash after it) but the record is
// still there: the second run deletes the record and the rest. A key that
// is not there is not reported as kept either.
for (predates_the_account, choice) in [
(false, DeviceKeyChoice::Auto),
(true, DeviceKeyChoice::Auto),
(true, DeviceKeyChoice::Forget(key().uid())),
] {
let store = SqliteKeyStore::open_in_memory().unwrap();
store
.put_account_record(&AccountRecord {
bound_existing_key: predates_the_account,
..record()
})
.unwrap();
store.put(&fresh_teamspeak(binding())).unwrap();
let done = store.sign_out(&binding().account, choice).unwrap();
assert_eq!(done.removed.len(), 2, "{predates_the_account}, {choice:?}: {done:?}");
assert!(done.unbound.is_empty(), "{predates_the_account}, {choice:?}: {done:?}");
assert!(store.list().unwrap().is_empty());
}
}
/// The three ways a record cannot be read.
fn unreadable_records() -> [(String, &'static str); 3] {
[
(RECORD_JSON.replace("\"v\":1", "\"v\":2"), "AccountVersion(2)"),
("not json".to_owned(), "AccountJson"),
("{}".to_owned(), "AccountJson"),
]
}
#[test]
fn an_unreadable_record_is_deleted_before_the_error_is_reported() {
// After a downgrade or damage, the record cannot be read. The first call
// must not leave it behind to fail the same way for ever.
for (json, expected) in unreadable_records() {
let Install { store, synced, device_only, local } = signed_in_install(true);
damage_the_record(&store, &json);
let error = store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap_err();
assert!(
matches!(&error, KeyStoreError::Blob(blob) if format!("{blob:?}") == expected),
"{expected}: {error:?}"
);
// The record is gone and so is the synced copy; the secret that only
// this device holds is unbound; the key the record named cannot be
// found from it and stays, which is the safe reading.
assert!(store.get(KIND_ACCOUNT, &record().blob_uid()).unwrap().is_none());
assert!(store.get(KIND_TEAMSPEAK, &synced.uid).unwrap().is_none());
assert_eq!(store.get(KIND_TEAMSPEAK, &device_only.uid).unwrap().unwrap().binding, None);
assert!(store.voelin_key(&key().uid()).unwrap().is_some());
// The second call completes instead of failing again.
assert_eq!(
store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap(),
SignOut::default()
);
assert_eq!(store.list().unwrap().len(), 3);
assert!(store.get(KIND_TEAMSPEAK, &local.uid).unwrap().is_some());
}
}
#[test]
fn forgetting_the_identity_with_an_unreadable_record_still_deletes_the_named_key() {
// The user chose "Forget this device's identity". The record that names
// the device key cannot be read (a version from a newer client, damage),
// so the call reports the error; it must not leave the key behind and
// look done on the retry, when nothing names the key any more.
for (json, expected) in unreadable_records() {
let Install { store, synced, device_only, .. } = signed_in_install(true);
damage_the_record(&store, &json);
let other = IdentityKey::generate().unwrap();
store.put_voelin_key(&other).unwrap();
let forget = DeviceKeyChoice::Forget(key().uid());
let error = store.sign_out(&binding().account, forget).unwrap_err();
assert!(
matches!(&error, KeyStoreError::Blob(blob) if format!("{blob:?}") == expected),
"{expected}: {error:?}"
);
// The key the caller named is gone, with the record and the synced
// copy; the device-only secret is unbound; another key stays.
assert!(store.voelin_key(&key().uid()).unwrap().is_none(), "{expected}");
assert!(store.get(KIND_ACCOUNT, &record().blob_uid()).unwrap().is_none());
assert!(store.get(KIND_TEAMSPEAK, &synced.uid).unwrap().is_none());
assert_eq!(store.get(KIND_TEAMSPEAK, &device_only.uid).unwrap().unwrap().binding, None);
assert!(store.voelin_key(&other.uid()).unwrap().is_some());
// The retry has nothing left to do, and the key is not back.
assert_eq!(store.sign_out(&binding().account, forget).unwrap(), SignOut::default());
assert!(store.voelin_key(&key().uid()).unwrap().is_none());
assert_eq!(
store.list().unwrap().len(),
3,
"the other key, the device secret, the local one"
);
}
}
/// A signed-in install on a file, with the device-only secret's `data`
/// replaced by `damage` through a second connection, as something outside this
/// crate could damage it.
struct Damaged {
_scratch: Scratch,
store: SqliteKeyStore,
synced: IdentityBlob,
device_only: IdentityBlob,
}
fn install_with_a_damaged_device_secret(bound_existing_key: bool, damage: &str) -> Damaged {
let scratch = Scratch::new("damaged-row");
let store = SqliteKeyStore::open(&scratch.db()).unwrap();
let synced = fresh_teamspeak(binding());
let device_only = fresh_teamspeak(AccountBinding { synced: false, ..binding() });
store.put_voelin_key(&key()).unwrap();
store.put_account_record(&AccountRecord { bound_existing_key, ..record() }).unwrap();
store.put(&synced).unwrap();
store.put(&device_only).unwrap();
let db = Connection::open(scratch.db()).unwrap();
let changed = db
.execute("UPDATE identities SET data = ?1 WHERE uid = ?2", params![damage, device_only.uid])
.unwrap();
assert_eq!(changed, 1);
Damaged { _scratch: scratch, store, synced, device_only }
}
#[test]
fn a_damaged_device_secret_does_not_block_a_sign_out() {
// The row is bound, device-only, and its JSON is no identity (it could only
// have been damaged outside this crate). Signing out unbinds it without
// reading the JSON again, deletes the record, and leaves the row as it is.
for damage in ["damaged", "", "{}", r#"{"key":"AAAA","counter":1,"max_counter":1}"#] {
let Damaged { _scratch, store, synced, device_only } =
install_with_a_damaged_device_secret(true, damage);
let listed = store.bound_to(&binding().account).unwrap();
assert_eq!(sorted(listed), sorted(vec![info_of(&synced), info_of(&device_only)]));
let done = store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap();
assert_eq!(done.removed.len(), 2, "{damage:?}: {done:?}");
assert!(done.removed.contains(&info_of(&synced)));
assert!(
done.removed.iter().any(|i| i.kind == KIND_ACCOUNT && i.uid == record().blob_uid())
);
let unbound: Vec<_> =
done.unbound.iter().map(|i| (i.kind.clone(), i.uid.clone())).collect();
assert!(unbound.contains(&pair(&device_only)), "{damage:?}: {done:?}");
assert!(unbound.contains(&pair(&IdentityBlob::voelin(&key()).unwrap())), "{done:?}");
// The record is gone, so the sign-out is complete and a retry has
// nothing to do; the row keeps its damaged JSON, unbound; the device key
// predates the account and stays.
assert!(store.get(KIND_ACCOUNT, &record().blob_uid()).unwrap().is_none(), "{damage:?}");
assert!(store.get(KIND_TEAMSPEAK, &synced.uid).unwrap().is_none());
let row = store.get(KIND_TEAMSPEAK, &device_only.uid).unwrap().unwrap();
assert_eq!((row.binding, row.json.as_str(), row.level), (None, damage, 0));
assert!(store.voelin_key(&key().uid()).unwrap().is_some());
assert!(store.bound_to(&binding().account).unwrap().is_empty());
assert_eq!(
store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap(),
SignOut::default()
);
}
}
#[test]
fn forgetting_the_identity_with_a_damaged_device_secret_still_deletes_the_named_key() {
// The user chose "Forget this device's identity" while a device-only secret
// is damaged: the named key is deleted, the record goes, and the secret is
// unbound, not left to fail every retry.
for bound_existing_key in [true, false] {
let Damaged { _scratch, store, synced, device_only } =
install_with_a_damaged_device_secret(bound_existing_key, "damaged");
let other = IdentityKey::generate().unwrap();
store.put_voelin_key(&other).unwrap();
let forget = DeviceKeyChoice::Forget(key().uid());
let done = store.sign_out(&binding().account, forget).unwrap();
assert!(done.removed.contains(&device_key_info()), "{done:?}");
assert!(store.voelin_key(&key().uid()).unwrap().is_none(), "{bound_existing_key}");
assert!(store.get(KIND_ACCOUNT, &record().blob_uid()).unwrap().is_none());
assert!(store.get(KIND_TEAMSPEAK, &synced.uid).unwrap().is_none());
let row = store.get(KIND_TEAMSPEAK, &device_only.uid).unwrap().unwrap();
assert_eq!((row.binding, row.json.as_str()), (None, "damaged"));
assert!(store.voelin_key(&other.uid()).unwrap().is_some());
assert_eq!(store.sign_out(&binding().account, forget).unwrap(), SignOut::default());
assert!(store.voelin_key(&key().uid()).unwrap().is_none());
}
}
#[test]
fn a_put_that_changes_only_the_binding_writes_the_binding_and_nothing_else() {
let Damaged { _scratch, store, device_only, .. } =
install_with_a_damaged_device_secret(true, "damaged");
let uid = &device_only.uid;
// The same data with another binding is accepted, however the data reads.
let moved = AccountBinding { rev: 9, ..binding() };
let rebound = IdentityBlob::from_row(KIND_TEAMSPEAK, uid.clone(), 0, "damaged".to_owned())
.with_binding(moved);
store.put(&rebound).unwrap();
let row = store.get(KIND_TEAMSPEAK, uid).unwrap().unwrap();
assert_eq!((row.binding, row.json.as_str()), (Some(moved), "damaged"));
let unbound = rebound.clone().with_binding(None);
store.put(&unbound).unwrap();
assert_eq!(store.get(KIND_TEAMSPEAK, uid).unwrap().unwrap().binding, None);
// Other data is a new identity for that uid and is checked as ever: damage
// is not replaced by more damage, nor by the key of a stranger.
let worse = IdentityBlob::from_row(KIND_TEAMSPEAK, uid.clone(), 0, "worse".to_owned());
assert!(matches!(store.put(&worse), Err(KeyStoreError::Backend(_))));
let stranger = Identity::create();
let hijack = IdentityBlob::teamspeak(
uid.clone(),
stranger.level(),
serde_json::to_string(&stranger).unwrap(),
);
assert!(matches!(store.put(&hijack), Err(KeyStoreError::Blob(BlobError::UidMismatch))));
let row = store.get(KIND_TEAMSPEAK, uid).unwrap().unwrap();
assert_eq!((row.binding, row.json.as_str()), (None, "damaged"));
// The fast path is for a row of the same kind: another kind's put of this
// uid is still refused, and replaces nothing.
let other_kind = IdentityBlob::new("other", uid.as_str(), 0, "damaged");
assert!(matches!(store.put(&other_kind), Err(KeyStoreError::Backend(_))));
assert!(store.get("other", uid).unwrap().is_none());
}
#[test]
fn forgetting_deletes_the_key_the_caller_names_and_no_other() {
// `Forget` acts on the uid it carries, not on what the record says.
let Install { store, .. } = signed_in_install(false);
let other = IdentityKey::generate().unwrap();
store.put_voelin_key(&other).unwrap();
let done = store.sign_out(&binding().account, DeviceKeyChoice::Forget(other.uid())).unwrap();
assert!(store.voelin_key(&other.uid()).unwrap().is_none());
assert!(
done.removed
.iter()
.any(|info| info.kind == KIND_VOELIN && info.uid == other.uid().to_base32())
);
// The record's key is not touched, and is not reported either way.
assert!(store.voelin_key(&key().uid()).unwrap().is_some());
assert!(
!done.removed.contains(&device_key_info()) && !done.unbound.contains(&device_key_info())
);
assert_eq!(store.account_record().unwrap(), None);
// A uid that is not stored deletes nothing and is not reported.
let Install { store, .. } = signed_in_install(true);
let done = store.sign_out(&binding().account, DeviceKeyChoice::Forget(other.uid())).unwrap();
assert!(store.voelin_key(&key().uid()).unwrap().is_some());
assert!(!done.removed.iter().any(|info| info.kind == KIND_VOELIN), "{done:?}");
}
#[test]
fn a_sign_out_is_durable_in_the_file() {
// What the sign-out did is in the database, not in the connection: a new
// connection finds the key unbound, the copies and the record gone, and a
// second sign-out has nothing to do.
let scratch = Scratch::new("signout");
let synced = fresh_teamspeak(binding());
let device_only = fresh_teamspeak(AccountBinding { synced: false, ..binding() });
{
let store = SqliteKeyStore::open(&scratch.db()).unwrap();
store.put_voelin_key(&key()).unwrap();
store.put_account_record(&AccountRecord { bound_existing_key: true, ..record() }).unwrap();
store.put(&synced).unwrap();
store.put(&device_only).unwrap();
let done = store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap();
assert_eq!(done.removed.len(), 2, "{done:?}");
assert_eq!(done.unbound.len(), 2, "{done:?}");
}
let store = SqliteKeyStore::open(&scratch.db()).unwrap();
assert_eq!(store.account_record().unwrap(), None);
assert!(store.get(KIND_TEAMSPEAK, &synced.uid).unwrap().is_none());
assert_eq!(store.get(KIND_TEAMSPEAK, &device_only.uid).unwrap().unwrap().binding, None);
let kept = store.get(KIND_VOELIN, &key().uid().to_base32()).unwrap().unwrap();
assert_eq!(kept, IdentityBlob::voelin(&key()).unwrap());
assert!(store.bound_to(&binding().account).unwrap().is_empty());
assert_eq!(
store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap(),
SignOut::default()
);
// And the raw row of the kept key has no account column set.
let db = Connection::open(scratch.db()).unwrap();
let account: Option<String> = db
.query_row("SELECT account FROM identities WHERE kind = 'voelin'", [], |r| r.get(0))
.unwrap();
assert_eq!(account, None);
}
// ------------------------------- sign-out with damaged rows (the gate's probe)
/// A signed-in install on a file, to damage through a second connection (as
/// something outside this crate could): the device key, the record with the
/// given key flag, a synced copy, a device-only secret and a local identity.
struct OnFile {
scratch: Scratch,
store: SqliteKeyStore,
synced: IdentityBlob,
device_only: IdentityBlob,
local: IdentityBlob,
}
fn signed_in_install_on_file(bound_existing_key: bool) -> OnFile {
let scratch = Scratch::new("signed-in");
let store = SqliteKeyStore::open(&scratch.db()).unwrap();
let synced = fresh_teamspeak(binding());
let device_only = fresh_teamspeak(AccountBinding { synced: false, ..binding() });
let local = fresh_teamspeak(None);
store.put_voelin_key(&key()).unwrap();
store.put_account_record(&AccountRecord { bound_existing_key, ..record() }).unwrap();
for blob in [&synced, &device_only, &local] {
store.put(blob).unwrap();
}
OnFile { scratch, store, synced, device_only, local }
}
impl OnFile {
/// Run one statement on the file, which must change a row.
fn damage(&self, sql: &str) {
let db = Connection::open(self.scratch.db()).unwrap();
assert_eq!(db.execute(sql, []).unwrap(), 1, "{sql}");
}
/// What a sign-out of `choice` must have done, whatever else was damaged:
/// the record and the synced copy are gone, the device-only secret is
/// unbound and the local identity is as it was; the device key is deleted
/// when the user forgot it, and reported as kept and unbound otherwise,
/// whether it predates the account or not.
fn assert_signed_out(&self, done: &SignOut, choice: DeviceKeyChoice, label: &str) {
let key_goes = matches!(choice, DeviceKeyChoice::Forget(_));
let mut removed = vec![(KIND_ACCOUNT.to_owned(), record().blob_uid()), pair(&self.synced)];
let mut unbound = vec![pair(&self.device_only)];
let device_key = (KIND_VOELIN.to_owned(), key().uid().to_base32());
if key_goes {
removed.push(device_key)
} else {
unbound.push(device_key)
}
removed.sort();
unbound.sort();
assert_eq!(sorted(done.removed.clone()), removed, "{label}: {done:?}");
assert_eq!(sorted(done.unbound.clone()), unbound, "{label}: {done:?}");
let store = &self.store;
assert!(store.get(KIND_ACCOUNT, &record().blob_uid()).unwrap().is_none(), "{label}");
assert!(store.get(KIND_TEAMSPEAK, &self.synced.uid).unwrap().is_none(), "{label}");
let secret = store.get(KIND_TEAMSPEAK, &self.device_only.uid).unwrap().unwrap();
assert_eq!(secret, self.device_only.clone().with_binding(None), "{label}");
assert_eq!(store.get(KIND_TEAMSPEAK, &self.local.uid).unwrap().unwrap(), self.local);
assert_eq!(store.voelin_key(&key().uid()).unwrap().is_none(), key_goes, "{label}");
// A retry has nothing left to do.
assert_eq!(
store.sign_out(&binding().account, choice).unwrap(),
SignOut::default(),
"{label}"
);
}
}
/// The ways the row of the account record can be damaged in its binding
/// columns, the first being the gate's probe.
const RECORD_ROW_DAMAGE: [&str; 5] = [
"UPDATE identities SET synced = 2 WHERE kind = 'account'",
"UPDATE identities SET account = 'junk' WHERE kind = 'account'",
"UPDATE identities SET integration = 'aaaqeayeaudaocajbifqydiob4' WHERE kind = 'account'",
"UPDATE identities SET integration_rev = 'many' WHERE kind = 'account'",
"UPDATE identities SET account = x'0102' WHERE kind = 'account'",
];
#[test]
fn a_damaged_account_record_row_does_not_keep_a_sign_out_from_finishing() {
// The record carries no binding, so damage in those columns says nothing
// about the record: it is read, and the sign-out does what it always does.
// `Forget` deletes the key it names; `Auto` keeps it.
for bound_existing_key in [true, false] {
for damage in RECORD_ROW_DAMAGE {
for choice in [DeviceKeyChoice::Auto, DeviceKeyChoice::Forget(key().uid())] {
let label = format!("{bound_existing_key}, {choice:?}, {damage}");
let install = signed_in_install_on_file(bound_existing_key);
install.damage(damage);
let done = install
.store
.sign_out(&binding().account, choice)
.unwrap_or_else(|error| panic!("{label}: {error}"));
install.assert_signed_out(&done, choice, &label);
}
}
}
}
#[test]
fn a_damaged_device_key_row_does_not_keep_a_sign_out_from_finishing() {
// With `Auto` the trait reads the key to report it as kept, whether it
// predates the account or not. Damage in its binding columns must not fail
// that.
for bound_existing_key in [true, false] {
for damage in [
"UPDATE identities SET synced = 2 WHERE kind = 'voelin'",
"UPDATE identities SET account = 'junk' WHERE kind = 'voelin'",
"UPDATE identities SET integration_rev = 'many' WHERE kind = 'voelin'",
] {
let label = format!("{bound_existing_key}, {damage}");
let install = signed_in_install_on_file(bound_existing_key);
install.damage(damage);
let done = install
.store
.sign_out(&binding().account, DeviceKeyChoice::Auto)
.unwrap_or_else(|error| panic!("{label}: {error}"));
install.assert_signed_out(&done, DeviceKeyChoice::Auto, &label);
// The key was kept, as it was stored.
let kept = install.store.voelin_key(&key().uid()).unwrap().unwrap();
assert_eq!(&kept.to_pkcs8().unwrap()[..], &key().to_pkcs8().unwrap()[..]);
}
}
}
#[test]
fn a_damaged_synced_copy_is_not_deleted_on_a_guess() {
// Its binding cannot be read, so a sign-out cannot know it is a copy of what
// the service holds: it stays, unbound as far as the store can tell, and the
// rest of the sign-out is done.
let install = signed_in_install_on_file(true);
install
.damage(&format!("UPDATE identities SET synced = 2 WHERE uid = '{}'", install.synced.uid));
let done = install.store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap();
assert_eq!(done.removed.len(), 1, "only the record: {done:?}");
assert!(done.removed.iter().all(|i| i.kind == KIND_ACCOUNT), "{done:?}");
let kept = install.store.get(KIND_TEAMSPEAK, &install.synced.uid).unwrap().unwrap();
assert_eq!((kept.binding, kept.json.as_str()), (None, install.synced.json.as_str()));
assert_eq!(install.store.account_record().unwrap(), None);
let again = install.store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap();
assert_eq!(again, SignOut::default());
}
#[test]
fn an_account_row_whose_data_is_not_text_is_deleted_like_an_unreadable_record() {
// A `data` column that holds bytes or a number reads as text that is no
// record: the trait deletes the record before it reports the error, so the
// sign-out finishes on the second call at the latest instead of failing the
// read for ever. `Forget` deletes the key it names first.
for damage in [
"UPDATE identities SET data = x'ff00fe' WHERE kind = 'account'",
"UPDATE identities SET data = 5 WHERE kind = 'account'",
"UPDATE identities SET data = 1.5 WHERE kind = 'account'",
] {
for choice in [DeviceKeyChoice::Auto, DeviceKeyChoice::Forget(key().uid())] {
let label = format!("{choice:?}, {damage}");
let install = signed_in_install_on_file(true);
install.damage(damage);
let error = install.store.sign_out(&binding().account, choice).unwrap_err();
assert!(
matches!(error, KeyStoreError::Blob(BlobError::AccountJson)),
"{label}: {error:?}"
);
let store = &install.store;
assert!(store.get(KIND_ACCOUNT, &record().blob_uid()).unwrap().is_none(), "{label}");
assert!(store.get(KIND_TEAMSPEAK, &install.synced.uid).unwrap().is_none(), "{label}");
let secret = store.get(KIND_TEAMSPEAK, &install.device_only.uid).unwrap().unwrap();
assert_eq!(secret.binding, None, "{label}");
// `Auto` keeps the key, as it always does; `Forget` deleted it first.
let forgot = matches!(choice, DeviceKeyChoice::Forget(_));
assert_eq!(store.voelin_key(&key().uid()).unwrap().is_none(), forgot, "{label}");
assert_eq!(store.sign_out(&binding().account, choice).unwrap(), SignOut::default());
}
}
}
// ------------------ a `data` column that is not text (the gate's second probe)
/// `data` of a row as SQLite holds it: its storage class and its bytes.
fn raw_data(db: &Connection, blob: &IdentityBlob) -> (String, Vec<u8>) {
db.query_row(
"SELECT typeof(data), CAST(data AS BLOB) FROM identities WHERE kind = ?1 AND uid = ?2",
params![blob.kind, blob.uid],
|row| Ok((row.get(0)?, row.get(1)?)),
)
.unwrap()
}
/// Bytes that are no UTF-8: `{"v":"`, 0xff, `1}`.
const NOT_UTF8: &str = "x'7b2276223aff317d'";
/// Five bound, device-only rows whose `data` is not text, as something outside
/// this crate could have left them (the identities as they were put, unbound,
/// are returned):
///
/// 0. a Voelin key whose data is a BLOB of bytes that are no UTF-8;
/// 1. a row of a kind a later version adds, whose data is a BLOB;
/// 2. a row of that kind whose data is TEXT of bytes that are no UTF-8;
/// 3. a TeamSpeak row whose data is a BLOB of bytes that are no identity;
/// 4. a TeamSpeak row whose data is a BLOB of a good identity.
fn rows_without_text(install: &OnFile) -> Vec<IdentityBlob> {
let device_only = AccountBinding { synced: false, ..binding() };
let blobs = vec![
IdentityBlob::voelin(&IdentityKey::generate().unwrap()).unwrap(),
IdentityBlob::new("future", "future:one", 0, r#"{"secret":"one"}"#),
IdentityBlob::new("future", "future:two", 0, r#"{"secret":"two"}"#),
fresh_teamspeak(None),
fresh_teamspeak(None),
];
let damage = [
NOT_UTF8,
"CAST(data AS BLOB)",
&format!("CAST({NOT_UTF8} AS TEXT)"),
"x'ff00fe'",
"CAST(data AS BLOB)",
];
for (blob, set) in blobs.iter().zip(damage) {
install.store.put(&blob.clone().with_binding(device_only)).unwrap();
install.damage(&format!(
"UPDATE identities SET data = {set} WHERE kind = '{}' AND uid = '{}'",
blob.kind, blob.uid
));
}
blobs
}
#[test]
fn a_sign_out_keeps_the_bytes_of_a_bound_row_whose_data_is_not_text() {
// The gate's probe. A `data` column that is a BLOB, or TEXT that is no
// UTF-8, is read as text with the odd bytes replaced. Unbinding such a row
// must write the binding and leave `data` the bytes it is (a Voelin key, a
// kind that passes through untouched), and a TeamSpeak row of that kind must
// not keep the sign-out from finishing because its replaced text is no
// identity.
for choice in [DeviceKeyChoice::Auto, DeviceKeyChoice::Forget(key().uid())] {
let install = signed_in_install_on_file(true);
let rows = rows_without_text(&install);
let db = Connection::open(install.scratch.db()).unwrap();
let before: Vec<_> = rows.iter().map(|blob| raw_data(&db, blob)).collect();
let types: Vec<_> = before.iter().map(|(class, _)| class.as_str()).collect();
assert_eq!(types, ["blob", "blob", "text", "blob", "blob"], "the setup: {choice:?}");
let done = install.store.sign_out(&binding().account, choice).unwrap();
let unbound = sorted(done.unbound.clone());
for row in &rows {
assert!(
unbound.contains(&pair(row)),
"{choice:?}: {:?} is unbound: {done:?}",
pair(row)
);
}
let after: Vec<_> = rows.iter().map(|blob| raw_data(&db, blob)).collect();
assert_eq!(after, before, "{choice:?}: data is byte for byte what it was");
for blob in &rows {
let stored = install.store.get(&blob.kind, &blob.uid).unwrap().unwrap();
assert_eq!(stored.binding, None, "{choice:?}: {:?}", pair(blob));
let account: Option<String> = db
.query_row(
"SELECT account FROM identities WHERE kind = ?1 AND uid = ?2",
params![blob.kind, blob.uid],
|row| row.get(0),
)
.unwrap();
assert_eq!(account, None, "{choice:?}: {:?}", pair(blob));
}
// The rest of the sign-out happened, and a retry has nothing to do.
let store = &install.store;
assert!(store.get(KIND_ACCOUNT, &record().blob_uid()).unwrap().is_none(), "{choice:?}");
assert!(store.get(KIND_TEAMSPEAK, &install.synced.uid).unwrap().is_none(), "{choice:?}");
assert!(store.bound_to(&binding().account).unwrap().is_empty(), "{choice:?}");
assert_eq!(store.sign_out(&binding().account, choice).unwrap(), SignOut::default());
}
}
#[test]
fn a_put_of_what_get_read_changes_the_binding_and_keeps_the_stored_bytes() {
let install = signed_in_install_on_file(true);
let rows = rows_without_text(&install);
let db = Connection::open(install.scratch.db()).unwrap();
let moved = AccountBinding { rev: 9, ..binding() };
for blob in &rows {
let before = raw_data(&db, blob);
let read = install.store.get(&blob.kind, &blob.uid).unwrap().unwrap();
for binding in [Some(moved), None] {
install.store.put(&read.clone().with_binding(binding)).unwrap();
let label = format!("{:?}, {binding:?}", pair(blob));
assert_eq!(raw_data(&db, blob), before, "{label}: the bytes are kept");
let stored = install.store.get(&blob.kind, &blob.uid).unwrap().unwrap();
assert_eq!(stored.binding, binding, "{label}");
}
}
}
#[test]
fn a_put_of_other_data_over_a_row_that_is_not_text_is_checked_and_replaces_it() {
// Only what `get` read is taken for the data that is there. Other data is a
// new identity for that uid: refused when it is not what its kind says, and
// stored (as TEXT) when it is.
let install = signed_in_install_on_file(true);
let rows = rows_without_text(&install);
let db = Connection::open(install.scratch.db()).unwrap();
let garbage = &rows[3];
let before = raw_data(&db, garbage);
let worse = IdentityBlob::from_row(KIND_TEAMSPEAK, garbage.uid.clone(), 0, "worse".to_owned());
assert!(matches!(install.store.put(&worse), Err(KeyStoreError::Backend(_))));
let stranger = Identity::create();
let hijack = IdentityBlob::teamspeak(
garbage.uid.clone(),
stranger.level(),
serde_json::to_string(&stranger).unwrap(),
);
assert!(matches!(install.store.put(&hijack), Err(KeyStoreError::Blob(BlobError::UidMismatch))));
assert_eq!(raw_data(&db, garbage), before, "refused, so nothing is written");
// The identity the uid names replaces the bytes, and the row is TEXT again.
install.store.put(garbage).unwrap();
assert_eq!(raw_data(&db, garbage), ("text".to_owned(), garbage.json.clone().into_bytes()));
assert_eq!(install.store.get(&garbage.kind, &garbage.uid).unwrap().unwrap(), *garbage);
// The same identity over the BLOB that holds it is not data of another
// value: the bytes stay.
let good = &rows[4];
let before = raw_data(&db, good);
assert_eq!(before.0, "blob");
install.store.put(good).unwrap();
assert_eq!(raw_data(&db, good), before);
}
// ------------------------------------------- a deleted key is gone from the file
/// The database file and its write-ahead log, as the bytes on disk.
struct RawFiles {
db: Vec<u8>,
wal: Vec<u8>,
}
impl RawFiles {
fn read(scratch: &Scratch) -> Self {
let wal = format!("{}-wal", scratch.db().display());
Self {
db: std::fs::read(scratch.db()).unwrap(),
wal: std::fs::read(wal).unwrap_or_default(),
}
}
fn holds(&self, text: &str) -> bool {
let contains = |bytes: &[u8]| bytes.windows(text.len()).any(|w| w == text.as_bytes());
contains(&self.db) || contains(&self.wal)
}
/// Where the text is, for a failure message.
fn where_is(&self, text: &str) -> (bool, bool) {
let contains = |bytes: &[u8]| bytes.windows(text.len()).any(|w| w == text.as_bytes());
(contains(&self.db), contains(&self.wal))
}
}
/// The text of the private key in a stored blob: `pkcs8` of a Voelin key,
/// `key` of a TeamSpeak identity.
fn key_text(json: &str, field: &str) -> String {
let json: serde_json::Value = serde_json::from_str(json).unwrap();
let text = json[field].as_str().unwrap().to_owned();
assert!(text.len() >= 40, "{field}: a short text would match anything");
text
}
#[test]
fn a_key_forgotten_by_a_sign_out_is_in_neither_the_database_file_nor_its_log() {
// The device key goes when the user forgets it, whether it predates the
// account or the client made it for the account. Its PKCS#8 text, and a
// synced TeamSpeak copy's key, must not stay in the free pages of
// `client.db` or in a frame of `client.db-wal`.
for bound_existing_key in [true, false] {
let choice = DeviceKeyChoice::Forget(key().uid());
let scratch = Scratch::new("scrub-signout");
let store = SqliteKeyStore::open(&scratch.db()).unwrap();
let device = IdentityBlob::voelin(&key()).unwrap();
let other = IdentityBlob::voelin(&IdentityKey::generate().unwrap()).unwrap();
let synced = fresh_teamspeak(binding());
let (device_text, other_text) =
(key_text(&device.json, "pkcs8"), key_text(&other.json, "pkcs8"));
let synced_text = key_text(&synced.json, "key");
store.put(&device).unwrap();
store.put(&other).unwrap();
store.put(&synced).unwrap();
store.put_account_record(&AccountRecord { bound_existing_key, ..record() }).unwrap();
// Another connection to the file (the settings writer, the chat history),
// idle, as the app has them.
let neighbour = Store::open(&scratch.db()).unwrap();
assert_eq!(neighbour.schema_version().unwrap(), Store::SCHEMA_VERSION);
// The keys are on disk before: the test proves nothing otherwise.
let before = RawFiles::read(&scratch);
assert!(before.holds(&device_text) && before.holds(&synced_text));
store.sign_out(&binding().account, choice).unwrap();
assert!(store.voelin_key(&key().uid()).unwrap().is_none(), "{choice:?}");
let after = RawFiles::read(&scratch);
assert_eq!(after.where_is(&device_text), (false, false), "{choice:?}: the device key");
assert_eq!(after.where_is(&synced_text), (false, false), "{choice:?}: the synced copy");
assert!(after.holds(&other_text), "{choice:?}: a key that stays is still stored");
assert!(after.wal.is_empty(), "{choice:?}: the log is truncated");
drop(neighbour);
}
}
#[test]
fn a_teamspeak_identity_deleted_by_the_store_is_in_neither_the_database_file_nor_its_log() {
let scratch = Scratch::new("scrub-delete");
let store = Store::open(&scratch.db()).unwrap();
let (doomed, kept) = (Identity::create(), Identity::create());
let doomed_text = key_text(&serde_json::to_string(&doomed).unwrap(), "key");
let kept_text = key_text(&serde_json::to_string(&kept).unwrap(), "key");
let doomed_id = store.add_identity("doomed", &doomed, IdentityOrigin::User).unwrap();
store.add_identity("kept", &kept, IdentityOrigin::User).unwrap();
assert!(RawFiles::read(&scratch).holds(&doomed_text), "the test proves nothing otherwise");
store.delete_identity(doomed_id).unwrap();
let after = RawFiles::read(&scratch);
assert_eq!(after.where_is(&doomed_text), (false, false));
assert!(after.holds(&kept_text));
assert!(after.wal.is_empty(), "the log is truncated");
}
#[test]
fn removing_through_the_key_store_leaves_no_key_behind_either() {
// `remove` is how a sign-out deletes, and it is public on its own.
let scratch = Scratch::new("scrub-remove");
let store = SqliteKeyStore::open(&scratch.db()).unwrap();
let device = IdentityBlob::voelin(&key()).unwrap();
let text = key_text(&device.json, "pkcs8");
store.put(&device).unwrap();
assert!(RawFiles::read(&scratch).holds(&text));
assert!(store.remove(KIND_VOELIN, &device.uid).unwrap());
assert_eq!(RawFiles::read(&scratch).where_is(&text), (false, false));
// Removing what is not there is not an error and changes nothing.
assert!(!store.remove(KIND_VOELIN, &device.uid).unwrap());
}
#[test]
fn a_reader_that_blocks_the_checkpoint_costs_one_checkpoint_and_starves_no_writer() {
// A connection that keeps a read snapshot (a long query of the UI, a backup)
// keeps the checkpoint that truncates the log from finishing. The sign-out
// still deletes and warns that the bytes may stay in the log, and it makes
// one checkpoint for all its removals, not one per removed row. While the
// checkpoint waits it holds the writer lock of the log, so a second
// connection that writes meanwhile must get through.
//
// No clock decides anything here. A checkpoint ends in two fsyncs, and under
// disk pressure (a build or a copy writing beside the tests) they take
// seconds: the review saw sign-outs of 1.2 to 1.9 s at 10 to 30 % I/O
// pressure, and `dd conv=fsync` loops beside 32 busy loops made them 5 s. A
// bound on the sign-out or a short busy timeout on the writer failed this
// test with "database is locked" for a checkpoint that was only slow. That a
// checkpoint gives up on a reader after a moment and does not wait out the
// connection's busy timeout is pinned where that timeout can be set to an
// hour: `store::tests::a_blocked_checkpoint_waits_briefly_and_leaves_the_busy_timeout_as_it_was`.
let scratch = Scratch::new("blocked-checkpoint");
let store = SqliteKeyStore::open(&scratch.db()).unwrap();
store.put_voelin_key(&key()).unwrap();
store.put_account_record(&AccountRecord { bound_existing_key: false, ..record() }).unwrap();
for copy in [fresh_teamspeak(binding()), fresh_teamspeak(binding())] {
store.put(&copy).unwrap();
}
// The snapshot is older than every removal below.
let reader = Connection::open(scratch.db()).unwrap();
reader.execute_batch("BEGIN").unwrap();
let rows: i64 = reader.query_row("SELECT count(*) FROM identities", [], |r| r.get(0)).unwrap();
assert_eq!(rows, 4);
let stop = AtomicBool::new(false);
let (done, elapsed, writes, errors, lines) = std::thread::scope(|scope| {
let writer = scope.spawn(|| {
// Its own connection, set up as the app's are (`Store::open`: the log
// and `synchronous = NORMAL`, so that a commit does not wait for the
// disk), with a busy timeout that a slow checkpoint does not reach.
let db = Connection::open(scratch.db()).unwrap();
db.pragma_update(None, "synchronous", "NORMAL").unwrap();
db.busy_timeout(Duration::from_secs(60)).unwrap();
let sql = "INSERT OR REPLACE INTO settings (key, value) VALUES ('probe', ?1)";
let (mut writes, mut errors) = (0, Vec::new());
while !stop.load(Ordering::Relaxed) {
match db.execute(sql, [writes.to_string()]) {
Ok(_) => writes += 1,
Err(error) => errors.push(error.to_string()),
}
std::thread::sleep(Duration::from_millis(5));
}
(writes, errors)
});
let started = Instant::now();
let (done, lines) = support::at_trace(|| {
store.sign_out(&binding().account, DeviceKeyChoice::Forget(key().uid()))
});
let elapsed = started.elapsed();
stop.store(true, Ordering::Relaxed);
let (writes, errors) = writer.join().unwrap();
(done.unwrap(), elapsed, writes, errors, lines)
});
// Four removals: the two copies, the device key the user forgot, the record.
assert_eq!(done.removed.len(), 4, "{done:?}");
assert!(store.list().unwrap().is_empty());
assert!(writes > 0, "the writer never ran");
assert!(errors.is_empty(), "a concurrent writer failed: {errors:?}");
// One checkpoint for the four removals: each one that is blocked says so.
let blocked = support::blocked_checkpoints(&lines);
assert_eq!(blocked, 1, "{lines:?} (the sign-out took {elapsed:?})");
// Nothing is lost by the wait: once the reader is gone, the next removal
// truncates the log.
reader.execute_batch("COMMIT").unwrap();
store.put_voelin_key(&key()).unwrap();
assert!(store.remove(KIND_VOELIN, &key().uid().to_base32()).unwrap());
assert!(RawFiles::read(&scratch).wal.is_empty(), "the log is truncated again");
}
// ------------------------- the keys a sign-out keeps, and the one the user forgets
//
// Open question 10 of the accounts design (Phase 2 task 34): a sign-out keeps
// every device key, and "Forget this device's identity" is the only deletion.
/// Every column of the row of this `(kind, uid)` as SQLite holds it, by name.
fn named_row(db: &Connection, kind: &str, uid: &str) -> Vec<(String, rusqlite::types::Value)> {
db.query_row(
"SELECT * FROM identities WHERE kind = ?1 AND uid = ?2",
params![kind, uid],
|row| {
let names: Vec<String> =
row.as_ref().column_names().iter().map(|n| n.to_string()).collect();
names
.into_iter()
.enumerate()
.map(|(index, name)| Ok((name, row.get(index)?)))
.collect::<rusqlite::Result<Vec<_>>>()
},
)
.unwrap()
}
#[test]
fn the_device_key_survives_a_sign_out_byte_for_byte_in_the_file() {
// Whether it predates the account or the client made it for the account, no
// column of its row changes: the key never carried a binding, and a sign-out
// writes nothing to it.
for bound_existing_key in [true, false] {
let install = signed_in_install_on_file(bound_existing_key);
let uid = key().uid().to_base32();
let db = Connection::open(install.scratch.db()).unwrap();
let before = named_row(&db, KIND_VOELIN, &uid);
assert!(before.len() >= 8, "{before:?}");
let done = install.store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap();
assert!(done.unbound.contains(&device_key_info()), "{bound_existing_key}: {done:?}");
assert!(!done.removed.contains(&device_key_info()), "{bound_existing_key}: {done:?}");
assert_eq!(named_row(&db, KIND_VOELIN, &uid), before, "{bound_existing_key}");
let kept = install.store.voelin_key(&key().uid()).unwrap().unwrap();
assert_eq!(&kept.to_pkcs8().unwrap()[..], &key().to_pkcs8().unwrap()[..]);
}
}
#[test]
fn a_device_key_that_carries_a_binding_is_unbound_and_keeps_the_rest_of_its_row() {
// The store accepts a binding with `synced = false` on the device key (a
// binding with `synced = true` is refused, see the last section). A sign-out
// unbinds it and keeps it: the four binding columns are the only ones that
// change.
const BINDING_COLUMNS: [&str; 4] = ["account", "integration", "integration_rev", "synced"];
for bound_existing_key in [true, false] {
let install = signed_in_install_on_file(bound_existing_key);
let uid = key().uid().to_base32();
let device_only = AccountBinding { synced: false, ..binding() };
install
.store
.put(&IdentityBlob::voelin(&key()).unwrap().with_binding(device_only))
.unwrap();
let db = Connection::open(install.scratch.db()).unwrap();
let before = named_row(&db, KIND_VOELIN, &uid);
let bound = |row: &[(String, rusqlite::types::Value)]| {
row.iter().any(|(name, value)| {
name == "account" && !matches!(value, rusqlite::types::Value::Null)
})
};
assert!(bound(&before), "the setup binds the key");
let done = install.store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap();
assert!(done.unbound.contains(&device_key_info()), "{bound_existing_key}: {done:?}");
assert!(!done.removed.contains(&device_key_info()), "{bound_existing_key}: {done:?}");
let after = named_row(&db, KIND_VOELIN, &uid);
assert!(!bound(&after), "{bound_existing_key}: unbound");
assert_eq!(before.len(), after.len());
for ((name, was), (_, is)) in before.iter().zip(&after) {
if !BINDING_COLUMNS.contains(&name.as_str()) {
assert_eq!(is, was, "{bound_existing_key}: column {name} is not a binding column");
}
}
let stored = install.store.get(KIND_VOELIN, &uid).unwrap().unwrap();
assert_eq!(stored, IdentityBlob::voelin(&key()).unwrap());
assert!(install.store.bound_to(&binding().account).unwrap().is_empty());
}
}
#[test]
fn a_sign_out_scrubs_the_copies_it_deletes_and_leaves_the_kept_keys_in_the_file() {
// What a sign-out still deletes is a synced copy (a private key, which
// the service holds again) and the record: those are gone from the file and
// its log. The device key and the device-only secret are kept, so their text
// is still there.
let scratch = Scratch::new("scrub-keeps");
let store = SqliteKeyStore::open(&scratch.db()).unwrap();
let device = IdentityBlob::voelin(&key()).unwrap();
let synced = fresh_teamspeak(binding());
let device_only = fresh_teamspeak(AccountBinding { synced: false, ..binding() });
let device_text = key_text(&device.json, "pkcs8");
let (synced_text, device_only_text) =
(key_text(&synced.json, "key"), key_text(&device_only.json, "key"));
for blob in [&device, &synced, &device_only] {
store.put(blob).unwrap();
}
store.put_account_record(&AccountRecord { bound_existing_key: false, ..record() }).unwrap();
let neighbour = Store::open(&scratch.db()).unwrap();
let before = RawFiles::read(&scratch);
assert!(before.holds(&device_text) && before.holds(&synced_text));
store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap();
let after = RawFiles::read(&scratch);
assert_eq!(after.where_is(&synced_text), (false, false), "the synced copy");
assert!(after.holds(&device_text), "the device key is kept");
assert!(after.holds(&device_only_text), "the device-only secret is kept");
assert!(after.wal.is_empty(), "the log is truncated");
drop(neighbour);
}
#[test]
fn a_sign_out_that_deletes_nothing_does_not_checkpoint() {
// With no record and no synced copy a sign-out only unbinds. The checkpoint
// belongs to deletions: with a reader that blocks it, a deletion says so, and
// the sign-out does not.
let scratch = Scratch::new("no-deletion");
let store = SqliteKeyStore::open(&scratch.db()).unwrap();
let device_only = fresh_teamspeak(AccountBinding { synced: false, ..binding() });
store.put(&device_only).unwrap();
let reader = Connection::open(scratch.db()).unwrap();
reader.execute_batch("BEGIN").unwrap();
let rows: i64 = reader.query_row("SELECT count(*) FROM identities", [], |r| r.get(0)).unwrap();
assert_eq!(rows, 1);
let (done, lines) =
support::at_trace(|| store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap());
assert!(done.removed.is_empty(), "{done:?}");
assert_eq!(done.unbound, vec![info_of(&device_only.clone().with_binding(None))]);
assert_eq!(support::blocked_checkpoints(&lines), 0, "{lines:?}");
// The same reader does block the checkpoint of a deletion, so the count above
// would have shown one.
store.put_voelin_key(&key()).unwrap();
let (removed, lines) =
support::at_trace(|| store.remove(KIND_VOELIN, &key().uid().to_base32()).unwrap());
assert!(removed);
assert_eq!(support::blocked_checkpoints(&lines), 1, "{lines:?}");
reader.execute_batch("COMMIT").unwrap();
}
#[test]
fn a_key_kept_by_a_sign_out_is_exported_and_then_forgotten_without_a_trace() {
// The flow of "Forget this device's identity" after a sign-out: the key is
// still there, unbound; the UI exports it, then deletes it. The export is
// what `voelin_key` and `to_pkcs8` give, and it restores the key.
let scratch = Scratch::new("export-forget");
let store = SqliteKeyStore::open(&scratch.db()).unwrap();
store.put_voelin_key(&key()).unwrap();
store.put_account_record(&AccountRecord { bound_existing_key: false, ..record() }).unwrap();
store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap();
let uid = key().uid();
let stored = store.get(KIND_VOELIN, &uid.to_base32()).unwrap().unwrap();
let text = key_text(&stored.json, "pkcs8");
let exported = store.voelin_key(&uid).unwrap().expect("the key is there").to_pkcs8().unwrap();
assert!(RawFiles::read(&scratch).holds(&text));
assert!(store.remove(KIND_VOELIN, &uid.to_base32()).unwrap());
assert!(store.voelin_key(&uid).unwrap().is_none());
let after = RawFiles::read(&scratch);
assert_eq!(after.where_is(&text), (false, false), "nothing of the key is left");
assert!(after.wal.is_empty(), "the log is truncated");
// The export brings the same key back.
let restored = IdentityKey::from_pkcs8(&exported).unwrap();
assert_eq!(restored.uid(), uid);
assert_eq!(restored.sign(b"the exported key"), key().sign(b"the exported key"));
store.put_voelin_key(&restored).unwrap();
assert_eq!(store.get(KIND_VOELIN, &uid.to_base32()).unwrap().unwrap(), stored);
}
// ------------------------------------------ releasing the device key from its account
//
// `AccountClient::release` asks the service to release the key and then runs the
// local sign-out with `Auto` (protocol 13.6, "Releasing this device's key"), so
// the store's part is the sign-out of the tests above, and the key has to be
// usable for another account afterwards.
#[test]
fn the_local_half_of_a_release_keeps_the_key_and_it_serves_another_account() {
let Install { store, .. } = signed_in_install(false);
let uid = key().uid().to_base32();
let before = store.get(KIND_VOELIN, &uid).unwrap().unwrap();
let signature = key().sign(b"the same key, before and after the release");
// The service released the key; the device finishes with a local sign-out.
let done = store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap();
assert!(done.unbound.contains(&device_key_info()), "{done:?}");
assert!(!done.removed.contains(&device_key_info()), "{done:?}");
assert_eq!(store.get(KIND_VOELIN, &uid).unwrap().unwrap(), before, "byte for byte");
assert_eq!(store.account_record().unwrap(), None);
// The key is registered with no account and signs up for another one: its
// record names the same key, and a copy of the new account's material is
// bound to it.
let other_id = AccountId::from_bytes([42; 16]);
let other = AccountRecord { account_id: other_id, login: "bob".into(), ..record() };
store.put_account_record(&other).unwrap();
assert_eq!(store.account_record().unwrap(), Some(other.clone()));
let other_binding = AccountBinding { account: account_uid(&issuer(), &other_id), ..binding() };
let other_copy = fresh_teamspeak(other_binding);
store.put(&other_copy).unwrap();
// Signing out of the new account keeps the key again, and the copy goes.
let done = store.sign_out(&other_binding.account, DeviceKeyChoice::Auto).unwrap();
assert!(done.unbound.contains(&device_key_info()), "{done:?}");
assert!(done.removed.contains(&info_of(&other_copy)), "{done:?}");
let kept = store.voelin_key(&key().uid()).unwrap().expect("the key stays");
assert_eq!(kept.sign(b"the same key, before and after the release"), signature);
assert_eq!(store.get(KIND_VOELIN, &uid).unwrap().unwrap(), before, "byte for byte");
}
#[test]
fn a_release_whose_local_half_was_cut_short_is_finished_by_a_sign_out() {
// The service released the device and the call was dropped before the local
// sign-out took the slot: the record and the copies are still here, and the
// key is still the record's device key. A sign-out with `Auto` finishes it
// and keeps the key; running it again finds nothing to do.
let Install { store, synced, device_only, .. } = signed_in_install(true);
let uid = key().uid().to_base32();
let before = store.get(KIND_VOELIN, &uid).unwrap().unwrap();
let done = store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap();
assert!(done.removed.contains(&info_of(&synced)), "{done:?}");
assert!(done.unbound.contains(&info_of(&device_only.clone().with_binding(None))), "{done:?}");
assert_eq!(store.account_record().unwrap(), None);
assert_eq!(store.get(KIND_VOELIN, &uid).unwrap().unwrap(), before);
assert_eq!(
store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap(),
SignOut::default()
);
}
// -------------------------------------- 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.
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 keeps the key, whether it predates the account or not.
let done = store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap();
assert!(done.unbound.contains(&device_key_info()), "{done:?}");
assert!(store.voelin_key(&key().uid()).unwrap().is_some());
}
}
#[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();
}
}