chat: send and receive as ratchet frames through the outbox payload
Chat plaintext is ratchet-encrypted once, before the first delivery attempt,
and the frame is what the outbox stores and retries, so a retried message
re-sends identical bytes instead of advancing the sending chain twice.
- dispatch: Kind::Ratchet for the `rat ` prefix, matched before the unknown
[a-z]{3} prefix rule
- node: encode_chat_frame / ingest_chat_frame (the wire halves of Node::send
and handle_incoming), bootstrap derived from the peers' static prekey DH
because the Noise handshake is frozen and carries no ratchet key
- outbox: nullable outbox.payload + Outbox::send_payload; NULL payload keeps
the previous row-for-row behaviour
- store: additive outbox.payload migration, enqueue_outbox_payload,
OutboxEntry::payload
- add_friend_payload: a changed prekey clears the (prekey-bound) ratchet state
tests/ratchet_wire.rs (5) covers one frame per send, byte-identical retries,
out-of-order delivery, replay, tampering and fresh-friend both directions.
tests/tui_spec.rs and crates/onionwire-sdk/src/lib.rs only gained a
`payload: None` field in their OutboxEntry test fixtures: the card's required
field on a pub struct cannot be added without it.
This commit is contained in:
parent
14fccd5396
commit
69a15fe909
9 changed files with 619 additions and 13 deletions
|
|
@ -32,6 +32,20 @@ fn known_prefixes_are_typed() {
|
|||
assert_eq!(classify(b"png 1"), Kind::Ping);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ratchet_frame_is_ratchet() {
|
||||
// `rat ` is a typed prefix, not chat: the plaintext is a ratchet frame.
|
||||
assert_eq!(classify(b"rat \x01rest-of-frame"), Kind::Ratchet);
|
||||
// Matched before the unknown-lowercase-prefix rule, which would Drop it.
|
||||
assert_eq!(classify(b"rat x"), Kind::Ratchet);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_lowercase_prefix_still_drops() {
|
||||
assert_eq!(classify(b"rax not a real type"), Kind::Drop);
|
||||
assert_eq!(classify(b"rat"), Kind::Chat, "3 letters is not a prefix");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uppercase_or_digit_prefix_is_chat() {
|
||||
assert_eq!(classify(b"ZZZ not typed"), Kind::Chat);
|
||||
|
|
|
|||
|
|
@ -275,6 +275,62 @@ async fn flush_friend_ignores_the_schedule_when_that_peer_was_seen() {
|
|||
assert_eq!(fired[0].1, OutboxStatus::Sent);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn payload_row_sends_the_payload_and_keeps_the_body_as_history() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let store = store_and_friend(dir.path(), "flaky.onion");
|
||||
// First dial fails, the retry succeeds: the payload must survive that.
|
||||
let flaky = Flaky::new(1, "connect flaky.onion:80: timed out");
|
||||
let ob = outbox(Arc::clone(&store), flaky.clone(), 8);
|
||||
let frame = b"rat \x01opaque-frame";
|
||||
|
||||
let status = ob.send_payload(&pk(1), b"chat text", frame).await.unwrap();
|
||||
assert_eq!(status, OutboxStatus::Queued);
|
||||
|
||||
let pending = ob.pending(&pk(1)).unwrap();
|
||||
assert_eq!(
|
||||
pending[0].payload.as_deref(),
|
||||
Some(&frame[..]),
|
||||
"the queued row carries the frame, not the plaintext"
|
||||
);
|
||||
assert_eq!(
|
||||
pending[0].body, b"chat text",
|
||||
"the chat row still holds the plaintext"
|
||||
);
|
||||
|
||||
let now = pending[0].next_attempt_at;
|
||||
let fired = ob.flush_friend(&pk(1), now).await.unwrap();
|
||||
assert_eq!(fired[0].1, OutboxStatus::Sent);
|
||||
assert_eq!(
|
||||
flaky.delivered(),
|
||||
vec![frame.to_vec()],
|
||||
"the retry put the frame on the wire, not the body"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn null_payload_rows_still_send_their_body() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let store = store_and_friend(dir.path(), "flaky.onion");
|
||||
let flaky = Flaky::new(1, "connect flaky.onion:80: timed out");
|
||||
let ob = outbox(Arc::clone(&store), flaky.clone(), 8);
|
||||
|
||||
// A locator/profile/payment-style row: no payload, so the body is the wire
|
||||
// form. This is the pre-payload behaviour, row for row.
|
||||
assert_eq!(
|
||||
ob.send(&pk(1), b"loc abc.onion\n1").await.unwrap(),
|
||||
OutboxStatus::Queued
|
||||
);
|
||||
assert_eq!(ob.pending(&pk(1)).unwrap()[0].payload, None);
|
||||
|
||||
let now = ob.pending(&pk(1)).unwrap()[0].next_attempt_at;
|
||||
assert_eq!(
|
||||
ob.flush_friend(&pk(1), now).await.unwrap()[0].1,
|
||||
OutboxStatus::Sent
|
||||
);
|
||||
assert_eq!(flaky.delivered(), vec![b"loc abc.onion\n1".to_vec()]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn wipe_clears_outbox_rows() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
|
|
|||
281
tests/ratchet_wire.rs
Normal file
281
tests/ratchet_wire.rs
Normal file
|
|
@ -0,0 +1,281 @@
|
|||
//! 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"
|
||||
);
|
||||
}
|
||||
|
|
@ -417,6 +417,7 @@ fn pending_row(
|
|||
friend_pk: vec![9u8; 32],
|
||||
message_id,
|
||||
body: body.as_bytes().to_vec(),
|
||||
payload: None,
|
||||
attempts,
|
||||
next_attempt_at: now + next_in,
|
||||
created_at: now,
|
||||
|
|
|
|||
Loading…
Reference in a new issue