onionwire/tests/ratchet_wire.rs

281 lines
8.8 KiB
Rust
Raw Normal View History

//! Chat travels as a `rat ` frame end to end: exactly one frame per send,
//! byte-identical retries, and a decrypt that appends the plaintext once.
//!
//! All offline. The peers are two stores holding each other's friend row, the
//! transport is a fake `Deliverer`, and `onionwire::node::{encode_chat_frame,
//! ingest_chat_frame}` are the same functions `Node::send` / `handle_incoming`
//! call, so this exercises the shipped wire path without Tor.
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-wire-pass";
const ONION: &str = "peer.onion";
/// Records every payload it is handed — including the ones it rejects — so a
/// retry can be compared byte-for-byte with the attempt before it. Fails the
/// first `fail_times` dials.
struct Recorder {
fail_times: AtomicUsize,
sent: Mutex<Vec<Vec<u8>>>,
}
impl Recorder {
fn new(fail_times: usize) -> Arc<Self> {
Arc::new(Self {
fail_times: AtomicUsize::new(fail_times),
sent: Mutex::new(Vec::new()),
})
}
fn sent(&self) -> Vec<Vec<u8>> {
self.sent.lock().unwrap().clone()
}
}
impl Deliverer for Recorder {
fn deliver<'a>(
&'a self,
_onion: &'a str,
_pinned_id: &'a [u8],
_prekey: &'a [u8],
payload: &'a [u8],
) -> BoxFut<'a, Result<(), String>> {
self.sent.lock().unwrap().push(payload.to_vec());
if self.fail_times.load(Ordering::SeqCst) > 0 {
self.fail_times.fetch_sub(1, Ordering::SeqCst);
return Box::pin(async { Err("connect peer.onion:80: timed out".to_string()) });
}
Box::pin(async { Ok(()) })
}
}
/// One node's local state: an encrypted store plus its identity/prekey keypair.
struct Peer {
store: Arc<Mutex<Store>>,
keys: Keys,
}
impl Peer {
fn new(dir: &Path) -> Self {
let store = Store::open_at_with_passphrase(dir, PASS).expect("open store");
Self {
store: Arc::new(Mutex::new(store)),
keys: Keys::generate(),
}
}
fn pk(&self) -> Vec<u8> {
self.keys.identity_pk.to_vec()
}
/// The friend row this peer would have after scanning the other's invite.
fn add_friend(&self, other: &Peer) {
let s = self.store.lock().unwrap();
s.upsert_friend(&other.pk(), ONION, None).unwrap();
s.set_friend_prekey(&other.pk(), &other.keys.prekey_pk)
.unwrap();
}
fn encode(&self, to: &Peer, text: &[u8]) -> Vec<u8> {
let s = self.store.lock().unwrap();
encode_chat_frame(&s, &self.keys, &to.pk(), text).expect("encode chat frame")
}
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: `(dir, plaintext)`, in row order.
fn lines(&self, other: &Peer) -> Vec<(String, String)> {
self.store
.lock()
.unwrap()
.list_messages(&other.pk())
.unwrap()
.into_iter()
.map(|m| {
(
m.dir,
String::from_utf8(m.plaintext).expect("utf8 chat line"),
)
})
.collect()
}
fn has_ratchet_row(&self, other: &Peer) -> bool {
self.store
.lock()
.unwrap()
.load_ratchet(&other.pk())
.unwrap()
.is_some()
}
}
/// Alice and Bob with mutual friend rows.
fn two_peers(dir: &Path) -> (Peer, Peer) {
let alice = Peer::new(&dir.join("alice"));
let bob = Peer::new(&dir.join("bob"));
alice.add_friend(&bob);
bob.add_friend(&alice);
(alice, bob)
}
#[tokio::test]
async fn send_encodes_one_frame_and_a_retry_resends_the_same_bytes() {
let dir = tempfile::tempdir().unwrap();
let (alice, bob) = two_peers(dir.path());
let frame = alice.encode(&bob, b"hello bob");
assert!(
frame.starts_with(b"rat "),
"chat must go out as a ratchet frame"
);
assert!(
!frame.windows(9).any(|w| w == b"hello bob"),
"the plaintext must not appear in the frame"
);
// First dial fails, so the send queues; the worker then delivers.
let recorder = Recorder::new(1);
let ob = Outbox::new(Arc::clone(&alice.store), recorder.clone());
let status = ob
.send_payload(&bob.pk(), b"hello bob", &frame)
.await
.unwrap();
assert_eq!(status, OutboxStatus::Queued);
let rows = ob.pending(&bob.pk()).unwrap();
assert_eq!(rows.len(), 1, "one outbox row");
assert_eq!(
rows[0].payload.as_deref(),
Some(frame.as_slice()),
"the row carries the frame, not the plaintext"
);
assert_eq!(
rows[0].body, b"hello bob",
"local history keeps the plaintext"
);
let fired = ob
.flush_friend(&bob.pk(), rows[0].next_attempt_at)
.await
.unwrap();
assert_eq!(fired[0].1, OutboxStatus::Sent);
let sent = recorder.sent();
assert_eq!(sent.len(), 2, "one immediate attempt plus one retry");
assert_eq!(
sent[0], sent[1],
"a retry re-sends the identical frame bytes"
);
assert_eq!(
sent[1], frame,
"and those bytes are the frame that was encoded"
);
// The receiver logs the plaintext exactly once, from that one frame.
assert_eq!(bob.ingest(&alice, &frame).unwrap(), b"hello bob");
assert_eq!(bob.lines(&alice), vec![("in".into(), "hello bob".into())]);
}
#[test]
fn out_of_order_frames_both_land_in_arrival_order() {
let dir = tempfile::tempdir().unwrap();
let (alice, bob) = two_peers(dir.path());
let first = alice.encode(&bob, b"first");
let second = alice.encode(&bob, b"second");
// Delivered the wrong way round: the ratchet must hold a skipped key.
assert_eq!(bob.ingest(&alice, &second).unwrap(), b"second");
assert_eq!(bob.ingest(&alice, &first).unwrap(), b"first");
assert_eq!(
bob.lines(&alice),
vec![
("in".into(), "second".into()),
("in".into(), "first".into())
],
"chat lines follow arrival order, each with its own plaintext"
);
}
#[test]
fn replayed_frame_produces_no_second_chat_line() {
let dir = tempfile::tempdir().unwrap();
let (alice, bob) = two_peers(dir.path());
let frame = alice.encode(&bob, b"only once");
assert_eq!(bob.ingest(&alice, &frame).unwrap(), b"only once");
assert!(
bob.ingest(&alice, &frame).is_err(),
"a replay must not authenticate a second time"
);
assert_eq!(bob.lines(&alice), vec![("in".into(), "only once".into())]);
}
#[test]
fn garbage_rat_frames_are_dropped_and_the_next_good_one_still_lands() {
let dir = tempfile::tempdir().unwrap();
let (alice, bob) = two_peers(dir.path());
let good = alice.encode(&bob, b"first");
// Truncated header, and a flipped ciphertext byte: both must be dropped
// without a chat row and without panicking.
assert!(bob.ingest(&alice, b"rat \x01").is_err());
let mut tampered = good.clone();
*tampered.last_mut().unwrap() ^= 0x01;
assert!(bob.ingest(&alice, &tampered).is_err());
assert!(
bob.lines(&alice).is_empty(),
"a rejected frame is never stored, as ciphertext or plaintext"
);
// The same state still handles the good frame, then the next one.
assert_eq!(bob.ingest(&alice, &good).unwrap(), b"first");
let next = alice.encode(&bob, b"second");
assert_eq!(bob.ingest(&alice, &next).unwrap(), b"second");
assert_eq!(
bob.lines(&alice),
vec![
("in".into(), "first".into()),
("in".into(), "second".into())
]
);
}
#[test]
fn a_fresh_friend_creates_state_on_demand_in_both_directions() {
let dir = tempfile::tempdir().unwrap();
let (alice, bob) = two_peers(dir.path());
assert!(
!alice.has_ratchet_row(&bob) && !bob.has_ratchet_row(&alice),
"a fresh friend starts with no ratchet row"
);
// Bob speaks first: no state existed for him to send on either.
let from_bob = bob.encode(&alice, b"hi alice");
assert_eq!(alice.ingest(&bob, &from_bob).unwrap(), b"hi alice");
assert_eq!(alice.lines(&bob), vec![("in".into(), "hi alice".into())]);
// Alice replies on the same session, and Bob reads it.
let from_alice = alice.encode(&bob, b"hi bob");
assert_eq!(bob.ingest(&alice, &from_alice).unwrap(), b"hi bob");
assert_eq!(bob.lines(&alice), vec![("in".into(), "hi bob".into())]);
assert!(
alice.has_ratchet_row(&bob) && bob.has_ratchet_row(&alice),
"both sides persisted the state they created on demand"
);
}