diff --git a/CHANGELOG.md b/CHANGELOG.md index e79177b..8f76932 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -188,6 +188,9 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows ### Fixed +- A deleted identity key no longer stays in the database file: SQLite overwrites + what it deletes, and the log is truncated after a key is deleted (an identity + you delete, a key a sign-out deletes). - Hover help in the Stream Studio (a source's error, the status details) shows each time and closes when the pointer leaves; it showed only once, and stayed open until a click. diff --git a/crates/voelin-store/src/keystore.rs b/crates/voelin-store/src/keystore.rs index f1fb940..23d035f 100644 --- a/crates/voelin-store/src/keystore.rs +++ b/crates/voelin-store/src/keystore.rs @@ -41,6 +41,15 @@ //! `kind` or `uid` is not text cannot be addressed, and the list leaves it out //! with a warning. //! +//! 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`] (which is how a sign-out deletes a key) +//! 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. A +//! checkpoint that another connection blocks cannot truncate; the removal still +//! succeeds and a warning says that the bytes stay in the log until the next +//! checkpoint (`Store::truncate_wal`). +//! //! 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 //! lines. @@ -214,6 +223,11 @@ impl KeyStore for SqliteKeyStore { .map_err(backend)? .execute(params![kind, uid]) .map_err(backend)?; + if removed > 0 { + // The row may be a key (a sign-out removes them one by one through + // this method): leave nothing of it in the log either. + store.truncate_wal(); + } Ok(removed > 0) } } diff --git a/crates/voelin-store/src/store.rs b/crates/voelin-store/src/store.rs index fe21b09..8aacd6b 100644 --- a/crates/voelin-store/src/store.rs +++ b/crates/voelin-store/src/store.rs @@ -270,6 +270,13 @@ impl Store { // Statements run through `prepare_cached` are parsed once per connection. db.set_prepared_statement_cache_capacity(64); db.pragma_update(None, "foreign_keys", true)?; + // Identities hold private keys. By default a delete only unlinks the + // row: its bytes stay in the free space of the page, and in earlier + // frames of the write-ahead log. With this SQLite overwrites what it + // deletes with zeros, and `truncate_wal` then folds the log into the + // file after a key is removed. It is a setting of the connection, so + // every connection that opens the file sets it here. + db.pragma_update(None, "secure_delete", true)?; // Each migration with its version bump in one write transaction: a // second connection that opens the file at the same time (the // settings writer, the chat history) waits, then sees the new version. @@ -401,11 +408,48 @@ impl Store { if n == 0 { Err(Error::NotFound("identity", id)) } else { Ok(()) } } + /// Delete the identity, key included: SQLite overwrites the row + /// (`secure_delete`) and the write-ahead log is truncated, so the key is + /// in neither the database file nor its log afterwards + /// (`truncate_wal` says when it cannot be). pub fn delete_identity(&self, id: i64) -> Result<()> { - self.db.execute("DELETE FROM identities WHERE id = ?1 AND kind = 'teamspeak'", [id])?; + let deleted = + self.db.execute("DELETE FROM identities WHERE id = ?1 AND kind = 'teamspeak'", [id])?; + if deleted > 0 { + self.truncate_wal(); + } Ok(()) } + /// Fold the write-ahead log into the database file and truncate it to + /// nothing. The delete of a key has overwritten its bytes in the page + /// (`secure_delete`), but the frame of the log that held the page when the + /// key was stored still has them until the log is reset, and a plain + /// checkpoint only copies the frames. Call it after the rows of a key were + /// deleted. + /// + /// It is best effort, because the delete it follows has happened and a + /// sign-out must still finish: a checkpoint that cannot complete (another + /// connection keeps reading an old snapshot for as long as the busy timeout) + /// or fails leaves the bytes in the log until the next checkpoint, and a + /// warning says so. It does nothing to a database that is not in WAL mode + /// and does not overwrite what was deleted before `secure_delete` was on + /// (`VACUUM` does). + pub(crate) fn truncate_wal(&self) { + let blocked = + self.db.query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |r| r.get::<_, i64>(0)); + match blocked { + Ok(0) => {} + Ok(_) => tracing::warn!( + "a deleted key may stay in the write-ahead log: another connection blocked the checkpoint" + ), + Err(error) => tracing::warn!( + %error, + "a deleted key may stay in the write-ahead log: the checkpoint failed" + ), + } + } + // Bookmarks pub fn add_bookmark(&self, bookmark: &Bookmark) -> Result { @@ -530,6 +574,20 @@ mod tests { assert!(matches!(store.identity(id), Err(Error::NotFound(..)))); } + #[test] + fn every_connection_overwrites_what_it_deletes() { + let secure_delete = |store: &Store| -> i64 { + store.db.pragma_query_value(None, "secure_delete", |r| r.get(0)).unwrap() + }; + assert_eq!(secure_delete(&Store::open_in_memory().unwrap()), 1); + let dir = scratch_dir("secure-delete"); + let path = dir.join("client.db"); + assert_eq!(secure_delete(&Store::open(&path).unwrap()), 1); + // A second connection to the same file sets it for itself. + assert_eq!(secure_delete(&Store::open(&path).unwrap()), 1); + std::fs::remove_dir_all(dir).unwrap(); + } + #[test] fn the_default_identity() { let store = Store::open_in_memory().unwrap(); diff --git a/crates/voelin-store/tests/keystore.rs b/crates/voelin-store/tests/keystore.rs index 8e4fdf5..003bf04 100644 --- a/crates/voelin-store/tests/keystore.rs +++ b/crates/voelin-store/tests/keystore.rs @@ -1429,3 +1429,115 @@ fn an_account_row_whose_data_is_not_text_is_deleted_like_an_unreadable_record() } } } + +// ------------------------------------------- a deleted key is gone from the file + +/// The database file and its write-ahead log, as the bytes on disk. +struct RawFiles { + db: Vec, + wal: Vec, +} + +impl RawFiles { + fn read(scratch: &Scratch) -> Self { + let wal = format!("{}-wal", scratch.db().display()); + Self { + db: std::fs::read(scratch.db()).unwrap(), + wal: std::fs::read(wal).unwrap_or_default(), + } + } + + fn holds(&self, text: &str) -> bool { + let contains = |bytes: &[u8]| bytes.windows(text.len()).any(|w| w == text.as_bytes()); + contains(&self.db) || contains(&self.wal) + } + + /// Where the text is, for a failure message. + fn where_is(&self, text: &str) -> (bool, bool) { + let contains = |bytes: &[u8]| bytes.windows(text.len()).any(|w| w == text.as_bytes()); + (contains(&self.db), contains(&self.wal)) + } +} + +/// The text of the private key in a stored blob: `pkcs8` of a Voelin key, +/// `key` of a TeamSpeak identity. +fn key_text(json: &str, field: &str) -> String { + let json: serde_json::Value = serde_json::from_str(json).unwrap(); + let text = json[field].as_str().unwrap().to_owned(); + assert!(text.len() >= 40, "{field}: a short text would match anything"); + text +} + +#[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()))] + { + let scratch = Scratch::new("scrub-signout"); + let store = SqliteKeyStore::open(&scratch.db()).unwrap(); + let device = IdentityBlob::voelin(&key()).unwrap(); + let other = IdentityBlob::voelin(&IdentityKey::generate().unwrap()).unwrap(); + let synced = fresh_teamspeak(binding()); + let (device_text, other_text) = + (key_text(&device.json, "pkcs8"), key_text(&other.json, "pkcs8")); + let synced_text = key_text(&synced.json, "key"); + store.put(&device).unwrap(); + store.put(&other).unwrap(); + store.put(&synced).unwrap(); + store.put_account_record(&AccountRecord { bound_existing_key, ..record() }).unwrap(); + // Another connection to the file (the settings writer, the chat history), + // idle, as the app has them. + let neighbour = Store::open(&scratch.db()).unwrap(); + assert_eq!(neighbour.schema_version().unwrap(), Store::SCHEMA_VERSION); + + // The keys are on disk before: the test proves nothing otherwise. + let before = RawFiles::read(&scratch); + assert!(before.holds(&device_text) && before.holds(&synced_text)); + + store.sign_out(&binding().account, choice).unwrap(); + assert!(store.voelin_key(&key().uid()).unwrap().is_none(), "{choice:?}"); + let after = RawFiles::read(&scratch); + assert_eq!(after.where_is(&device_text), (false, false), "{choice:?}: the device key"); + assert_eq!(after.where_is(&synced_text), (false, false), "{choice:?}: the synced copy"); + assert!(after.holds(&other_text), "{choice:?}: a key that stays is still stored"); + assert!(after.wal.is_empty(), "{choice:?}: the log is truncated"); + drop(neighbour); + } +} + +#[test] +fn a_teamspeak_identity_deleted_by_the_store_is_in_neither_the_database_file_nor_its_log() { + let scratch = Scratch::new("scrub-delete"); + let store = Store::open(&scratch.db()).unwrap(); + let (doomed, kept) = (Identity::create(), Identity::create()); + let doomed_text = key_text(&serde_json::to_string(&doomed).unwrap(), "key"); + let kept_text = key_text(&serde_json::to_string(&kept).unwrap(), "key"); + let doomed_id = store.add_identity("doomed", &doomed, IdentityOrigin::User).unwrap(); + store.add_identity("kept", &kept, IdentityOrigin::User).unwrap(); + assert!(RawFiles::read(&scratch).holds(&doomed_text), "the test proves nothing otherwise"); + + store.delete_identity(doomed_id).unwrap(); + let after = RawFiles::read(&scratch); + assert_eq!(after.where_is(&doomed_text), (false, false)); + assert!(after.holds(&kept_text)); + assert!(after.wal.is_empty(), "the log is truncated"); +} + +#[test] +fn removing_through_the_key_store_leaves_no_key_behind_either() { + // `remove` is how a sign-out deletes, and it is public on its own. + let scratch = Scratch::new("scrub-remove"); + let store = SqliteKeyStore::open(&scratch.db()).unwrap(); + let device = IdentityBlob::voelin(&key()).unwrap(); + let text = key_text(&device.json, "pkcs8"); + store.put(&device).unwrap(); + assert!(RawFiles::read(&scratch).holds(&text)); + assert!(store.remove(KIND_VOELIN, &device.uid).unwrap()); + assert_eq!(RawFiles::read(&scratch).where_is(&text), (false, false)); + // Removing what is not there is not an error and changes nothing. + assert!(!store.remove(KIND_VOELIN, &device.uid).unwrap()); +} diff --git a/docs/architecture.md b/docs/architecture.md index 5a0b51a..00409fb 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -360,6 +360,17 @@ 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. +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. If another connection blocks the checkpoint the delete +stands, a warning is logged, and the bytes stay in the log until the next +checkpoint. Keys deleted before `secure_delete` was on stay in the free pages +until the database is vacuumed. + `voelin-identity` comes from the private VoelinProtocol repository as a git dependency pinned by commit ([building.md](building.md#depending-on-voelinprotocol)).