onionwire/tests/ratchet.rs
agent 1aec007601
All checks were successful
ci / test (pull_request) Successful in 4m47s
ci / sdk (pull_request) Successful in 57s
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.
2026-09-17 20:43:31 -04:00

576 lines
21 KiB
Rust

//! Double Ratchet module tests: KDF vectors, ratchet steps, skipped-key bounds,
//! replay/tamper failure, serialization and zeroize.
use onionwire::ratchet::{
Error, FRAME_PREFIX, FRAME_VERSION, HEADER_LEN, HEADER_OFFSET, MAX_SKIP, MAX_SKIPPED_KEYS,
RatchetKeyPair, RatchetState, STATE_VERSION, kdf_ck,
};
use zeroize::{Zeroize, ZeroizeOnDrop};
const ROOT: [u8; 32] = [0x7au8; 32];
/// Two peers from one bootstrap root. `a` is always the peer whose ratchet key
/// sorts lower, so the documented bootstrap tie-break (lower key rotates first)
/// is predictable instead of coin-flip dependent.
fn peers() -> (RatchetState, RatchetState) {
let k1 = RatchetKeyPair::from_secret([0x11u8; 32]);
let k2 = RatchetKeyPair::from_secret([0x22u8; 32]);
let (lo, hi) = if k1.public() < k2.public() {
(k1, k2)
} else {
(k2, k1)
};
let (lo_pub, hi_pub) = (lo.public(), hi.public());
assert_ne!(lo_pub, hi_pub, "test keypairs must differ");
(
RatchetState::bootstrap(ROOT, lo, hi_pub),
RatchetState::bootstrap(ROOT, hi, lo_pub),
)
}
fn header_at(frame: &[u8]) -> [u8; 40] {
frame[HEADER_OFFSET..HEADER_OFFSET + 40]
.try_into()
.expect("40")
}
fn patch(frame: &[u8], offset: usize, value: &[u8]) -> Vec<u8> {
let mut out = frame.to_vec();
let at = HEADER_OFFSET + offset;
out[at..at + value.len()].copy_from_slice(value);
out
}
/// Failing test first: `KDF_CK(ck) = (HMAC-SHA256(ck, 0x01), HMAC-SHA256(ck, 0x02))`,
/// first 32 bytes each, for `ck = 0x00..0x1f`.
///
/// Independently computed with:
///
/// ```text
/// python3 -c "
/// import hmac,hashlib
/// ck=bytes(range(32))
/// print(hmac.new(ck,bytes([1]),hashlib.sha256).digest().hex())
/// print(hmac.new(ck,bytes([2]),hashlib.sha256).digest().hex())
/// "
/// ```
#[test]
fn kdf_ck_matches_an_independently_computed_vector() {
let ck: [u8; 32] = std::array::from_fn(|i| i as u8);
let (message_key, next_chain_key) = kdf_ck(&ck);
let expected_message_key = "9b4c8120a4823a95f47cde17a244f4507244ee6e3957d1fab9fa29b44d3829b7";
let expected_next_chain_key =
"4304c22c84a53755ab08ead8d97a8d429be5efa480682d7ad1da27f73e1fbe1d";
assert_eq!(hex(&message_key[..]), expected_message_key);
assert_eq!(hex(&next_chain_key), expected_next_chain_key);
}
fn hex(bytes: &[u8]) -> String {
bytes.iter().map(|b| format!("{b:02x}")).collect()
}
#[test]
fn frames_use_the_typed_prefix_and_version() {
let (mut a, _b) = peers();
let frame = a.encrypt(b"hi").expect("encrypt");
assert_eq!(&frame[..4], FRAME_PREFIX);
assert_eq!(&frame[..4], b"rat ");
assert_eq!(frame[4], FRAME_VERSION);
assert_eq!(header_at(&frame).len(), 40);
}
/// The gate of the card: both peers build and use a sending chain before either
/// has received anything, then both receive, then keep exchanging.
#[test]
fn both_peers_send_first_converges() {
let (mut a, mut b) = peers();
let (a_pub, b_pub) = (a.public(), b.public());
let a1 = a.encrypt(b"a-first").expect("a encrypt");
let b1 = b.encrypt(b"b-first").expect("b encrypt");
assert_eq!(b.decrypt(&a1).expect("b decrypt a1"), b"a-first");
assert_eq!(a.decrypt(&b1).expect("a decrypt b1"), b"b-first");
// A further exchange in both directions must still decrypt.
let a2 = a.encrypt(b"a-second").expect("a encrypt");
let b2 = b.encrypt(b"b-second").expect("b encrypt");
assert_eq!(b.decrypt(&a2).expect("b decrypt a2"), b"a-second");
assert_eq!(a.decrypt(&b2).expect("a decrypt b2"), b"b-second");
// And the DH ratchet actually moved on both sides.
assert_ne!(a.public(), a_pub, "a never rotated its ratchet key");
assert_ne!(b.public(), b_pub, "b never rotated its ratchet key");
let a3 = a.encrypt(b"a-third").expect("a encrypt");
assert_eq!(b.decrypt(&a3).expect("b decrypt a3"), b"a-third");
}
/// Same race, delivered in the other order: the receiving order must not matter.
#[test]
fn both_peers_send_first_converges_in_either_receive_order() {
let (mut a, mut b) = peers();
let a1 = a.encrypt(b"one").expect("a encrypt");
let b1 = b.encrypt(b"two").expect("b encrypt");
assert_eq!(a.decrypt(&b1).expect("a first"), b"two");
assert_eq!(b.decrypt(&a1).expect("b second"), b"one");
let a2 = a.encrypt(b"three").expect("a encrypt");
let b2 = b.encrypt(b"four").expect("b encrypt");
assert_eq!(b.decrypt(&a2).expect("b"), b"three");
assert_eq!(a.decrypt(&b2).expect("a"), b"four");
}
/// A→B, B→A, A→B with the DH ratchet stepping along the way.
#[test]
fn round_trip_across_two_dh_ratchet_steps() {
let (mut a, mut b) = peers();
let (a_pub, b_pub) = (a.public(), b.public());
let m1 = a.encrypt(b"m1").expect("encrypt");
assert_eq!(b.decrypt(&m1).expect("decrypt m1"), b"m1");
let m2 = b.encrypt(b"m2").expect("encrypt");
assert_eq!(a.decrypt(&m2).expect("decrypt m2"), b"m2");
let m3 = a.encrypt(b"m3").expect("encrypt");
assert_eq!(b.decrypt(&m3).expect("decrypt m3"), b"m3");
// Both directions took at least one DH ratchet step.
assert_ne!(a.public(), a_pub, "a's sending ratchet never advanced");
assert_ne!(b.public(), b_pub, "b's sending ratchet never advanced");
let m4 = b.encrypt(b"m4").expect("encrypt");
assert_eq!(a.decrypt(&m4).expect("decrypt m4"), b"m4");
}
#[test]
fn out_of_order_within_one_chain() {
let (mut a, mut b) = peers();
let frames: Vec<Vec<u8>> = (0..5)
.map(|i| a.encrypt(format!("m{i}").as_bytes()).expect("encrypt"))
.collect();
assert_eq!(b.decrypt(&frames[4]).expect("4"), b"m4");
for i in [2usize, 0, 1, 3] {
assert_eq!(
b.decrypt(&frames[i]).expect("out of order"),
format!("m{i}").as_bytes()
);
}
assert_eq!(
b.recv_index(),
5,
"chain index should have consumed all five"
);
assert_eq!(b.skipped_len(), 0, "every skipped key was used");
// A fresh message continues the same chain.
let next = a.encrypt(b"m5").expect("encrypt");
assert_eq!(b.decrypt(&next).expect("m5"), b"m5");
}
/// The `PN` case: a key skipped in the previous chain survives a DH ratchet step.
#[test]
fn key_skipped_before_a_ratchet_step_still_decrypts_after_it() {
let (mut a, mut b) = peers();
// A sends three; B only gets the last, so 0 and 1 are skipped.
let old: Vec<Vec<u8>> = (0..3)
.map(|i| a.encrypt(format!("old{i}").as_bytes()).expect("encrypt"))
.collect();
assert_eq!(b.decrypt(&old[2]).expect("old2"), b"old2");
assert_eq!(b.skipped_len(), 2);
// B replies; A (the lower ratchet key) rotates its sending chain.
let reply = b.encrypt(b"reply").expect("encrypt");
assert_eq!(a.decrypt(&reply).expect("reply"), b"reply");
let b_pub = b.public();
// Two messages on the new epoch. B's first one is a full DH ratchet step.
let new0 = a.encrypt(b"new0").expect("encrypt");
let new1 = a.encrypt(b"new1").expect("encrypt");
assert_eq!(b.decrypt(&new0).expect("new0"), b"new0");
assert_ne!(b.public(), b_pub, "b should have rotated in the step");
assert_eq!(b.decrypt(&new1).expect("new1"), b"new1");
// The old chain's skipped keys are still usable after the step.
assert_eq!(b.decrypt(&old[0]).expect("old0"), b"old0");
assert_eq!(b.decrypt(&old[1]).expect("old1"), b"old1");
assert_eq!(b.skipped_len(), 0);
}
#[test]
fn n_beyond_max_skip_is_rejected_and_the_state_is_untouched() {
let (mut a, mut b) = peers();
let frame = a.encrypt(b"far").expect("encrypt");
let too_far = patch(&frame, 32, &(MAX_SKIP + 1).to_be_bytes());
let before = b.to_bytes();
let err = b
.decrypt(&too_far)
.expect_err("must reject a >MAX_SKIP jump");
assert_eq!(err, Error::MaxSkipExceeded);
assert_eq!(before, b.to_bytes(), "state changed on a rejected frame");
// MAX_SKIP itself is legal: the bound is exclusive of the limit, so the
// frame gets as far as the AEAD (wrong key -> Authentication), and the
// failed open still leaves the state byte-identical.
let at_limit = patch(&frame, 32, &MAX_SKIP.to_be_bytes());
let after_limit_check = b.to_bytes();
assert_eq!(
b.decrypt(&at_limit).expect_err("wrong key"),
Error::Authentication
);
assert_eq!(after_limit_check, b.to_bytes());
}
#[test]
fn replay_fails_closed() {
let (mut a, mut b) = peers();
let frame = a.encrypt(b"once").expect("encrypt");
assert_eq!(b.decrypt(&frame).expect("first"), b"once");
let err = b.decrypt(&frame).expect_err("replay must fail");
assert_eq!(err, Error::UsedMessageKey);
// And it really did not yield plaintext a second time: the error carries no
// payload, and a decrypted-once frame is gone from the skipped store too.
assert_eq!(b.skipped_len(), 0);
}
#[test]
fn skipped_keys_never_exceed_the_cap_and_evict_oldest_first() {
let (mut a, mut b) = peers();
let per_epoch = 1400usize;
let mut first_epoch: Vec<Vec<u8>> = Vec::new();
let mut last_epoch: Vec<Vec<u8>> = Vec::new();
for epoch in 0..3 {
let frames: Vec<Vec<u8>> = (0..per_epoch)
.map(|i| {
a.encrypt(format!("e{epoch}-{i}").as_bytes())
.expect("encrypt")
})
.collect();
// B only receives the last frame of each chain: the rest are skipped.
assert_eq!(
b.decrypt(frames.last().expect("frame")).expect("last"),
format!("e{epoch}-{}", per_epoch - 1).as_bytes()
);
assert!(
b.skipped_len() <= MAX_SKIPPED_KEYS,
"store grew past the cap: {}",
b.skipped_len()
);
if epoch == 0 {
first_epoch = frames;
} else if epoch == 2 {
last_epoch = frames;
} else {
// A reply moves A to a new sending chain for the next epoch.
let reply = b.encrypt(b"reply").expect("encrypt");
assert_eq!(a.decrypt(&reply).expect("reply"), b"reply");
}
}
assert_eq!(
b.skipped_len(),
MAX_SKIPPED_KEYS,
"store should be full, not under the cap"
);
// The newest chain's early keys are present...
assert_eq!(
b.decrypt(&last_epoch[0]).expect("newest chain key kept"),
b"e2-0"
);
// ...and the first chain's are the ones that were evicted.
assert!(
b.decrypt(&first_epoch[0]).is_err(),
"oldest skipped key should have been evicted"
);
}
#[test]
fn header_tamper_fails_authentication() {
// dh_pub[0], N low byte, PN low byte: each is covered by the AEAD's AAD.
for offset in [0usize, 35, 39] {
let (mut a, mut b) = peers();
let frame = a.encrypt(b"secret").expect("encrypt");
let mut tampered = frame.clone();
tampered[HEADER_OFFSET + offset] ^= 0x01;
let err = b
.decrypt(&tampered)
.expect_err("tampered header must not decrypt");
assert!(
matches!(
err,
Error::Authentication | Error::MaxSkipExceeded | Error::UsedMessageKey
),
"unexpected error for header byte {offset}: {err:?}"
);
// State was not advanced by the rejected frame: the real one still opens.
assert_eq!(b.decrypt(&frame).expect("untampered"), b"secret");
}
}
#[test]
fn state_round_trips_and_rejects_garbage() {
let (mut a, mut b) = peers();
let frames: Vec<Vec<u8>> = (0..3)
.map(|i| a.encrypt(format!("m{i}").as_bytes()).expect("encrypt"))
.collect();
assert_eq!(b.decrypt(&frames[2]).expect("m2"), b"m2");
assert_eq!(b.skipped_len(), 2);
let bytes = b.to_bytes();
assert_eq!(bytes[0], STATE_VERSION);
let mut reloaded = RatchetState::from_bytes(&bytes).expect("reload");
assert_eq!(reloaded.to_bytes(), bytes, "round trip is not stable");
assert_eq!(reloaded.skipped_len(), 2);
assert_eq!(reloaded.recv_index(), b.recv_index());
assert_eq!(reloaded.public(), b.public());
assert_eq!(reloaded.remote_pub(), b.remote_pub());
// A reloaded state keeps the conversation going, skipped keys included.
let next = a.encrypt(b"after reload").expect("encrypt");
assert_eq!(reloaded.decrypt(&next).expect("next"), b"after reload");
assert_eq!(reloaded.decrypt(&frames[0]).expect("skipped"), b"m0");
// Truncated, empty, wrong version, trailing bytes.
assert!(RatchetState::from_bytes(&[]).is_err());
assert!(RatchetState::from_bytes(&bytes[..bytes.len() - 1]).is_err());
assert!(RatchetState::from_bytes(&[0u8; 3]).is_err());
let mut trailing = bytes.clone();
trailing.push(0);
assert!(RatchetState::from_bytes(&trailing).is_err());
let mut wrong_version = bytes.clone();
wrong_version[0] = STATE_VERSION + 1;
assert_eq!(
RatchetState::from_bytes(&wrong_version).expect_err("wrong version"),
Error::UnsupportedStateVersion(STATE_VERSION + 1)
);
// A tampered secret no longer matches its public key.
let mut bad_secret = bytes.clone();
bad_secret[33] ^= 0xff;
assert!(RatchetState::from_bytes(&bad_secret).is_err());
// An absurd skipped-key count is a truncation error, not a panic or an
// allocation of 4 billion entries.
let mut huge_count = bytes.clone();
huge_count[206..210].copy_from_slice(&u32::MAX.to_be_bytes());
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<Vec<u8>> = (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.
const MIN_FRAME_LEN: usize = HEADER_OFFSET + HEADER_LEN + 12 + 16;
/// A frame too short to hold a header, nonce and tag is rejected, and the bare
/// 4-byte `rat ` prefix in particular must not panic by indexing `frame[4]`
/// before the length check. Every rejection leaves the state byte-identical.
#[test]
fn short_frames_are_rejected_without_panicking() {
let local = RatchetKeyPair::from_secret([0x11u8; 32]);
let remote = RatchetKeyPair::from_secret([0x22u8; 32]);
let mut state = RatchetState::bootstrap(ROOT, local, remote.public());
let before = state.to_bytes();
// The bare prefix: a prefix hit, so it must fall through to the length
// check. This is the case that used to index `frame[4]` on a 4-byte slice.
let mut tail = vec![FRAME_VERSION];
tail.extend_from_slice(b"abcd");
let mut short = Vec::new();
short.extend_from_slice(FRAME_PREFIX);
short.extend_from_slice(&tail);
assert_eq!(short.len(), 9, "prefix plus a five-byte tail");
// A well-formed-looking header that is one byte too short to hold the
// nonce and tag.
let mut too_short = Vec::new();
too_short.extend_from_slice(FRAME_PREFIX);
too_short.push(FRAME_VERSION);
too_short.resize(MIN_FRAME_LEN - 1, 0);
for (why, frame) in [
("the bare rat prefix", &FRAME_PREFIX[..]),
("an empty slice", &[][..]),
("a partial prefix", &b"rat"[..]),
("a five-byte tail after rat ", &short[..]),
("MIN_FRAME_LEN - 1 bytes", &too_short[..]),
] {
match state.decrypt(frame) {
Err(Error::BadFrame(_)) => {}
other => panic!("{why} was not rejected as a bad frame: {other:?}"),
}
assert_eq!(state.to_bytes(), before, "{why} mutated the state");
}
}
/// A frame long enough to hold the header but carrying a version byte this
/// implementation does not speak is a version error, not a truncation.
#[test]
fn a_wrong_frame_version_is_rejected() {
let local = RatchetKeyPair::from_secret([0x11u8; 32]);
let remote = RatchetKeyPair::from_secret([0x22u8; 32]);
let mut state = RatchetState::bootstrap(ROOT, local, remote.public());
let before = state.to_bytes();
let mut wrong = Vec::new();
wrong.extend_from_slice(FRAME_PREFIX);
wrong.push(FRAME_VERSION + 1);
wrong.resize(MIN_FRAME_LEN, 0);
assert_eq!(
state.decrypt(&wrong).expect_err("wrong version"),
Error::BadFrame("version")
);
assert_eq!(
state.to_bytes(),
before,
"a rejected frame mutated the state"
);
// Below the minimum the length check wins, whatever the version byte says:
// a frame that cannot hold a header, nonce and tag is truncated.
let mut short_wrong = FRAME_PREFIX.to_vec();
short_wrong.push(FRAME_VERSION + 1);
assert!(matches!(
state.decrypt(&short_wrong),
Err(Error::BadFrame(_))
));
assert_eq!(state.to_bytes(), before);
}
fn assert_zeroize_on_drop<T: ZeroizeOnDrop>() {}
#[test]
fn ratchet_state_wipes_its_secrets() {
assert_zeroize_on_drop::<RatchetState>();
assert_zeroize_on_drop::<RatchetKeyPair>();
let (mut a, mut b) = peers();
let frames: Vec<Vec<u8>> = (0..3)
.map(|i| a.encrypt(format!("m{i}").as_bytes()).expect("encrypt"))
.collect();
let _ = b.decrypt(&frames[2]).expect("m2");
let before = b.to_bytes();
assert!(
before[1..33].iter().any(|byte| *byte != 0),
"root key should be live before zeroize"
);
assert!(
before[33..65].iter().any(|byte| *byte != 0),
"ratchet secret should be live before zeroize"
);
assert!(before[206..210] != 0u32.to_be_bytes(), "no skipped keys");
b.zeroize();
let after = b.to_bytes();
assert!(
after[1..33].iter().all(|byte| *byte == 0),
"root key survived zeroize"
);
assert!(
after[33..65].iter().all(|byte| *byte == 0),
"ratchet secret survived zeroize"
);
assert!(
after[129..161].iter().all(|byte| *byte == 0)
&& after[165..197].iter().all(|byte| *byte == 0),
"chain keys survived zeroize"
);
assert_eq!(
after[206..210],
0u32.to_be_bytes(),
"skipped message keys survived zeroize"
);
}