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..8553c92 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. 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/support/mod.rs b/crates/voelin-store/tests/support/mod.rs index 9da2602..4284422 100644 --- a/crates/voelin-store/tests/support/mod.rs +++ b/crates/voelin-store/tests/support/mod.rs @@ -1,5 +1,8 @@ //! 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}; diff --git a/docs/session-seam.md b/docs/session-seam.md index d681fa4..d584e80 100644 --- a/docs/session-seam.md +++ b/docs/session-seam.md @@ -1753,15 +1753,27 @@ were fresh compose projects (`down -v`, `up -d`) for each smoke run. 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. -- **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 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