//! 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"); } }