onionwire/tests/ratchet_e2e.rs
rust-dev 3620e4f38f
All checks were successful
ci / test (pull_request) Successful in 4m54s
ci / sdk (pull_request) Successful in 1m0s
android-ci / android (pull_request) Successful in 9m26s
ratchet: end-to-end and adversarial tests on the wired send/receive path
Drives the shipped chat ratchet offline against real SQLCipher stores and
the real encode/decode pair Node::send and Node::handle_incoming call, with
a capture-and-release Deliverer so arrival order and drops are controlled.

tests/ratchet_e2e.rs: full exchange, out-of-order arrival, a dropped frame,
a retried frame re-sent byte-identically, and a restart of both peers.

tests/ratchet_adversarial.rs: a frame claiming a jump past MAX_SKIP, a
post-compromise snapshot across a DH step, an unknown friend, a retired
epoch after an invite refresh, and five corruption shapes. Every rejected
frame is asserted to leave the persisted ratchet blob byte-identical.

src/node.rs gains a test-only module that builds a Node with an
unbootstrapped Tor client and drives Node::send plus the real receive path
(Noise IK handshake over an in-memory stream into handle_incoming).
2026-09-16 19:30:39 -04:00

406 lines
14 KiB
Rust

//! The chat ratchet on the wired path: the lifecycle, offline.
//!
//! `Node::send` is three lines — encode exactly one `rat ` frame with
//! [`encode_chat_frame`], then hand *the frame* (not the plaintext) to
//! `Outbox::send_payload` so a retry re-sends identical bytes. The receive half,
//! `Node::handle_incoming`'s `Kind::Ratchet` arm, is [`ingest_chat_frame`]:
//! load the session under the store lock, decrypt, log the plaintext, drop
//! anything that does not authenticate.
//!
//! `Node::start` is the only public constructor and it bootstraps Tor and
//! publishes an onion service, so a test outside the crate cannot build one.
//! These tests therefore drive that exact pair of functions against real
//! encrypted stores with a capture-and-release `Deliverer`, which is what makes
//! delivery order and drops controllable; the `Node` struct itself (its send
//! body and its dispatch arm, over a real Noise session on an in-memory stream)
//! is driven in `src/node.rs`'s test module, and the live Tor path stays
//! `#[ignore]`d in `tests/two_node.rs`.
//!
//! Every store here is a real SQLCipher file in a temp dir, and every identity
//! is loaded back out of it, so "restart" means reopening the same home
//! directory exactly as `Node::start_with_passphrase` does.
use std::collections::{HashMap, VecDeque};
use std::path::Path;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use onionwire::Store;
use onionwire::node::{encode_chat_frame, ingest_chat_frame};
use onionwire::outbox::{BoxFut, Deliverer, Outbox, OutboxStatus};
use onionwire::session::Keys;
const PASS: &str = "ratchet-e2e-pass";
const ONION: &str = "peer.onion";
/// Capture-and-release transport.
///
/// A delivery is recorded for its recipient and reported successful, so the
/// sending side believes it went out; the test then decides when each captured
/// frame reaches the recipient and in what order. `fail_next` makes the next
/// `n` dials fail, which is how a queued row — and therefore a byte-identical
/// retry — is produced.
#[derive(Default)]
struct Wire {
queues: Mutex<HashMap<Vec<u8>, VecDeque<Vec<u8>>>>,
fail_next: AtomicUsize,
}
impl Wire {
fn new() -> Arc<Self> {
Arc::new(Self::default())
}
/// The next `n` dials fail and are not captured.
fn fail_next(&self, n: usize) {
self.fail_next.store(n, Ordering::SeqCst);
}
/// Frames captured for `to`, in send order, drained.
fn take(&self, to: &[u8]) -> Vec<Vec<u8>> {
self.queues
.lock()
.unwrap()
.remove(to)
.map(|q| q.into_iter().collect())
.unwrap_or_default()
}
}
impl Deliverer for Wire {
fn deliver<'a>(
&'a self,
_onion: &'a str,
pinned_id: &'a [u8],
_prekey: &'a [u8],
payload: &'a [u8],
) -> BoxFut<'a, Result<(), String>> {
if self.fail_next.load(Ordering::SeqCst) > 0 {
self.fail_next.fetch_sub(1, Ordering::SeqCst);
return Box::pin(async { Err("connect peer.onion:80: timed out".to_string()) });
}
self.queues
.lock()
.unwrap()
.entry(pinned_id.to_vec())
.or_default()
.push_back(payload.to_vec());
Box::pin(async { Ok(()) })
}
}
/// One peer: a real encrypted store on disk plus the identity and prekey loaded
/// back out of it, which is what `Node::start_with_passphrase` builds.
struct Peer {
store: Arc<Mutex<Store>>,
keys: Keys,
}
impl Peer {
fn open_at(home: &Path) -> Self {
let store = Store::open_at_with_passphrase(home, PASS).expect("open store");
let me = store.self_identity().expect("self identity");
let keys = Keys::from_self(&me).expect("keys from store identity");
Self {
store: Arc::new(Mutex::new(store)),
keys,
}
}
fn pk(&self) -> Vec<u8> {
self.keys.identity_pk.to_vec()
}
/// The friend row a scanned invite leaves behind.
fn add_friend(&self, other: &Peer) {
let s = self.store.lock().unwrap();
s.upsert_friend(&other.pk(), ONION, None)
.expect("upsert friend");
s.set_friend_prekey(&other.pk(), &other.keys.prekey_pk)
.expect("set friend prekey");
}
/// `Node::send`: encode the frame once, hand the frame to the outbox.
async fn send(&self, outbox: &Outbox, to: &Peer, text: &[u8]) -> OutboxStatus {
let frame = {
let s = self.store.lock().unwrap();
encode_chat_frame(&s, &self.keys, &to.pk(), text).expect("encode chat frame")
};
outbox
.send_payload(&to.pk(), text, &frame)
.await
.expect("send payload")
}
/// `Node::handle_incoming`'s `Kind::Ratchet` arm.
fn ingest(&self, from: &Peer, frame: &[u8]) -> Result<Vec<u8>, String> {
let s = self.store.lock().unwrap();
ingest_chat_frame(&s, &self.keys, &from.pk(), frame)
}
/// Chat lines with one peer as `(dir, plaintext)`, in row order.
fn lines(&self, other: &Peer) -> Vec<(String, String)> {
self.store
.lock()
.unwrap()
.list_messages(&other.pk())
.expect("list messages")
.into_iter()
.map(|m| {
(
m.dir,
String::from_utf8(m.plaintext).expect("utf8 chat line"),
)
})
.collect()
}
/// The persisted `ratchet_sessions` blob for one peer.
fn ratchet_blob(&self, other: &Peer) -> Option<Vec<u8>> {
self.store
.lock()
.unwrap()
.load_ratchet(&other.pk())
.expect("load ratchet")
}
}
/// Just the plaintexts of a peer's chat lines, for a readable assertion.
fn texts(lines: &[(String, String)]) -> Vec<&str> {
lines.iter().map(|(_, t)| t.as_str()).collect()
}
fn chat(dir: &str, text: &str) -> (String, String) {
(dir.to_string(), text.to_string())
}
fn two_peers(dir: &Path) -> (Peer, Peer, Arc<Wire>) {
let wire = Wire::new();
let alice = Peer::open_at(&dir.join("alice"));
let bob = Peer::open_at(&dir.join("bob"));
alice.add_friend(&bob);
bob.add_friend(&alice);
(alice, bob, wire)
}
#[tokio::test]
async fn a_full_exchange_in_both_directions_logs_each_frame_once() {
let dir = tempfile::tempdir().unwrap();
let (alice, bob, wire) = two_peers(dir.path());
let to_bob = Outbox::new(Arc::clone(&alice.store), wire.clone());
let to_alice = Outbox::new(Arc::clone(&bob.store), wire.clone());
assert_eq!(
alice.send(&to_bob, &bob, b"hi bob").await,
OutboxStatus::Sent
);
let frames = wire.take(&bob.pk());
assert_eq!(frames.len(), 1, "one frame per send");
assert!(
frames[0].starts_with(b"rat "),
"chat goes out as a ratchet frame"
);
assert!(
!frames[0].windows(6).any(|w| w == b"hi bob"),
"the plaintext is not on the wire"
);
assert_eq!(bob.ingest(&alice, &frames[0]).unwrap(), b"hi bob");
assert_eq!(
bob.send(&to_alice, &alice, b"hi alice").await,
OutboxStatus::Sent
);
let frames = wire.take(&alice.pk());
assert_eq!(frames.len(), 1);
assert_eq!(alice.ingest(&bob, &frames[0]).unwrap(), b"hi alice");
assert_eq!(
alice.lines(&bob),
vec![chat("out", "hi bob"), chat("in", "hi alice")]
);
assert_eq!(
bob.lines(&alice),
vec![chat("in", "hi bob"), chat("out", "hi alice")]
);
}
#[tokio::test]
async fn out_of_order_delivery_keeps_every_message_once_in_arrival_order() {
let dir = tempfile::tempdir().unwrap();
let (alice, bob, wire) = two_peers(dir.path());
let to_bob = Outbox::new(Arc::clone(&alice.store), wire.clone());
for text in [b"m0".as_slice(), b"m1", b"m2"] {
assert_eq!(alice.send(&to_bob, &bob, text).await, OutboxStatus::Sent);
}
let mut frames = wire.take(&bob.pk());
assert_eq!(frames.len(), 3, "one captured frame per send");
// Arrival order 2, 0, 1: the ratchet must hold message keys for the two it
// has not seen yet and never log a frame twice.
let last = frames.remove(2);
let first = frames.remove(0);
let second = frames.remove(0);
assert_eq!(bob.ingest(&alice, &last).unwrap(), b"m2");
assert_eq!(bob.ingest(&alice, &first).unwrap(), b"m0");
assert_eq!(bob.ingest(&alice, &second).unwrap(), b"m1");
assert_eq!(
bob.lines(&alice),
vec![chat("in", "m2"), chat("in", "m0"), chat("in", "m1")],
"three lines, arrival order, no duplicates"
);
}
#[tokio::test]
async fn a_frame_that_never_arrives_does_not_stall_the_conversation() {
let dir = tempfile::tempdir().unwrap();
let (alice, bob, wire) = two_peers(dir.path());
let to_bob = Outbox::new(Arc::clone(&alice.store), wire.clone());
for text in [b"m0".as_slice(), b"m1", b"m2", b"m3"] {
assert_eq!(alice.send(&to_bob, &bob, text).await, OutboxStatus::Sent);
}
let frames = wire.take(&bob.pk());
assert_eq!(frames.len(), 4);
assert_eq!(bob.ingest(&alice, &frames[0]).unwrap(), b"m0");
// frames[1] is lost: nothing is delivered for it at all.
assert_eq!(bob.ingest(&alice, &frames[2]).unwrap(), b"m2");
assert_eq!(bob.ingest(&alice, &frames[3]).unwrap(), b"m3");
assert_eq!(
texts(&bob.lines(&alice)),
["m0", "m2", "m3"],
"the messages after the gap still decrypt"
);
// The gap was held as a skipped key, not a stall: the lost frame is still
// readable inside the skip window when it finally turns up.
assert_eq!(bob.ingest(&alice, &frames[1]).unwrap(), b"m1");
assert_eq!(texts(&bob.lines(&alice)), ["m0", "m2", "m3", "m1"]);
}
#[tokio::test]
async fn a_retry_that_re_sends_the_same_bytes_is_not_logged_twice() {
let dir = tempfile::tempdir().unwrap();
let (alice, bob, wire) = two_peers(dir.path());
wire.fail_next(1);
let to_bob = Outbox::new(Arc::clone(&alice.store), wire.clone());
// The dial fails, so the frame is persisted on the outbox row.
assert_eq!(alice.send(&to_bob, &bob, b"m0").await, OutboxStatus::Queued);
let rows = to_bob.pending(&bob.pk()).unwrap();
assert_eq!(rows.len(), 1);
assert!(
rows[0]
.payload
.as_deref()
.is_some_and(|p| p.starts_with(b"rat ")),
"the row carries the encoded frame, not the body"
);
// The worker retries: the very same bytes go out.
let fired = to_bob
.flush_friend(&bob.pk(), rows[0].next_attempt_at)
.await
.unwrap();
assert_eq!(fired[0].1, OutboxStatus::Sent);
let frames = wire.take(&bob.pk());
assert_eq!(frames.len(), 1);
assert_eq!(bob.ingest(&alice, &frames[0]).unwrap(), b"m0");
let replay = bob
.ingest(&alice, &frames[0])
.expect_err("a replay must not authenticate");
assert!(
replay.contains("already used"),
"the message key is gone, not a decryption failure: {replay}"
);
assert_eq!(
texts(&bob.lines(&alice)),
["m0"],
"exactly one chat line after the retry"
);
}
#[tokio::test]
async fn the_conversation_continues_after_both_peers_restart() {
let dir = tempfile::tempdir().unwrap();
let wire = Wire::new();
let alice_home = dir.path().join("alice");
let bob_home = dir.path().join("bob");
let alice_pk;
let bob_pk;
{
let alice = Peer::open_at(&alice_home);
let bob = Peer::open_at(&bob_home);
alice.add_friend(&bob);
bob.add_friend(&alice);
alice_pk = alice.pk();
bob_pk = bob.pk();
let to_bob = Outbox::new(Arc::clone(&alice.store), wire.clone());
assert_eq!(
alice.send(&to_bob, &bob, b"before").await,
OutboxStatus::Sent
);
let frame = wire.take(&bob_pk).remove(0);
assert_eq!(bob.ingest(&alice, &frame).unwrap(), b"before");
let to_alice = Outbox::new(Arc::clone(&bob.store), wire.clone());
assert_eq!(
bob.send(&to_alice, &alice, b"before-reply").await,
OutboxStatus::Sent
);
let frame = wire.take(&alice_pk).remove(0);
assert_eq!(alice.ingest(&bob, &frame).unwrap(), b"before-reply");
assert!(
alice.ratchet_blob(&bob).is_some() && bob.ratchet_blob(&alice).is_some(),
"both sides persisted the session they just used"
);
}
// Both processes are gone: reopen the same home directories, which is the
// only way the state can come back.
let alice = Peer::open_at(&alice_home);
let bob = Peer::open_at(&bob_home);
assert_eq!(alice.pk(), alice_pk, "identity survives the restart");
assert_eq!(bob.pk(), bob_pk);
let to_bob = Outbox::new(Arc::clone(&alice.store), wire.clone());
assert_eq!(
alice.send(&to_bob, &bob, b"after").await,
OutboxStatus::Sent
);
let frame = wire.take(&bob_pk).remove(0);
assert_eq!(bob.ingest(&alice, &frame).unwrap(), b"after");
let to_alice = Outbox::new(Arc::clone(&bob.store), wire.clone());
assert_eq!(
bob.send(&to_alice, &alice, b"after-reply").await,
OutboxStatus::Sent
);
let frame = wire.take(&alice_pk).remove(0);
assert_eq!(alice.ingest(&bob, &frame).unwrap(), b"after-reply");
assert_eq!(
bob.lines(&alice),
vec![
chat("in", "before"),
chat("out", "before-reply"),
chat("in", "after"),
chat("out", "after-reply")
]
);
assert_eq!(
alice.lines(&bob),
vec![
chat("out", "before"),
chat("in", "before-reply"),
chat("out", "after"),
chat("in", "after-reply")
]
);
}