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
Owner

What

Persistent per-peer Double Ratchet state, so a chat session survives a restart. Follows on from #85 (merged as 5a36338), which shipped src/ratchet.rs.

  • New additive table in the schema block of src/store.rs:

    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
    );
    

    Keyed by friend_id like outbox, not by raw pubkey.

  • Store::load_ratchet(&self, friend_pk) -> Result<Option<Vec<u8>>> — Ok(None) means no session yet, not an error.

  • Store::save_ratchet(&self, friend_pk, state) -> Result<()> — upsert, stamps updated_at.

  • Store::clear_ratchet(&self, friend_pk) -> Result<()> — prekey change / explicit reset; a missing row is a no-op.

The blob is the opaque, versioned RatchetState::to_bytes output. The store does not parse, re-serialize or encrypt it (that format belongs to src/ratchet.rs, and the db is SQLCipher-encrypted wholesale); the new API mirrors the existing outbox helpers and uses the same Error/Result.

Friend deletion: which statement deletes the ratchet row

DELETE FROM friends WHERE pubkey = ?1 — the ratchet row goes via the ON DELETE CASCADE foreign key; no explicit delete was needed. The test asserts PRAGMA foreign_keys is 1 first, and I confirmed the test has teeth by building the table without the cascade clause: the delete then failed with FOREIGN KEY constraint failed (extended_code 787) and the test failed. It passes once ON DELETE CASCADE is in place.

wipe_messages does not touch ratchet state, and the method carries a comment explaining why: wiping chat history is not a session reset, and resetting would break decryption against a peer that still holds the old state. The cascade test asserts the row survives wipe_messages and then disappears with the friend.

Tests

tests/store.rs (new, public API only):

  1. ratchet_save_load_round_trips_exact_bytes — exact bytes back, and the blob is not in the db files in the clear after drop.
  2. ratchet_load_for_friend_without_a_row_is_none — Ok(None) for a known friend with no row and for an unknown peer.
  3. ratchet_sessions_are_per_friend — two friends, independent blobs; clearing one leaves the other.
  4. ratchet_clear_on_missing_row_is_a_no_op
  5. ratchet_state_survives_reopening_the_store — save, drop, reopen the same path, load.

src/store.rs, mod at_rest (needs the keyed connection / private field view):

  1. removing_a_friend_cascades_to_its_ratchet_row_and_wipe_messages_keeps_it (cascade + wipe).
  2. ratchet_save_overwrites_the_row_and_bumps_updated_at — the row count stays 1 and updated_at is rewritten (clock parked at 0 first, so the assertion cannot pass on an untouched row).
  3. store_predating_the_ratchet_table_gains_it_on_reopen — a store written with the table dropped gains it from CREATE TABLE IF NOT EXISTS on the next open, with message history intact and the ratchet API usable.

RED/GREEN: the first run of the new tests failed to compile with error[E0599]: no method named save_ratchet/load_ratchet/clear_ratchet found for struct Store in both test targets; the cascade test then failed for real (FOREIGN KEY constraint failed) before the ON DELETE CASCADE clause was added, then passed.

Deviations from the card (and why)

  1. Test placement. The card says append everything to tests/store.rs. Three tests need the store's keyed connection (private conn) or the raw DELETE FROM friends statement, because the crate has no public friend-delete API and no public way to read updated_at — git grep -n 'DELETE FROM friends' src/ is empty. Those three live in the existing #[cfg(test)] mod at_rest in src/store.rs (precedent: the WAL-checkpoint, zeroize and legacy-fixture tests are already there). The five behaviours expressible through the public API are in tests/store.rs, so pub visibility of the new methods is exercised from outside the crate.
  2. The legacy schema fixture is unchanged. The card points at a second CREATE TABLE friends block in tests/store.rs; the only fixture is LEGACY_SCHEMA in src/store.rs (mod at_rest), documented as "the exact v0.2.1 on-disk layout … pin it here so the migration test cannot drift with the production schema". It already omits outbox, which postdates v0.2.1. Adding a post-v0.2.1 table to it would falsify the pin, so I left it byte-identical and covered the upgrade path with test 8 instead (build a db, DROP TABLE ratchet_sessions, reopen, use the API).
  3. No src/ratchet.rs change. to_bytes/from_bytes already exist there (v1 layout); this card only stores the bytes.

Verification

  • cargo test --locked --target x86_64-unknown-linux-gnu: 266 passed; 0 failed (was 258; +8). The 4 #[ignore = "needs live Tor network"] tests are unchanged.
  • cargo clippy --locked --all-targets --target x86_64-unknown-linux-gnu -- -D warnings: clean, exit 0.
  • rustfmt --edition 2024 --check: tests/store.rs clean; src/store.rs reports the same 8 inherited hunks as HEAD (that file was not rustfmt-clean before this branch) and no new ones.
  • Nothing outside src/store.rs and tests/store.rs; no wire-protocol change (src/node.rs / src/dispatch.rs untouched); Cargo.toml / Cargo.lock untouched.
## What Persistent per-peer Double Ratchet state, so a chat session survives a restart. Follows on from #85 (merged as `5a36338`), which shipped `src/ratchet.rs`. - New additive table in the schema block of `src/store.rs`: ``` 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 ); ``` Keyed by `friend_id` like `outbox`, not by raw pubkey. - `Store::load_ratchet(&self, friend_pk) -> Result<Option<Vec<u8>>>` — `Ok(None)` means no session yet, not an error. - `Store::save_ratchet(&self, friend_pk, state) -> Result<()>` — upsert, stamps `updated_at`. - `Store::clear_ratchet(&self, friend_pk) -> Result<()>` — prekey change / explicit reset; a missing row is a no-op. The blob is the opaque, versioned `RatchetState::to_bytes` output. The store does not parse, re-serialize or encrypt it (that format belongs to `src/ratchet.rs`, and the db is SQLCipher-encrypted wholesale); the new API mirrors the existing outbox helpers and uses the same `Error`/`Result`. ## Friend deletion: which statement deletes the ratchet row `DELETE FROM friends WHERE pubkey = ?1` — the ratchet row goes via the `ON DELETE CASCADE` foreign key; no explicit delete was needed. The test asserts `PRAGMA foreign_keys` is 1 first, and I confirmed the test has teeth by building the table without the cascade clause: the delete then failed with `FOREIGN KEY constraint failed` (extended_code 787) and the test failed. It passes once `ON DELETE CASCADE` is in place. `wipe_messages` does not touch ratchet state, and the method carries a comment explaining why: wiping chat history is not a session reset, and resetting would break decryption against a peer that still holds the old state. The cascade test asserts the row survives `wipe_messages` and then disappears with the friend. ## Tests `tests/store.rs` (new, public API only): 1. `ratchet_save_load_round_trips_exact_bytes` — exact bytes back, and the blob is not in the db files in the clear after drop. 2. `ratchet_load_for_friend_without_a_row_is_none` — `Ok(None)` for a known friend with no row and for an unknown peer. 3. `ratchet_sessions_are_per_friend` — two friends, independent blobs; clearing one leaves the other. 4. `ratchet_clear_on_missing_row_is_a_no_op` 5. `ratchet_state_survives_reopening_the_store` — save, drop, reopen the same path, load. `src/store.rs`, `mod at_rest` (needs the keyed connection / private field view): 6. `removing_a_friend_cascades_to_its_ratchet_row_and_wipe_messages_keeps_it` (cascade + wipe). 7. `ratchet_save_overwrites_the_row_and_bumps_updated_at` — the row count stays 1 and `updated_at` is rewritten (clock parked at 0 first, so the assertion cannot pass on an untouched row). 8. `store_predating_the_ratchet_table_gains_it_on_reopen` — a store written with the table dropped gains it from `CREATE TABLE IF NOT EXISTS` on the next open, with message history intact and the ratchet API usable. RED/GREEN: the first run of the new tests failed to compile with `error[E0599]: no method named save_ratchet/load_ratchet/clear_ratchet found for struct Store` in both test targets; the cascade test then failed for real (`FOREIGN KEY constraint failed`) before the `ON DELETE CASCADE` clause was added, then passed. ## Deviations from the card (and why) 1. **Test placement.** The card says append everything to `tests/store.rs`. Three tests need the store's keyed connection (private `conn`) or the raw `DELETE FROM friends` statement, because the crate has no public friend-delete API and no public way to read `updated_at` — `git grep -n 'DELETE FROM friends' src/` is empty. Those three live in the existing `#[cfg(test)] mod at_rest` in `src/store.rs` (precedent: the WAL-checkpoint, zeroize and legacy-fixture tests are already there). The five behaviours expressible through the public API are in `tests/store.rs`, so `pub` visibility of the new methods is exercised from outside the crate. 2. **The legacy schema fixture is unchanged.** The card points at a second `CREATE TABLE friends` block in `tests/store.rs`; the only fixture is `LEGACY_SCHEMA` in `src/store.rs` (`mod at_rest`), documented as "the exact v0.2.1 on-disk layout … pin it here so the migration test cannot drift with the production schema". It already omits `outbox`, which postdates v0.2.1. Adding a post-v0.2.1 table to it would falsify the pin, so I left it byte-identical and covered the upgrade path with test 8 instead (build a db, `DROP TABLE ratchet_sessions`, reopen, use the API). 3. **No `src/ratchet.rs` change.** `to_bytes`/`from_bytes` already exist there (v1 layout); this card only stores the bytes. ## Verification - `cargo test --locked --target x86_64-unknown-linux-gnu`: **266 passed; 0 failed** (was 258; +8). The 4 `#[ignore = "needs live Tor network"]` tests are unchanged. - `cargo clippy --locked --all-targets --target x86_64-unknown-linux-gnu -- -D warnings`: clean, exit 0. - `rustfmt --edition 2024 --check`: `tests/store.rs` clean; `src/store.rs` reports the same 8 inherited hunks as `HEAD` (that file was not rustfmt-clean before this branch) and no new ones. - Nothing outside `src/store.rs` and `tests/store.rs`; no wire-protocol change (`src/node.rs` / `src/dispatch.rs` untouched); `Cargo.toml` / `Cargo.lock` untouched.
store: persist per-peer ratchet session state in the SQLCipher store
All checks were successful
android-ci / android (pull_request) Successful in 9m3s
ci / test (pull_request) Successful in 4m11s
ci / sdk (pull_request) Successful in 59s
34c257dab5
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.
sirius merged commit 14fccd5396 into main 2026-09-16 22:35:11 +00:00
Sign in to join this conversation.
No reviewers
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
sirius/onionwire!86
No description provided.