diff --git a/CHANGELOG.md b/CHANGELOG.md index fb388f8..88ac674 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -69,6 +69,12 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows ### Changed +- The key store now keeps the device key when signing out of an account, + unbound, whether it was in use before the account or was made for it; "Forget + this device's identity" is the only way a key is deleted. The identity store + also reports a damaged TeamSpeak identity by the kind of damage and never + repeats its key in an error. Nothing changes on screen yet: accounts and + sign-in are later steps. - The view models, the app's state, the state change of every engine event and the decisions of the settings pages, the Stream Studio, the streams, the chat, the servers, the audio settings page, the friends and the development diff --git a/Cargo.lock b/Cargo.lock index 19f94d7..31c9466 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9578,7 +9578,7 @@ dependencies = [ [[package]] name = "voelin-identity" version = "0.2.0" -source = "git+ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git?rev=c8e0e5a17c1ff5dfaefa087f49b395d2918af650#c8e0e5a17c1ff5dfaefa087f49b395d2918af650" +source = "git+ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git?rev=c5bb6b914bdab86eb36f6e32a1a5bc9ac4785562#c5bb6b914bdab86eb36f6e32a1a5bc9ac4785562" dependencies = [ "aws-lc-rs", "base64 0.23.1", @@ -9637,7 +9637,7 @@ dependencies = [ [[package]] name = "voelin-model" version = "0.1.0" -source = "git+ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git?rev=c8e0e5a17c1ff5dfaefa087f49b395d2918af650#c8e0e5a17c1ff5dfaefa087f49b395d2918af650" +source = "git+ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git?rev=c5bb6b914bdab86eb36f6e32a1a5bc9ac4785562#c5bb6b914bdab86eb36f6e32a1a5bc9ac4785562" dependencies = [ "prost", "serde", @@ -9676,7 +9676,7 @@ dependencies = [ [[package]] name = "voelin-proto" version = "0.2.0" -source = "git+ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git?rev=c8e0e5a17c1ff5dfaefa087f49b395d2918af650#c8e0e5a17c1ff5dfaefa087f49b395d2918af650" +source = "git+ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git?rev=c5bb6b914bdab86eb36f6e32a1a5bc9ac4785562#c5bb6b914bdab86eb36f6e32a1a5bc9ac4785562" dependencies = [ "bytes", "prost", diff --git a/Cargo.toml b/Cargo.toml index 10350af..61c3b6f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -58,13 +58,14 @@ publish = false # docs/development.md names, so that a per-developer .cargo/config.toml [patch] # can point it at a sibling checkout (docs/building.md, "Working with a sibling # VoelinProtocol checkout"). Pinned by commit until the protocol tags a release: -# the three crates below are at one revision (main c8e0e5a: the account-bound -# KeyStore of Phase 2 task 28, the account types of the session seam). -voelin-identity = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", rev = "c8e0e5a17c1ff5dfaefa087f49b395d2918af650" } +# the three crates below are at one revision (main c5bb6b9: the account-bound +# KeyStore whose sign-out keeps every device key and the release of a device key, +# Phase 2 task 34; the account types of the session seam). +voelin-identity = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", rev = "c5bb6b914bdab86eb36f6e32a1a5bc9ac4785562" } # The backend-neutral session seam (`voelin_proto::link`) and the v1 messages. -voelin-proto = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", rev = "c8e0e5a17c1ff5dfaefa087f49b395d2918af650" } +voelin-proto = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", rev = "c5bb6b914bdab86eb36f6e32a1a5bc9ac4785562" } # The UI-facing domain model and the client's replica of v1 entities. -voelin-model = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", rev = "c8e0e5a17c1ff5dfaefa087f49b395d2918af650" } +voelin-model = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", rev = "c5bb6b914bdab86eb36f6e32a1a5bc9ac4785562" } [workspace.lints.rust] # deny, not forbid: generated code (Slint) needs a local allow. diff --git a/crates/voelin-core/src/link/fake_tests.rs b/crates/voelin-core/src/link/fake_tests.rs index f428d5c..a04b9ee 100644 --- a/crates/voelin-core/src/link/fake_tests.rs +++ b/crates/voelin-core/src/link/fake_tests.rs @@ -313,7 +313,7 @@ async fn the_conformance_suite_passes_on_a_session_of_the_registry() { } let report = conformance::run(&through_the_registry).await; assert_eq!(report.cases.len(), conformance::CASES.len()); - assert_eq!(report.cases.len(), 17, "the suite of c8e0e5a has 17 cases"); + assert_eq!(report.cases.len(), 17, "the suite of c5bb6b9 has 17 cases"); assert!( report.cases.iter().all(|(_, verdict)| *verdict == Verdict::Passed), "{:?}", diff --git a/crates/voelin-core/src/ts/ts_session/live_tests.rs b/crates/voelin-core/src/ts/ts_session/live_tests.rs index 87966e7..ba51e9a 100644 --- a/crates/voelin-core/src/ts/ts_session/live_tests.rs +++ b/crates/voelin-core/src/ts/ts_session/live_tests.rs @@ -333,7 +333,7 @@ enum Expect { } use Expect::{NotRun, Passes, Skipped}; -/// Every case of the suite of the protocol repository at `c8e0e5a`, in its +/// Every case of the suite of the protocol repository at `c5bb6b9`, in its /// order, with what a TeamSpeak session does with it. A case the suite gains /// fails `the_suite_is_known` until it is listed here. /// diff --git a/crates/voelin-store/src/keystore.rs b/crates/voelin-store/src/keystore.rs index 185433b..34a797b 100644 --- a/crates/voelin-store/src/keystore.rs +++ b/crates/voelin-store/src/keystore.rs @@ -35,44 +35,119 @@ //! the trait's [`KeyStore::sign_out`] starts with it and then reads the account //! record and the device key with [`KeyStore::get`]: one damaged row, the //! record's own included, would otherwise keep a sign-out from ever finishing, -//! and with it the deletion of the key the user asked to forget. Unbound is the -//! reading that never deletes on a guess: a sign-out neither deletes such a row -//! as a synced copy nor writes it, it stays as it is until a `put` of it writes -//! four good binding columns. A `data` column that is not text (a BLOB, or text -//! of bytes that are no UTF-8) is read as text with the odd bytes replaced, so -//! that a record that cannot be read is deleted by the sign-out, as the trait -//! says, instead of its read failing. A [`KeyStore::put`] of the text that +//! and with it the deletion of the synced copies and of the record, and the +//! forgetting of the key the user asked to forget. Unbound is the reading that +//! never deletes on a guess: a sign-out neither deletes such a row as a synced +//! copy nor writes it, it stays as it is until a `put` of it writes four good +//! binding columns. A `data` column that is not text (a BLOB, or text of bytes +//! that are no UTF-8) is read as text with the odd bytes replaced, so that a +//! record that cannot be read is deleted by the sign-out, as the trait says, +//! instead of its read failing. A [`KeyStore::put`] of the text that //! [`KeyStore::get`] returned for such a row is taken for the data that is //! there: it changes the binding and keeps the stored bytes, where any other //! text replaces them (a TeamSpeak blob still has to be an identity). A row //! whose `kind` or `uid` is not text cannot be addressed, and the list leaves it //! out with a warning. //! +//! # Signing out keeps every key +//! +//! [`KeyStore::sign_out`] is the trait's own, run on this table, and since +//! Phase 2 task 34 of the protocol repository (open question 10 of its accounts +//! design, answered by the owner on 2026-10-24) it keeps every key of the +//! device. The device key stays, unbound and byte for byte, whether it was in +//! use before the account existed or the client made it for the account: +//! `AccountRecord::bound_existing_key` only records which, for the client's +//! wording, and no rule reads it. At every host without accounts that the user +//! reached with it, either key is the user's identity, and deleting it would +//! lose their servers, roles and memberships there. The identities that only +//! this device holds (a TeamSpeak identity of custody `DEVICE`, one the user +//! kept local) are unbound and kept as well. +//! +//! What a sign-out deletes is not a key of the device: the synced copies of +//! integration secrets, which the account service holds and every device can +//! fetch again (a copy of a TeamSpeak identity is a private key, and is deleted +//! like one, see below), and the account record, which holds no secret. A +//! sign-out does not release the device key at the account service either: the +//! key stays registered with the account there. The release is its own +//! operation, see below. +//! +//! # Releasing a device key +//! +//! The release of the device key from its account (part 2 of open question 10) +//! is the account service's operation followed by a local unbind, and the unbind +//! is a sign-out: `AccountClient::release` of `voelin-account-client` calls +//! `POST /v1/devices//release` after a password check, and then runs +//! [`KeyStore::sign_out`] with [`DeviceKeyChoice::Auto`], which keeps the key, +//! unbound. So the store needs nothing of its own for it: no call that unbinds +//! one key (a [`KeyStore::put`] of the blob without its binding does that, and +//! keeps the data, as the sign-out does), and no record that the key was +//! released. The accounts design asks the client to remember nothing of the +//! kind: the service holds the registration of the key (after a release it is +//! registered with no account, after a sign-out with the account that was +//! signed out of), and the client learns which at the next sign-in or sign-up, +//! from the service's answer (`CONFLICT`, field `device`), not from a note kept +//! here. The deletion of the account (`AccountClient::delete_account`) is the +//! same: the service writes a DEVICE and a RELEASED entry for every device key +//! of the account, and the local half is this sign-out, which keeps this +//! device's key. +//! +//! # Forgetting the device's identity +//! +//! "Forget this device's identity" is the user's explicit choice and the only +//! deletion of a key of the device; the UI offers to export the key first and +//! asks before it deletes. +//! +//! - Signed in, it is a sign-out with [`DeviceKeyChoice::Forget`] and the uid of +//! the device key. The caller names the key, because the key goes before the +//! record is read: a record that cannot be read does not keep it. +//! - Signed out, or with a key that no account ever bound, it is +//! [`KeyStore::remove`] of `(KIND_VOELIN, uid)`; a TeamSpeak identity is +//! [`Store::delete_identity`]. Neither looks at an account record, so a UI +//! that forgets the device key of the account it is signed in to does it +//! through the sign-out, not through `remove`. +//! +//! The store has no call that exports, because it would only wrap what the +//! caller can read before it deletes: a Voelin key is +//! `KeyStore::voelin_key(uid)` followed by `IdentityKey::to_pkcs8` (the DER that +//! `voelin_identity::FileSigner` reads back; the buffer is zeroized when it is +//! dropped), and a TeamSpeak identity is `Store::identity(id)` followed by +//! `voelin_core::ts::identity::export` or `write_export`. The same two calls, +//! with [`KeyStore::list`] for the `voelin` rows, serve the dialog that deletes +//! the account: it offers an export of the device keys before the service is +//! asked. +//! +//! # Deleted keys leave no trace +//! //! The rows are private keys, so a removed row is not left behind in the file: //! every connection sets `secure_delete`, which makes SQLite overwrite what it //! deletes, and [`KeyStore::remove`] truncates the write-ahead log after it, as //! [`Store::delete_identity`] does, so that the frame of the log that held the -//! page with the key is gone too. [`KeyStore::sign_out`], which deletes with -//! `remove`, truncates the log once, after its last step, not after each -//! removal. The checkpoint waits for another connection for a moment at most -//! (`Store::truncate_wal`): one that keeps reading an old snapshot blocks it, -//! and then the removal still succeeds and a warning says that the deleted -//! bytes may stay in the log file, until a later checkpoint truncates the log, -//! later writes overwrite those frames, or the last connection to the database -//! closes and the log is deleted. +//! page with the key is gone too. A forgotten key needs exactly that. So does +//! the one deletion a sign-out still makes of a key: a synced copy of a +//! TeamSpeak identity, and with `Forget` the device key itself. The sign-out +//! deletes with `remove` on a `SignOutPass` and truncates the log once, after +//! its last step, not after each removal; one that deletes nothing (the record +//! was gone, no copies) truncates nothing. The checkpoint waits for another +//! connection for a moment at most (`Store::truncate_wal`): one that keeps +//! reading an old snapshot blocks it, and then the removal still succeeds and a +//! warning says that the deleted bytes may stay in the log file, until a later +//! checkpoint truncates the log, later writes overwrite those frames, or the +//! last connection to the database closes and the log is deleted. //! -//! The device key is never a synced copy. The account record names the Voelin key -//! that is the installation's device key, and [`KeyStore::sign_out`] deletes -//! every identity bound with `synced = true` in its first step, before it reads -//! the record, so a key stored that way would be deleted whatever the record -//! says (a key that predates the account is to be kept). The store therefore -//! refuses, with an error that says why, a [`KeyStore::put`] of a `voelin` blob -//! with `synced = true` while an account record names its uid as the device, or -//! while a record cannot be read, because then it cannot tell; and a put of an +//! # The device key is never a synced copy +//! +//! A sign-out keeps the device key, but its first step deletes every identity +//! bound with `synced = true`, before it reads the account record that names +//! the device key. A device key stored that way would be deleted by that step, +//! whether it predates the account or not, which is what the rule that a +//! sign-out keeps every device key forbids. The store therefore refuses, with an +//! error that says why, a [`KeyStore::put`] of a `voelin` blob with +//! `synced = true` while an account record names its uid as the device, or while +//! a record cannot be read, because then it cannot tell; and a put of an //! account record that names a key which is stored as a synced copy. A binding -//! with `synced = false` is accepted: a sign-out unbinds such a key and then -//! follows the record. The check and the write are done under the store's lock; -//! a second process writing the same file at the same moment is not covered. +//! with `synced = false` is accepted: a sign-out unbinds such a key and keeps +//! it. The check and the write are done under the store's lock; a second +//! process writing the same file at the same moment is not covered. //! //! A TeamSpeak blob that is refused says why in words that carry none of its //! input: its `data` is the identity's private key, and an error reaches log @@ -136,8 +211,10 @@ const PUT: &str = "INSERT INTO identities /// access to the TeamSpeak methods of the same connection. /// /// [`KeyStore::sign_out`] and the rest of the trait's provided methods work as -/// `voelin-identity` defines them, on top of the five methods here; the -/// sign-out only truncates the write-ahead log once, at its end. +/// `voelin-identity` defines them, on top of the five methods here: a sign-out +/// keeps every key of the device (only [`DeviceKeyChoice::Forget`] deletes the +/// device key), and only truncates the write-ahead log once, at its end, when +/// it deleted something. pub struct SqliteKeyStore { store: Mutex, } @@ -270,10 +347,13 @@ impl KeyStore for SqliteKeyStore { /// The trait's sign-out, with the log truncated once after its last step /// instead of after each of its removals: it removes up to a handful of - /// rows, and a checkpoint that another connection blocks costs a moment + /// rows (the synced copies, the account record and, with + /// [`DeviceKeyChoice::Forget`], the device key; every other key stays), and + /// a checkpoint that another connection blocks costs a moment /// (`Store::truncate_wal`) each time. The steps are the trait's own; they /// run on a `SignOutPass`, which deletes like [`Self::remove`] and leaves - /// the checkpoint to this method. + /// the checkpoint to this method. A sign-out that deleted nothing does not + /// checkpoint. fn sign_out(&self, account: &Uid, device_key: DeviceKeyChoice) -> KsResult { let pass = SignOutPass { store: self, deleted: AtomicBool::new(false) }; let outcome = KeyStore::sign_out(&pass, account, device_key); @@ -299,7 +379,10 @@ fn delete_row(store: &Store, kind: &str, uid: &str) -> KsResult { /// A [`SqliteKeyStore`] for the length of one [`KeyStore::sign_out`]: the same /// rows, but `remove` only notes that it deleted something, so that the sign-out -/// truncates the log once at its end. +/// truncates the log once at its end. What a sign-out removes is the synced +/// copies of integration secrets, the account record and, when the user chose +/// to forget it, the device key; unbinding goes through `put`, which deletes +/// nothing. struct SignOutPass<'a> { store: &'a SqliteKeyStore, /// Whether a row was deleted. @@ -470,26 +553,28 @@ enum Refused { /// `uid` is unique across kinds in this table. #[error("the uid {uid:?} is already stored as an identity of kind {kind:?}")] UidHeld { uid: String, kind: String }, - /// The Voelin key is the device key of an account record. A sign-out - /// deletes a synced copy without reading the record, so the key the record - /// says to keep would be deleted. + /// The Voelin key is the device key of an account record. A sign-out keeps + /// the device key, but it deletes a synced copy without reading the record, + /// so a device key stored as one would be deleted all the same. #[error( "the Voelin key {uid:?} is the device key of the account record {record:?} and cannot be \ - stored as a synced copy (synced = true): a sign-out would delete it whatever the record says" + stored as a synced copy (synced = true): a sign-out deletes every synced copy before it \ + reads the record, so it would delete the device key that it keeps" )] SyncedDeviceKey { uid: String, record: String }, /// An account record cannot be read, so the store cannot tell whether the /// Voelin key is its device key. #[error( "the Voelin key {uid:?} cannot be stored as a synced copy (synced = true): the account \ - record {record:?} cannot be read, so it may name this key as the device key" + record {record:?} cannot be read, so it may name this key as the device key, which a \ + sign-out keeps but would delete as a synced copy" )] UnreadableRecord { uid: String, record: String }, /// The device key of the record is stored as a synced copy already. #[error( "the account record {record:?} names the Voelin key {device:?} as the device key, which is \ - stored as a synced copy (synced = true): a sign-out would delete it whatever the record \ - says" + stored as a synced copy (synced = true): a sign-out deletes every synced copy before it \ + reads the record, so it would delete the device key that it keeps" )] RecordNamesSyncedKey { record: String, device: String }, } diff --git a/crates/voelin-store/src/lib.rs b/crates/voelin-store/src/lib.rs index 696290a..8a126f7 100644 --- a/crates/voelin-store/src/lib.rs +++ b/crates/voelin-store/src/lib.rs @@ -33,12 +33,48 @@ pub use store::{ Bookmark, CachedServerIcon, IdentityEntry, IdentityOrigin, QueryConfig, QueryTransport, Store, }; +/// How the JSON of a stored TeamSpeak identity is wrong: the category of the +/// reader's complaint and nothing of the text, which holds a private key. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum IdentityDamage { + /// The text is not JSON. + Malformed, + /// The text ends before the JSON does. + CutShort, + /// The JSON is not that of an identity: a field is missing or of another + /// type, or the key does not import. + NotAnIdentity, + /// The text could not be read. + Unreadable, +} + +impl std::fmt::Display for IdentityDamage { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(match self { + Self::Malformed => "malformed", + Self::CutShort => "cut short", + Self::NotAnIdentity => "not an identity", + Self::Unreadable => "unreadable", + }) + } +} + #[derive(Debug, thiserror::Error)] pub enum Error { #[error("database: {0}")] Db(#[from] rusqlite::Error), #[error("serialization: {0}")] Json(#[from] serde_json::Error), + /// The JSON of a stored TeamSpeak identity cannot be read, which only damage + /// outside the client can cause. It says how the text is wrong and where, and + /// never what it holds: the text is a private key, and the message of the + /// JSON reader quotes the value it refuses (`tsproto` reports a key that does + /// not import as an invalid value, the key string and all), so that message is + /// not kept, not here and not in a log line. + #[error( + "the stored TeamSpeak identity cannot be read: {damage} at line {line}, column {column}" + )] + Identity { damage: IdentityDamage, line: usize, column: usize }, #[error("{0} {1} not found")] NotFound(&'static str, i64), #[error("secret store: {0}")] diff --git a/crates/voelin-store/src/store.rs b/crates/voelin-store/src/store.rs index a1a0623..a79b3c6 100644 --- a/crates/voelin-store/src/store.rs +++ b/crates/voelin-store/src/store.rs @@ -8,7 +8,7 @@ use serde::de::DeserializeOwned; use serde::{Deserialize, Serialize}; use tsclientlib::Identity; -use crate::{Error, Result}; +use crate::{Error, IdentityDamage, Result}; /// A schema migration: SQL, or code for what SQL alone cannot do. enum Migration { @@ -244,6 +244,28 @@ impl Bookmark { /// waits. const CHECKPOINT_WAIT: Duration = Duration::from_millis(150); +/// The TeamSpeak identity in the JSON of a stored row. +/// +/// A text that does not read (it could only have been damaged outside the +/// client: [`Store::add_identity`] writes what `serde_json` makes of an +/// identity) is refused with [`Error::Identity`], which says how it is wrong and +/// where and never what it holds, as `voelin-core`'s `ts::identity::from_json` +/// does for the text it is handed. The reader's own message is dropped: it +/// quotes a value it refuses, and `tsproto` reports a key that does not import +/// as an invalid value, the key string and all, which would reach a status line +/// or a log. +fn identity_from_json(json: &str) -> Result { + serde_json::from_str(json).map_err(|error| { + let damage = match error.classify() { + serde_json::error::Category::Syntax => IdentityDamage::Malformed, + serde_json::error::Category::Eof => IdentityDamage::CutShort, + serde_json::error::Category::Data => IdentityDamage::NotAnIdentity, + serde_json::error::Category::Io => IdentityDamage::Unreadable, + }; + Error::Identity { damage, line: error.line(), column: error.column() } + }) +} + pub struct Store { pub(crate) db: Connection, } @@ -348,7 +370,7 @@ impl Store { })?; rows.map(|row| { let (id, name, uid, data, origin, is_default) = row?; - let identity: Identity = serde_json::from_str(&data)?; + let identity = identity_from_json(&data)?; let origin = IdentityOrigin::parse(&origin); Ok(IdentityEntry { id, name, uid, level: identity.level(), origin, is_default }) }) @@ -395,7 +417,7 @@ impl Store { ) .optional()?; let data = data.ok_or(Error::NotFound("identity", id))?; - Ok(serde_json::from_str(&data)?) + identity_from_json(&data) } /// Store an identity again, e.g. after its security level was improved. @@ -630,23 +652,43 @@ mod tests { reader.query_row("SELECT count(*) FROM identities", [], |r| r.get::<_, i64>(0)).unwrap(); store.add_identity("second", &Identity::create(), IdentityOrigin::User).unwrap(); - // A value that is not the default, so that restoring a constant would show. + // A value that is not the default, so that restoring a constant would + // show, and one so long that a checkpoint that waited as long as the + // connection allows would not come back by itself. + const HOUR_MS: i64 = 3_600_000; let timeout = |store: &Store| -> i64 { store.db.pragma_query_value(None, "busy_timeout", |r| r.get(0)).unwrap() }; - store.db.busy_timeout(Duration::from_millis(2345)).unwrap(); - let started = std::time::Instant::now(); - store.truncate_wal(); - let elapsed = started.elapsed(); - assert!(elapsed < Duration::from_secs(1), "the checkpoint waited {elapsed:?}"); + store.db.busy_timeout(Duration::from_secs(3600)).unwrap(); + + // "Briefly" is not a time: a checkpoint ends in two fsyncs, which take + // seconds under disk pressure (it took 6 s here beside `dd conv=fsync` + // loops), and only a checkpoint that comes back while the reader still + // holds its snapshot has not waited for it. So the reader lets go from + // another thread after 30 s, which ends a checkpoint that does not give + // up with a failure here and not with an hour's wait. + let (back, hear) = std::sync::mpsc::channel::<()>(); + let watchdog = std::thread::spawn(move || { + let in_time = hear.recv_timeout(Duration::from_secs(30)).is_ok(); + if !in_time { + reader.execute_batch("COMMIT").unwrap(); + } + (reader, in_time) + }); + // One attempt, which the reader blocks (`1`). + let blocked = store.checkpoint_truncate(); + back.send(()).ok(); + let (reader, in_time) = watchdog.join().unwrap(); + assert!(in_time, "the checkpoint waited for the reader instead of giving up"); + assert_eq!(blocked.unwrap(), 1, "the reader should block the reset"); assert!(std::fs::metadata(&wal).unwrap().len() > 0, "the reader should block the reset"); - assert_eq!(timeout(&store), 2345); + assert_eq!(timeout(&store), HOUR_MS); // Without the reader the same call resets the log. reader.execute_batch("COMMIT").unwrap(); store.truncate_wal(); assert_eq!(std::fs::metadata(&wal).unwrap().len(), 0); - assert_eq!(timeout(&store), 2345); + assert_eq!(timeout(&store), HOUR_MS); drop(reader); drop(store); std::fs::remove_dir_all(dir).unwrap(); diff --git a/crates/voelin-store/tests/identity_text.rs b/crates/voelin-store/tests/identity_text.rs new file mode 100644 index 0000000..6297829 --- /dev/null +++ b/crates/voelin-store/tests/identity_text.rs @@ -0,0 +1,330 @@ +//! A damaged identity row: what the store returns and logs about it says how +//! the row is wrong and never what it holds. +//! +//! The `data` of a TeamSpeak row is the JSON of a private key. Only something +//! outside the client can damage it, but when that happens the error of the +//! JSON reader quotes the value it refuses (`tsproto` reports a key that does +//! not import as an invalid value, the key string and all), and an error +//! reaches a status line, an event or a log. `Store::identity` and +//! `Store::identities` used to return that error as it was. +//! +//! Every case here damages a row of a database file through a second +//! connection, calls everything of the store that reads or writes the row, and +//! looks through the errors (their text, their `Debug` text and their sources) +//! and the logs at TRACE for any 8 characters in a row of what the row held. + +use rusqlite::types::Value; +use rusqlite::{Connection, params}; +use tsclientlib::Identity; +use voelin_identity::{ + AccountBinding, AccountId, DeviceKeyChoice, IdentityBlob, IntegrationId, KIND_TEAMSPEAK, + KeyStore, Uid, account_uid, +}; +use voelin_store::{Error, IdentityDamage, IdentityOrigin, SqliteKeyStore, Store}; + +mod support; + +/// A directory of its own 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-identity-text-{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); + } +} + +/// Letters and digits that no message of this crate, of `serde_json` or of +/// SQLite is made of in a run of eight. +const SECRET: &str = "Zq7Xm2Vb9Lk4Pw8Rt3Yn6Hd1Fs5Jc0Ga"; +const OTHER_SECRET: &str = "Qx3Wv8Nb5Mj1Kh6Gf2Dt9Rs4Pl7Yc0Za"; + +/// The JSON of a fresh identity whose key lost its last two characters (a key +/// that does not import), and that cut key. +fn json_with_a_cut_key() -> (String, String) { + let mut json = serde_json::to_value(Identity::create()).unwrap(); + let key = json["key"].as_str().unwrap().to_owned(); + let cut = key[..key.len() - 2].to_owned(); + json["key"] = cut.clone().into(); + (json.to_string(), cut) +} + +/// The JSON of a fresh identity whose counter is a string (`SECRET`), and that +/// string: the reader quotes it in its message. +fn json_with_a_counter_of_the_wrong_type() -> String { + let mut json = serde_json::to_value(Identity::create()).unwrap(); + json["counter"] = SECRET.into(); + json.to_string() +} + +/// The JSON of a fresh identity cut in the middle of its key, and the key. +fn json_cut_inside_its_key() -> (String, String) { + let json = serde_json::to_value(Identity::create()).unwrap(); + let key = json["key"].as_str().unwrap().to_owned(); + let text = json.to_string(); + let cut = text.find(&key).unwrap() + key.len() / 2; + (text[..cut].to_owned(), key) +} + +/// How a row's `data` is damaged: what is stored, as which storage class, and +/// the text of it that must never be repeated. +struct Damage { + label: &'static str, + value: Value, + /// `CAST(? AS TEXT)`: the bytes are stored as TEXT, not as a BLOB. + as_text: bool, + secret: String, + /// What the store says of it, when it reads it as JSON. + damage: Option, +} + +fn damages() -> Vec { + let (cut, cut_key) = json_with_a_cut_key(); + let (cut_short, whole_key) = json_cut_inside_its_key(); + let mut not_utf8 = format!(r#"{{"key":"{SECRET}","counter":1}}"#).into_bytes(); + not_utf8.push(0xff); + vec![ + Damage { + label: "a key that does not import", + value: Value::Text(cut), + as_text: false, + secret: cut_key, + damage: Some(IdentityDamage::NotAnIdentity), + }, + Damage { + label: "a field of the wrong type", + value: Value::Text(json_with_a_counter_of_the_wrong_type()), + as_text: false, + secret: SECRET.to_owned(), + damage: Some(IdentityDamage::NotAnIdentity), + }, + Damage { + label: "syntax", + value: Value::Text(format!("not json: {SECRET}")), + as_text: false, + secret: SECRET.to_owned(), + damage: Some(IdentityDamage::Malformed), + }, + Damage { + label: "cut short", + value: Value::Text(cut_short), + as_text: false, + secret: whole_key, + damage: Some(IdentityDamage::CutShort), + }, + Damage { + label: "bytes that are no UTF-8, stored as a BLOB", + value: Value::Blob(not_utf8.clone()), + as_text: false, + secret: SECRET.to_owned(), + damage: None, + }, + Damage { + label: "bytes that are no UTF-8, stored as TEXT", + value: Value::Blob(not_utf8), + as_text: true, + secret: SECRET.to_owned(), + damage: None, + }, + ] +} + +/// Fail if `text` holds any 8 characters in a row of `secret`. +fn assert_holds_no_piece_of(text: &str, secret: &str, what: &str) { + assert!(secret.len() >= 8 && secret.is_ascii()); + for piece in secret.as_bytes().windows(8) { + let piece = std::str::from_utf8(piece).unwrap(); + assert!(!text.contains(piece), "{what}: {text:?} holds {piece:?} of the row's data"); + } +} + +/// The texts an error shows to a caller: how it reads, its `Debug` text and +/// those of everything it was caused by. +fn texts_of(error: &(dyn std::error::Error + 'static)) -> Vec { + let mut texts = vec![error.to_string(), format!("{error:?}")]; + let mut source = error.source(); + while let Some(cause) = source { + texts.push(cause.to_string()); + texts.push(format!("{cause:?}")); + source = cause.source(); + } + texts +} + +fn binding() -> AccountBinding { + let account = account_uid(&Uid::from_bytes([1; 32]), &AccountId::from_bytes([2; 16])); + AccountBinding { + account, + integration: Some(IntegrationId::from_bytes([7; 16])), + rev: 3, + synced: false, + } +} + +/// A database file with one TeamSpeak identity, its `data` replaced by `damage` +/// through a second connection. Returns the id and uid of the row. +fn damaged_database(scratch: &Scratch, damage: &Damage) -> (i64, String) { + let store = Store::open(&scratch.db()).unwrap(); + let identity = Identity::create(); + let id = store.add_identity("damaged", &identity, IdentityOrigin::User).unwrap(); + let uid = identity.key().to_pub().get_uid(); + drop(store); + + let db = Connection::open(scratch.db()).unwrap(); + let sql = if damage.as_text { + "UPDATE identities SET data = CAST(?1 AS TEXT) WHERE id = ?2" + } else { + "UPDATE identities SET data = ?1 WHERE id = ?2" + }; + assert_eq!(db.execute(sql, params![damage.value, id]).unwrap(), 1); + (id, uid) +} + +#[test] +fn the_json_readers_own_message_quotes_what_it_refuses() { + // Without this the cases below could not fail: serde's message for a key + // that does not import and for a field of the wrong type repeats the value. + let (json, cut_key) = json_with_a_cut_key(); + let raw = serde_json::from_str::(&json).unwrap_err().to_string(); + assert!(raw.contains(&cut_key), "the reader's own message quotes the key: {raw}"); + let typed = json_with_a_counter_of_the_wrong_type(); + let raw = serde_json::from_str::(&typed).unwrap_err().to_string(); + assert!(raw.contains(SECRET), "the reader's own message quotes the value: {raw}"); +} + +#[test] +fn a_damaged_identity_row_is_reported_by_its_kind_of_damage_and_never_by_its_text() { + for damage in damages() { + let scratch = Scratch::new("store"); + let (id, _) = damaged_database(&scratch, &damage); + let label = damage.label; + let store = Store::open(&scratch.db()).unwrap(); + + let ((one, all, default), lines) = support::at_trace(|| { + ( + store.identity(id).unwrap_err(), + store.identities().unwrap_err(), + store.default_identity().unwrap_err(), + ) + }); + for (call, error) in [("identity", &one), ("identities", &all), ("default", &default)] { + for text in texts_of(error) { + assert_holds_no_piece_of(&text, &damage.secret, &format!("{label}: {call}")); + } + if let Some(expected) = damage.damage { + // The kind of damage and where, in the store's own words. + match error { + Error::Identity { damage, line, column } => { + assert_eq!(*damage, expected, "{label}: {call}"); + assert_eq!((*line, *column > 0), (1, true), "{label}: {call}: {error}"); + let shown = error.to_string(); + assert!( + shown.starts_with(&format!( + "the stored TeamSpeak identity cannot be read: {expected} at line 1, column " + )), + "{label}: {call}: {shown}" + ); + } + other => panic!("{label}: {call}: {other:?}"), + } + } + } + for line in &lines { + assert_holds_no_piece_of(line, &damage.secret, &format!("{label}: a log line")); + } + } +} + +#[test] +fn a_damaged_identity_row_does_not_leak_through_the_key_store_either() { + for damage in damages() { + let scratch = Scratch::new("keystore"); + let (_id, uid) = damaged_database(&scratch, &damage); + let label = damage.label; + let store = SqliteKeyStore::open(&scratch.db()).unwrap(); + + // Everything that reads or writes the row, in the order a sign-out would, + // with the errors and the logs of all of it kept. + let (results, lines) = support::at_trace(|| { + let mut errors: Vec> = Vec::new(); + let mut note = |result: Result<(), voelin_identity::KeyStoreError>| { + if let Err(error) = result { + errors.push(Box::new(error)); + } + }; + let listed = store.list().unwrap(); + let entry = listed.iter().find(|info| info.uid == uid).expect("the row is listed"); + assert_eq!(entry.level, 0, "{label}: damage reads as level 0"); + + // What `get` hands out is the data itself; a `put` of it rebinds the row. + let blob = store.get(KIND_TEAMSPEAK, &uid).unwrap().expect("the row is read"); + note(store.put(&blob.clone().with_binding(binding()))); + // Other data over the row is checked and refused, and the refusal does + // not repeat it. + let other = format!(r#"{{"key":"{SECRET}","counter":"{OTHER_SECRET}"}}"#); + note(store.put(&IdentityBlob::from_row(KIND_TEAMSPEAK, uid.clone(), 0, other))); + note(store.put(&IdentityBlob::teamspeak(uid.clone(), 8, SECRET))); + // The sign-out that unbinds it, and the delete that removes it. + store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap(); + store.remove(KIND_TEAMSPEAK, &uid).unwrap(); + errors + }); + assert_eq!(results.len(), 2, "{label}: the two refusals: {results:?}"); + for error in &results { + for text in texts_of(error.as_ref()) { + assert_holds_no_piece_of(&text, &damage.secret, &format!("{label}: a refusal")); + assert_holds_no_piece_of( + &text, + SECRET, + &format!("{label}: a refusal of other data"), + ); + assert_holds_no_piece_of(&text, OTHER_SECRET, &format!("{label}: other data")); + } + } + for line in &lines { + assert_holds_no_piece_of(line, &damage.secret, &format!("{label}: a log line")); + assert_holds_no_piece_of(line, SECRET, &format!("{label}: a log line, other data")); + } + } +} + +#[test] +fn the_capture_sees_what_the_store_logs() { + // A control for the cases above: a row whose binding columns are damaged is + // listed with a warning that names it, and the capture takes it in at TRACE. + let scratch = Scratch::new("control"); + let store = SqliteKeyStore::open(&scratch.db()).unwrap(); + let blob = IdentityBlob::new("future", "future:one", 0, format!(r#"{{"secret":"{SECRET}"}}"#)); + store.put(&blob).unwrap(); + let db = Connection::open(scratch.db()).unwrap(); + assert_eq!( + db.execute("UPDATE identities SET synced = 2 WHERE kind = 'future'", []).unwrap(), + 1 + ); + + let (listed, lines) = support::at_trace(|| store.list().unwrap()); + assert_eq!(listed.len(), 1); + let warning = lines + .iter() + .find(|line| line.contains("the binding columns of an identity cannot be read")) + .unwrap_or_else(|| panic!("no warning in {lines:?}")); + assert!(warning.starts_with("WARN "), "{warning}"); + assert!(warning.contains("future:one"), "{warning}"); + // And it does not carry the row's data either. + for line in &lines { + assert_holds_no_piece_of(line, SECRET, "a log line"); + } +} diff --git a/crates/voelin-store/tests/keystore.rs b/crates/voelin-store/tests/keystore.rs index 5da0b3e..cb1b595 100644 --- a/crates/voelin-store/tests/keystore.rs +++ b/crates/voelin-store/tests/keystore.rs @@ -31,6 +31,8 @@ use voelin_identity::{ }; use voelin_store::{IdentityOrigin, SqliteKeyStore, Store}; +mod support; + /// What `serde_json::to_string(&tsproto::Identity)` writes for the test /// identity of tsproto's own `identity_tests`. const TEAMSPEAK_JSON: &str = r#"{"key":"YTyJofmztcTBjq3KZcDdxu+G4RPVwE5vg8VaN2jbQao=","counter":2792354,"max_counter":2792354}"#; @@ -803,8 +805,9 @@ fn the_record_fixture_is_what_the_protocol_writes() { } #[test] -fn signing_out_deletes_the_copies_and_keeps_the_device_secrets() { - // The device key was made for the account: signing out deletes it. +fn signing_out_deletes_the_copies_and_keeps_the_keys_and_the_device_secrets() { + // The device key was made for the account: signing out keeps it all the + // same, unbound (open question 10 of the accounts design). let Install { store, synced, device_only, local } = signed_in_install(false); let mine = binding().account; let theirs = account_uid(&issuer(), &AccountId::from_bytes([9; 16])); @@ -815,19 +818,20 @@ fn signing_out_deletes_the_copies_and_keeps_the_device_secrets() { 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()), - ]; + let mut expected_removed = vec![(KIND_ACCOUNT.to_owned(), record().blob_uid()), pair(&synced)]; expected_removed.sort(); assert_eq!(sorted(done.removed.clone()), expected_removed, "{done:?}"); - assert_eq!(done.unbound, vec![info_of(&device_only.clone().with_binding(None))]); + assert_eq!( + sorted(done.unbound.clone()), + sorted(vec![device_key_info(), info_of(&device_only.clone().with_binding(None))]), + "{done:?}" + ); - // What is left: the device secret unbound and byte for byte as it was, the - // local and the other account's identities as they were, the other key. + // What is left: the device key, the device secret unbound and byte for + // byte as it was, the local and the other account's identities as they + // were, the other key. assert!(store.get(KIND_TEAMSPEAK, &synced.uid).unwrap().is_none()); - assert!(store.voelin_key(&key().uid()).unwrap().is_none()); + assert_eq!(store.voelin_key(&key().uid()).unwrap().unwrap().uid(), key().uid()); assert_eq!(store.account_record().unwrap(), None); let kept = store.get(KIND_TEAMSPEAK, &device_only.uid).unwrap().unwrap(); assert_eq!(kept, device_only.clone().with_binding(None)); @@ -835,11 +839,11 @@ fn signing_out_deletes_the_copies_and_keeps_the_device_secrets() { 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); + assert_eq!(store.list().unwrap().len(), 5); // Signing out again finds nothing to do. assert_eq!(store.sign_out(&mine, DeviceKeyChoice::Auto).unwrap(), SignOut::default()); - assert_eq!(store.list().unwrap().len(), 4); + assert_eq!(store.list().unwrap().len(), 5); // Another account's sign-out acts on that account's identities only. assert_eq!( store.sign_out(&theirs, DeviceKeyChoice::Auto).unwrap().removed, @@ -892,17 +896,38 @@ fn signing_out_keeps_a_device_key_that_predates_the_account() { } #[test] -fn signing_out_deletes_a_device_key_the_client_made_for_the_account() { +fn signing_out_keeps_a_device_key_the_client_made_for_the_account_too() { + // Open question 10 of the accounts design (answered 2026-10-24): a key that + // the client made for the account is the user's identity at every host + // without accounts that the user reached with it as well, so `Auto` keeps + // it like a key that predates the account. Only `Forget` deletes it. let Install { store, device_only, local, .. } = signed_in_install(false); + let key_before = store.get(KIND_VOELIN, &key().uid().to_base32()).unwrap().unwrap(); + let signature = key().sign(b"the same key, signed before and after"); + let done = store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap(); - assert!(done.removed.contains(&device_key_info()), "{done:?}"); - assert!(!done.unbound.contains(&device_key_info()), "{done:?}"); - assert!(store.voelin_key(&key().uid()).unwrap().is_none()); + assert!(!done.removed.contains(&device_key_info()), "{done:?}"); + assert!(done.unbound.contains(&device_key_info()), "{done:?}"); + let kept = store.voelin_key(&key().uid()).unwrap().expect("the key stays"); + assert_eq!(kept.sign(b"the same key, signed before and after"), signature); + let key_after = store.get(KIND_VOELIN, &key().uid().to_base32()).unwrap().unwrap(); + assert_eq!(key_after, key_before, "the stored blob is untouched"); + assert_eq!(key_after.binding, None); let mut left = sorted(store.list().unwrap()); left.sort(); - let mut expected = vec![pair(&device_only), pair(&local)]; + let mut expected = vec![pair(&device_only), pair(&local), pair(&key_after)]; expected.sort(); - assert_eq!(left, expected, "the device secret and the local one"); + assert_eq!(left, expected, "the key, the device secret and the local one"); + + // The flag changes nothing: a key that predates the account gets the same + // treatment. (The other identities of the two installs are fresh ones, so + // the reports differ in them.) + let existing = signed_in_install(true); + let again = existing.store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap(); + assert!(again.unbound.contains(&device_key_info()), "{again:?}"); + assert!(!again.removed.contains(&device_key_info()), "{again:?}"); + assert_eq!(again.removed.len(), done.removed.len()); + assert_eq!(again.unbound.len(), done.unbound.len()); } #[test] @@ -1282,16 +1307,10 @@ impl OnFile { /// What a sign-out of `choice` must have done, whatever else was damaged: /// the record and the synced copy are gone, the device-only secret is /// unbound and the local identity is as it was; the device key is deleted - /// when the user forgot it or the client made it for the account, and - /// reported as kept and unbound otherwise. - fn assert_signed_out( - &self, - done: &SignOut, - bound_existing_key: bool, - choice: DeviceKeyChoice, - label: &str, - ) { - let key_goes = matches!(choice, DeviceKeyChoice::Forget(_)) || !bound_existing_key; + /// when the user forgot it, and reported as kept and unbound otherwise, + /// whether it predates the account or not. + fn assert_signed_out(&self, done: &SignOut, choice: DeviceKeyChoice, label: &str) { + let key_goes = matches!(choice, DeviceKeyChoice::Forget(_)); let mut removed = vec![(KIND_ACCOUNT.to_owned(), record().blob_uid()), pair(&self.synced)]; let mut unbound = vec![pair(&self.device_only)]; let device_key = (KIND_VOELIN.to_owned(), key().uid().to_base32()); @@ -1335,7 +1354,7 @@ const RECORD_ROW_DAMAGE: [&str; 5] = [ fn a_damaged_account_record_row_does_not_keep_a_sign_out_from_finishing() { // The record carries no binding, so damage in those columns says nothing // about the record: it is read, and the sign-out does what it always does. - // `Forget` deletes the key it names; `Auto` follows the record. + // `Forget` deletes the key it names; `Auto` keeps it. for bound_existing_key in [true, false] { for damage in RECORD_ROW_DAMAGE { for choice in [DeviceKeyChoice::Auto, DeviceKeyChoice::Forget(key().uid())] { @@ -1346,7 +1365,7 @@ fn a_damaged_account_record_row_does_not_keep_a_sign_out_from_finishing() { .store .sign_out(&binding().account, choice) .unwrap_or_else(|error| panic!("{label}: {error}")); - install.assert_signed_out(&done, bound_existing_key, choice, &label); + install.assert_signed_out(&done, choice, &label); } } } @@ -1354,8 +1373,9 @@ fn a_damaged_account_record_row_does_not_keep_a_sign_out_from_finishing() { #[test] fn a_damaged_device_key_row_does_not_keep_a_sign_out_from_finishing() { - // With `Auto` and a key that predates the account, the trait reads the key - // to report it as kept. Damage in its binding columns must not fail that. + // With `Auto` the trait reads the key to report it as kept, whether it + // predates the account or not. Damage in its binding columns must not fail + // that. for bound_existing_key in [true, false] { for damage in [ "UPDATE identities SET synced = 2 WHERE kind = 'voelin'", @@ -1369,12 +1389,10 @@ fn a_damaged_device_key_row_does_not_keep_a_sign_out_from_finishing() { .store .sign_out(&binding().account, DeviceKeyChoice::Auto) .unwrap_or_else(|error| panic!("{label}: {error}")); - install.assert_signed_out(&done, bound_existing_key, DeviceKeyChoice::Auto, &label); - if bound_existing_key { - // The key was kept, as it was stored. - let kept = install.store.voelin_key(&key().uid()).unwrap().unwrap(); - assert_eq!(&kept.to_pkcs8().unwrap()[..], &key().to_pkcs8().unwrap()[..]); - } + install.assert_signed_out(&done, DeviceKeyChoice::Auto, &label); + // The key was kept, as it was stored. + let kept = install.store.voelin_key(&key().uid()).unwrap().unwrap(); + assert_eq!(&kept.to_pkcs8().unwrap()[..], &key().to_pkcs8().unwrap()[..]); } } } @@ -1423,7 +1441,7 @@ fn an_account_row_whose_data_is_not_text_is_deleted_like_an_unreadable_record() assert!(store.get(KIND_TEAMSPEAK, &install.synced.uid).unwrap().is_none(), "{label}"); let secret = store.get(KIND_TEAMSPEAK, &install.device_only.uid).unwrap().unwrap(); assert_eq!(secret.binding, None, "{label}"); - // `Auto` cannot find the key the record named, and keeps it. + // `Auto` keeps the key, as it always does; `Forget` deleted it first. let forgot = matches!(choice, DeviceKeyChoice::Forget(_)); assert_eq!(store.voelin_key(&key().uid()).unwrap().is_none(), forgot, "{label}"); assert_eq!(store.sign_out(&binding().account, choice).unwrap(), SignOut::default()); @@ -1623,14 +1641,13 @@ fn key_text(json: &str, field: &str) -> String { } #[test] -fn a_key_deleted_by_a_sign_out_is_in_neither_the_database_file_nor_its_log() { - // The device key the client made for the account goes with `Auto`, and a - // key that predates the account goes when the user forgets it. Either way - // its PKCS#8 text, and a synced TeamSpeak copy's key, must not stay in the - // free pages of `client.db` or in a frame of `client.db-wal`. - for (bound_existing_key, choice) in - [(false, DeviceKeyChoice::Auto), (true, DeviceKeyChoice::Forget(key().uid()))] - { +fn a_key_forgotten_by_a_sign_out_is_in_neither_the_database_file_nor_its_log() { + // The device key goes when the user forgets it, whether it predates the + // account or the client made it for the account. Its PKCS#8 text, and a + // synced TeamSpeak copy's key, must not stay in the free pages of + // `client.db` or in a frame of `client.db-wal`. + for bound_existing_key in [true, false] { + let choice = DeviceKeyChoice::Forget(key().uid()); let scratch = Scratch::new("scrub-signout"); let store = SqliteKeyStore::open(&scratch.db()).unwrap(); let device = IdentityBlob::voelin(&key()).unwrap(); @@ -1697,13 +1714,23 @@ fn removing_through_the_key_store_leaves_no_key_behind_either() { } #[test] -fn a_reader_that_blocks_the_checkpoint_costs_milliseconds_and_starves_no_writer() { +fn a_reader_that_blocks_the_checkpoint_costs_one_checkpoint_and_starves_no_writer() { // A connection that keeps a read snapshot (a long query of the UI, a backup) // keeps the checkpoint that truncates the log from finishing. The sign-out - // still deletes and warns that the bytes may stay in the log, and it waits - // for the checkpoint a moment, not for the busy timeout of five seconds once - // per removed row. While the checkpoint waits it holds the writer lock of the - // log, so a second connection that writes meanwhile must get through. + // still deletes and warns that the bytes may stay in the log, and it makes + // one checkpoint for all its removals, not one per removed row. While the + // checkpoint waits it holds the writer lock of the log, so a second + // connection that writes meanwhile must get through. + // + // No clock decides anything here. A checkpoint ends in two fsyncs, and under + // disk pressure (a build or a copy writing beside the tests) they take + // seconds: the review saw sign-outs of 1.2 to 1.9 s at 10 to 30 % I/O + // pressure, and `dd conv=fsync` loops beside 32 busy loops made them 5 s. A + // bound on the sign-out or a short busy timeout on the writer failed this + // test with "database is locked" for a checkpoint that was only slow. That a + // checkpoint gives up on a reader after a moment and does not wait out the + // connection's busy timeout is pinned where that timeout can be set to an + // hour: `store::tests::a_blocked_checkpoint_waits_briefly_and_leaves_the_busy_timeout_as_it_was`. let scratch = Scratch::new("blocked-checkpoint"); let store = SqliteKeyStore::open(&scratch.db()).unwrap(); store.put_voelin_key(&key()).unwrap(); @@ -1718,37 +1745,71 @@ fn a_reader_that_blocks_the_checkpoint_costs_milliseconds_and_starves_no_writer( let rows: i64 = reader.query_row("SELECT count(*) FROM identities", [], |r| r.get(0)).unwrap(); assert_eq!(rows, 4); + /// Stops the writer when dropped, so that a failed assertion of the test does + /// not leave the scope waiting for it. + struct StopsTheWriter<'a>(&'a AtomicBool); + impl Drop for StopsTheWriter<'_> { + fn drop(&mut self) { + self.0.store(true, Ordering::Relaxed); + } + } let stop = AtomicBool::new(false); - let (done, elapsed, writes, errors) = std::thread::scope(|scope| { + let written = AtomicUsize::new(0); + let (done, elapsed, errors, lines) = std::thread::scope(|scope| { + let _stops = StopsTheWriter(&stop); let writer = scope.spawn(|| { - // Its own connection, which gives up on a lock after one second. + // Its own connection, set up as the app's are (`Store::open`: the log + // and `synchronous = NORMAL`, so that a commit does not wait for the + // disk), with a busy timeout that a slow checkpoint does not reach. let db = Connection::open(scratch.db()).unwrap(); - db.busy_timeout(Duration::from_secs(1)).unwrap(); + db.pragma_update(None, "synchronous", "NORMAL").unwrap(); + db.busy_timeout(Duration::from_secs(60)).unwrap(); let sql = "INSERT OR REPLACE INTO settings (key, value) VALUES ('probe', ?1)"; - let (mut writes, mut errors) = (0, Vec::new()); + let mut errors = Vec::new(); while !stop.load(Ordering::Relaxed) { - match db.execute(sql, [writes.to_string()]) { - Ok(_) => writes += 1, + let began = Instant::now(); + match db.execute(sql, [written.load(Ordering::Relaxed).to_string()]) { + Ok(_) => { + written.fetch_add(1, Ordering::Relaxed); + } Err(error) => errors.push(error.to_string()), } - std::thread::sleep(Duration::from_millis(5)); + // It pauses ten times as long as the write took, and 5 ms at least. + // Under disk pressure a commit takes 100 ms and more, and a writer + // that paused 5 ms after each would hold the writer lock nearly all + // the time and keep the sign-out, whose busy timeout is the default + // five seconds, from getting it (`DatabaseBusy`). + let wake = Instant::now() + (began.elapsed() * 10).max(Duration::from_millis(5)); + while Instant::now() < wake && !stop.load(Ordering::Relaxed) { + std::thread::sleep(Duration::from_millis(1)); + } } - (writes, errors) + errors }); + // The sign-out starts when the writer is up and has written, not when + // the thread was spawned: a thread of a busy machine can start late. + let deadline = Instant::now() + Duration::from_secs(60); + while written.load(Ordering::Relaxed) == 0 { + assert!(Instant::now() < deadline, "the writer never ran"); + std::thread::sleep(Duration::from_millis(1)); + } let started = Instant::now(); - let done = store.sign_out(&binding().account, DeviceKeyChoice::Auto); + let (done, lines) = support::at_trace(|| { + store.sign_out(&binding().account, DeviceKeyChoice::Forget(key().uid())) + }); let elapsed = started.elapsed(); stop.store(true, Ordering::Relaxed); - let (writes, errors) = writer.join().unwrap(); - (done.unwrap(), elapsed, writes, errors) + let errors = writer.join().unwrap(); + (done.unwrap(), elapsed, errors, lines) }); - // Four removals: the two copies, the device key the client made, the record. + // Four removals: the two copies, the device key the user forgot, the record. assert_eq!(done.removed.len(), 4, "{done:?}"); assert!(store.list().unwrap().is_empty()); - assert!(writes > 0, "the writer never ran"); assert!(errors.is_empty(), "a concurrent writer failed: {errors:?}"); - assert!(elapsed < Duration::from_secs(1), "the sign-out took {elapsed:?}"); + // One checkpoint for the four removals: each one that is blocked says so. + let blocked = support::blocked_checkpoints(&lines); + assert_eq!(blocked, 1, "{lines:?} (the sign-out took {elapsed:?})"); // Nothing is lost by the wait: once the reader is gone, the next removal // truncates the log. @@ -1758,6 +1819,245 @@ fn a_reader_that_blocks_the_checkpoint_costs_milliseconds_and_starves_no_writer( assert!(RawFiles::read(&scratch).wal.is_empty(), "the log is truncated again"); } +// ------------------------- the keys a sign-out keeps, and the one the user forgets +// +// Open question 10 of the accounts design (Phase 2 task 34): a sign-out keeps +// every device key, and "Forget this device's identity" is the only deletion. + +/// Every column of the row of this `(kind, uid)` as SQLite holds it, by name. +fn named_row(db: &Connection, kind: &str, uid: &str) -> Vec<(String, rusqlite::types::Value)> { + db.query_row( + "SELECT * FROM identities WHERE kind = ?1 AND uid = ?2", + params![kind, uid], + |row| { + let names: Vec = + row.as_ref().column_names().iter().map(|n| n.to_string()).collect(); + names + .into_iter() + .enumerate() + .map(|(index, name)| Ok((name, row.get(index)?))) + .collect::>>() + }, + ) + .unwrap() +} + +#[test] +fn the_device_key_survives_a_sign_out_byte_for_byte_in_the_file() { + // Whether it predates the account or the client made it for the account, no + // column of its row changes: the key never carried a binding, and a sign-out + // writes nothing to it. + for bound_existing_key in [true, false] { + let install = signed_in_install_on_file(bound_existing_key); + let uid = key().uid().to_base32(); + let db = Connection::open(install.scratch.db()).unwrap(); + let before = named_row(&db, KIND_VOELIN, &uid); + assert!(before.len() >= 8, "{before:?}"); + + let done = install.store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap(); + assert!(done.unbound.contains(&device_key_info()), "{bound_existing_key}: {done:?}"); + assert!(!done.removed.contains(&device_key_info()), "{bound_existing_key}: {done:?}"); + assert_eq!(named_row(&db, KIND_VOELIN, &uid), before, "{bound_existing_key}"); + let kept = install.store.voelin_key(&key().uid()).unwrap().unwrap(); + assert_eq!(&kept.to_pkcs8().unwrap()[..], &key().to_pkcs8().unwrap()[..]); + } +} + +#[test] +fn a_device_key_that_carries_a_binding_is_unbound_and_keeps_the_rest_of_its_row() { + // The store accepts a binding with `synced = false` on the device key (a + // binding with `synced = true` is refused, see the last section). A sign-out + // unbinds it and keeps it: the four binding columns are the only ones that + // change. + const BINDING_COLUMNS: [&str; 4] = ["account", "integration", "integration_rev", "synced"]; + for bound_existing_key in [true, false] { + let install = signed_in_install_on_file(bound_existing_key); + let uid = key().uid().to_base32(); + let device_only = AccountBinding { synced: false, ..binding() }; + install + .store + .put(&IdentityBlob::voelin(&key()).unwrap().with_binding(device_only)) + .unwrap(); + let db = Connection::open(install.scratch.db()).unwrap(); + let before = named_row(&db, KIND_VOELIN, &uid); + let bound = |row: &[(String, rusqlite::types::Value)]| { + row.iter().any(|(name, value)| { + name == "account" && !matches!(value, rusqlite::types::Value::Null) + }) + }; + assert!(bound(&before), "the setup binds the key"); + + let done = install.store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap(); + assert!(done.unbound.contains(&device_key_info()), "{bound_existing_key}: {done:?}"); + assert!(!done.removed.contains(&device_key_info()), "{bound_existing_key}: {done:?}"); + + let after = named_row(&db, KIND_VOELIN, &uid); + assert!(!bound(&after), "{bound_existing_key}: unbound"); + assert_eq!(before.len(), after.len()); + for ((name, was), (_, is)) in before.iter().zip(&after) { + if !BINDING_COLUMNS.contains(&name.as_str()) { + assert_eq!(is, was, "{bound_existing_key}: column {name} is not a binding column"); + } + } + let stored = install.store.get(KIND_VOELIN, &uid).unwrap().unwrap(); + assert_eq!(stored, IdentityBlob::voelin(&key()).unwrap()); + assert!(install.store.bound_to(&binding().account).unwrap().is_empty()); + } +} + +#[test] +fn a_sign_out_scrubs_the_copies_it_deletes_and_leaves_the_kept_keys_in_the_file() { + // What a sign-out still deletes is a synced copy (a private key, which + // the service holds again) and the record: those are gone from the file and + // its log. The device key and the device-only secret are kept, so their text + // is still there. + let scratch = Scratch::new("scrub-keeps"); + let store = SqliteKeyStore::open(&scratch.db()).unwrap(); + let device = IdentityBlob::voelin(&key()).unwrap(); + let synced = fresh_teamspeak(binding()); + let device_only = fresh_teamspeak(AccountBinding { synced: false, ..binding() }); + let device_text = key_text(&device.json, "pkcs8"); + let (synced_text, device_only_text) = + (key_text(&synced.json, "key"), key_text(&device_only.json, "key")); + for blob in [&device, &synced, &device_only] { + store.put(blob).unwrap(); + } + store.put_account_record(&AccountRecord { bound_existing_key: false, ..record() }).unwrap(); + let neighbour = Store::open(&scratch.db()).unwrap(); + let before = RawFiles::read(&scratch); + assert!(before.holds(&device_text) && before.holds(&synced_text)); + + store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap(); + let after = RawFiles::read(&scratch); + assert_eq!(after.where_is(&synced_text), (false, false), "the synced copy"); + assert!(after.holds(&device_text), "the device key is kept"); + assert!(after.holds(&device_only_text), "the device-only secret is kept"); + assert!(after.wal.is_empty(), "the log is truncated"); + drop(neighbour); +} + +#[test] +fn a_sign_out_that_deletes_nothing_does_not_checkpoint() { + // With no record and no synced copy a sign-out only unbinds. The checkpoint + // belongs to deletions: with a reader that blocks it, a deletion says so, and + // the sign-out does not. + let scratch = Scratch::new("no-deletion"); + let store = SqliteKeyStore::open(&scratch.db()).unwrap(); + let device_only = fresh_teamspeak(AccountBinding { synced: false, ..binding() }); + store.put(&device_only).unwrap(); + let reader = Connection::open(scratch.db()).unwrap(); + reader.execute_batch("BEGIN").unwrap(); + let rows: i64 = reader.query_row("SELECT count(*) FROM identities", [], |r| r.get(0)).unwrap(); + assert_eq!(rows, 1); + + let (done, lines) = + support::at_trace(|| store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap()); + assert!(done.removed.is_empty(), "{done:?}"); + assert_eq!(done.unbound, vec![info_of(&device_only.clone().with_binding(None))]); + assert_eq!(support::blocked_checkpoints(&lines), 0, "{lines:?}"); + + // The same reader does block the checkpoint of a deletion, so the count above + // would have shown one. + store.put_voelin_key(&key()).unwrap(); + let (removed, lines) = + support::at_trace(|| store.remove(KIND_VOELIN, &key().uid().to_base32()).unwrap()); + assert!(removed); + assert_eq!(support::blocked_checkpoints(&lines), 1, "{lines:?}"); + reader.execute_batch("COMMIT").unwrap(); +} + +#[test] +fn a_key_kept_by_a_sign_out_is_exported_and_then_forgotten_without_a_trace() { + // The flow of "Forget this device's identity" after a sign-out: the key is + // still there, unbound; the UI exports it, then deletes it. The export is + // what `voelin_key` and `to_pkcs8` give, and it restores the key. + let scratch = Scratch::new("export-forget"); + let store = SqliteKeyStore::open(&scratch.db()).unwrap(); + store.put_voelin_key(&key()).unwrap(); + store.put_account_record(&AccountRecord { bound_existing_key: false, ..record() }).unwrap(); + store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap(); + let uid = key().uid(); + let stored = store.get(KIND_VOELIN, &uid.to_base32()).unwrap().unwrap(); + let text = key_text(&stored.json, "pkcs8"); + + let exported = store.voelin_key(&uid).unwrap().expect("the key is there").to_pkcs8().unwrap(); + assert!(RawFiles::read(&scratch).holds(&text)); + assert!(store.remove(KIND_VOELIN, &uid.to_base32()).unwrap()); + assert!(store.voelin_key(&uid).unwrap().is_none()); + let after = RawFiles::read(&scratch); + assert_eq!(after.where_is(&text), (false, false), "nothing of the key is left"); + assert!(after.wal.is_empty(), "the log is truncated"); + + // The export brings the same key back. + let restored = IdentityKey::from_pkcs8(&exported).unwrap(); + assert_eq!(restored.uid(), uid); + assert_eq!(restored.sign(b"the exported key"), key().sign(b"the exported key")); + store.put_voelin_key(&restored).unwrap(); + assert_eq!(store.get(KIND_VOELIN, &uid.to_base32()).unwrap().unwrap(), stored); +} + +// ------------------------------------------ releasing the device key from its account +// +// `AccountClient::release` asks the service to release the key and then runs the +// local sign-out with `Auto` (protocol 13.6, "Releasing this device's key"), so +// the store's part is the sign-out of the tests above, and the key has to be +// usable for another account afterwards. + +#[test] +fn the_local_half_of_a_release_keeps_the_key_and_it_serves_another_account() { + let Install { store, .. } = signed_in_install(false); + let uid = key().uid().to_base32(); + let before = store.get(KIND_VOELIN, &uid).unwrap().unwrap(); + let signature = key().sign(b"the same key, before and after the release"); + + // The service released the key; the device finishes with a local sign-out. + let done = store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap(); + assert!(done.unbound.contains(&device_key_info()), "{done:?}"); + assert!(!done.removed.contains(&device_key_info()), "{done:?}"); + assert_eq!(store.get(KIND_VOELIN, &uid).unwrap().unwrap(), before, "byte for byte"); + assert_eq!(store.account_record().unwrap(), None); + + // The key is registered with no account and signs up for another one: its + // record names the same key, and a copy of the new account's material is + // bound to it. + let other_id = AccountId::from_bytes([42; 16]); + let other = AccountRecord { account_id: other_id, login: "bob".into(), ..record() }; + store.put_account_record(&other).unwrap(); + assert_eq!(store.account_record().unwrap(), Some(other.clone())); + let other_binding = AccountBinding { account: account_uid(&issuer(), &other_id), ..binding() }; + let other_copy = fresh_teamspeak(other_binding); + store.put(&other_copy).unwrap(); + + // Signing out of the new account keeps the key again, and the copy goes. + let done = store.sign_out(&other_binding.account, DeviceKeyChoice::Auto).unwrap(); + assert!(done.unbound.contains(&device_key_info()), "{done:?}"); + assert!(done.removed.contains(&info_of(&other_copy)), "{done:?}"); + let kept = store.voelin_key(&key().uid()).unwrap().expect("the key stays"); + assert_eq!(kept.sign(b"the same key, before and after the release"), signature); + assert_eq!(store.get(KIND_VOELIN, &uid).unwrap().unwrap(), before, "byte for byte"); +} + +#[test] +fn a_release_whose_local_half_was_cut_short_is_finished_by_a_sign_out() { + // The service released the device and the call was dropped before the local + // sign-out took the slot: the record and the copies are still here, and the + // key is still the record's device key. A sign-out with `Auto` finishes it + // and keeps the key; running it again finds nothing to do. + let Install { store, synced, device_only, .. } = signed_in_install(true); + let uid = key().uid().to_base32(); + let before = store.get(KIND_VOELIN, &uid).unwrap().unwrap(); + + let done = store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap(); + assert!(done.removed.contains(&info_of(&synced)), "{done:?}"); + assert!(done.unbound.contains(&info_of(&device_only.clone().with_binding(None))), "{done:?}"); + assert_eq!(store.account_record().unwrap(), None); + assert_eq!(store.get(KIND_VOELIN, &uid).unwrap().unwrap(), before); + assert_eq!( + store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap(), + SignOut::default() + ); +} + // -------------------------------------- the device key is never a synced copy // // `KeyStore::sign_out` deletes everything bound with `synced = true` in its @@ -1798,15 +2098,15 @@ fn a_synced_binding_on_the_device_key_is_refused_with_a_precise_error() { assert_eq!(store.list().unwrap().iter().filter(|i| i.binding.is_some()).count(), 0); // A binding that is not synced is a device-only secret: accepted, and a - // sign-out unbinds it and keeps it (or deletes it, as the record says). + // sign-out unbinds it and keeps it. let device_only = AccountBinding { synced: false, ..binding() }; store.put(&IdentityBlob::voelin(&key()).unwrap().with_binding(device_only)).unwrap(); store.put(&before).unwrap(); - // So the sign-out still does what the record says with the key. + // So the sign-out keeps the key, whether it predates the account or not. let done = store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap(); - assert_eq!(done.unbound.contains(&device_key_info()), bound_existing_key, "{done:?}"); - assert_eq!(store.voelin_key(&key().uid()).unwrap().is_some(), bound_existing_key); + assert!(done.unbound.contains(&device_key_info()), "{done:?}"); + assert!(store.voelin_key(&key().uid()).unwrap().is_some()); } } diff --git a/crates/voelin-store/tests/support/mod.rs b/crates/voelin-store/tests/support/mod.rs new file mode 100644 index 0000000..4284422 --- /dev/null +++ b/crates/voelin-store/tests/support/mod.rs @@ -0,0 +1,87 @@ +//! Helpers the integration tests of this crate share. + +// Each integration test crate of this directory uses some of these helpers. +#![allow(dead_code)] + +use std::fmt::{self, Write as _}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex, PoisonError}; + +use tracing::field::{Field, Visit}; +use tracing::level_filters::LevelFilter; +use tracing::span::{Attributes, Id, Record}; +use tracing::{Event, Metadata, Subscriber}; + +/// A subscriber that keeps every event and span it sees as one line of text +/// each: level, target and every field with its `Debug` text, as a log line +/// would show them. +struct Capture { + lines: Arc>>, + spans: AtomicU64, +} + +impl Capture { + fn push(&self, line: String) { + self.lines.lock().unwrap_or_else(PoisonError::into_inner).push(line); + } +} + +/// The fields of an event or a span as ` name=value` text. +struct Fields<'a>(&'a mut String); + +impl Visit for Fields<'_> { + fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) { + let _ = write!(self.0, " {}={value:?}", field.name()); + } +} + +impl Subscriber for Capture { + fn enabled(&self, _: &Metadata<'_>) -> bool { + true + } + + fn max_level_hint(&self) -> Option { + Some(LevelFilter::TRACE) + } + + fn new_span(&self, attributes: &Attributes<'_>) -> Id { + let mut line = format!("span {}", attributes.metadata().name()); + attributes.record(&mut Fields(&mut line)); + self.push(line); + Id::from_u64(self.spans.fetch_add(1, Ordering::Relaxed) + 1) + } + + fn record(&self, _: &Id, values: &Record<'_>) { + let mut line = String::from("span record"); + values.record(&mut Fields(&mut line)); + self.push(line); + } + + fn record_follows_from(&self, _: &Id, _: &Id) {} + + fn event(&self, event: &Event<'_>) { + let metadata = event.metadata(); + let mut line = format!("{} {}:", metadata.level(), metadata.target()); + event.record(&mut Fields(&mut line)); + self.push(line); + } + + fn enter(&self, _: &Id) {} + + fn exit(&self, _: &Id) {} +} + +/// Run `f` on this thread with a subscriber that takes in everything logged at +/// TRACE and above, and return what `f` returned with the lines logged. +pub fn at_trace(f: impl FnOnce() -> R) -> (R, Vec) { + let lines = Arc::new(Mutex::new(Vec::new())); + let subscriber = Capture { lines: Arc::clone(&lines), spans: AtomicU64::new(0) }; + let out = tracing::subscriber::with_default(subscriber, f); + let lines = std::mem::take(&mut *lines.lock().unwrap_or_else(PoisonError::into_inner)); + (out, lines) +} + +/// How many of the lines say that a checkpoint was blocked. +pub fn blocked_checkpoints(lines: &[String]) -> usize { + lines.iter().filter(|line| line.contains("another connection blocked the checkpoint")).count() +} diff --git a/docs/architecture.md b/docs/architecture.md index 08a2609..486509f 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -419,33 +419,93 @@ A row whose binding columns cannot be read is listed and read as unbound, with a warning, instead of failing the list; so no damaged row, the account record's included, keeps a sign-out from finishing, and `Forget` still deletes the key it names. -Signing out of an account is the trait's `sign_out`, run on this table: it -removes the account record and the synced copies, unbinds the identities only -this device holds, keeps the device key (unbound, byte for byte) when the -record says it predates the account, and deletes it when it does not or when -the caller asks to forget it. The engine and the UI do not use the key store -yet; accounts, sign-in and the integrations page are later steps. +Signing out of an account is the trait's `sign_out`, run on this table, and it +keeps every key (Phase 2 task 34 of the protocol repository, open question 10 +of its accounts design, answered by the owner on 2026-10-24). The device key +stays, unbound and byte for byte, whether it was in use before the account +existed or the client made it for the account: at every host without accounts +that the user reached with it, it is the user's identity, and deleting it would +lose their servers, roles and memberships there. +`AccountRecord.bound_existing_key` stays in the record for the client's wording, +and no rule reads it. The sign-out unbinds the identities only this device holds +and deletes what is not a key of the device: the account record, and the synced +copies of integration secrets, which the account service holds. It does not +release the device key at the service. The engine and the UI do not use the key +store yet; accounts, sign-in and the integrations page are later steps. -The device key is never a synced copy. The trait's `sign_out` deletes every -identity bound with `synced = true` in its first step, before it reads the -record, so a device key stored that way would be deleted even where the record -says to keep it. `SqliteKeyStore` therefore refuses, with an error that names -the key and the record, a `put` of a `voelin` blob with `synced = true` while an -account record names its uid as the device key, or while an account record -cannot be read (it may name the key); and a `put` of an account record whose -device key is stored as a synced copy. A key bound with `synced = false` is -accepted: a sign-out unbinds it and then follows the record. The check is made -under the store's lock; it is defence in depth against the code that signs in, -which does not exist yet. +The three parts of open question 10, and what each asks of the store and of the +client: + +1. **A sign-out keeps every device key.** The only deletion of a key of the + device is "Forget this device's identity", the user's explicit choice, after + an offer to export the key. Signed in, it is a sign-out with + `DeviceKeyChoice::Forget(uid)` (the key goes before the record is read, so an + unreadable record does not keep it); signed out, it is `KeyStore::remove` of + the key, and for a TeamSpeak identity `Store::delete_identity`. The store has + no export call: the UI reads the bytes first, a Voelin key with + `KeyStore::voelin_key` and `IdentityKey::to_pkcs8`, a TeamSpeak identity with + `Store::identity` and `ts::identity::export`. +2. **A device key can be released from its account**, so that it can serve + another account. Releasing is the account service's operation + (`AccountClient::release`: `POST /v1/devices//release`, after a password + check) followed by the same local sign-out with `Auto`, which keeps the key, + unbound. The store has nothing to add and the client remembers nothing of the + release: the service holds the registration of the key, and a sign-in or a + sign-up refused with `CONFLICT`, field `device`, is how the client learns + that the key is still registered with an account it signed out of. +3. **The deletion of an account releases every device key of it.** The service + writes a DEVICE and a RELEASED entry for each key, the hosts that adopted a + key end their record of it at their next poll, and the account's users on + them stay the deleted account's, out of reach for good: nobody inherits them, + neither a key nor another account. The local half is + `AccountClient::delete_account(choice)`, the same sign-out: this device's key + is kept with `Auto`. + +What the screens owe, as duties of the GPUI client (they do not exist yet; the +acceptance of the task in the protocol repository names the fixtures): + +- The sign-out dialog says what is kept: "This device's identity stays on this + device. Servers that do not use accounts still know you by it. Choose 'Forget + this device's identity' to delete it (you can export it first)." Forgetting is + a separate, explicit choice there, with the export offered before it. +- Settings → Account offers "Release this device's identity from the account", + apart from signing out: the password first (`AccountClient::reauth`), then + `release`, then the text of protocol section 13.6 (the key can sign in to, or + up for, another account; a host that adopted it and knows the kind RELEASED + accepts it after its next poll, within five minutes). After a release the + client closes its own account sessions and shows no prompt to sign in again + when a host closes one with code 11; a release whose answer was lost + (`SignedOut`) is finished with a sign-out with `Auto`; a `CONFLICT`, field + `device`, at sign-in or sign-up is explained. +- **The delete-account dialog warns that the servers of the account become + unreachable** (its users on the hosts that adopted its keys stay the deleted + account's, and nobody inherits them) **and offers an export of the device keys + first**, before the deletion is sent: `KeyStore::list` names the `voelin` + rows, and each is read and exported as above. + +The device key is never a synced copy. The trait's `sign_out` keeps the device +key, but its first step deletes every identity bound with `synced = true`, +before it reads the record, so a device key stored that way would be deleted +all the same, whichever way the record says it came. `SqliteKeyStore` therefore +refuses, with an error that names the key and the record, a `put` of a `voelin` +blob with `synced = true` while an account record names its uid as the device +key, or while an account record cannot be read (it may name the key); and a +`put` of an account record whose device key is stored as a synced copy. A key +bound with `synced = false` is accepted: a sign-out unbinds it and keeps it. The +check is made under the store's lock; it is defence in depth against the code +that signs in, which does not exist yet. The rows are private keys, so a deleted key must not stay in the file. Every connection to the database sets `secure_delete`, which makes SQLite overwrite what it deletes, and deleting a key (`Store::delete_identity`, and the -`KeyStore::remove` a sign-out deletes with) is followed by a -`PRAGMA wal_checkpoint(TRUNCATE)`, so that the frame of the write-ahead log that -held the key's page goes too: neither `client.db` nor `client.db-wal` has the -key's text afterwards. A sign-out runs the checkpoint once, after its last step, -not after each row it removes. The checkpoint waits for another connection for +`KeyStore::remove` that forgetting a Voelin key and a sign-out delete with) is +followed by a `PRAGMA wal_checkpoint(TRUNCATE)`, so that the frame of the +write-ahead log that held the key's page goes too: neither `client.db` nor +`client.db-wal` has the key's text afterwards. A sign-out deletes the synced +copies (private keys of TeamSpeak identities), the account record and, when the +user chose to forget it, the device key; it runs the checkpoint once, after its +last step, not after each row it removes, and not at all when it deleted +nothing. The checkpoint waits for another connection for 150 ms at most (the connection's own busy timeout is restored after it), because while it waits for a reader it holds the writer lock of the log and every other writer waits with it. If another connection blocks it (one that keeps reading an diff --git a/docs/session-seam.md b/docs/session-seam.md index 26c7ee0..72673a8 100644 --- a/docs/session-seam.md +++ b/docs/session-seam.md @@ -19,7 +19,8 @@ here; section 11 lists what it has to do. Read for this design: `crates/voelin-core/src/link.rs`, `ts_link.rs`, `voice.rs`, `book.rs`, `stream.rs`, `files.rs`, `session.rs` (its use of the link), `tests/link_fake.rs`, `voelin-audio/src/packet.rs`; and in -VoelinProtocol (main `c8e0e5a`) `crates/voelin-proto/src/link.rs`, +VoelinProtocol (main at the pin of that round; moved to `c5bb6b9` by task 34) +`crates/voelin-proto/src/link.rs`, `media.rs` with `media/`, `test_util/` (FakeHost, FakeSession, FakeConnector, FakeAccountAgent, the conformance suite), `proto/voelin/v1/*.proto`, `crates/voelin-model/src/replica/` and @@ -789,8 +790,8 @@ against this record, not against an assumption. ### Slice 1: the adapter 1. **Protocol crates at one revision.** `voelin-identity`, `voelin-proto` - and `voelin-model` from VoelinProtocol at one rev (main `c8e0e5a` or - later: it has `AccountAgent`, `IssuerTrust`, `Credential::Account`; + and `voelin-model` from VoelinProtocol at one rev (the main of the seam + round or later: it has `AccountAgent`, `IssuerTrust`, `Credential::Account`; `voelin-identity` changed only in `cert.rs` and `revocation.rs` since `64808cc`). `crates/voelin-model` is removed and every crate that used it takes `voelin-model = { workspace = true }` (`voelin-core`, `-ui`, @@ -1217,7 +1218,8 @@ second that works. ### 16.2 The conformance suite **Through the registry.** `the_conformance_suite_passes_on_a_session_of_the_registry` -runs the 17 cases of `c8e0e5a` against the `FakeSession` that +runs the 17 cases of the protocol's suite (still 17, in the same order, at +`c5bb6b9`) against the `FakeSession` that `Backends::connect(params, LocalCtx::standalone())` hands over: 17 of 17 pass, none is skipped. The registry adds nothing to a plain connector's session (`host_uid` is the connector's, there is no stream port), so the @@ -1733,15 +1735,52 @@ were fresh compose projects (`down -v`, `up -d`) for each smoke run. `Command::ObserveGateway` link `ts::identity::to_blob`, `VoiceOptions::client_version` links `ts::versions::resolve`. -- **The same leak in `voelin-store`, not closed.** `Store::identity` and - `Store::identities` read the stored JSON of a TeamSpeak identity with `?`, so - an `Error::Json` whose text is the `serde_json` message, which quotes a key - that does not import, as the gate's minor did in the connector. The rows are - written from a `tsclientlib::Identity` (`add_identity`), so a damaged - database is the only way to such a row; the key store (`keystore.rs`) drops - the parse error for the same reason. `ts::identity::from_json` cannot be - used there (`voelin-core` depends on `voelin-store`); the fix is the same - classification in `voelin-store`, or `from_json` moved down. +- **The key store follows task 34 (`phase4/keystore-task34`).** Open question 10 + of the accounts design (answered by the owner on 2026-10-24) made + `KeyStore::sign_out` keep every device key, and VoelinProtocol `main` + (`c5bb6b9`) has it. `SqliteKeyStore` runs that trait method, so the follow-up + that Phase 2 task 34 leaves to this repository ("Note for VoelinClient") is + the pin of the three protocol crates, the tests that asserted the deletion + of a key made for the account (now kept, unbound, byte for byte; only + `DeviceKeyChoice::Forget` deletes a key of the device), and the documents: + `keystore.rs` and `docs/architecture.md`, "Identities", which has the three + parts of the question and the duties of the GPUI client (the sign-out + dialog's wording with "Forget this device's identity" and an export first, + the release in Settings → Account, and the delete-account dialog, which + warns that the account's servers become unreachable and offers an export of + the device keys first). A sign-out still deletes the synced copies and the + account record, so `SignOutPass` stays for their one checkpoint, and the + refusal of a device key stored as a synced copy stays, with its reason + reworded: the sign-out keeps the key but deletes every synced copy before it + reads the record. The store gained no release call and no "released" record: + `AccountClient::release` ends in `sign_out` with `Auto`, and the design asks + the client to remember nothing of a release. A note for VoelinProtocol, not + fixed here: when the device key's own row carries a device-only binding, the + trait's provided `sign_out` lists the key twice in `SignOut.unbound` (once in + its loop over the identities bound to the account, once in the `Auto` branch), + which the tests of this repository do not mind (they use `contains`) and which + is a follow-up for the protocol repository. +- **The same leak in `voelin-store`, closed in `phase4/keystore-task34`.** + `Store::identity` and `Store::identities` read the stored JSON of a + TeamSpeak identity with `?`, so an `Error::Json` whose text is the + `serde_json` message, which quotes a key that does not import, as the gate's + minor did in the connector. The rows are written from a + `tsclientlib::Identity` (`add_identity`), so a damaged database is the only + way to such a row. `ts::identity::from_json` cannot be used there + (`voelin-core` depends on `voelin-store`), so the same classification is in + `voelin-store` (`identity_from_json`): the new `Error::Identity { damage, + line, column }` says malformed, cut short, not an identity or unreadable + (`IdentityDamage`), and where, and never the text. The key store + (`keystore.rs`) was checked line by line and does not leak: `check_teamspeak` + and `Columns::level` drop the parse error (`let Ok(..) else` and `map_or`), + and the binding warning names the row's kind and uid, not its data. A test + with six damaged rows (a key that does not import, a field of the wrong type, + syntax, a cut text, bytes that are no UTF-8 as a BLOB and as TEXT) calls + everything of the store and of the key store that reads or writes the row and + looks through the errors (text, `Debug` and sources) and the logs at TRACE for + any 8 characters in a row of what the row held + (`crates/voelin-store/tests/identity_text.rs`); it fails with the reader's + message put back. - The bookmark tests of `link/connect.rs` that still sit in `ts/ts_session/mod.rs` (17.2) belong next to it. - `QueryLogin.allowlisted` goes with the query observer (H5), which becomes a @@ -1795,7 +1834,8 @@ changes). `Cargo.lock`, `Cargo.toml`, `README.md`, `docs/ui.md`, `crates/voelin-ui/Cargo.toml`, `app.rs` and `servers.rs` merged without a conflict: the lock resolves with `--locked`, and its difference to `main`'s is the branch's alone (the edges of `voelin-core` to `voelin-identity` and -`voelin-proto`, the revision `c8e0e5a` of the three protocol crates, and +`voelin-proto`, the revision of the three protocol crates that the branch +pinned (since moved to `c5bb6b9` by task 34), and `voelin-model` as a git package). `CHANGELOG.md` is `main`'s entry (`voelin-ui-vm`); the branch adds none (17.1), and still needs none: nothing of this round is visible to a user. @@ -1815,7 +1855,7 @@ included. |---|---| | `cargo fmt $(scripts/own-crates.sh) -- --check` | 1.94: clean at the head and at every commit (the merge first differed by the order of one `use` in `voelin-ui-vm`, fixed in the merge commit). Nightly: five files, the baseline's six without `voelin-ui/src/studio.rs`, which `main`'s split removed (`voelin-core/src/history.rs`, `voelin-media/src/ffmpeg/encoder.rs`, `voelin-stream/src/discovery.rs`, `voelin-ui/src/chat.rs`, `tools/voelinctl/src/engine.rs`); `voelin-ui-vm` is clean on both. | | `cargo clippy $(scripts/own-crates.sh) --all-targets --no-deps --locked -- -D warnings` | 1.94: clean at the merge (and `-p voelin-ui` alone) and at the head. Each of the five new commits was checked out detached in this worktree and passes `fmt` and `clippy`: the merge on all own crates and on `-p voelin-ui` alone, the four others on `-p voelin-core -p voelin-store`. Nightly, `-p voelin-core --all-targets`: the same five errors as in 17.5 (`result_large_err` of `shutdown_connection` in `ts/voice.rs`, four `chunks_exact` in `audio.rs`), none in new code. | -| `cargo test -p voelin-core --locked --no-fail-fast` | At the head, 1.94 and nightly: 246 lib tests pass (244 + the two of this round), 2 are ignored, 2 fail, the two of the baseline (`discover::tests::without_records_the_gateway_itself_is_asked`, `web::tests::pictures_go_through_the_proxy_named_for_each_hop`: `localhost` resolves to `::1` only here); the integration tests pass (`session_fake` 19 and 2 ignored, the others as in 17.5). At the merge, before the minors: 244, the same two, and the integration numbers of 17.5. `cargo test -p voelin-ui -p voelin-ui-vm -p voelinctl`: 35, 146 and 7 pass. `voelin-store` (a comment changed): 31 lib tests and 49 of its integration tests pass, but `store::tests::a_blocked_checkpoint_waits_briefly_and_leaves_the_busy_timeout_as_it_was` failed once, in a run under a load average of 8.5 from other jobs on this machine (it asserts that a checkpoint returned in under a second of wall clock); it passed in five isolated runs and three more runs of the crate; it was not chased (a crate this round left alone). | +| `cargo test -p voelin-core --locked --no-fail-fast` | At the head, 1.94 and nightly: 246 lib tests pass (244 + the two of this round), 2 are ignored, 2 fail, the two of the baseline (`discover::tests::without_records_the_gateway_itself_is_asked`, `web::tests::pictures_go_through_the_proxy_named_for_each_hop`: `localhost` resolves to `::1` only here); the integration tests pass (`session_fake` 19 and 2 ignored, the others as in 17.5). At the merge, before the minors: 244, the same two, and the integration numbers of 17.5. `cargo test -p voelin-ui -p voelin-ui-vm -p voelinctl`: 35, 146 and 7 pass. `voelin-store` (a comment changed): 31 lib tests and 49 of its integration tests pass, but `store::tests::a_blocked_checkpoint_waits_briefly_and_leaves_the_busy_timeout_as_it_was` failed once, in a run under a load average of 8.5 from other jobs on this machine (it asserts that a checkpoint returned in under a second of wall clock); it passed in five isolated runs and three more runs of the crate; it was not chased (a crate this round left alone; the bound was replaced in `phase4/keystore-task34` by a one-hour busy timeout and a 30 s hang detector). | | The lib suite 10 times in a row (1.94) | `cargo test -p voelin-core --lib`: ten runs, each 246 passed, 2 failed, 2 ignored, the same two failing tests every time, the banner test passing every time. The same ten runs with those two tests skipped (`--skip`): exit 0 every time (246 passed, 2 ignored). `session::banner_tests::a_failing_banner_is_logged_once_with_its_address` (17.5 saw it fail once) did not fail in these 20 full runs, so the test is as it was: a fix would be a guess at a cause nobody has seen. | | `RUSTDOCFLAGS='-D warnings' cargo doc --no-deps -p voelin-core` | passes, with and without `--features media-desktop`. | | The acceptance of section 10 | The `rg` is empty from the repository root (`--glob '!**/ts/**'`) and from `crates/voelin-core/src` (`--glob '!ts/**'`), with the four exceptions; `session.rs` names none of `tsclientlib`, `tsproto`, `voelin_query`, `ts_bookkeeping`; the grep of `pub` items outside `ts/` is empty; the rustdoc JSON of `voelin-core` (nightly, `--features media-desktop`; every item of the crate, 5,292 of them, whose type references name `tsclientlib`, `tsproto*`, `ts_bookkeeping`, `voelin_query` or `voelin_observer`) has 11 items with such references, all in `voelin_core::ts` (`to_blob`, `from_blob`, `export`, `write_export`, `improve_level`, `Found::identity`, `resolve`, `native_version`, `KnownVersion::to_version` and the two setters), none elsewhere; `voelin_core::stream` keeps its re-exports; `cargo tree -p voelin-core -e normal` still lists `tsclientlib` and `tsproto*`. |