store: persist per-peer ratchet session state in the SQLCipher store
New additive ratchet_sessions table (friend_id PK -> friends(id) ON DELETE CASCADE, state BLOB, updated_at), plus load/save/clear_ratchet on Store. The blob is the opaque versioned RatchetState::to_bytes output; the store never parses or re-serializes it. wipe_messages deliberately keeps sessions: wiping history is not a session reset.
This commit is contained in:
parent
5a36338178
commit
34c257dab5
2 changed files with 262 additions and 0 deletions
162
src/store.rs
162
src/store.rs
|
|
@ -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"[..])
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue