KeyStore::sign_out unbinds a device-only secret by get() and put() of the same blob with the binding cleared. put() ran check_teamspeak on the data first, so a bound row whose JSON had been damaged outside this crate made the put fail on every call: the account record was never reached, and with DeviceKeyChoice::Forget the order of the sign-out kept the named key from being deleted by the retry loop the module doc promised was unnecessary. put() now first tries a statement that rewrites only the four binding columns of the row of the same (kind, uid) whose data equals the blob's, and returns if it changed a row. Anything else, a new row or other data, goes through the check and the upsert as before: damage is not replaced by more damage, a stranger's key still cannot take over a uid, and another kind's put of a held uid is still refused. Nothing but the binding of the row is written, so the name, origin, default flag and creation time stay as they were. Tests: sign_out (Auto, and Forget with and without bound_existing_key) completes on a damaged bound row, deletes the record, unbinds the row and leaves its data as it was; the put cases above; each fails on the previous commit. The scratch directories of the test file are unique per call now, as two tests that pass the same name run side by side. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
1171 lines
49 KiB
Rust
1171 lines
49 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::{AtomicUsize, Ordering};
|
|
|
|
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, UidParseError, account_uid,
|
|
};
|
|
use voelin_store::{IdentityOrigin, SqliteKeyStore, Store};
|
|
|
|
/// 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))));
|
|
}
|
|
|
|
#[test]
|
|
fn damaged_binding_columns_are_precise_errors_when_read() {
|
|
let scratch = Scratch::new("damaged");
|
|
let store = SqliteKeyStore::open(&scratch.db()).unwrap();
|
|
store.put(&teamspeak_blob()).unwrap();
|
|
let db = Connection::open(scratch.db()).unwrap();
|
|
let set = |sql: &str| {
|
|
db.execute(&format!("UPDATE identities SET {sql} WHERE uid = ?1"), [TEAMSPEAK_UID]).unwrap()
|
|
};
|
|
let read = || store.get(KIND_TEAMSPEAK, TEAMSPEAK_UID);
|
|
|
|
set("account = 'junk'");
|
|
assert!(matches!(
|
|
read(),
|
|
Err(KeyStoreError::Blob(BlobError::BindingAccount(UidParseError::Length(4))))
|
|
));
|
|
// A listing fails the same way: a damaged row is reported, not skipped.
|
|
assert!(matches!(store.list(), Err(KeyStoreError::Blob(BlobError::BindingAccount(_)))));
|
|
|
|
set(&format!("account = '{}'", binding_for(1).to_base32()));
|
|
assert_eq!(read().unwrap().unwrap().binding.unwrap().account, binding_for(1));
|
|
|
|
set("synced = 2");
|
|
assert!(matches!(read(), Err(KeyStoreError::Blob(BlobError::BindingSynced(2)))));
|
|
set("synced = 0, integration_rev = -3");
|
|
assert!(matches!(read(), Err(KeyStoreError::Blob(BlobError::BindingRevision))));
|
|
set("integration_rev = 0, integration = 'nope'");
|
|
assert!(matches!(read(), Err(KeyStoreError::Blob(BlobError::BindingIntegration(_)))));
|
|
// An integration without an account.
|
|
set("account = NULL, integration = 'aaaqeayeaudaocajbifqydiob4'");
|
|
assert!(matches!(read(), Err(KeyStoreError::Blob(BlobError::BindingOrphan))));
|
|
}
|
|
|
|
// ------------------------------------- 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_device_secrets() {
|
|
// The device key was made for the account: signing out deletes it.
|
|
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),
|
|
(KIND_VOELIN.to_owned(), key().uid().to_base32()),
|
|
];
|
|
expected_removed.sort();
|
|
assert_eq!(sorted(done.removed.clone()), expected_removed, "{done:?}");
|
|
assert_eq!(done.unbound, vec![info_of(&device_only.clone().with_binding(None))]);
|
|
|
|
// What is left: 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!(store.voelin_key(&key().uid()).unwrap().is_none());
|
|
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(), 4);
|
|
|
|
// Signing out again finds nothing to do.
|
|
assert_eq!(store.sign_out(&mine, DeviceKeyChoice::Auto).unwrap(), SignOut::default());
|
|
assert_eq!(store.list().unwrap().len(), 4);
|
|
// 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_deletes_a_device_key_the_client_made_for_the_account() {
|
|
let Install { store, device_only, local, .. } = signed_in_install(false);
|
|
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:?}");
|
|
assert!(store.voelin_key(&key().uid()).unwrap().is_none());
|
|
let mut left = sorted(store.list().unwrap());
|
|
left.sort();
|
|
let mut expected = vec![pair(&device_only), pair(&local)];
|
|
expected.sort();
|
|
assert_eq!(left, expected, "the device secret and the local one");
|
|
}
|
|
|
|
#[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);
|
|
}
|