ratchet: end-to-end and adversarial tests on the wired send/receive path
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

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).
This commit is contained in:
rust-dev 2026-09-16 19:30:39 -04:00
commit 3620e4f38f
No known key found for this signature in database
3 changed files with 1162 additions and 0 deletions

View file

@ -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<std::io::Result<usize>> {
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<std::io::Result<usize>> {
Pin::new(&mut self.get_mut().0).poll_write(cx, buf)
}
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
Pin::new(&mut self.get_mut().0).poll_flush(cx)
}
fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
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<dyn crate::outbox::Deliverer>) -> 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<Vec<u8>> = ["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"
);
}
}