From 69a15fe90978cbb9a571d7121f8ccc292bfd652f Mon Sep 17 00:00:00 2001 From: agent Date: Wed, 16 Sep 2026 19:02:52 -0400 Subject: [PATCH] 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. --- crates/onionwire-sdk/src/lib.rs | 1 + src/dispatch.rs | 7 + src/node.rs | 163 +++++++++++++++++- src/outbox.rs | 54 ++++-- src/store.rs | 55 ++++++- tests/dispatch.rs | 14 ++ tests/outbox.rs | 56 +++++++ tests/ratchet_wire.rs | 281 ++++++++++++++++++++++++++++++++ tests/tui_spec.rs | 1 + 9 files changed, 619 insertions(+), 13 deletions(-) create mode 100644 tests/ratchet_wire.rs diff --git a/crates/onionwire-sdk/src/lib.rs b/crates/onionwire-sdk/src/lib.rs index a28e804..6238005 100644 --- a/crates/onionwire-sdk/src/lib.rs +++ b/crates/onionwire-sdk/src/lib.rs @@ -1061,6 +1061,7 @@ mod tests { friend_pk: vec![0xaa; 32], message_id: 42, body: b"hello".to_vec(), + payload: None, attempts, next_attempt_at: 1_700_000_045, created_at: 1_700_000_000, diff --git a/src/dispatch.rs b/src/dispatch.rs index 92a5f2c..3383f4f 100644 --- a/src/dispatch.rs +++ b/src/dispatch.rs @@ -10,10 +10,17 @@ pub enum Kind { Tip, Ping, File, + /// Double Ratchet frame (`rat `, `src/ratchet.rs`). Chat travels as a + /// ratchet frame; the plaintext only exists after decryption. + Ratchet, Drop, } pub fn classify(pt: &[u8]) -> Kind { + // Before the `[a-z]{3} ` catch-all below, which would drop it as unknown. + if pt.starts_with(crate::ratchet::FRAME_PREFIX) { + return Kind::Ratchet; + } if pt.starts_with(b"loc ") { return Kind::Loc; } diff --git a/src/node.rs b/src/node.rs index c6e3fd5..19c8cea 100644 --- a/src/node.rs +++ b/src/node.rs @@ -7,8 +7,11 @@ use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; use futures::StreamExt; use futures::io::{AsyncRead, AsyncWrite}; +use hkdf::Hkdf; +use sha2::Sha256; use tor_cell::relaycell::msg::Connected; use tor_hsservice::{RunningOnionService, handle_rend_requests}; +use x25519_dalek::{PublicKey as X25519Public, StaticSecret}; use zeroize::Zeroizing; use crate::dispatch::{self, Kind}; @@ -20,6 +23,7 @@ use crate::outbox::{ArtiDeliverer, Outbox, OutboxStatus}; use crate::pay; use crate::profile; use crate::qr; +use crate::ratchet::{RatchetKeyPair, RatchetState}; use crate::ratelimit::TokenBucket; use crate::sanitize; use crate::session::{self, Keys}; @@ -387,12 +391,23 @@ impl Node { pub fn add_friend_payload(&self, p: &qr::QrPayload) -> Result<(), String> { let store = self.store.lock().map_err(|e| e.to_string())?; + let prekey_changed = store + .get_friend(&p.pubkey) + .map_err(|e| e.to_string())? + .map(|f| f.prekey != p.signed_prekey) + .unwrap_or(false); store .upsert_friend(&p.pubkey, &p.onion, None) .map_err(|e| e.to_string())?; store .set_friend_prekey(&p.pubkey, &p.signed_prekey) .map_err(|e| e.to_string())?; + if prekey_changed { + // The bootstrap epoch is derived from the peers' static prekey DH, + // so a refreshed invite makes the stored ratchet state unusable on + // both sides. Drop it: the next frame rebuilds a fresh state. + store.clear_ratchet(&p.pubkey).map_err(|e| e.to_string())?; + } Ok(()) } @@ -876,9 +891,18 @@ impl Node { /// when the peer's onion is unreachable — the outbox worker then retries with /// backoff. A real protocol error (signature mismatch, unknown/short/oversize /// frame) still fails immediately and is never retried. + /// + /// Chat travels as a `rat ` frame: the plaintext is ratchet-encrypted once, + /// here, before the first attempt, and the frame is what the outbox retries. + /// Local history keeps the plaintext (the store is encrypted at rest). pub async fn send(&self, friend_pk: &[u8], plaintext: &[u8]) -> Result { self.ensure_running()?; - self.outbox.send(friend_pk, plaintext).await + let keys = self.keys()?; + let frame = { + let store = self.store.lock().map_err(|e| e.to_string())?; + encode_chat_frame(&store, &keys, friend_pk, plaintext)? + }; + self.outbox.send_payload(friend_pk, plaintext, &frame).await } /// Pending and failed outbox rows for a friend, for UI surfacing. @@ -1001,6 +1025,17 @@ impl Node { .map_err(|e| e.to_string())?; Ok(()) } + Kind::Ratchet => { + // Chat arrives as a ratchet frame: decrypt, log the plaintext, + // drop the frame. A bad frame is logged and dropped — the + // ciphertext is never stored and there is no plaintext fallback. + let keys = self.keys()?; + let store = self.store.lock().map_err(|e| e.to_string())?; + if let Err(e) = ingest_chat_frame(&store, &keys, &sess.peer_identity, &pt) { + eprintln!("rat dropped ({e})"); + } + Ok(()) + } Kind::Invoice => self.ingest_invoice(&sess.peer_identity, &pt).await, Kind::Receipt => self.ingest_receipt(&sess.peer_identity, &pt).await, Kind::Tip => self.ingest_tip(&sess.peer_identity, &pt).await, @@ -1175,6 +1210,132 @@ impl Node { } } +/// HKDF info strings for the bootstrap derivation (see [`bootstrap_ratchet`]). +const RATCHET_BOOTSTRAP_SALT: &[u8] = b"onionwire-ratchet-v1-bootstrap"; +const RATCHET_BOOTSTRAP_ROOT_INFO: &[u8] = b"root"; +const RATCHET_BOOTSTRAP_KEY_INFO: &[u8] = b"ratchet-key"; + +/// Bootstrap a peer's ratchet state from key material both sides already have. +/// +/// The Noise handshake is frozen and carries no payload, so no wire field can +/// hand over an initial ratchet public key. Both peers instead derive the +/// bootstrap epoch from the X25519 DH of the two signed prekeys — each side +/// computes the same secret — and seed each side's initial ratchet keypair with +/// that DH plus *its own* identity pubkey. Each peer therefore derives its own +/// keypair and the peer's, and the two agree on the epoch without a new wire +/// field; fresh entropy enters at the first DH ratchet step. Because the +/// derivation is prekey-bound, a peer whose prekey changed gets its stored state +/// dropped (`Node::add_friend_payload`). +fn bootstrap_ratchet( + keys: &Keys, + peer_pk: &[u8], + peer_prekey: &[u8], +) -> Result { + let peer_pk: [u8; 32] = peer_pk + .try_into() + .map_err(|_| "peer pubkey is not 32 bytes".to_string())?; + let peer_prekey: [u8; 32] = peer_prekey + .try_into() + .map_err(|_| "peer prekey is not 32 bytes".to_string())?; + let shared = + StaticSecret::from(keys.prekey_sk).diffie_hellman(&X25519Public::from(peer_prekey)); + let hk = Hkdf::::new(Some(RATCHET_BOOTSTRAP_SALT), shared.as_bytes()); + + let mut root_key = [0u8; 32]; + hk.expand(RATCHET_BOOTSTRAP_ROOT_INFO, &mut root_key) + .map_err(|e| e.to_string())?; + let local = RatchetKeyPair::from_secret(ratchet_seed(&hk, &keys.identity_pk)?); + let remote = ratchet_seed(&hk, &peer_pk)?; + let remote_pub = X25519Public::from(&StaticSecret::from(remote)).to_bytes(); + Ok(RatchetState::bootstrap(root_key, local, remote_pub)) +} + +/// `HKDF(info = "ratchet-key" || pubkey)` — the initial ratchet secret both +/// peers compute for the peer with that identity pubkey. +fn ratchet_seed(hk: &Hkdf, pubkey: &[u8; 32]) -> Result<[u8; 32], String> { + let mut info = Vec::with_capacity(RATCHET_BOOTSTRAP_KEY_INFO.len() + 32); + info.extend_from_slice(RATCHET_BOOTSTRAP_KEY_INFO); + info.extend_from_slice(pubkey); + let mut seed = Zeroizing::new([0u8; 32]); + hk.expand(&info, &mut seed[..]).map_err(|e| e.to_string())?; + Ok(*seed) +} + +/// The peer's ratchet state: the persisted blob when there is one, a freshly +/// bootstrapped state otherwise. +/// +/// The blob is opaque to the store; `RatchetState::to_bytes`/`from_bytes` own +/// the format. Nothing is written here — the caller persists once, after a +/// successful encrypt/decrypt, so a rejected frame cannot leave a half-created +/// session behind. +fn ratchet_for(store: &Store, keys: &Keys, friend_pk: &[u8]) -> Result { + if let Some(blob) = store.load_ratchet(friend_pk).map_err(|e| e.to_string())? { + return RatchetState::from_bytes(&blob).map_err(|e| format!("ratchet state: {e}")); + } + let f = store + .get_friend(friend_pk) + .map_err(|e| e.to_string())? + .ok_or_else(|| "unknown friend".to_string())?; + if f.prekey.len() != 32 { + return Err("friend missing prekey".into()); + } + bootstrap_ratchet(keys, friend_pk, &f.prekey) +} + +/// Encode one chat send as a `rat ` frame, then persist the advanced state. +/// +/// Exactly one frame per call, and the caller passes those bytes to +/// `Outbox::send_payload`, so a retry re-sends them verbatim instead of +/// advancing the sending chain a second time. +/// +/// Public because it is the wire half of `Node::send`: `tests/ratchet_wire.rs` +/// drives the real path without Tor. Callers hold the store lock across +/// load → encrypt → save. +pub fn encode_chat_frame( + store: &Store, + keys: &Keys, + friend_pk: &[u8], + plaintext: &[u8], +) -> Result, String> { + let mut state = ratchet_for(store, keys, friend_pk)?; + let frame = state.encrypt(plaintext).map_err(|e| e.to_string())?; + let blob = Zeroizing::new(state.to_bytes()); + store + .save_ratchet(friend_pk, &blob) + .map_err(|e| e.to_string())?; + Ok(frame) +} + +/// Decrypt one inbound `rat ` frame and append it to the chat log as an +/// incoming line, then persist the advanced state. +/// +/// Returns the logged plaintext, or `Err` for anything that did not +/// authenticate — a bad frame writes no chat row and leaves the stored state +/// untouched, because `RatchetState` validates fully before it mutates. The +/// ciphertext is never stored and there is no plaintext fallback. +/// +/// Public for the same reason as [`encode_chat_frame`]. Callers hold the store +/// lock across load → decrypt → append → save, which is what makes the +/// read-modify-write atomic against a second inbound session on the same peer. +pub fn ingest_chat_frame( + store: &Store, + keys: &Keys, + peer_pk: &[u8], + frame: &[u8], +) -> Result, String> { + let mut state = ratchet_for(store, keys, peer_pk)?; + let plaintext = state.decrypt(frame).map_err(|e| e.to_string())?; + let line = Zeroizing::new(sanitize::display_text(&plaintext).as_bytes().to_vec()); + store + .append_message(peer_pk, "in", &line[..]) + .map_err(|e| e.to_string())?; + let blob = Zeroizing::new(state.to_bytes()); + store + .save_ratchet(peer_pk, &blob) + .map_err(|e| e.to_string())?; + Ok(line.to_vec()) +} + fn spawn_rend( node: Arc, rend: impl futures::Stream + Send + 'static, diff --git a/src/outbox.rs b/src/outbox.rs index 495e63e..325b9a3 100644 --- a/src/outbox.rs +++ b/src/outbox.rs @@ -143,9 +143,38 @@ impl Outbox { /// Try once. `Ok(Sent)` — delivered now. `Ok(Queued)` — the peer's onion is /// unreachable, the message is persisted and will be retried. `Err` — a /// protocol error or a bad local state, never retried. + /// + /// The bytes on the wire are `plaintext`; the *retry* path is where chat + /// differs, so chat uses [`Self::send_payload`]. pub async fn send(&self, friend_pk: &[u8], plaintext: &[u8]) -> Result { + self.send_inner(friend_pk, plaintext, None).await + } + + /// Same as [`Self::send`], but the wire bytes are an opaque `payload` that + /// a retry re-sends verbatim while the chat history keeps `plaintext`. + /// + /// Chat calls this with its ratchet frame: encoding the frame inside the + /// retry loop would advance the sending chain a second time and the peer + /// would see a second chat line under a new key. The frame is encoded once + /// by the caller, stored on the row, and replayed byte-for-byte. + pub async fn send_payload( + &self, + friend_pk: &[u8], + plaintext: &[u8], + payload: &[u8], + ) -> Result { + self.send_inner(friend_pk, plaintext, Some(payload)).await + } + + async fn send_inner( + &self, + friend_pk: &[u8], + plaintext: &[u8], + payload: Option<&[u8]>, + ) -> Result { let (onion, prekey) = self.target(friend_pk)?; - match self.deliverer.deliver(&onion, friend_pk, &prekey, plaintext).await { + let wire = payload.unwrap_or(plaintext); + match self.deliverer.deliver(&onion, friend_pk, &prekey, wire).await { Ok(()) => { self.store()?.append_message(friend_pk, "out", plaintext)?; Ok(OutboxStatus::Sent) @@ -155,14 +184,13 @@ impl Outbox { let now = unix_now(); let store = self.store()?; let message_id = store.append_message_id(friend_pk, "out", plaintext)?; - store.enqueue_outbox( - friend_pk, - message_id, - 1, - now + backoff_secs(0), - &e, - now, - )?; + let next = now + backoff_secs(0); + match payload { + Some(payload) => store.enqueue_outbox_payload( + friend_pk, message_id, payload, next, &e, now, + )?, + None => store.enqueue_outbox(friend_pk, message_id, 1, next, &e, now)?, + }; Ok(OutboxStatus::Queued) } } @@ -248,7 +276,13 @@ impl Outbox { }; let result = self .deliverer - .deliver(&onion, &entry.friend_pk, &prekey, &entry.body) + .deliver( + &onion, + &entry.friend_pk, + &prekey, + // Chat stores its frame here; everything else sends its body. + entry.payload.as_deref().unwrap_or(&entry.body), + ) .await; let status = match result { Ok(()) => { diff --git a/src/store.rs b/src/store.rs index 82669fe..496e004 100644 --- a/src/store.rs +++ b/src/store.rs @@ -154,6 +154,12 @@ pub struct OutboxEntry { pub friend_pk: Vec, pub message_id: i64, pub body: Vec, + /// What to put on the wire when it is set, instead of `body`. A chat send + /// stores its already-encoded ratchet frame here so a retry re-sends the + /// identical bytes instead of re-encrypting (which would burn a second + /// chain key and land as a second chat line at the peer). `None` means the + /// row predates payloads or is a locator/profile/payment row: send `body`. + pub payload: Option>, pub attempts: u32, pub next_attempt_at: i64, pub created_at: i64, @@ -272,7 +278,8 @@ impl Store { status TEXT NOT NULL CHECK(status IN ('queued','sending','sent','failed')), last_error TEXT, created_at INTEGER NOT NULL, - updated_at INTEGER NOT NULL + updated_at INTEGER NOT NULL, + payload BLOB ); CREATE INDEX IF NOT EXISTS outbox_due ON outbox (status, next_attempt_at); CREATE TABLE IF NOT EXISTS ratchet_sessions ( @@ -350,6 +357,14 @@ impl Store { "hs_nickname", "ALTER TABLE self ADD COLUMN hs_nickname TEXT NOT NULL DEFAULT 'ow0'", )?; + // Opaque send payload for rows that cannot re-derive their bytes (a + // chat send's ratchet frame). NULL means "send the message body", the + // pre-payload behaviour, so locator/profile/payment rows are unchanged. + self.add_column_if_missing( + "outbox", + "payload", + "ALTER TABLE outbox ADD COLUMN payload BLOB", + )?; Ok(()) } @@ -903,6 +918,39 @@ impl Store { Ok(self.conn.last_insert_rowid()) } + /// Queue one already-stored chat message for retry, with the exact bytes to + /// put on the wire. Chat uses this: the frame is encoded once, before the + /// first attempt, and every retry re-sends these bytes, so a retried + /// message cannot arrive as a second chat line under a new key. + /// + /// Narrower than [`Self::enqueue_outbox`] on purpose: a payload row is only + /// ever queued by the first attempt failing, so it is created at + /// `attempts = 1` and takes no attempt count. + pub fn enqueue_outbox_payload( + &self, + friend_pk: &[u8], + message_id: i64, + payload: &[u8], + next_attempt_at: i64, + last_error: &str, + now: i64, + ) -> Result { + let friend_id: i64 = self + .conn + .query_row( + "SELECT id FROM friends WHERE pubkey = ?1", + params![friend_pk], + |row| row.get(0), + ) + .map_err(|_| Error("friend not found".into()))?; + self.conn.execute( + "INSERT INTO outbox (friend_id, message_id, attempts, next_attempt_at, status, last_error, created_at, updated_at, payload) + VALUES (?1, ?2, 1, ?3, 'queued', ?4, ?5, ?5, ?6)", + params![friend_id, message_id, next_attempt_at, last_error, now, payload], + )?; + Ok(self.conn.last_insert_rowid()) + } + /// Rows whose backoff has elapsed: the timer trigger for the worker. pub fn due_outbox(&self, now: i64, limit: i64) -> Result> { self.outbox_query( @@ -1072,6 +1120,7 @@ impl Store { row.get::<_, i64>(8)?, row.get::<_, String>(9)?, row.get::<_, Vec>(10)?, + row.get::<_, Option>>(11)?, )) })?; let mut out = Vec::new(); @@ -1088,6 +1137,7 @@ impl Store { m_friend_id, dir, blob, + payload, ) = row?; let aad = message_aad(m_friend_id, &dir, message_id); let body = crate::backup::aead_decrypt(&self.msg_key, &blob, &aad) @@ -1097,6 +1147,7 @@ impl Store { friend_pk, message_id, body, + payload, attempts: attempts as u32, next_attempt_at, created_at, @@ -1431,7 +1482,7 @@ fn mkdir_700(path: &Path) -> Result<()> { /// Base projection for outbox rows: the body comes from the `messages` row the /// outbox row points at, so it stays under that row's AEAD + AAD. const OUTBOX_SELECT: &str = "SELECT o.id, f.pubkey, o.message_id, o.attempts, o.next_attempt_at, \ - o.status, o.last_error, o.created_at, m.friend_id, m.dir, m.plaintext \ + o.status, o.last_error, o.created_at, m.friend_id, m.dir, m.plaintext, o.payload \ FROM outbox o JOIN friends f ON f.id = o.friend_id JOIN messages m ON m.id = o.message_id"; /// AAD: `owmsg1` || friend_id_le64 || dir || 0x00 || row_id_le64 diff --git a/tests/dispatch.rs b/tests/dispatch.rs index f97254d..00e9d9f 100644 --- a/tests/dispatch.rs +++ b/tests/dispatch.rs @@ -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); diff --git a/tests/outbox.rs b/tests/outbox.rs index 3b7cc13..2be2a8f 100644 --- a/tests/outbox.rs +++ b/tests/outbox.rs @@ -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(); diff --git a/tests/ratchet_wire.rs b/tests/ratchet_wire.rs new file mode 100644 index 0000000..de32fbd --- /dev/null +++ b/tests/ratchet_wire.rs @@ -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>>, +} + +impl Recorder { + fn new(fail_times: usize) -> Arc { + Arc::new(Self { + fail_times: AtomicUsize::new(fail_times), + sent: Mutex::new(Vec::new()), + }) + } + + fn sent(&self) -> Vec> { + 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>, + 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 { + 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 { + 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, 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" + ); +} diff --git a/tests/tui_spec.rs b/tests/tui_spec.rs index 549b63b..d81dd41 100644 --- a/tests/tui_spec.rs +++ b/tests/tui_spec.rs @@ -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, -- 2.52.0