From 1aec007601e61ebe81a731a9c2ce81da0faaf080 Mon Sep 17 00:00:00 2001 From: agent Date: Thu, 17 Sep 2026 20:43:31 -0400 Subject: [PATCH] ratchet: freeze the v1 state/frame wire format with guard tests The persisted ratchet state had a version byte and typed errors but no test that a format change would actually be caught. Add two dedicated guards to tests/ratchet.rs that assert the frozen shape as literals (0x01, 210-byte prefix) rather than via STATE_VERSION, so a bump breaks them visibly, and pin that any foreign version byte is rejected with Error::UnsupportedStateVersion before any field is read. Document the frozen v1 state layout, the rat frame layout, and the migration path a v2 must follow in references/ratchet-wire-frozen.md. Verified by flipping STATE_VERSION to 2: both guards fail ("the frozen version byte changed"), then revert. --- references/ratchet-wire-frozen.md | 101 ++++++++++++++++++++++++++++++ tests/ratchet.rs | 75 ++++++++++++++++++++++ 2 files changed, 176 insertions(+) create mode 100644 references/ratchet-wire-frozen.md diff --git a/references/ratchet-wire-frozen.md b/references/ratchet-wire-frozen.md new file mode 100644 index 0000000..89204f1 --- /dev/null +++ b/references/ratchet-wire-frozen.md @@ -0,0 +1,101 @@ +# Ratchet wire format — frozen at v1 + +Status: **frozen**. A change to the persisted ratchet state layout, or to the +`rat ` frame layout, is a wire-format break and needs a migration path (see +"Changing the format" below). The guard tests that enforce this live in +`tests/ratchet.rs`: + +- `ratchet_state_blob_is_frozen_at_version_v1` +- `ratchet_state_foreign_version_is_rejected_not_misread` + +Both are written to fail visibly on a version bump or a field insertion: +they assert the literal byte `0x01` and the literal 210-byte prefix length, +not the `STATE_VERSION` constant, so a bump cannot quietly follow them. + +## Persisted state (`ratchet_sessions.state`) + +Written by `RatchetState::to_bytes`, read by `RatchetState::from_bytes` +(`src/ratchet.rs`). The store treats the blob as opaque +(`Store::load_ratchet` / `Store::save_ratchet`, `src/store.rs`; the row is +`ratchet_sessions(state BLOB NOT NULL)` keyed by `friend_id`). There is no +public `decode_state` function in the crate: the persisted blob is decoded by +`RatchetState::from_bytes`, reached from `ratchet_for` in `src/node.rs`, and +the resulting version error is reported as `Error::UnsupportedStateVersion`. + +Layout — version `0x01`: + +``` +0 version byte 0x01 (STATE_VERSION) +1..33 root_key +33..65 local ratchet secret +65..97 local ratchet public +97..129 remote ratchet public +129..161 sending chain key +161..165 send_n u32 BE +165..197 receiving chain key +197..201 recv_n u32 BE +201..205 prev_send_len u32 BE +205 established (0 or 1) +206..210 skipped-key count u32 BE +210.. per skipped key, in insertion order: dh_pub[32] || n u32 BE || key[32] +``` + +The fixed prefix is **210 bytes** (pinned as `STATE_PREFIX_LEN` in the test); +the skipped-key tail is `68` bytes per key, capped at `MAX_SKIPPED_KEYS` +(2000). The blob contains secret key material — the caller owns wiping it. + +`from_bytes` is fail-closed on every malformed input it can see: a foreign +version byte returns `Error::UnsupportedStateVersion(byte)` *before* any field +is read, so a blob from another version is never decoded under the v1 layout; +empty, truncated, trailing-byte, bad-`established`-flag, bad skipped-count and +secret-does-not-match-its-public-key inputs return `Error::BadState(&str)`. +None of them panic or partially apply. + +## Frames (`rat ` chat frames) + +Written by `RatchetState::encrypt`, parsed by `Frame::parse` +(`src/ratchet.rs`). Framing constants: `FRAME_PREFIX = b"rat "`, +`FRAME_VERSION = 0x01`, `HEADER_LEN = 40`, `HEADER_OFFSET = 5`. + +``` +0..4 b"rat " +4 version byte 0x01 (FRAME_VERSION) +5..45 header: dh_pub[32] || N u32 BE || PN u32 BE +45..57 nonce[12] +57.. ciphertext || Poly1305 tag[16] (ChaCha20-Poly1305) +``` + +The 40-byte header is also the AEAD associated data, so any header edit fails +authentication rather than being silently ignored. `Frame::parse` checks the +prefix, then the minimum length (`HEADER_OFFSET + HEADER_LEN + 12 + 16 = 73`), +then the version byte; a sub-73-byte frame is a length error whatever its +version byte says, and a frame of 73 bytes or more with a foreign version is a +version error. Rejected frames leave the state byte-identical. + +## Changing the format + +There is **no migration code today**, and a version bump must not silently +re-bootstrap a session: replacing an unreadable stored session with a fresh +bootstrap produces traffic the peer cannot decrypt and loses the established +epoch. The required shape for a v2 is: + +1. Bump `STATE_VERSION` and make `from_bytes` keep the v1 decoder reachable + (match on the version byte, decode old blobs with the old layout, then + re-serialize as v2). +2. Do **not** let an older build read a newer blob: it must keep rejecting + anything that is not its own version with `UnsupportedStateVersion`, never + decode it under the old layout. That is what the current code does, and it + is why only the *newer* build may convert a blob in place. +3. Surface the refusal to the user. Today the message only reaches a log: + an outbound `Node::send` fails closed with `Err(String)` + (`ratchet state: unsupported ratchet state version N`, from + `ratchet_for`), and an inbound frame is dropped with + `eprintln!("rat dropped ({e})")` in `Node::handle_incoming`'s + `Kind::Ratchet` arm. There is no dialog and no automatic recovery; a v2 + must add the user-visible message rather than rely on stderr. +4. Keep the freeze tests green only by updating the pinned literals in + `tests/ratchet.rs` *and* the layout docs in this file in the same change. + +An additive change with no version bump is not an option: the skipped-key tail +is read by count, so appending a field changes what the tail means for every +stored blob. diff --git a/tests/ratchet.rs b/tests/ratchet.rs index 3407afa..138f431 100644 --- a/tests/ratchet.rs +++ b/tests/ratchet.rs @@ -372,6 +372,81 @@ fn state_round_trips_and_rejects_garbage() { assert!(RatchetState::from_bytes(&huge_count).is_err()); } +/// Fixed size of a v1 state blob's prefix: the version byte, the root key, the +/// local secret and public, the remote public, both chain keys, both counters, +/// `prev_send_len`, the established flag and the skipped-key count. +/// Documented in `src/ratchet.rs`'s `to_bytes` layout. +const STATE_PREFIX_LEN: usize = 1 + 32 + 32 + 32 + 32 + 32 + 4 + 32 + 4 + 4 + 1 + 4; + +/// Freeze guard for the persisted wire format. A stored session is only +/// meaningful if both sides agree byte for byte on the layout, so a version +/// bump or a field insertion must break this test on purpose. +/// +/// `0x01` is asserted as a literal: asserting `STATE_VERSION` would silently +/// follow a bump instead of catching it, which is the whole point of the +/// guard. +#[test] +fn ratchet_state_blob_is_frozen_at_version_v1() { + let local = RatchetKeyPair::from_secret([0x11u8; 32]); + let remote = RatchetKeyPair::from_secret([0x22u8; 32]); + let state = RatchetState::bootstrap(ROOT, local, remote.public()); + let bytes = state.to_bytes(); + + assert_eq!( + STATE_VERSION, 1, + "the frozen version byte changed: this is a wire-format break, not a refactor" + ); + assert_eq!( + bytes[0], 0x01, + "a state blob must start with the v1 version byte" + ); + assert_eq!( + bytes.len(), + STATE_PREFIX_LEN, + "the fixed part of the v1 layout changed (a field was added, removed or resized)" + ); + assert_eq!( + bytes.len(), + 210, + "the documented v1 prefix is 210 bytes; a different number means the \ + format moved and stored sessions need a migration path" + ); +} + +/// A blob written by another version must come back as a typed +/// `UnsupportedStateVersion`, never as a panic and never as a state decoded +/// under the wrong layout. The guard must also not be over-eager: the +/// untouched v1 blob still loads. +#[test] +fn ratchet_state_foreign_version_is_rejected_not_misread() { + let (mut a, mut b) = peers(); + // Decrypting m2 first leaves m0/m1 in the skipped store, so the blob is + // longer than the fixed prefix and the check cannot pass by luck. + let frames: Vec> = (0..3) + .map(|i| a.encrypt(format!("m{i}").as_bytes()).expect("encrypt")) + .collect(); + assert_eq!(b.decrypt(&frames[2]).expect("m2"), b"m2"); + let bytes = b.to_bytes(); + assert!( + bytes.len() > STATE_PREFIX_LEN, + "expected skipped keys in the blob, got {} bytes", + bytes.len() + ); + + for version in [0x00u8, 0x02, 0x7f, 0xff] { + let mut foreign = bytes.clone(); + foreign[0] = version; + assert_eq!( + RatchetState::from_bytes(&foreign).expect_err("a foreign version must be rejected"), + Error::UnsupportedStateVersion(version), + "version {version:#04x} must be rejected under its own code, not misread or panicked on" + ); + } + + let reloaded = RatchetState::from_bytes(&bytes).expect("the untouched v1 blob still loads"); + assert_eq!(reloaded.to_bytes(), bytes, "v1 round trip is not stable"); +} + /// Mirrors the private `MIN_FRAME_LEN` in `src/ratchet.rs` /// (`HEADER_OFFSET + HEADER_LEN + NONCE_LEN + TAG_LEN`), which the crate does /// not export.