diff --git a/crates/voelin-store/tests/keystore.rs b/crates/voelin-store/tests/keystore.rs index edaad7b..6d57660 100644 --- a/crates/voelin-store/tests/keystore.rs +++ b/crates/voelin-store/tests/keystore.rs @@ -13,15 +13,19 @@ //! - 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 rusqlite::{Connection, params}; use tsclientlib::Identity; use voelin_identity::{ - AccountBinding, AccountId, AccountRecord, BlobError, IdentityBlob, IdentityInfo, IdentityKey, - IntegrationId, KIND_ACCOUNT, KIND_TEAMSPEAK, KIND_VOELIN, KeyStore, KeyStoreError, Uid, - UidParseError, account_uid, + 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}; @@ -604,3 +608,392 @@ fn the_sqlite_store_is_the_store_the_client_already_has() { 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) -> 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" + ); + } +} + +#[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 = db + .query_row("SELECT account FROM identities WHERE kind = 'voelin'", [], |r| r.get(0)) + .unwrap(); + assert_eq!(account, None); +}