store: persist per-peer ratchet session state in the SQLCipher store #86

Merged
sirius merged 1 commit from wt/t_657d57c1 into main 2026-09-16 22:35:11 +00:00
2 changed files with 262 additions and 0 deletions

View file

@ -275,6 +275,11 @@ impl Store {
updated_at INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS outbox_due ON outbox (status, next_attempt_at);
CREATE TABLE IF NOT EXISTS ratchet_sessions (
friend_id INTEGER PRIMARY KEY REFERENCES friends(id) ON DELETE CASCADE,
state BLOB NOT NULL,
updated_at INTEGER NOT NULL
);
INSERT OR IGNORE INTO self_profile (id) VALUES (1);
",
)?;
@ -1004,6 +1009,54 @@ impl Store {
Ok(n)
}
/// The persisted Double Ratchet state for one peer, exactly as
/// `RatchetState::to_bytes` wrote it. Opaque here: the store never parses or
/// re-serializes it, so a state-format change stays a `src/ratchet.rs`
/// concern. `Ok(None)` means no session yet, not a failure.
pub fn load_ratchet(&self, friend_pk: &[u8]) -> Result<Option<Vec<u8>>> {
let state = self
.conn
.query_row(
"SELECT r.state FROM ratchet_sessions r
JOIN friends f ON f.id = r.friend_id
WHERE f.pubkey = ?1",
params![friend_pk],
|row| row.get::<_, Vec<u8>>(0),
)
.optional()?;
Ok(state)
}
/// Upsert the session blob for one peer, stamping `updated_at`.
pub fn save_ratchet(&self, friend_pk: &[u8], state: &[u8]) -> Result<()> {
let friend_id: i64 = self
.conn
.query_row(
"SELECT id FROM friends WHERE pubkey = ?1",
params![friend_pk],
|row| row.get(0),
)
.map_err(|_| Error("friend not found".into()))?;
self.conn.execute(
"INSERT INTO ratchet_sessions (friend_id, state, updated_at) VALUES (?1, ?2, ?3)
ON CONFLICT(friend_id) DO UPDATE SET
state = excluded.state, updated_at = excluded.updated_at",
params![friend_id, state, unix_now()],
)?;
Ok(())
}
/// Forget the session: a peer prekey change or an explicit reset. A missing
/// row is a no-op.
pub fn clear_ratchet(&self, friend_pk: &[u8]) -> Result<()> {
self.conn.execute(
"DELETE FROM ratchet_sessions WHERE friend_id IN
(SELECT id FROM friends WHERE pubkey = ?1)",
params![friend_pk],
)?;
Ok(())
}
fn outbox_query(&self, sql: &str, args: &[&dyn rusqlite::ToSql]) -> Result<Vec<OutboxEntry>> {
let mut stmt = self.conn.prepare(sql)?;
let rows = stmt.query_map(args, |row| {
@ -1080,6 +1133,10 @@ impl Store {
}
/// Drop chat + payments history. Identity + friends stay.
///
/// Ratchet sessions are deliberately left alone: wiping chat history is not
/// a session reset, and silently resetting would break decryption against a
/// peer that still holds the old state.
/// Not a forensic erase: SSD wear-leveling can keep copies.
pub fn wipe_messages(&self) -> Result<()> {
self.conn.execute("DELETE FROM outbox", [])?;
@ -1831,4 +1888,109 @@ mod at_rest {
);
}
}
/// `ratchet_sessions` keys on `friend_id`, and nothing in the crate deletes
/// friends yet, so the cascade is exercised with the raw statement a future
/// friend-removal path would run.
#[test]
fn removing_a_friend_cascades_to_its_ratchet_row_and_wipe_messages_keeps_it() {
let dir = tempfile::tempdir().unwrap();
let store = Store::open_at_with_passphrase(dir.path(), "cascade-pass").unwrap();
let foreign_keys: i64 = store
.conn
.query_row("PRAGMA foreign_keys", [], |row| row.get(0))
.unwrap();
assert_eq!(foreign_keys, 1, "ON DELETE CASCADE needs foreign_keys ON");
let pk = [0x21u8; 32];
store.upsert_friend(&pk, "peer.onion", None).unwrap();
store.save_ratchet(&pk, b"ratchet-state-blob").unwrap();
store.append_message(&pk, "out", b"hi").unwrap();
// Wiping chat history is not a session reset: the peer still holds the
// old ratchet state, so dropping ours would break its next frame.
store.wipe_messages().unwrap();
assert_eq!(
store.load_ratchet(&pk).unwrap().as_deref(),
Some(&b"ratchet-state-blob"[..]),
"wipe_messages must not clear ratchet state"
);
store
.conn
.execute(
"DELETE FROM friends WHERE pubkey = ?1",
params![pk.as_slice()],
)
.unwrap();
assert_eq!(
store.load_ratchet(&pk).unwrap(),
None,
"deleting the friend must take its ratchet row with it"
);
}
#[test]
fn ratchet_save_overwrites_the_row_and_bumps_updated_at() {
let dir = tempfile::tempdir().unwrap();
let store = Store::open_at_with_passphrase(dir.path(), "upsert-pass").unwrap();
let pk = [0x22u8; 32];
store.upsert_friend(&pk, "peer.onion", None).unwrap();
store.save_ratchet(&pk, b"first-state").unwrap();
// Park the clock so the assertion cannot pass on an untouched row.
store
.conn
.execute("UPDATE ratchet_sessions SET updated_at = 0", [])
.unwrap();
store.save_ratchet(&pk, b"second-state-longer").unwrap();
assert_eq!(
store.load_ratchet(&pk).unwrap().as_deref(),
Some(&b"second-state-longer"[..])
);
let rows: i64 = store
.conn
.query_row("SELECT count(*) FROM ratchet_sessions", [], |row| {
row.get(0)
})
.unwrap();
assert_eq!(rows, 1, "save_ratchet upserts, it does not insert twice");
let updated_at: i64 = store
.conn
.query_row("SELECT updated_at FROM ratchet_sessions", [], |row| {
row.get(0)
})
.unwrap();
assert!(updated_at > 0, "save_ratchet must set updated_at");
}
/// The table is additive: a store written before this card existed gains it
/// from `CREATE TABLE IF NOT EXISTS` on the next open, with no data loss.
#[test]
fn store_predating_the_ratchet_table_gains_it_on_reopen() {
let dir = tempfile::tempdir().unwrap();
let pk = [0x23u8; 32];
{
let store = Store::open_at_with_passphrase(dir.path(), "old-pass").unwrap();
store.upsert_friend(&pk, "peer.onion", None).unwrap();
store.append_message(&pk, "in", b"written-before").unwrap();
store
.conn
.execute_batch("DROP TABLE ratchet_sessions")
.unwrap();
}
let store = Store::open_at_with_passphrase(dir.path(), "old-pass").unwrap();
assert_eq!(
store.list_messages(&pk).unwrap()[0].plaintext,
b"written-before"
);
assert_eq!(store.load_ratchet(&pk).unwrap(), None);
store.save_ratchet(&pk, b"fresh-state").unwrap();
assert_eq!(
store.load_ratchet(&pk).unwrap().as_deref(),
Some(&b"fresh-state"[..])
);
}
}

View file

@ -440,3 +440,103 @@ fn missing_env_empty_secret_is_rejected() {
let err = onionwire::resolve_store_passphrase(|_| Ok(String::new())).unwrap_err();
assert!(err.to_string().contains("empty"), "got {err}");
}
/// A stand-in for `RatchetState::to_bytes()`: version byte then secrets. The
/// store must treat it as opaque, so the exact bytes are the contract.
fn ratchet_blob(tag: u8) -> Vec<u8> {
let mut blob = Vec::with_capacity(64);
blob.push(1);
blob.extend_from_slice(&[tag; 63]);
blob
}
#[test]
fn ratchet_save_load_round_trips_exact_bytes() {
let dir = tempfile::tempdir().expect("tempdir");
let store = Store::open_at_with_passphrase(dir.path(), "ratchet-pass").expect("open");
store
.upsert_friend(&pk(1), "a.onion", None)
.expect("friend");
let blob = ratchet_blob(0x11);
store.save_ratchet(&pk(1), &blob).expect("save");
assert_eq!(
store.load_ratchet(&pk(1)).expect("load"),
Some(blob.clone())
);
drop(store);
assert!(
!store_contains(dir.path(), &blob),
"ratchet secrets must not sit in the db file in the clear"
);
}
#[test]
fn ratchet_load_for_friend_without_a_row_is_none() {
let dir = tempfile::tempdir().expect("tempdir");
let store = Store::open_at_with_passphrase(dir.path(), "ratchet-pass").expect("open");
store
.upsert_friend(&pk(1), "a.onion", None)
.expect("friend");
assert_eq!(store.load_ratchet(&pk(1)).expect("known friend"), None);
assert_eq!(
store.load_ratchet(&pk(2)).expect("unknown friend"),
None,
"an unknown peer is not an error, just no session"
);
}
#[test]
fn ratchet_sessions_are_per_friend() {
let dir = tempfile::tempdir().expect("tempdir");
let store = Store::open_at_with_passphrase(dir.path(), "ratchet-pass").expect("open");
store
.upsert_friend(&pk(1), "a.onion", None)
.expect("friend a");
store
.upsert_friend(&pk(2), "b.onion", None)
.expect("friend b");
let a = ratchet_blob(0xaa);
let b = ratchet_blob(0xbb);
store.save_ratchet(&pk(1), &a).expect("save a");
store.save_ratchet(&pk(2), &b).expect("save b");
assert_eq!(store.load_ratchet(&pk(1)).unwrap(), Some(a.clone()));
assert_eq!(store.load_ratchet(&pk(2)).unwrap(), Some(b.clone()));
store.clear_ratchet(&pk(1)).expect("clear a");
assert_eq!(store.load_ratchet(&pk(1)).unwrap(), None);
assert_eq!(store.load_ratchet(&pk(2)).unwrap(), Some(b));
}
#[test]
fn ratchet_clear_on_missing_row_is_a_no_op() {
let dir = tempfile::tempdir().expect("tempdir");
let store = Store::open_at_with_passphrase(dir.path(), "ratchet-pass").expect("open");
store
.upsert_friend(&pk(1), "a.onion", None)
.expect("friend");
store.clear_ratchet(&pk(1)).expect("no row to clear");
store
.clear_ratchet(&pk(9))
.expect("unknown friend is not an error");
let blob = ratchet_blob(0x22);
store.save_ratchet(&pk(1), &blob).expect("save");
store.clear_ratchet(&pk(1)).expect("clear");
assert_eq!(store.load_ratchet(&pk(1)).unwrap(), None);
}
#[test]
fn ratchet_state_survives_reopening_the_store() {
let dir = tempfile::tempdir().expect("tempdir");
let blob = ratchet_blob(0x33);
{
let store = Store::open_at_with_passphrase(dir.path(), "same-pass").expect("open");
store
.upsert_friend(&pk(1), "a.onion", None)
.expect("friend");
store.append_message(&pk(1), "in", b"hello").expect("msg");
store.save_ratchet(&pk(1), &blob).expect("save");
}
let store = Store::open_at_with_passphrase(dir.path(), "same-pass").expect("reopen");
assert_eq!(store.load_ratchet(&pk(1)).expect("load"), Some(blob));
assert_eq!(store.list_messages(&pk(1)).unwrap()[0].plaintext, b"hello");
}