Implement voelin-identity's KeyStore on the SQLite identities table
SqliteKeyStore is the identities table as a KeyStore: every kind (TeamSpeak, a Voelin key, the account record, an unknown kind that passes through) with the account binding of the columns that ADD_ACCOUNT_COLUMNS added. It owns a Store behind a mutex, because a KeyStore is Sync and a connection is not; with_store runs the TeamSpeak methods on the same connection. The trait's provided methods (bound_to, account_record, put_account_record, sign_out) are used as they are. - put is one upsert; a replaced row keeps its name, origin, default flag and creation time, and a blob without a binding unbinds the row. The uid is UNIQUE across kinds, so a uid another kind holds is a backend error that replaces nothing; get and remove are addressed by kind and uid. - The TeamSpeak level stays computed from the key and counter, as before; the level of a blob that is put is not stored. A TeamSpeak row whose JSON was damaged outside this crate lists and reads with level 0. - A TeamSpeak blob is stored only if its JSON is a tsproto identity and its key has the uid the blob names. Without the first one bad row breaks the list of TeamSpeak identities; without the second a blob could replace, by its uid, the key of a different identity. Tests copy the exercise() cases of voelin-identity's tests/storage.rs into the client (with the two deviations of a SQLite store, marked), round-trip bound and synced entries through the table and a reopen with their raw columns, and load a client.db migrated from schema versions 5 and 6 through the key store: kind teamspeak, no binding, JSON byte for byte, origin and default flag kept. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
0137d03d5b
commit
2898281d35
4 files changed
+936
No files matched your search
@@ -0,0 +1,606 @@
|
||||
//! 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.
|
||||
|
||||
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,
|
||||
};
|
||||
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 {
|
||||
fn new(name: &str) -> Self {
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("voelin-keystore-{name}-{}", 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 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));
|
||||
}
|
||||
Reference in new issue
Block a user