Adds an ML-KEM-768 install key beside the ed25519 identity and x25519 prekey. A friend added from a v2 invite always gets a version-2 PQ prelude before Noise msg 1, and both sides bind (ct, ss_kem) into the Noise prologue (onionwire-v2 \0 ct \0 ss_kem). The row decides: a kem_pk friend without a prelude is rejected with 'prelude required', a prelude for a classical row with 'unexpected prelude'. Invites are now onionwire:v2 with kem=<base64url pk>; decode still accepts v1 (no kem) and yields a classical friend. F8 rotates the KEM key with the prekey and hard-cuts stored ratchet state. The TUI labels a legacy friend 'classical'. Docs: PROTOCOL (keys, framing, prologues, no-downgrade, invite v2), THREAT_MODEL (what PQ transport does and does not buy; epoch 0 stays classical), README (invite size, F8, legacy caveat). SDK exposes pq on InviteInfo/FriendInfo and gains a v2 decode round-trip test.
414 lines
14 KiB
Rust
414 lines
14 KiB
Rust
//! Local outbox: queue a chat send when the peer's onion is unreachable, retry
|
|
//! with exponential backoff, expose a terminal status. All offline — the
|
|
//! transport is a fake deliverer, so these run without Tor.
|
|
|
|
use std::sync::atomic::{AtomicUsize, Ordering};
|
|
use std::sync::{Arc, Mutex};
|
|
|
|
use onionwire::outbox::{
|
|
BACKOFF_CAP_SECS, BACKOFF_START_SECS, BoxFut, Deliverer, Outbox, OutboxStatus, backoff_secs,
|
|
is_permanent_send_error,
|
|
};
|
|
use onionwire::Store;
|
|
|
|
const PASS: &str = "outbox-pass";
|
|
|
|
fn pk(tag: u8) -> [u8; 32] {
|
|
let mut k = [0u8; 32];
|
|
k[0] = tag;
|
|
k
|
|
}
|
|
|
|
/// Fails `fail_times` dials with `err`, then succeeds and records the plaintext.
|
|
struct Flaky {
|
|
fail_times: AtomicUsize,
|
|
err: String,
|
|
calls: AtomicUsize,
|
|
delivered: Mutex<Vec<Vec<u8>>>,
|
|
kems: Mutex<Vec<Option<Vec<u8>>>>,
|
|
}
|
|
|
|
impl Flaky {
|
|
fn new(fail_times: usize, err: &str) -> Arc<Self> {
|
|
Arc::new(Self {
|
|
fail_times: AtomicUsize::new(fail_times),
|
|
err: err.into(),
|
|
calls: AtomicUsize::new(0),
|
|
delivered: Mutex::new(Vec::new()),
|
|
kems: Mutex::new(Vec::new()),
|
|
})
|
|
}
|
|
|
|
fn calls(&self) -> usize {
|
|
self.calls.load(Ordering::SeqCst)
|
|
}
|
|
|
|
fn delivered(&self) -> Vec<Vec<u8>> {
|
|
self.delivered.lock().unwrap().clone()
|
|
}
|
|
}
|
|
|
|
impl Deliverer for Flaky {
|
|
fn deliver<'a>(
|
|
&'a self,
|
|
_onion: &'a str,
|
|
_pinned_id: &'a [u8],
|
|
_prekey: &'a [u8],
|
|
plaintext: &'a [u8],
|
|
_remote_kem: Option<&'a [u8]>,
|
|
) -> BoxFut<'a, Result<(), String>> {
|
|
self.calls.fetch_add(1, Ordering::SeqCst);
|
|
self.kems
|
|
.lock()
|
|
.unwrap()
|
|
.push(_remote_kem.map(|k| k.to_vec()));
|
|
let left = self.fail_times.load(Ordering::SeqCst);
|
|
if left > 0 {
|
|
self.fail_times.fetch_sub(1, Ordering::SeqCst);
|
|
let err = self.err.clone();
|
|
return Box::pin(async move { Err(err) });
|
|
}
|
|
self.delivered.lock().unwrap().push(plaintext.to_vec());
|
|
Box::pin(async move { Ok(()) })
|
|
}
|
|
}
|
|
|
|
fn store_and_friend(dir: &std::path::Path, onion: &str) -> Arc<Mutex<Store>> {
|
|
let store = Store::open_at_with_passphrase(dir, PASS).expect("open store");
|
|
store.upsert_friend(&pk(1), onion, None).unwrap();
|
|
store.set_friend_prekey(&pk(1), &[7u8; 32]).unwrap();
|
|
Arc::new(Mutex::new(store))
|
|
}
|
|
|
|
fn outbox(store: Arc<Mutex<Store>>, deliverer: Arc<dyn Deliverer>, max_attempts: u32) -> Outbox {
|
|
Outbox::new(store, deliverer).with_max_attempts(max_attempts)
|
|
}
|
|
|
|
#[test]
|
|
fn backoff_schedule_doubles_from_30s_and_caps_at_30m() {
|
|
assert_eq!(BACKOFF_START_SECS, 30);
|
|
assert_eq!(BACKOFF_CAP_SECS, 1800);
|
|
let got: Vec<i64> = (0..9).map(backoff_secs).collect();
|
|
assert_eq!(
|
|
got,
|
|
vec![30, 60, 120, 240, 480, 960, 1800, 1800, 1800],
|
|
"exponential backoff, capped"
|
|
);
|
|
assert_eq!(
|
|
backoff_secs(u32::MAX),
|
|
BACKOFF_CAP_SECS,
|
|
"no overflow at silly attempt counts"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn transport_errors_are_retryable_protocol_errors_are_not() {
|
|
assert!(!is_permanent_send_error(
|
|
"connect abc.onion:80: timed out"
|
|
));
|
|
assert!(!is_permanent_send_error("connect abc.onion:80: refused"));
|
|
assert!(is_permanent_send_error("fingerprint mismatch"));
|
|
assert!(is_permanent_send_error("frame too large"));
|
|
assert!(is_permanent_send_error("bad version"));
|
|
assert!(is_permanent_send_error("bad identity proof"));
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn send_to_dead_onion_is_queued_and_row_persists() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let store = store_and_friend(dir.path(), "dead.onion");
|
|
let dead = Flaky::new(usize::MAX, "connect dead.onion:80: timed out");
|
|
let ob = outbox(Arc::clone(&store), dead, 8);
|
|
|
|
let status = ob.send(&pk(1), b"hello dead peer").await.unwrap();
|
|
assert_eq!(status, OutboxStatus::Queued, "dead onion must queue, not Err");
|
|
assert!(!status.is_terminal());
|
|
|
|
let pending = ob.pending(&pk(1)).unwrap();
|
|
assert_eq!(pending.len(), 1, "one outbox row");
|
|
assert_eq!(pending[0].status, OutboxStatus::Queued);
|
|
assert_eq!(pending[0].attempts, 1, "the immediate attempt counted");
|
|
assert!(
|
|
ob.status_of_message(pending[0].message_id).unwrap().is_some(),
|
|
"status is addressable by chat row id"
|
|
);
|
|
|
|
// The chat line is already in local history while it waits.
|
|
let msgs = store.lock().unwrap().list_messages(&pk(1)).unwrap();
|
|
assert_eq!(msgs.len(), 1);
|
|
assert_eq!(msgs[0].dir, "out");
|
|
assert_eq!(msgs[0].plaintext, b"hello dead peer");
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn flaky_peer_is_flushed_by_the_worker_on_schedule() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let store = store_and_friend(dir.path(), "flaky.onion");
|
|
// First dial fails (the immediate one), the rest succeed: "peer came up".
|
|
let flaky = Flaky::new(1, "connect flaky.onion:80: timed out");
|
|
let ob = outbox(Arc::clone(&store), flaky.clone(), 8);
|
|
|
|
let status = ob.send(&pk(1), b"late hello").await.unwrap();
|
|
assert_eq!(status, OutboxStatus::Queued);
|
|
let next = ob.pending(&pk(1)).unwrap()[0].next_attempt_at;
|
|
assert_eq!(
|
|
next - ob.pending(&pk(1)).unwrap()[0].created_at,
|
|
BACKOFF_START_SECS,
|
|
"first retry waits the start of the schedule"
|
|
);
|
|
|
|
// Too early: the worker must not dial out of schedule.
|
|
let t0 = next - BACKOFF_START_SECS;
|
|
let fired = ob.tick(t0 + BACKOFF_START_SECS - 1).await.unwrap();
|
|
assert!(fired.is_empty(), "not due yet");
|
|
|
|
let fired = ob.tick(t0 + BACKOFF_START_SECS).await.unwrap();
|
|
assert_eq!(fired.len(), 1);
|
|
assert_eq!(fired[0].1, OutboxStatus::Sent);
|
|
assert_eq!(flaky.delivered(), vec![b"late hello".to_vec()]);
|
|
assert!(
|
|
ob.pending(&pk(1)).unwrap().is_empty(),
|
|
"delivered rows leave the pending set"
|
|
);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn max_attempts_reaches_failed_and_stops_retrying() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let store = store_and_friend(dir.path(), "gone.onion");
|
|
let dead = Flaky::new(usize::MAX, "connect gone.onion:80: timed out");
|
|
let ob = outbox(Arc::clone(&store), dead.clone(), 3);
|
|
|
|
assert_eq!(
|
|
ob.send(&pk(1), b"never lands").await.unwrap(),
|
|
OutboxStatus::Queued
|
|
);
|
|
assert_eq!(dead.calls(), 1, "immediate attempt");
|
|
|
|
// Walk the schedule forward; each tick is one more attempt.
|
|
let mut now = ob.pending(&pk(1)).unwrap()[0].next_attempt_at;
|
|
let mut last = OutboxStatus::Queued;
|
|
for _ in 0..6 {
|
|
let fired = ob.tick(now).await.unwrap();
|
|
if let Some((_, st)) = fired.first() {
|
|
last = st.clone();
|
|
}
|
|
if last == OutboxStatus::Failed("connect gone.onion:80: timed out".into()) {
|
|
break;
|
|
}
|
|
now += BACKOFF_CAP_SECS;
|
|
}
|
|
assert_eq!(
|
|
last,
|
|
OutboxStatus::Failed("connect gone.onion:80: timed out".into()),
|
|
"gives up after max_attempts"
|
|
);
|
|
assert_eq!(dead.calls(), 3, "attempts stop at the cap");
|
|
|
|
let calls_at_cap = dead.calls();
|
|
for _ in 0..3 {
|
|
now += BACKOFF_CAP_SECS;
|
|
assert!(ob.tick(now).await.unwrap().is_empty(), "no more retries");
|
|
}
|
|
assert_eq!(dead.calls(), calls_at_cap);
|
|
|
|
let pending = ob.pending(&pk(1)).unwrap();
|
|
assert_eq!(pending.len(), 1);
|
|
assert!(matches!(pending[0].status, OutboxStatus::Failed(_)));
|
|
assert!(pending[0].status.is_terminal());
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn queued_message_survives_reopen_and_flushes_after_unlock() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let pk1 = pk(1);
|
|
let next_attempt_at = {
|
|
let store = store_and_friend(dir.path(), "later.onion");
|
|
let dead = Flaky::new(usize::MAX, "connect later.onion:80: timed out");
|
|
let ob = outbox(Arc::clone(&store), dead, 8);
|
|
assert_eq!(
|
|
ob.send(&pk1, b"survives restart").await.unwrap(),
|
|
OutboxStatus::Queued
|
|
);
|
|
ob.pending(&pk1).unwrap()[0].next_attempt_at
|
|
};
|
|
|
|
// Process exit: everything above is dropped and the store is reopened.
|
|
let store = Arc::new(Mutex::new(
|
|
Store::open_at_with_passphrase(dir.path(), PASS).unwrap(),
|
|
));
|
|
let up = Flaky::new(0, "");
|
|
let ob = outbox(Arc::clone(&store), up.clone(), 8);
|
|
let fired = ob.flush_all(next_attempt_at).await.unwrap();
|
|
assert_eq!(fired.len(), 1);
|
|
assert_eq!(fired[0].1, OutboxStatus::Sent);
|
|
assert_eq!(up.delivered(), vec![b"survives restart".to_vec()]);
|
|
assert!(ob.pending(&pk1).unwrap().is_empty());
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn protocol_error_fails_immediately_and_is_not_queued() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let store = store_and_friend(dir.path(), "liar.onion");
|
|
let liar = Flaky::new(usize::MAX, "fingerprint mismatch");
|
|
let ob = outbox(Arc::clone(&store), liar, 8);
|
|
|
|
let err = ob.send(&pk(1), b"hello liar").await.unwrap_err();
|
|
assert!(err.contains("fingerprint mismatch"), "got {err}");
|
|
assert!(
|
|
ob.pending(&pk(1)).unwrap().is_empty(),
|
|
"protocol errors are never queued"
|
|
);
|
|
assert!(
|
|
store.lock().unwrap().list_messages(&pk(1)).unwrap().is_empty(),
|
|
"a failed protocol send is not written to history"
|
|
);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn flush_friend_ignores_the_schedule_when_that_peer_was_seen() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let store = store_and_friend(dir.path(), "seen.onion");
|
|
let flaky = Flaky::new(1, "connect seen.onion:80: timed out");
|
|
let ob = outbox(Arc::clone(&store), flaky.clone(), 8);
|
|
|
|
assert_eq!(
|
|
ob.send(&pk(1), b"you are back").await.unwrap(),
|
|
OutboxStatus::Queued
|
|
);
|
|
let now = ob.pending(&pk(1)).unwrap()[0].created_at;
|
|
let fired = ob.flush_friend(&pk(1), now).await.unwrap();
|
|
assert_eq!(fired.len(), 1, "a live handshake flushes without waiting");
|
|
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();
|
|
let store = store_and_friend(dir.path(), "dead.onion");
|
|
let dead = Flaky::new(usize::MAX, "connect dead.onion:80: timed out");
|
|
let ob = outbox(Arc::clone(&store), dead, 8);
|
|
assert_eq!(
|
|
ob.send(&pk(1), b"wipe me").await.unwrap(),
|
|
OutboxStatus::Queued
|
|
);
|
|
assert_eq!(ob.pending(&pk(1)).unwrap().len(), 1);
|
|
|
|
store.lock().unwrap().wipe_messages().unwrap();
|
|
|
|
assert!(
|
|
ob.pending(&pk(1)).unwrap().is_empty(),
|
|
"wipe must drop queued sends, not only chat"
|
|
);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn missing_prekey_is_fatal_not_queued() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let store = Arc::new(Mutex::new(
|
|
Store::open_at_with_passphrase(dir.path(), PASS).unwrap(),
|
|
));
|
|
{
|
|
let s = store.lock().unwrap();
|
|
s.upsert_friend(&pk(2), "noprekey.onion", None).unwrap();
|
|
}
|
|
let ob = outbox(Arc::clone(&store), Flaky::new(0, ""), 8);
|
|
let err = ob.send(&pk(2), b"hi").await.unwrap_err();
|
|
assert!(err.contains("prekey"), "got {err}");
|
|
assert!(ob.pending(&pk(2)).unwrap().is_empty());
|
|
}
|
|
|
|
/// The outbound rule is derived from the friend row: a v2 friend always gets
|
|
/// the KEM key handed to the dialer (which then sends the prelude), a v1 friend
|
|
/// gets `None` and stays classical. The outbox never decides from wire input.
|
|
#[tokio::test]
|
|
async fn the_outbox_hands_the_kem_key_from_the_friend_row_to_the_dialer() {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let store = store_and_friend(dir.path(), "pq.onion");
|
|
let kp = onionwire::kem::generate();
|
|
store
|
|
.lock()
|
|
.unwrap()
|
|
.set_friend_kem(&pk(1), Some(&kp.pk))
|
|
.unwrap();
|
|
|
|
let pq = Flaky::new(0, "");
|
|
outbox(Arc::clone(&store), Arc::clone(&pq) as Arc<dyn Deliverer>, 8)
|
|
.send(&pk(1), b"pq")
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(
|
|
pq.kems.lock().unwrap().as_slice(),
|
|
[Some(kp.pk.to_vec())],
|
|
"a v2 friend must always send the prelude"
|
|
);
|
|
|
|
// A legacy row (v1 invite) has no kem column value -> classical session.
|
|
let legacy = Flaky::new(0, "");
|
|
store.lock().unwrap().set_friend_kem(&pk(1), None).unwrap();
|
|
outbox(Arc::clone(&store), Arc::clone(&legacy) as Arc<dyn Deliverer>, 8)
|
|
.send(&pk(1), b"legacy")
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(
|
|
legacy.kems.lock().unwrap().as_slice(),
|
|
[None],
|
|
"a v1 friend stays classical; no invented PQ protection"
|
|
);
|
|
}
|