diff --git a/src/node.rs b/src/node.rs index 19c8cea..21bd1ef 100644 --- a/src/node.rs +++ b/src/node.rs @@ -1427,3 +1427,282 @@ pub fn dir_contains_bytes(dir: &Path, needle: &[u8]) -> bool { false } +#[cfg(test)] +mod tests { + use super::*; + use std::pin::Pin; + use std::task::{Context, Poll}; + + use futures::io::{AsyncRead, AsyncWrite}; + use tokio::io::AsyncRead as TokioRead; + use tokio::io::AsyncWrite as TokioWrite; + + const PASS: &str = "node-ratchet-test-pass"; + + /// Never dials: every send queues, which is what leaves the encoded frame + /// visible on the outbox row. + struct NoDial; + + impl crate::outbox::Deliverer for NoDial { + fn deliver<'a>( + &'a self, + _onion: &'a str, + _pinned_id: &'a [u8], + _prekey: &'a [u8], + _payload: &'a [u8], + ) -> crate::outbox::BoxFut<'a, Result<(), String>> { + Box::pin(async { Err("connect peer.onion:80: timed out".to_string()) }) + } + } + + /// `handle_incoming` is generic over `futures::io` streams while + /// `tokio::io::duplex` hands out `tokio::io` ones; one line per method + /// beats a new dev-dependency. + struct Duplex(tokio::io::DuplexStream); + + impl AsyncRead for Duplex { + fn poll_read( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &mut [u8], + ) -> Poll> { + let mut read_buf = tokio::io::ReadBuf::new(buf); + match Pin::new(&mut self.get_mut().0).poll_read(cx, &mut read_buf) { + Poll::Ready(Ok(())) => Poll::Ready(Ok(read_buf.filled().len())), + Poll::Ready(Err(e)) => Poll::Ready(Err(e)), + Poll::Pending => Poll::Pending, + } + } + } + + impl AsyncWrite for Duplex { + fn poll_write( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &[u8], + ) -> Poll> { + Pin::new(&mut self.get_mut().0).poll_write(cx, buf) + } + + fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.get_mut().0).poll_flush(cx) + } + + fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.get_mut().0).poll_shutdown(cx) + } + } + + /// A real `Node` with no Tor: an unbootstrapped client, no onion service, + /// and a deliverer that never dials. `Node::start` / `start_with_passphrase` + /// are the only public constructors and both bootstrap Tor and publish an + /// onion service, so this is the only way to drive the shipped send and + /// receive path offline. + fn offline_node(home: &Path, deliverer: Arc) -> Node { + std::fs::create_dir_all(home).expect("create home"); + let store = Store::open_at_with_passphrase(home, PASS).expect("open store"); + let keys = Keys::from_self(&store.self_identity().expect("self identity")).expect("keys"); + let client = arti_client::TorClient::builder() + .config(hs::client_config(&home.join("arti"), &home.join("cache"))) + .create_unbootstrapped() + .expect("unbootstrapped Tor client"); + let store = Arc::new(Mutex::new(store)); + let outbox = Arc::new(Outbox::new(Arc::clone(&store), deliverer)); + Node { + home: home.to_path_buf(), + store, + client, + hs: Mutex::new(None), + onion: Mutex::new("test.onion".to_string()), + keys: Mutex::new(keys), + wallet: Wallet::disabled(), + incoming_limit: Mutex::new(TokenBucket::default()), + inbox: Mutex::new(file::Inbox::new(home.join("inbox"))), + outbox, + worker: Mutex::new(None), + stopped: AtomicBool::new(false), + onion_reachable: AtomicBool::new(false), + } + } + + /// The friend row a scanned invite leaves behind. + fn befriend(store: &Store, other_pk: &[u8], other_prekey: &[u8], onion: &str) { + store + .upsert_friend(other_pk, onion, None) + .expect("upsert friend"); + store + .set_friend_prekey(other_pk, other_prekey) + .expect("set friend prekey"); + } + + fn node_prekey(node: &Node) -> [u8; 32] { + node.keys.lock().unwrap().prekey_pk + } + + /// One peer→node dial, end to end: a real Noise IK handshake and one + /// already-encoded frame over an in-memory stream, into `handle_incoming`. + async fn deliver_frame(node: &Node, peer: &Keys, frame: &[u8]) -> Result<(), String> { + let node_pk = node.identity_pk(); + let node_prekey = node_prekey(node); + let (client_side, server_side) = tokio::io::duplex(64 * 1024); + + let send = async { + let mut stream = Duplex(client_side); + let mut sess = session::handshake_initiator(&mut stream, peer, &node_pk, &node_prekey) + .await + .map_err(|e| e.into_message())?; + let ct = sess.encrypt(frame).map_err(|e| e.into_message())?; + frame::write_frame(&mut stream, &ct) + .await + .map_err(|e| e.to_string()) + }; + let receive = async { + let mut stream = Duplex(server_side); + node.handle_incoming(&mut stream).await + }; + let (sent, received) = futures::join!(send, receive); + sent?; + received + } + + fn chat_lines(node: &Node, peer: &Keys) -> Vec<(String, String)> { + node.list_messages(&peer.identity_pk) + .expect("list messages") + .into_iter() + .map(|m| { + ( + m.dir, + String::from_utf8(m.plaintext).expect("utf8 chat line"), + ) + }) + .collect() + } + + #[tokio::test] + async fn send_queues_one_ratchet_frame_and_keeps_the_plaintext_local() { + let dir = tempfile::tempdir().unwrap(); + let node = offline_node(&dir.path().join("bob"), Arc::new(NoDial)); + let peer = Keys::generate(); + befriend( + &node.store.lock().unwrap(), + &peer.identity_pk, + &peer.prekey_pk, + "peer.onion", + ); + + assert_eq!( + node.send(&peer.identity_pk, b"hello bob").await.unwrap(), + OutboxStatus::Queued, + "with nothing to dial, the send queues for the retry worker" + ); + + let rows = node.outbox_pending(&peer.identity_pk).unwrap(); + assert_eq!(rows.len(), 1); + let payload = rows[0] + .payload + .clone() + .expect("the encoded frame rides on the outbox row"); + assert!( + payload.starts_with(b"rat "), + "chat goes out as a ratchet frame" + ); + assert!( + !payload.windows(9).any(|w| w == b"hello bob"), + "the plaintext is not on the wire" + ); + assert_eq!( + rows[0].body, b"hello bob", + "local history keeps the plaintext" + ); + + assert_eq!( + chat_lines(&node, &peer), + vec![("out".to_string(), "hello bob".to_string())] + ); + } + + #[tokio::test] + async fn an_inbound_frame_is_dispatched_to_the_ratchet_and_logged() { + let dir = tempfile::tempdir().unwrap(); + let node = offline_node(&dir.path().join("bob"), Arc::new(NoDial)); + let peer = Keys::generate(); + befriend( + &node.store.lock().unwrap(), + &peer.identity_pk, + &peer.prekey_pk, + "peer.onion", + ); + // The peer's own store holds its ratchet state, as a second Node does. + let peer_store = + Store::open_at_with_passphrase(&dir.path().join("alice"), PASS).expect("peer store"); + befriend( + &peer_store, + &node.identity_pk(), + &node_prekey(&node), + "node.onion", + ); + + let frame = + encode_chat_frame(&peer_store, &peer, &node.identity_pk(), b"hi bob").expect("encode"); + deliver_frame(&node, &peer, &frame).await.expect("receive"); + + assert_eq!( + chat_lines(&node, &peer), + vec![("in".to_string(), "hi bob".to_string())], + "`rat ` is dispatched to the ratchet, not logged as ciphertext chat" + ); + } + + #[tokio::test] + async fn the_receive_path_keeps_arrival_order_and_drops_replays_and_garbage() { + let dir = tempfile::tempdir().unwrap(); + let node = offline_node(&dir.path().join("bob"), Arc::new(NoDial)); + let peer = Keys::generate(); + befriend( + &node.store.lock().unwrap(), + &peer.identity_pk, + &peer.prekey_pk, + "peer.onion", + ); + let peer_store = + Store::open_at_with_passphrase(&dir.path().join("alice"), PASS).expect("peer store"); + befriend( + &peer_store, + &node.identity_pk(), + &node_prekey(&node), + "node.onion", + ); + + let frames: Vec> = ["m0", "m1", "m2"] + .iter() + .map(|t| { + encode_chat_frame(&peer_store, &peer, &node.identity_pk(), t.as_bytes()) + .expect("encode") + }) + .collect(); + + // Arrival order 2, 0, 1 — the ratchet holds the two it has not seen. + deliver_frame(&node, &peer, &frames[2]).await.unwrap(); + deliver_frame(&node, &peer, &frames[0]).await.unwrap(); + deliver_frame(&node, &peer, &frames[1]).await.unwrap(); + // A replay of an already-consumed frame, and a corrupted one: both are + // dropped inside `handle_incoming` without a chat row and without + // wedging the session. + deliver_frame(&node, &peer, &frames[0]).await.unwrap(); + let mut corrupt = frames[1].clone(); + let last = corrupt.len() - 1; + corrupt[last] ^= 0x01; + deliver_frame(&node, &peer, &corrupt).await.unwrap(); + + assert_eq!( + chat_lines(&node, &peer), + vec![ + ("in".to_string(), "m2".to_string()), + ("in".to_string(), "m0".to_string()), + ("in".to_string(), "m1".to_string()) + ], + "three lines, arrival order, no duplicates" + ); + } +} + diff --git a/tests/ratchet_adversarial.rs b/tests/ratchet_adversarial.rs new file mode 100644 index 0000000..eccc206 --- /dev/null +++ b/tests/ratchet_adversarial.rs @@ -0,0 +1,477 @@ +//! What the chat ratchet refuses: attacks, bounds, desync, corruption. +//! +//! Same offline harness as `tests/ratchet_e2e.rs` — real encrypted stores, real +//! identity keys, the real `encode_chat_frame` / `ingest_chat_frame` pair that +//! `Node::send` and `Node::handle_incoming` call, and a capture-and-release +//! `Deliverer` so the test decides what arrives, when, and how often. +//! +//! The load-bearing assertions are that a rejected frame is *dropped* (no chat +//! line) and that it leaves the persisted `ratchet_sessions` blob byte-identical +//! — not merely that a message did not appear. + +use std::collections::{HashMap, VecDeque}; +use std::path::Path; +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::ratchet::{HEADER_OFFSET, MAX_SKIP, RatchetState}; +use onionwire::session::Keys; + +const PASS: &str = "ratchet-adv-pass"; +const ONION: &str = "peer.onion"; + +/// Capture-and-release transport: a delivery is recorded for its recipient and +/// reported successful, so the test controls arrival order and drops. +#[derive(Default)] +struct Wire { + queues: Mutex, VecDeque>>>, +} + +impl Wire { + fn new() -> Arc { + Arc::new(Self::default()) + } + + fn take(&self, to: &[u8]) -> Vec> { + 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>> { + self.queues + .lock() + .unwrap() + .entry(pinned_id.to_vec()) + .or_default() + .push_back(payload.to_vec()); + Box::pin(async { Ok(()) }) + } +} + +struct Peer { + store: Arc>, + 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 { + self.keys.identity_pk.to_vec() + } + + 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"); + } + + 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") + } + + fn ingest(&self, from: &Peer, frame: &[u8]) -> Result, String> { + let s = self.store.lock().unwrap(); + ingest_chat_frame(&s, &self.keys, &from.pk(), frame) + } + + 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() + } + + fn ratchet_blob(&self, other: &Peer) -> Option> { + self.store + .lock() + .unwrap() + .load_ratchet(&other.pk()) + .expect("load ratchet") + } + + fn clear_ratchet(&self, other: &Peer) { + self.store + .lock() + .unwrap() + .clear_ratchet(&other.pk()) + .expect("clear ratchet"); + } +} + +/// Send `count` chat lines from `from` and hand back the captured frames. +async fn send_n(from: &Peer, to: &Peer, wire: &Arc, count: usize) -> Vec> { + let outbox = Outbox::new(Arc::clone(&from.store), wire.clone()); + for i in 0..count { + let text = format!("m{i}"); + assert_eq!( + from.send(&outbox, to, text.as_bytes()).await, + OutboxStatus::Sent + ); + } + let frames = wire.take(&to.pk()); + assert_eq!(frames.len(), count, "one captured frame per send"); + frames +} + +/// The `N` (sender's index in its sending chain) carried by a frame header. +fn frame_n(frame: &[u8]) -> u32 { + let at = HEADER_OFFSET + 32; + u32::from_be_bytes(frame[at..at + 4].try_into().expect("4 bytes")) +} + +/// A frame with a rewritten `N`, still well-formed: whatever rejects it in +/// `decrypt` is the bound, not the parser. +fn with_n(frame: &[u8], n: u32) -> Vec { + let mut out = frame.to_vec(); + let at = HEADER_OFFSET + 32; + out[at..at + 4].copy_from_slice(&n.to_be_bytes()); + out +} + +fn two_peers(dir: &Path) -> (Peer, Peer, Arc) { + 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_frame_claiming_a_skip_past_max_skip_is_dropped_with_the_state_untouched() { + let dir = tempfile::tempdir().unwrap(); + let (alice, bob, wire) = two_peers(dir.path()); + + let frames = send_n(&alice, &bob, &wire, 2).await; + assert_eq!(bob.ingest(&alice, &frames[0]).unwrap(), b"m0"); + + // The next frame Alice would send claims index 1 on the chain Bob is on. + let fresh = frames[1].clone(); + assert_eq!(frame_n(&fresh), 1, "the sender's chain index"); + let before = bob.ratchet_blob(&alice).expect("bob has a session"); + let lines_before = bob.lines(&alice); + + // A well-formed frame claiming 2001 messages further along the chain. + let crafted = with_n(&fresh, 1 + MAX_SKIP + 1); + let err = bob + .ingest(&alice, &crafted) + .expect_err("a jump past MAX_SKIP must be dropped"); + assert!( + err.contains("MAX_SKIP"), + "the bound must reject it, not the AEAD: {err}" + ); + assert_eq!(bob.lines(&alice), lines_before, "no chat line"); + assert_eq!( + bob.ratchet_blob(&alice).expect("session still there"), + before, + "the persisted ratchet state is byte-identical" + ); + + // The bound is exclusive of the limit: a jump of exactly MAX_SKIP is inside + // it, so that frame is rejected for its tag, not for its length. This pins + // the off-by-one in the other direction. + let at_limit = with_n(&fresh, 1 + MAX_SKIP); + let err = bob + .ingest(&alice, &at_limit) + .expect_err("a tampered header still fails to authenticate"); + assert!( + !err.contains("MAX_SKIP"), + "MAX_SKIP itself is allowed through the bound: {err}" + ); + assert_eq!( + bob.ratchet_blob(&alice).expect("session still there"), + before, + "and it too left the state byte-identical" + ); + + // Nothing is wedged: the real frame still lands. + assert_eq!(bob.ingest(&alice, &fresh).unwrap(), b"m1"); +} + +#[tokio::test] +async fn a_snapshot_heals_only_once_the_ratchet_key_it_held_has_been_replaced() { + 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()); + + // Three frames on one chain; Bob takes the last two, so his state also + // legitimately holds the skipped key for the first. + let frames = send_n(&alice, &bob, &wire, 3).await; + assert_eq!(bob.ingest(&alice, &frames[1]).unwrap(), b"m1"); + assert_eq!(bob.ingest(&alice, &frames[2]).unwrap(), b"m2"); + + // The compromise: everything Bob's session was at this point. + let snapshot_blob = bob.ratchet_blob(&alice).expect("bob has a session"); + let mut snapshot = RatchetState::from_bytes(&snapshot_blob).expect("snapshot parses"); + + // What the snapshot can still read: exactly the skipped key it was holding, + // once. Everything it already consumed is gone. + assert_eq!( + snapshot.decrypt(&frames[0]).unwrap(), + b"m0", + "a skipped key it legitimately holds" + ); + let again = snapshot + .decrypt(&frames[0]) + .expect_err("the skipped key is used up") + .to_string(); + assert!(again.contains("already used"), "{again}"); + let used = snapshot + .decrypt(&frames[1]) + .expect_err("a consumed message key is gone") + .to_string(); + assert!(used.contains("already used"), "{used}"); + + // Round one: Bob speaks, Alice adopts his key and answers. That epoch is + // built on Bob's ratchet key, which the snapshot still holds — a Double + // Ratchet heals on the *next* step, not this one. + assert_eq!(bob.send(&to_alice, &alice, b"r0").await, OutboxStatus::Sent); + let r0 = wire.take(&alice.pk()).remove(0); + assert_eq!(alice.ingest(&bob, &r0).unwrap(), b"r0"); + assert_eq!(alice.send(&to_bob, &bob, b"a3").await, OutboxStatus::Sent); + let a3 = wire.take(&bob.pk()).remove(0); + assert_eq!(bob.ingest(&alice, &a3).unwrap(), b"a3"); + + // Round two: Bob answers on the key he minted when he adopted `a3`, and + // Alice adopts that. This epoch needs a ratchet secret the snapshot never + // had — Bob generated it after the compromise. + assert_eq!(bob.send(&to_alice, &alice, b"r1").await, OutboxStatus::Sent); + let r1 = wire.take(&alice.pk()).remove(0); + assert_eq!(alice.ingest(&bob, &r1).unwrap(), b"r1"); + assert_eq!(alice.send(&to_bob, &bob, b"a4").await, OutboxStatus::Sent); + let a4 = wire.take(&bob.pk()).remove(0); + assert_eq!( + bob.ingest(&alice, &a4).unwrap(), + b"a4", + "the live session, which minted a new ratchet key, keeps working" + ); + + let live = RatchetState::from_bytes(&bob.ratchet_blob(&alice).expect("live session")) + .expect("live state parses"); + assert!( + live.public() != snapshot.public() && live.remote_pub() != snapshot.remote_pub(), + "at least one DH ratchet step happened after the snapshot" + ); + + // The epoch built on the snapshot's own key is still readable: that is the + // documented Double Ratchet hop, and it is why the claim below is worded + // about the epoch that requires a secret minted after the compromise. + assert_eq!( + snapshot.decrypt(&a3).unwrap(), + b"a3", + "the epoch built on the key the snapshot already held" + ); + + let after = snapshot + .decrypt(&a4) + .expect_err("the compromised snapshot must not read the healed epoch") + .to_string(); + assert!( + !after.contains("MAX_SKIP") && !after.contains("bad frame"), + "it fails on the keys, not the framing: {after}" + ); + + // The live session's history is the whole conversation and nothing extra. + assert_eq!( + bob.lines(&alice) + .iter() + .map(|(_, t)| t.as_str()) + .collect::>(), + ["m1", "m2", "r0", "a3", "r1", "a4"] + ); +} + +#[tokio::test] +async fn a_ratchet_frame_for_an_unknown_friend_is_dropped_without_a_session() { + let dir = tempfile::tempdir().unwrap(); + let (alice, bob, wire) = two_peers(dir.path()); + // A third identity Bob has never scanned an invite from. + let stranger = Peer::open_at(&dir.path().join("stranger")); + stranger.add_friend(&bob); + + let outbox = Outbox::new(Arc::clone(&stranger.store), wire.clone()); + assert_eq!( + stranger.send(&outbox, &bob, b"who am i").await, + OutboxStatus::Sent + ); + let frames = wire.take(&bob.pk()); + assert_eq!(frames.len(), 1); + + let err = bob + .ingest(&stranger, &frames[0]) + .expect_err("no friend row"); + assert!(err.contains("unknown friend"), "{err}"); + assert!(bob.lines(&stranger).is_empty(), "no chat line"); + assert!( + bob.ratchet_blob(&stranger).is_none(), + "a dropped frame writes no session row" + ); + + // Bob's real conversation is unaffected. + let to_bob = Outbox::new(Arc::clone(&alice.store), wire.clone()); + assert_eq!(alice.send(&to_bob, &bob, b"m0").await, OutboxStatus::Sent); + let frames = wire.take(&bob.pk()); + assert_eq!(bob.ingest(&alice, &frames[0]).unwrap(), b"m0"); +} + +#[tokio::test] +async fn a_frame_from_a_retired_epoch_is_dropped_and_the_resynced_epoch_works() { + 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()); + + // Get both sides off the bootstrap epoch. + assert_eq!(alice.send(&to_bob, &bob, b"m0").await, OutboxStatus::Sent); + let m0 = wire.take(&bob.pk()).remove(0); + assert_eq!(bob.ingest(&alice, &m0).unwrap(), b"m0"); + assert_eq!(bob.send(&to_alice, &alice, b"r0").await, OutboxStatus::Sent); + let r0 = wire.take(&alice.pk()).remove(0); + assert_eq!(alice.ingest(&bob, &r0).unwrap(), b"r0"); + + // A refreshed invite: Bob's friend row now carries Alice's *new* signed + // prekey, and the bootstrap epoch is derived from exactly that prekey — so + // `Node::add_friend_payload` drops the stored session on this change. Bob's + // side of the old epoch is gone, and the epoch he would now derive is a + // different one. + let refreshed = Keys::generate(); + bob.clear_ratchet(&alice); + bob.store + .lock() + .unwrap() + .set_friend_prekey(&alice.pk(), &refreshed.prekey_pk) + .expect("refresh the prekey"); + let lines_before = bob.lines(&alice); + + assert_eq!( + alice.send(&to_bob, &bob, b"stale").await, + OutboxStatus::Sent + ); + let stale = wire.take(&bob.pk()).remove(0); + let err = bob + .ingest(&alice, &stale) + .expect_err("an epoch derived from a prekey Bob no longer holds"); + assert!( + err.contains("authentication"), + "well-formed, but its keys come from an epoch Bob cannot derive: {err}" + ); + assert_eq!(bob.lines(&alice), lines_before, "no chat line"); + assert!( + bob.ratchet_blob(&alice).is_none(), + "the rejected frame must not leave a half-built session behind" + ); + + // Recovery is the documented one: the invite is scanned again with the right + // prekey and both sides re-derive from it, then keep talking both ways. + bob.store + .lock() + .unwrap() + .set_friend_prekey(&alice.pk(), &alice.keys.prekey_pk) + .expect("re-scan the invite"); + alice.clear_ratchet(&bob); + assert_eq!( + alice.send(&to_bob, &bob, b"fresh").await, + OutboxStatus::Sent + ); + let fresh = wire.take(&bob.pk()).remove(0); + assert_eq!(bob.ingest(&alice, &fresh).unwrap(), b"fresh"); + assert_eq!( + bob.send(&to_alice, &alice, b"fresh-reply").await, + OutboxStatus::Sent + ); + let reply = wire.take(&alice.pk()).remove(0); + assert_eq!(alice.ingest(&bob, &reply).unwrap(), b"fresh-reply"); +} + +#[tokio::test] +async fn corrupted_frames_are_dropped_without_touching_the_state() { + let dir = tempfile::tempdir().unwrap(); + let (alice, bob, wire) = two_peers(dir.path()); + + let frames = send_n(&alice, &bob, &wire, 2).await; + assert_eq!(bob.ingest(&alice, &frames[0]).unwrap(), b"m0"); + + let before = bob.ratchet_blob(&alice).expect("bob has a session"); + let lines_before = bob.lines(&alice); + let good = frames[1].clone(); + + let mut bad_version = good.clone(); + bad_version[4] ^= 0xff; + let mut flipped_key = good.clone(); + flipped_key[HEADER_OFFSET] ^= 0x01; + let mut flipped_n = good.clone(); + flipped_n[HEADER_OFFSET + 32 + 3] ^= 0x01; + let mut flipped_ct = good.clone(); + let last = flipped_ct.len() - 1; + flipped_ct[last] ^= 0x01; + + let cases: [(&str, Vec); 6] = [ + ("truncated", good[..good.len() - 1].to_vec()), + ("header only", b"rat \x01".to_vec()), + ("bad version", bad_version), + ("flipped dh_pub", flipped_key), + ("flipped N", flipped_n), + ("flipped ciphertext", flipped_ct), + ]; + + for (label, frame) in cases { + assert!( + bob.ingest(&alice, &frame).is_err(), + "{label}: must be dropped" + ); + assert_eq!( + bob.lines(&alice), + lines_before, + "{label}: must log no chat line" + ); + assert_eq!( + bob.ratchet_blob(&alice).expect("session still there"), + before, + "{label}: must leave the persisted state byte-identical" + ); + } + + assert_eq!(bob.ingest(&alice, &good).unwrap(), b"m1"); +} diff --git a/tests/ratchet_e2e.rs b/tests/ratchet_e2e.rs new file mode 100644 index 0000000..a86bfd6 --- /dev/null +++ b/tests/ratchet_e2e.rs @@ -0,0 +1,406 @@ +//! 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, VecDeque>>>, + fail_next: AtomicUsize, +} + +impl Wire { + fn new() -> Arc { + 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> { + 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>, + 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 { + 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, 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> { + 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) { + 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") + ] + ); +}