From 30f438c394e5ef231a98b9f1821896d4b1cf687d Mon Sep 17 00:00:00 2001 From: agent Date: Thu, 22 Oct 2026 22:46:28 -0400 Subject: [PATCH 1/2] fil: pad chunk bodies to a length ladder, document the residual MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Each `fil ` chunk carried its raw bytes in a one-shot Noise session, so the frame length was the exact chunk size: the tail chunk of every file told an observer the file's size, and the chunk count told them the rest. Pad the chunk body with the chat encoding (uint16 pad_len || data || random fill) on a `fil ` ladder that continues past chat's 32 KiB ceiling — 512..49152 — because a chunk is bounded by the frame budget (~64 KiB of plaintext), not by a line of human text. The top rung is a half-step: 65536 cannot fit one Noise body, and 48 KiB leaves the worst-case header (128-byte name, 5-digit counters) more than 16 KiB of slack. The raw chunk cap becomes the top rung's body (49150 bytes), so a 1 MiB file is 22 one-shot sessions instead of 17. `pad_len` is authenticated by the session's ChaCha20-Poly1305 tag; `decode_checked` treats an overrunning `pad_len` as a protocol error and drops the chunk whole rather than writing a truncated one. `total_chunks`/`data_cap` stay the reassembly authority and the hash check is untouched. PROTOCOL.md gains the ladder in “Length buckets” and the padded `fil ` frame layout, and states the honest residual: padding hides per-chunk size only — the chunk count still reveals total size in buckets, and timing, circuit patterns and retry cadence remain visible. No persistent session, no channel binding, no ratcheting of chunks. --- docs/PROTOCOL.md | 70 ++++++++++++++++++++++------- src/file.rs | 100 +++++++++++++++++++++++++++++++++--------- src/node.rs | 23 ++++++++-- src/padding.rs | 50 +++++++++++++++++---- tests/file.rs | 112 ++++++++++++++++++++++++++++++++++++++++++++--- tests/padding.rs | 82 +++++++++++++++++++++++++++++++++- 6 files changed, 383 insertions(+), 54 deletions(-) diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.md index bec89a8..0b8415f 100644 --- a/docs/PROTOCOL.md +++ b/docs/PROTOCOL.md @@ -96,17 +96,19 @@ uint8 body[length] - Other `version` values are a hard fail (close the stream). - Length that does not match the bytes on the wire is a hard fail. -`length` still reveals the exact ciphertext size. Chat hides it by padding the -plaintext to a bucket before encryption (see [Length buckets](#length-buckets)). -Other frame types are not padded. +`length` still reveals the exact ciphertext size. Chat and `fil ` chunk bodies +hide it by padding the plaintext to a bucket before encryption (see +[Length buckets](#length-buckets)). Other frame types are not padded. ## Length buckets -Normative for chat. A chat line is padded to one fixed ladder **before** the -ratchet encrypts it, so the padding is inside ChaCha20-Poly1305, inside the -Noise session, and authenticated by both. An observer sees a ciphertext whose -length is one of the ladder values (plus constant overhead), never the body -length. +Normative for chat lines and `fil ` chunk bodies. A chat line is padded to one +fixed ladder **before** the ratchet encrypts it, so the padding is inside +ChaCha20-Poly1305, inside the Noise session, and authenticated by both. A `fil ` +chunk body is padded with the same encoding on a longer ladder before its +one-shot Noise session encrypts it, so its padding is authenticated by that +session's tag. An observer sees a ciphertext whose length is one of the ladder +values (plus constant overhead), never the body length. Ladder — padded-plaintext sizes in bytes: @@ -179,10 +181,36 @@ first hybrid ratchet step (`kem_pub[1184] || kem_ct[1088]`). Epoch 0 of a chat is always classical, so the first `rat ` frame of a friend relationship uses the 40-byte header. -`fil ` chunks are deliberately **not** padded. They are raw file bytes paced -through the accept token bucket, and padding them would either cut the usable -chunk size or spend the 65535 frame cap on fill; the chunk size stays as -specified under `fil ` — file chunk. +### `fil ` chunk bodies + +A `fil ` chunk body — everything after the last newline of the frame, see +`fil ` — file chunk below — is padded with the chat encoding above and a longer +ladder: + +``` +512, 1024, 2048, 4096, 8192, 16384, 32768, 49152 +``` + +- The rungs up to 32768 are the chat ladder's. The chat floor of 256 is not + used: every `fil ` frame already carries ~115 bytes of ASCII header, so a + 256-byte rung would round almost every chunk up for no gain. +- 49152 (48 KiB) is the top rung. The doubled 65536 cannot fit one Noise body + (a plaintext is at most 65519 bytes, tag included), and 48 KiB leaves the + worst-case `fil ` header — 128-byte name, 5-digit `idx` and `total`, 243 + bytes — more than 16 KiB of slack. +- The raw chunk cap is the top rung's body, 49150 bytes. A chunk therefore + never needs more than one rung and `pad_len` always fits a `uint16`. A chunk + body larger than 49150 bytes is a protocol error and MUST fail closed. +- The receiver rules above are unchanged: `pad_len` is the only authority for + the chunk body's length, an overrun is a hard failure and the chunk is + dropped whole, and the total padded length is not required to be a ladder + value. + +This hides the chunk body length only. The *number* of `fil ` chunks still +reveals the file's size in buckets (a 1 MiB file is 22 chunks), and transfer is +still one Noise session per chunk, so timing, circuit patterns and retry +cadence remain visible exactly as they are for chat. Padding adds no persistent +session, no channel binding and no ratchet between chunks. This hides length, not timing: one Noise session per message, retry cadence and circuit timing are unchanged and remain accepted costs (see @@ -499,15 +527,27 @@ fails the transfer. No outbox, no resume, no continuation under a new `xfer_id`. ``` -fil \n\n\n/\n +fil \n\n\n/\n ``` - `xfer_id` — 16 random bytes (32 hex) - `filename` — 1–128 bytes, no `/`, NUL, newline, `.`, or `..`; no C0/C1 controls or bidi/format marks (U+202A–U+202E, U+2066–U+2069, U+200E, U+200F, U+200B, U+200C) - `sha256` — SHA-256 of the **entire** file (64 hex), repeated on every chunk - `idx` is 0-based; `total` ≥ 1; `idx < total` -- last line is raw chunk bytes (not hex), length chosen so the framed Noise - ciphertext stays ≤ 65535 (account for a 16-byte Poly1305 tag plus ASCII header) +- last line is the chunk body padded to a `fil ` length bucket (see + [Length buckets](#length-buckets)): `uint16 pad_len` big-endian, the raw + chunk bytes, then `pad_len` random fill bytes. The padded body MUST be + exactly the smallest `fil ` ladder value that is at least `2 + data_len`, + and `pad_len = bucket - 2 - data_len`. +- The raw chunk is at most **49150** bytes (the top rung's body). The ASCII + header, the padded body and the 16-byte Poly1305 tag together stay under the + 65535 frame cap. +- The padding is inside the one-shot Noise session, so `pad_len` is + authenticated by that session's ChaCha20-Poly1305 tag — a tampered length + fails the session rather than a checksum and the chunk is never written. + `pad_len` is the only authority for the boundary: a receiver MUST NOT trim + trailing fill, and MUST reject a `pad_len` that overruns the body as a + protocol error, dropping the whole chunk instead of writing a truncated one. Chunks MUST arrive in order for a given `xfer_id`. A bad chunk or hash mismatch deletes the partial. Empty files are one chunk. Successful receive diff --git a/src/file.rs b/src/file.rs index 0c8798e..58dce7b 100644 --- a/src/file.rs +++ b/src/file.rs @@ -12,6 +12,7 @@ use rand::RngCore; use sha2::{Digest, Sha256}; use crate::frame; +use crate::padding; use crate::sanitize; pub type Result = std::result::Result; @@ -141,8 +142,32 @@ pub fn chunks(filename: &str, bytes: &[u8]) -> Result> { Ok(out) } -pub fn encode(chunk: &Chunk) -> Vec { - let mut out = Vec::from(PREFIX); +/// Bytes of a `fil ` plaintext before the padded chunk body: prefix, the four +/// newline-terminated metadata fields and the final newline. The body that +/// follows is `uint16 pad_len || data || random fill`, sized to one +/// [`padding::FIL_BUCKETS`] rung, so +/// `encode(chunk).len() == overhead(chunk) + fil_bucket_for(data.len())`. +pub fn overhead(chunk: &Chunk) -> usize { + PREFIX.len() + + XFER_LEN * 2 + + 1 + + chunk.filename.len() + + 1 + + 64 + + 1 + + chunk.idx.to_string().len() + + 1 + + chunk.total.to_string().len() + + 1 +} + +/// `fil ` plaintext with the chunk body padded to a length bucket. The padding +/// sits after the last newline, inside the Noise session, so its `pad_len` is +/// authenticated by the same ChaCha20-Poly1305 tag as the chunk itself. +pub fn encode(chunk: &Chunk) -> Result> { + let body = padding::encode_fil(&chunk.data).map_err(Error)?; + let mut out = Vec::with_capacity(overhead(chunk) + body.len()); + out.extend_from_slice(PREFIX); out.extend_from_slice(to_hex(&chunk.xfer_id).as_bytes()); out.push(b'\n'); out.extend_from_slice(chunk.filename.as_bytes()); @@ -153,35 +178,63 @@ pub fn encode(chunk: &Chunk) -> Vec { out.push(b'/'); out.extend_from_slice(chunk.total.to_string().as_bytes()); out.push(b'\n'); - out.extend_from_slice(&chunk.data); - out + out.extend_from_slice(&body); + Ok(out) } -pub fn decode(pt: &[u8]) -> Option { - let rest = pt.strip_prefix(PREFIX)?; +/// Decode one `fil ` plaintext. `Ok(None)` means the bytes are not a `fil ` +/// frame at all; `Err` means a `fil ` frame that is malformed or whose +/// `pad_len` does not describe a body, which the caller must drop rather than +/// truncate. `pad_len` is the only authority for the body boundary. +pub fn decode_checked(pt: &[u8]) -> Result> { + let Some(rest) = pt.strip_prefix(PREFIX) else { + return Ok(None); + }; let mut parts = rest.splitn(5, |&b| b == b'\n'); - let xfer_hex = std::str::from_utf8(parts.next()?).ok()?; - let filename = std::str::from_utf8(parts.next()?).ok()?; - let sha_hex = std::str::from_utf8(parts.next()?).ok()?; - let idx_total = std::str::from_utf8(parts.next()?).ok()?; - let data = parts.next()?.to_vec(); - safe_name(filename).ok()?; - let xfer_id: [u8; XFER_LEN] = from_hex(xfer_hex)?.try_into().ok()?; - let sha256: [u8; 32] = from_hex(sha_hex)?.try_into().ok()?; - let (idx_s, total_s) = idx_total.split_once('/')?; - let idx: u32 = idx_s.parse().ok()?; - let total: u32 = total_s.parse().ok()?; + let (Some(xfer_hex), Some(filename), Some(sha_hex), Some(idx_total), Some(body)) = ( + parts.next(), + parts.next(), + parts.next(), + parts.next(), + parts.next(), + ) else { + return Err(Error("short fil frame".into())); + }; + let bad = || Error("bad fil frame".into()); + let xfer_hex = std::str::from_utf8(xfer_hex).map_err(|_| bad())?; + let filename = std::str::from_utf8(filename).map_err(|_| bad())?; + let sha_hex = std::str::from_utf8(sha_hex).map_err(|_| bad())?; + let idx_total = std::str::from_utf8(idx_total).map_err(|_| bad())?; + safe_name(filename)?; + let xfer_id: [u8; XFER_LEN] = from_hex(xfer_hex) + .ok_or_else(bad)? + .try_into() + .map_err(|_| bad())?; + let sha256: [u8; 32] = from_hex(sha_hex) + .ok_or_else(bad)? + .try_into() + .map_err(|_| bad())?; + let (idx_s, total_s) = idx_total.split_once('/').ok_or_else(bad)?; + let idx: u32 = idx_s.parse().map_err(|_| bad())?; + let total: u32 = total_s.parse().map_err(|_| bad())?; if total == 0 || idx >= total { - return None; + return Err(Error("bad chunk index".into())); } - Some(Chunk { + let data = padding::decode(body).map_err(Error)?; + Ok(Some(Chunk { xfer_id, filename: filename.to_string(), sha256, idx, total, - data, - }) + data: data.to_vec(), + })) +} + +/// `Option` shape for callers that only care whether a chunk parsed. Use +/// [`decode_checked`] when the failure reason matters. +pub fn decode(pt: &[u8]) -> Option { + decode_checked(pt).ok().flatten() } pub fn chat_line(name: &str, nbytes: usize) -> String { @@ -347,6 +400,9 @@ fn total_chunks(filename: &str, len: usize) -> Result { } } +/// Raw chunk bytes that fit one frame once the body is padded: the frame budget +/// (`MAX_FRAME` minus the Noise tag, the ASCII header and the 2-byte `pad_len`) +/// and never more than the largest `fil ` bucket body. fn data_cap(filename: &str, total: u32) -> usize { let digits = total.to_string().len().max(1); let header = @@ -354,6 +410,8 @@ fn data_cap(filename: &str, total: u32) -> usize { frame::MAX_FRAME .saturating_sub(NOISE_TAG) .saturating_sub(header) + .saturating_sub(padding::PAD_HEADER_LEN) + .min(padding::FIL_MAX_BODY) } fn write_partial(path: &Path, data: &[u8], append: bool) -> Result<()> { diff --git a/src/node.rs b/src/node.rs index 86b6412..2111d48 100644 --- a/src/node.rs +++ b/src/node.rs @@ -1875,7 +1875,15 @@ impl Node { pub async fn send_file(&self, friend_pk: &[u8], path: &Path) -> Result { let (name, bytes) = file::read_limited(path).map_err(|e| e.to_string())?; let chunks = file::chunks(&name, &bytes).map_err(|e| e.to_string())?; - let frames: Vec> = chunks.iter().map(file::encode).collect(); + // Each chunk body is padded to the `fil ` length ladder before the + // one-shot Noise session encrypts it, so the frame length reveals only + // a bucket. A chunk is capped at the largest bucket body, so `encode` + // cannot fail here. + let frames: Vec> = chunks + .iter() + .map(file::encode) + .collect::>() + .map_err(|e| e.to_string())?; file::send_chunks(frames.len(), |i| self.send_once(friend_pk, &frames[i])).await?; self.store .lock() @@ -2058,8 +2066,17 @@ impl Node { } fn ingest_file(&self, peer: &[u8], pt: &[u8]) -> Result<(), String> { - let Some(chunk) = file::decode(pt) else { - return Ok(()); + // A `fil ` plaintext carries its chunk body padded to a length bucket; + // `decode_checked` strips the fill and treats an overrunning `pad_len` + // as a protocol error rather than writing a truncated chunk. Bytes that + // are not a `fil ` frame are simply not ours. + let chunk = match file::decode_checked(pt) { + Ok(Some(chunk)) => chunk, + Ok(None) => return Ok(()), + Err(e) => { + eprintln!("fil dropped ({e})"); + return Ok(()); + } }; let fp: String = peer.iter().map(|b| format!("{b:02x}")).collect(); let done = { diff --git a/src/padding.rs b/src/padding.rs index 4b6e15f..490c097 100644 --- a/src/padding.rs +++ b/src/padding.rs @@ -1,10 +1,13 @@ -//! Length buckets for chat plaintext. Normative spec: `docs/PROTOCOL.md`, -//! “Length buckets”. +//! Length buckets for chat and file-chunk plaintext. Normative spec: +//! `docs/PROTOCOL.md`, “Length buckets”. //! //! Chat bodies are padded to one of eight sizes *before* the ratchet encrypts //! them, so the padding is authenticated by ChaCha20-Poly1305 and by the Noise -//! session around it. An observer sees only the bucket. The encoding is -//! explicit and never trimmed: +//! session around it. `fil ` chunk bodies use the same encoding and a longer +//! ladder ([`FIL_BUCKETS`]): a chunk is capped by the frame budget rather than +//! by a line of human text, so chat's 32 KiB ceiling would double the number of +//! one-shot sessions a file costs. An observer sees only the bucket. The +//! encoding is explicit and never trimmed: //! //! ```text //! uint16 pad_len = big-endian length of the random fill that follows @@ -29,19 +32,50 @@ pub const BUCKETS: [usize; 8] = [256, 512, 1024, 2048, 4096, 8192, 16384, 32768] /// The largest body that fits the largest bucket (`32768 - 2`). pub const MAX_BODY: usize = BUCKETS[BUCKETS.len() - 1] - PAD_HEADER_LEN; +/// The `fil ` chunk ladder. Same encoding and the same 2-byte header as chat; +/// the rungs continue past chat's 32 KiB ceiling because a chunk body is +/// bounded by the frame budget (one Noise plaintext is at most 65519 bytes), +/// not by a line of human text. The top rung is a half-step: the next doubling +/// (65536) cannot fit one Noise body, and 49152 leaves the worst-case `fil ` +/// header (128-byte name, 5-digit counters, ~243 bytes) 16 KiB of slack. +pub const FIL_BUCKETS: [usize; 8] = [512, 1024, 2048, 4096, 8192, 16384, 32768, 49152]; + +/// The largest chunk body that fits the largest `fil ` bucket. +pub const FIL_MAX_BODY: usize = FIL_BUCKETS[FIL_BUCKETS.len() - 1] - PAD_HEADER_LEN; + /// The ladder value a body of `body_len` bytes is padded to, or `None` when it /// does not fit the largest bucket. pub fn bucket_for(body_len: usize) -> Option { - BUCKETS + bucket_in(&BUCKETS, body_len) +} + +/// The `fil ` ladder value a chunk body of `body_len` bytes is padded to, or +/// `None` when it does not fit [`FIL_MAX_BODY`]. +pub fn fil_bucket_for(body_len: usize) -> Option { + bucket_in(&FIL_BUCKETS, body_len) +} + +fn bucket_in(ladder: &[usize], body_len: usize) -> Option { + ladder .iter() .copied() .find(|bucket| bucket - PAD_HEADER_LEN >= body_len) } -/// `uint16 pad_len || body || random fill`, sized to one ladder value. +/// `uint16 pad_len || body || random fill`, sized to one chat ladder value. pub fn encode(body: &[u8]) -> Result, String> { - let bucket = bucket_for(body.len()).ok_or_else(|| { - format!("chat message too large for the largest length bucket ({MAX_BODY} bytes)") + encode_in(body, &BUCKETS, "chat message") +} + +/// `uint16 pad_len || body || random fill`, sized to one [`FIL_BUCKETS`] value. +pub fn encode_fil(body: &[u8]) -> Result, String> { + encode_in(body, &FIL_BUCKETS, "file chunk") +} + +fn encode_in(body: &[u8], ladder: &[usize], what: &str) -> Result, String> { + let bucket = bucket_in(ladder, body.len()).ok_or_else(|| { + let max = ladder[ladder.len() - 1] - PAD_HEADER_LEN; + format!("{what} too large for the largest length bucket ({max} bytes)") })?; let pad_len = bucket - PAD_HEADER_LEN - body.len(); let mut out = Vec::with_capacity(bucket); diff --git a/tests/file.rs b/tests/file.rs index 5b1f794..cc0e3e8 100644 --- a/tests/file.rs +++ b/tests/file.rs @@ -4,6 +4,7 @@ use std::time::Instant; use onionwire::dispatch::{Kind, classify}; use onionwire::file::{self, MAX_BYTES}; +use onionwire::padding; use onionwire::ratelimit::TokenBucket; use onionwire::tui::{SlashCmd, parse_cmd}; @@ -12,7 +13,7 @@ fn encode_decode_roundtrip_one_chunk() { let body = b"hello file"; let chunks = file::chunks("note.txt", body).unwrap(); assert_eq!(chunks.len(), 1); - let encoded = file::encode(&chunks[0]); + let encoded = file::encode(&chunks[0]).expect("encode"); let decoded = file::decode(&encoded).expect("decode"); assert_eq!(decoded.filename, "note.txt"); assert_eq!(decoded.idx, 0); @@ -22,6 +23,103 @@ fn encode_decode_roundtrip_one_chunk() { assert_eq!(decoded.xfer_id, chunks[0].xfer_id); } +#[test] +fn every_fil_frame_lands_on_the_fil_ladder() { + for size in [0usize, 1, 510, 511, 49_150, 49_151, 80_000, MAX_BYTES] { + let body = vec![0x5au8; size]; + let chunks = file::chunks("bucket.bin", &body).unwrap(); + assert!(!chunks.is_empty(), "a {size}-byte file must have chunks"); + for c in &chunks { + let encoded = file::encode(c).expect("encode"); + let bucket = padding::fil_bucket_for(c.data.len()).expect("must fit the ladder"); + assert_eq!( + encoded.len(), + file::overhead(c) + bucket, + "chunk {} of a {size}-byte file is not a ladder value", + c.idx + ); + assert!( + padding::FIL_BUCKETS.contains(&(encoded.len() - file::overhead(c))), + "chunk {} of a {size}-byte file is not on the ladder", + c.idx + ); + let decoded = file::decode_checked(&encoded) + .expect("decode") + .expect("still a fil frame"); + assert_eq!(decoded.data, c.data); + } + } +} + +#[test] +fn a_one_byte_file_and_a_bucket_sized_file_send_identical_frame_lengths() { + // Both fit the smallest fil bucket, so the tail chunk no longer reveals + // whether the file was 1 byte or 510. + let tiny = file::chunks("same.bin", b"x").unwrap(); + let fullest = file::chunks("same.bin", &vec![0u8; 510]).unwrap(); + assert_eq!(tiny.len(), 1); + assert_eq!(fullest.len(), 1); + let a = file::encode(&tiny[0]).expect("encode"); + let b = file::encode(&fullest[0]).expect("encode"); + assert_eq!(a.len(), file::overhead(&tiny[0]) + 512); + assert_eq!( + a.len(), + b.len(), + "frame length must not reveal the file size" + ); +} + +#[test] +fn an_oversized_pad_len_is_a_clean_protocol_error_not_a_truncation() { + let chunks = file::chunks("pad.bin", b"hello").unwrap(); + let mut pt = file::encode(&chunks[0]).expect("encode"); + let at = file::overhead(&chunks[0]); + pt[at..at + 2].copy_from_slice(&u16::MAX.to_be_bytes()); + let err = file::decode_checked(&pt).expect_err("must fail closed"); + assert!(err.to_string().contains("overrun"), "{err}"); + assert_eq!(file::decode(&pt), None, "no partial chunk may surface"); +} + +#[test] +fn a_malformed_fil_frame_is_an_error_while_chat_is_not_a_fil_frame() { + assert_eq!( + file::decode_checked(b"hello wire").expect("not a fil frame"), + None + ); + assert!(file::decode_checked(b"fil ").is_err(), "short headers fail"); + let chunks = file::chunks("x.bin", b"x").unwrap(); + let mut bare = file::encode(&chunks[0]).expect("encode"); + bare.truncate(file::overhead(&chunks[0]) + 1); + assert!( + file::decode_checked(&bare).is_err(), + "a missing pad_len header is not an empty body" + ); +} + +#[test] +fn a_padded_multi_chunk_transfer_round_trips_with_an_equal_hash() { + let dir = tempfile::tempdir().unwrap(); + let body: Vec = (0..120_000u32).map(|i| (i % 251) as u8).collect(); + let chunks = file::chunks("payload.bin", &body).unwrap(); + assert_eq!(chunks.len(), 3, "120000 bytes over 49150-byte chunks"); + let mut inbox = file::Inbox::new(dir.path()); + let mut done = None; + let mut reassembled = Vec::new(); + for c in &chunks { + let wire = file::encode(c).expect("encode"); + let got = file::decode_checked(&wire) + .expect("decode") + .expect("fil frame"); + assert_eq!(got.data, c.data, "padding must not leak into the data"); + assert_eq!(got.data.len(), c.data.len(), "no trailing fill"); + reassembled.extend_from_slice(&got.data); + done = inbox.ingest("aabbccdd", &got).unwrap(); + } + assert_eq!(reassembled, body); + let path = done.expect("assembled path"); + assert_eq!(std::fs::read(&path).unwrap(), body); +} + #[test] fn chat_is_not_file() { assert_eq!(file::decode(b"hello wire"), None); @@ -145,13 +243,15 @@ fn dispatch_fil_is_file_not_chat() { } #[test] -fn one_mib_seventeen_chunks_fit_default_bucket_when_paced() { +fn one_mib_twenty_two_chunks_fit_default_bucket_when_paced() { let body = vec![0u8; MAX_BYTES]; let chunks = file::chunks("file.bin", &body).unwrap(); + // The chunk cap is the top `fil ` bucket body (49150), so padding costs + // five more one-shot sessions than the old raw 64 KiB cap (17). assert_eq!( chunks.len(), - 17, - "1 MiB with an 8-char name must be 17 one-shot sessions" + 22, + "1 MiB with an 8-char name must be 22 one-shot sessions" ); let t0 = Instant::now(); @@ -160,8 +260,8 @@ fn one_mib_seventeen_chunks_fit_default_bucket_when_paced() { .filter(|_| !unpaced.try_acquire_at(t0)) .count(); assert_eq!( - dropped, 7, - "the bug: 17 back-to-back accepts blow the burst of 10" + dropped, 12, + "the bug: 22 back-to-back accepts blow the burst of 10" ); let mut paced = TokenBucket::default(); diff --git a/tests/padding.rs b/tests/padding.rs index c9464a9..677d5f6 100644 --- a/tests/padding.rs +++ b/tests/padding.rs @@ -3,7 +3,7 @@ //! bucketed size, a tampered field failing closed) lives in `src/node.rs`'s //! unit tests, because `tests/*.rs` cannot build a `Node`. -use onionwire::padding::{self, BUCKETS, MAX_BODY, PAD_HEADER_LEN}; +use onionwire::padding::{self, BUCKETS, FIL_BUCKETS, FIL_MAX_BODY, MAX_BODY, PAD_HEADER_LEN}; use onionwire::ratchet::{ FRAME_VERSION, FRAME_VERSION_HYBRID, HEADER_LEN, HEADER_LEN_HYBRID, RatchetKeyPair, RatchetState, @@ -221,6 +221,86 @@ fn a_classical_frame_keeps_the_329_byte_floor() { assert_eq!(frame.len() + 16 + 5, 350, "classical frame on the wire"); } +#[test] +fn the_fil_ladder_continues_past_the_chat_ceiling_and_fits_one_noise_body() { + // `fil ` chunk bodies are bounded by the frame budget (~64 KiB plaintext), + // not by a line of human text, so the ladder cannot stop at chat's 32 KiB: + // that would double the chunk count of a 1 MiB file and spend twice the + // one-shot sessions. The top rung is a half-step because the next doubling + // (65536) does not fit one Noise body. + assert_eq!( + FIL_BUCKETS, + [512, 1024, 2048, 4096, 8192, 16384, 32768, 49152] + ); + assert_eq!(FIL_MAX_BODY, 49150); + assert_eq!( + FIL_BUCKETS[FIL_BUCKETS.len() - 1] - PAD_HEADER_LEN, + FIL_MAX_BODY + ); + // Strictly increasing rungs, same 2-byte header as chat. + for w in FIL_BUCKETS.windows(2) { + assert!(w[1] > w[0], "ladder must increase: {w:?}"); + } + // Worst-case `fil ` header (128-byte name, 5-digit idx/total) plus the top + // rung plus the Noise tag must still fit one frame body. + let worst_header = 4 + 32 + 1 + 128 + 1 + 64 + 1 + 5 + 1 + 5 + 1; + assert!( + worst_header + FIL_BUCKETS[FIL_BUCKETS.len() - 1] + 16 <= onionwire::frame::MAX_FRAME, + "the top rung must fit one Noise body" + ); +} + +#[test] +fn fil_buckets_follow_the_body_plus_the_two_byte_header() { + let cases = [ + (0, Some(512)), + (1, Some(512)), + (510, Some(512)), + (511, Some(1024)), + (1022, Some(1024)), + (1023, Some(2048)), + (32766, Some(32768)), + (32767, Some(49152)), + (49150, Some(49152)), + (49151, None), + ]; + for (body_len, want) in cases { + assert_eq!( + padding::fil_bucket_for(body_len), + want, + "fil bucket for a {body_len}-byte body" + ); + } +} + +#[test] +fn a_fil_chunk_body_round_trips_and_an_oversized_one_fails_closed() { + for body in [&b""[..], &b"x"[..], &[0u8; 510][..], &[7u8; 49150][..]] { + let padded = padding::encode_fil(body).expect("encode"); + let bucket = padding::fil_bucket_for(body.len()).expect("bucket"); + assert_eq!(padded.len(), bucket); + assert_eq!(padding::decode(&padded).expect("decode"), body); + } + let err = padding::encode_fil(&vec![0u8; FIL_MAX_BODY + 1]).expect_err("must not fit"); + assert!(err.contains("too large"), "{err}"); +} + +/// `fil ` bodies reuse the chat encoding verbatim: the same `uint16 pad_len`, +/// the same "overrun is a hard failure" rule. The ladders differ, the bytes do +/// not. +#[test] +fn fil_and_chat_share_the_same_encoding() { + let padded = padding::encode_fil(b"hello").expect("encode"); + assert_eq!(padded.len(), 512); + assert_eq!(padded[..2], [0x01, 0xf9], "pad_len = 512 - 2 - 5 = 505"); + assert_eq!(padding::decode(&padded).expect("decode"), b"hello"); + + let mut bad = Vec::new(); + bad.extend_from_slice(&15u16.to_be_bytes()); + bad.extend_from_slice(&[0u8; 14]); + assert!(padding::decode(&bad).is_err()); +} + #[test] fn a_receiver_accepts_a_padded_plaintext_of_any_total_length() { // Interop: another implementation's ladder is not ours, and the receiver From 9b536328594d069058abc1a0d1f6d21897a26797 Mon Sep 17 00:00:00 2001 From: rust-dev Date: Thu, 22 Oct 2026 23:38:30 -0400 Subject: [PATCH 2/2] tui: mark friends invite-stale after an F8 prekey rotation F8 replaces the Noise static prekey and the ML-KEM key together and clears every stored ratchet, but nothing recorded the cut: a friend on the roster still held an invite with the old prekey, the next inbound frame could not be decrypted, our own outbound re-bootstrapped an epoch they did not have, and the send looked delivered. The only fix -- ask them to paste the new invite -- was never said. - `rotate_prekey` snapshots the roster into `$ONIONWIRE_HOME/invite-stale` (derived local state; no store schema change, no wire field, no new crate). `Node::invite_stale(pk)` / `invite_stale_friends()` answer the question, and an install that never rotated has no file and nothing marked. - `Node::send` and `Node::send_once` fail closed with `invite stale` for a pre-rotation friend instead of silently re-bootstrapping past the cut. - The roster gains its own `invite stale` word and colour token (violet; `stale` keeps meaning "the last dial did not answer"), and the alert row above the panes carries `invite stale -- F2 to share your new invite, they F3-paste it`, recomputed every draw so F3-pasting an invite for that friend clears it. - `add_friend_payload` removes the pubkey from the set, which is the test the card asks for; docs/TUI.md documents the marker. This makes the existing hard cut legible. It does not add in-band revocation or a soft rotation; the threat model's hard-cut wording stays as it is. --- docs/TUI.md | 8 +- src/node.rs | 229 +++++++++++++++++++++++++++++++++++++++++++- src/tui.rs | 83 ++++++++++++++-- tests/tui_frames.rs | 136 +++++++++++++++++++++++++- 4 files changed, 436 insertions(+), 20 deletions(-) diff --git a/docs/TUI.md b/docs/TUI.md index bcd8e7a..c6af7f3 100644 --- a/docs/TUI.md +++ b/docs/TUI.md @@ -108,7 +108,13 @@ the composer types the letter. `loc `; offline friends must F3-paste the new invite. - **F8.** Type `ROTATE`. Prekey is the Noise static **and** the ratchet bootstrap seed. Every friend must F3-paste the new invite. Status: - `prekey rotated · friends must F3-paste your new invite`. + `prekey rotated · friends must F3-paste your new invite`. The cut is recorded + locally (`$ONIONWIRE_HOME/invite-stale`), so every friend who was on the roster + shows `invite stale` on their row, in violet, and the alert row above the panes + reads `invite stale — F2 to share your new invite, they F3-paste it`. Sends to + that friend fail closed with `invite stale` instead of looking delivered. The + marker is not the dial marker: `stale` keeps meaning "the last dial did not + answer". F3-pasting an invite for that friend clears it. ## Wallet (`F6`) diff --git a/src/node.rs b/src/node.rs index 2111d48..95277e4 100644 --- a/src/node.rs +++ b/src/node.rs @@ -65,6 +65,47 @@ pub const SHUTDOWN_FLUSH_TIMEOUT: Duration = Duration::from_secs(10); /// immediately, and a live one answers in milliseconds. const DAEMON_PROBE_BUDGET: Duration = Duration::from_secs(3); +/// Local record of the friends who were on the roster when the prekey last +/// rotated (F8). Not a store column and not a wire field: derived state under +/// `$ONIONWIRE_HOME`, so an install that never pressed F8 has no file and every +/// friend reads as current. The header carries the rotation timestamp; the body +/// is one 64-char hex identity pubkey per line. +const INVITE_STALE_FILE: &str = "invite-stale"; +const INVITE_STALE_HEADER: &str = "onionwire-invite-stale-v1"; + +/// What a send to a pre-rotation friend answers. The roster marker and the +/// alert-row hint carry the instruction; the error only has to name the cause. +pub const INVITE_STALE_REASON: &str = "invite stale"; + +/// Lowercase hex, the on-disk form for a pubkey line. +fn hex_line(bytes: &[u8]) -> String { + bytes.iter().map(|b| format!("{b:02x}")).collect() +} + +/// One hex line back to 32 bytes; anything else is skipped (the file is a cache +/// of a set, not a trusted input). +fn hex_pubkey(line: &str) -> Option> { + let line = line.trim(); + if line.len() != 64 || !line.is_ascii() { + return None; + } + let mut out = Vec::with_capacity(32); + for chunk in line.as_bytes().chunks(2) { + let hi = (chunk[0] as char).to_digit(16)?; + let lo = (chunk[1] as char).to_digit(16)?; + out.push((hi * 16 + lo) as u8); + } + Some(out) +} + +/// Write `bytes` beside `path` and rename over it, so a crash cannot leave a +/// half-written set that reads as "some friends are stale, some are not". +fn write_atomic(path: &Path, bytes: &[u8]) -> Result<(), String> { + let tmp = path.with_extension("tmp"); + std::fs::write(&tmp, bytes).map_err(|e| format!("{}: {e}", tmp.display()))?; + std::fs::rename(&tmp, path).map_err(|e| format!("{}: {e}", path.display())) +} + struct HsHandle { svc: Arc, rend: tokio::task::JoinHandle<()>, @@ -512,6 +553,9 @@ impl Node { // state is unusable. Drop it; the next frame rebuilds a fresh state. store.clear_ratchet(&p.pubkey).map_err(|e| e.to_string())?; } + // An invite we just accepted is current by definition, so a friend F8 + // had marked as holding the old one is no longer marked. + self.clear_invite_stale(&p.pubkey)?; Ok(()) } @@ -1737,6 +1781,11 @@ impl Node { } async fn send_once(&self, friend_pk: &[u8], plaintext: &[u8]) -> Result<(), String> { + // One-shot frames (file, pay, tip, profile) have no outbox to retry + // them, so a pre-rotation invite must not look delivered either. + if self.invite_stale(friend_pk) { + return Err(INVITE_STALE_REASON.into()); + } self.ensure_running()?; let (onion, prekey, kem) = { let f = self.friend(friend_pk)?; @@ -1847,7 +1896,7 @@ impl Node { let sk = StaticSecret::random_from_rng(OsRng); let pk = X25519Public::from(&sk).to_bytes(); let kem_kp = crate::kem::generate(); - { + let friends = { let store = self.store.lock().map_err(|e| e.to_string())?; // `replace_identity_keys` rewrites the prekey columns too; the // identity values passed back are the ones already stored. @@ -1857,18 +1906,111 @@ impl Node { store .set_kem_keys(&kem_kp.seed[..], &kem_kp.pk) .map_err(|e| e.to_string())?; - for f in store.list_friends().map_err(|e| e.to_string())? { - store.clear_ratchet(&f.pubkey).map_err(|e| e.to_string())?; + let friends: Vec> = store + .list_friends() + .map_err(|e| e.to_string())? + .into_iter() + .map(|f| f.pubkey) + .collect(); + for f in &friends { + store.clear_ratchet(f).map_err(|e| e.to_string())?; } - } + friends + }; k.prekey_sk = sk.to_bytes(); k.prekey_pk = pk; k.kem_seed = *kem_kp.seed; k.kem_pk = kem_kp.pk; *self.keys.lock().map_err(|e| e.to_string())? = k; + // Every friend on the roster holds an invite with the prekey we just + // replaced; their next inbound frame cannot be decrypted and our own + // outbound re-bootstraps an epoch they do not have. Record the cut so + // the roster can say so instead of a send looking delivered. + self.record_invite_stale(unix_now(), &friends) + .map_err(|e| format!("prekey rotated, but the invite-stale marker failed: {e}"))?; Ok(pk) } + /// Friends whose recorded invite predates the current prekey (F8). + /// + /// The set lives in `home/invite-stale` — derived local state, not a store + /// column and not a wire field. An install that never rotated has no file + /// and therefore an empty set. A missing or unreadable file reads as + /// "nothing stale": the marker is advisory, and a damaged file must not + /// make the roster accuse every friend. + pub fn invite_stale_friends(&self) -> Vec> { + let Ok(text) = std::fs::read_to_string(self.invite_stale_file()) else { + return Vec::new(); + }; + let mut lines = text.lines(); + if !lines + .next() + .is_some_and(|l| l.split_whitespace().next() == Some(INVITE_STALE_HEADER)) + { + return Vec::new(); + } + lines.filter_map(hex_pubkey).collect() + } + + /// Does this friend still hold an invite with the pre-rotation prekey? + pub fn invite_stale(&self, friend_pk: &[u8]) -> bool { + self.invite_stale_friends().iter().any(|p| p == friend_pk) + } + + fn invite_stale_file(&self) -> PathBuf { + self.home.join(INVITE_STALE_FILE) + } + + /// Write the roster snapshot taken by `rotate_prekey`. `rotated_at` is kept + /// in the header for a future reader; the set itself is the state. + fn record_invite_stale(&self, rotated_at: i64, friends: &[Vec]) -> Result<(), String> { + let mut text = format!("{INVITE_STALE_HEADER} {rotated_at}\n"); + for pk in friends { + text.push_str(&hex_line(pk)); + text.push('\n'); + } + write_atomic(&self.invite_stale_file(), text.as_bytes()) + } + + /// A re-pasted invite is the exchange that closes the cut, so it takes the + /// pubkey out of the set. + fn clear_invite_stale(&self, friend_pk: &[u8]) -> Result<(), String> { + let path = self.invite_stale_file(); + let Ok(text) = std::fs::read_to_string(&path) else { + return Ok(()); + }; + let mut lines = text.lines(); + let Some(header) = lines.next() else { + return Ok(()); + }; + if header.split_whitespace().next() != Some(INVITE_STALE_HEADER) { + return Ok(()); + } + let target = hex_line(friend_pk); + let mut changed = false; + let kept: Vec<&str> = lines + .map(str::trim) + .filter(|l| !l.is_empty()) + .filter(|l| { + if l.eq_ignore_ascii_case(&target) { + changed = true; + false + } else { + true + } + }) + .collect(); + if !changed { + return Ok(()); + } + let mut out = format!("{header}\n"); + for l in kept { + out.push_str(l); + out.push('\n'); + } + write_atomic(&path, out.as_bytes()) + } + /// One-shot file to a friend. Fail closed; no outbox, no resume. /// Chunks are paced (`file::CHUNK_PACE`) with bounded per-chunk retry so /// a 1 MiB transfer fits the receiver's rendezvous token bucket. @@ -1906,6 +2048,12 @@ impl Node { /// 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 { + // A pre-rotation invite is a hard cut, not a reachability problem: the + // frame would encode and look delivered while the peer cannot decrypt + // it. Fail closed with the cause instead of silently re-bootstrapping. + if self.invite_stale(friend_pk) { + return Err(INVITE_STALE_REASON.into()); + } self.ensure_running()?; let keys = self.keys()?; let frame = { @@ -3558,6 +3706,79 @@ pub(crate) mod tests { ); } + /// F8 is a hard cut that leaves every friend holding an invite with the old + /// prekey. The roster has to say so instead of letting the next send look + /// delivered and then fail to decrypt on the far side. + #[tokio::test] + async fn rotating_the_prekey_marks_existing_friends_invite_stale() { + let dir = tempfile::tempdir().unwrap(); + let node = offline_node(&dir.path().join("bob"), Arc::new(NoDial)); + let peer = Keys::generate(); + let fresh = Keys::generate(); + { + let store = node.store.lock().unwrap(); + befriend(&store, &peer.identity_pk, &peer.prekey_pk, "peer.onion"); + store + .save_ratchet(&peer.identity_pk, b"epoch-bound-to-the-old-prekey") + .expect("seed ratchet state"); + } + assert!( + !node.invite_stale(&peer.identity_pk), + "nothing is invite-stale before a rotation" + ); + + node.rotate_prekey().expect("rotate prekey"); + + assert!( + node.invite_stale(&peer.identity_pk), + "a friend on the roster when the prekey rotated holds the old invite" + ); + { + let store = node.store.lock().unwrap(); + befriend(&store, &fresh.identity_pk, &fresh.prekey_pk, "fresh.onion"); + } + assert!( + !node.invite_stale(&fresh.identity_pk), + "a friend added after the rotation is not marked" + ); + let err = node + .send(&peer.identity_pk, b"hello") + .await + .expect_err("a stale invite must fail closed, not queue"); + assert!( + err.contains("invite stale"), + "the send must name the cause, got {err:?}" + ); + } + + /// A re-pasted invite for that friend is the exchange that fixes the cut, so + /// it is also what takes the marker off the roster. + #[tokio::test] + async fn pasting_a_new_invite_clears_the_invite_stale_marker() { + let dir = tempfile::tempdir().unwrap(); + let node = offline_node(&dir.path().join("bob"), Arc::new(NoDial)); + let peer = Keys::generate(); + { + let store = node.store.lock().unwrap(); + befriend(&store, &peer.identity_pk, &peer.prekey_pk, "peer.onion"); + } + node.rotate_prekey().expect("rotate prekey"); + assert!(node.invite_stale(&peer.identity_pk), "precondition"); + + node.add_friend_payload(&crate::qr::QrPayload { + pubkey: peer.identity_pk.to_vec(), + onion: "peer.onion".into(), + signed_prekey: peer.prekey_pk.to_vec(), + kem_pk: None, + }) + .expect("accept invite"); + + assert!( + !node.invite_stale(&peer.identity_pk), + "a freshly accepted invite clears the marker" + ); + } + /// An outbound tip must be recorded as a *tip*. The receipt row is the /// recipient's view of a receipt frame; for money the user just spent the /// wallet history wants the tip they paid. `ingest_tip` already stores diff --git a/src/tui.rs b/src/tui.rs index ecc3dee..c00aaae 100644 --- a/src/tui.rs +++ b/src/tui.rs @@ -29,6 +29,9 @@ const C_TEXT: Color = Color::Rgb(196, 214, 176); const C_DIM: Color = Color::Rgb(98, 110, 92); const C_ALERT: Color = Color::Rgb(220, 80, 70); const C_STALE: Color = Color::Rgb(210, 180, 80); +/// F8: the friend holds an invite with the pre-rotation prekey. Violet, not the +/// dial-stale amber — a stale invite is an exchange problem, not a dead peer. +const C_INVITE_STALE: Color = Color::Rgb(178, 128, 216); const C_HL_BG: Color = Color::Rgb(48, 42, 28); const C_BORDER: Color = Color::Rgb(72, 84, 64); @@ -403,6 +406,8 @@ pub struct TokenStyles { pub alert: Style, /// Stale data (unconfirmed, timed out). pub stale: Style, + /// F8: the friend's copy of our invite predates the current prekey. + pub invite_stale: Style, /// Border / chrome lines. pub border: Style, /// Highlight block (selected list row). @@ -438,6 +443,11 @@ pub fn tokens_for(mode: ColorMode) -> TokenStyles { accent, alert: rgb(C_ALERT, Color::Red), stale: rgb(C_STALE, Color::Yellow), + invite_stale: match mode { + ColorMode::None => Style::default().add_modifier(Modifier::BOLD), + ColorMode::Ansi16 => Style::default().fg(Color::Magenta), + ColorMode::Rgb => Style::default().fg(C_INVITE_STALE), + }, border: rgb(C_BORDER, Color::DarkGray), highlight, } @@ -464,6 +474,10 @@ fn style_stale() -> Style { tokens_for(color_mode()).stale } +fn style_invite_stale() -> Style { + tokens_for(color_mode()).invite_stale +} + fn style_border() -> Style { tokens_for(color_mode()).border } @@ -493,6 +507,13 @@ pub fn fingerprint_mismatch_banner() -> &'static str { "fingerprint mismatch" } +/// The one-line hint for a friend whose invite predates our current prekey +/// (F8). Rendered in the same alert row as `fingerprint_mismatch_banner`, so the +/// user reads it where every other fail-closed sentence appears. Fits 80. +pub fn invite_stale_banner() -> &'static str { + "invite stale — F2 to share your new invite, they F3-paste it" +} + pub fn rotate_screen_text() -> &'static str { "Rotate onion address?\n\ Your identity key stays the same.\n\ @@ -1236,6 +1257,9 @@ struct App { rt: tokio::runtime::Handle, screen: Screen, friends: Vec, + /// Pubkeys whose invite predates our current prekey (F8), straight from + /// `Node::invite_stale_friends`. Refreshed with the roster, read on draw. + invite_stale: Vec>, selected: usize, me_fp: String, me_onion: String, @@ -1823,6 +1847,7 @@ fn function_key_for(screen: &Screen, code: KeyCode) -> Option { impl App { fn new(node: Arc, rt: tokio::runtime::Handle) -> Result { let friends = node.list_friends()?; + let invite_stale = node.invite_stale_friends(); // A fresh install has no wallet to pick and nothing to warn about yet, // so it starts on the main view. The spend-authority warning is not // weakened by this: every path where a user commits to creating or @@ -1847,6 +1872,7 @@ impl App { rt, screen, friends, + invite_stale, selected: 0, alert: None, status_note: None, @@ -2436,6 +2462,10 @@ impl App { fn confirm_rotate_prekey(&mut self) -> Result<(), String> { match self.node.rotate_prekey() { Ok(_) => { + // Every friend on the roster just became "invite stale"; the + // markers have to be on the roster before the share screen + // opens, not after the next friend-list refresh. + self.reload_friends()?; self.status_note = Some("prekey rotated · friends must F3-paste your new invite".into()); self.open_share() @@ -3141,6 +3171,7 @@ impl App { fn reload_friends(&mut self) -> Result<(), String> { self.friends = self.node.list_friends()?; + self.invite_stale = self.node.invite_stale_friends(); if self.friends.is_empty() { self.selected = 0; } else { @@ -3409,7 +3440,12 @@ impl App { fn draw_main(&self, f: &mut Frame) { let phase = Some(TorPhase::of(self.node.tor_state())); let (chat_lines, summary, chat_style) = self.chat_view(phase); - let rows: Vec = self.friends.iter().map(friend_row).collect(); + let invite_set = &self.invite_stale; + let rows: Vec = self + .friends + .iter() + .map(|f| friend_row(f, invite_set.iter().any(|pk| pk == &f.pubkey))) + .collect(); let chat_name = self.friends.get(self.selected).map(|friend| { friend .petname @@ -3420,10 +3456,20 @@ impl App { // The outbox is the source of truth while anything is outstanding; the // transient note still covers "sending", "sent file x", "invoice sent". let mut note = summary.note().or_else(|| self.status_note.clone()); + // F8's cut is a standing fact about the selected friend, not a transient + // error: with nothing else failing, the alert row carries the sentence + // that turns it into an action. It clears with the marker (a re-pasted + // invite), so it is recomputed every draw rather than set once. + let invite_hint = self + .friends + .get(self.selected) + .filter(|f| self.invite_stale.iter().any(|pk| pk == &f.pubkey)) + .map(|_| invite_stale_banner()); + let alert = self.alert.as_deref().or(invite_hint); // The alert row above the panes is the error channel. When it already // carries the same sentence, drop it from the footer: one statement of a // failure, in the place the eye goes for errors. - if note.as_deref() == self.alert.as_deref() { + if note.as_deref() == alert { note = None; } let view = MainView { @@ -3438,7 +3484,7 @@ impl App { chat_name: chat_name.as_deref(), chat_scroll: self.chat_scroll, composer: &self.composer, - alert: self.alert.as_deref(), + alert, note: note.as_deref(), }; draw_main_chrome(f, &view); @@ -3470,12 +3516,20 @@ impl App { } } -/// One roster row: the label, the fingerprint, and the word `stale` when the -/// last dial did not answer. Colour is what the row is (text vs stale), never a -/// decoration — the word carries the state on a monochrome terminal. +/// One roster row: the label, the fingerprint, and the state word — `stale` +/// when the last dial did not answer, `invite stale` when F8 replaced the prekey +/// the friend still holds. Colour is what the row is (text / dial stale / invite +/// stale), never a decoration — the word carries the state on a monochrome +/// terminal. pub fn roster_line(row: &FriendRow, inner_width: u16) -> Line<'static> { let text = roster_row_text(row, inner_width); - let style = if row.stale { style_stale() } else { style_text() }; + let style = if row.invite_stale { + style_invite_stale() + } else if row.stale { + style_stale() + } else { + style_text() + }; Line::from(Span::raw(text).style(style)) } @@ -3750,6 +3804,9 @@ pub struct FriendRow { pub fingerprint: String, /// Last dial to this peer's onion did not answer. pub stale: bool, + /// The friend's recorded invite predates our current prekey (F8): their + /// next inbound frame cannot be decrypted until they paste the new invite. + pub invite_stale: bool, /// Friend row has an ML-KEM key (v2 invite). `false` means sessions to /// this friend are the classical `onionwire-v1` transport, and the roster /// says so in words — no pretending it is hybrid. @@ -3757,12 +3814,14 @@ pub struct FriendRow { } /// The roster row for one friend, fitted to the pane's inner width in cells. -pub fn friend_row(friend: &Friend) -> FriendRow { +/// `invite_stale` is `Node::invite_stale`'s answer for this pubkey. +pub fn friend_row(friend: &Friend, invite_stale: bool) -> FriendRow { let raw = friend.petname.as_deref().unwrap_or(&friend.fingerprint); FriendRow { label: sanitize::display_text(raw.as_bytes()).to_string(), fingerprint: friend.fingerprint.clone(), stale: !friend.last_connect_ok, + invite_stale, pq: friend.kem_pk.is_some(), } } @@ -5557,10 +5616,14 @@ fn truncate_fp(fp: &str) -> String { fn roster_row_text(row: &FriendRow, inner_width: u16) -> String { let budget = (inner_width as usize).saturating_sub(2); let stale_s = if row.stale { " stale" } else { "" }; + // F8's cut is not a failed dial: its own word, beside `stale` when both are + // true (the invite is old *and* the last dial timed out). + let invite_s = if row.invite_stale { " invite stale" } else { "" }; // A legacy v1 friend has no PQ transport; say the word rather than let the // roster imply protection it does not have. let pq_s = if row.pq { "" } else { " classical" }; - let avail = budget.saturating_sub(cell_width(stale_s) + cell_width(pq_s)); + let avail = + budget.saturating_sub(cell_width(stale_s) + cell_width(invite_s) + cell_width(pq_s)); // The name is what the reader is looking for. The fingerprint only // disambiguates two friends with the same petname, so it gets what is left // and is dropped entirely when the pane is too narrow to show a usable @@ -5576,7 +5639,7 @@ fn roster_row_text(row: &FriendRow, inner_width: u16) -> String { } else { (fit_cells(&row.label, avail), String::new()) }; - fit_cells(&format!("{shown}{fp_part}{pq_s}{stale_s}"), budget) + fit_cells(&format!("{shown}{fp_part}{pq_s}{invite_s}{stale_s}"), budget) } fn to_hex(bytes: &[u8]) -> String { diff --git a/tests/tui_frames.rs b/tests/tui_frames.rs index 4a5abe0..b424e33 100644 --- a/tests/tui_frames.rs +++ b/tests/tui_frames.rs @@ -16,11 +16,11 @@ use onionwire::outbox::{OutboxEntry, OutboxStatus}; use onionwire::qr; use onionwire::tui::{ ChatRowStyle, FriendRow, MainView, Pane, TorPhase, backup_screen_text, banner_for_width, - cell_width, chat_no_friends_lines, chat_with_delivery, compact_banner, draw_main_chrome, - draw_share, draw_text_overlay, fingerprint_mismatch_banner, help_overlay_text, - main_footer_hints, onion_glyph, quit_screen_text, restore_screen_text, rotate_screen_text, - roster_line, status_footer, who_overlay_text, wipe_screen_text, wordmark_banner, ProfileEditor, - WipeKind, + cell_width, chat_no_friends_lines, chat_with_delivery, color_mode, compact_banner, + draw_main_chrome, draw_share, draw_text_overlay, fingerprint_mismatch_banner, + help_overlay_text, invite_stale_banner, main_footer_hints, onion_glyph, quit_screen_text, + restore_screen_text, rotate_screen_text, roster_line, status_footer, tokens_for, + who_overlay_text, wipe_screen_text, wordmark_banner, ProfileEditor, WipeKind, }; use onionwire::{FriendProfile, Message}; use ratatui::Frame; @@ -91,12 +91,14 @@ fn friend_rows() -> Vec { label: "alice".into(), fingerprint: "aaaaaaaaaaaaaaaa".into(), stale: false, + invite_stale: false, pq: true, }, FriendRow { label: "bob-the-stale-peer".into(), fingerprint: "bbbbbbbbbbbbbbbb".into(), stale: true, + invite_stale: false, pq: true, }, ] @@ -108,6 +110,7 @@ fn a_legacy_friend_row_says_classical_in_the_roster() { label: "alice".into(), fingerprint: "aaaaaaaaaaaaaaaa".into(), stale: false, + invite_stale: false, pq: true, }; let legacy = FriendRow { @@ -131,6 +134,129 @@ fn a_legacy_friend_row_says_classical_in_the_roster() { ); } +/// F8 invalidates every friend's stored copy of our invite. That is a different +/// fact from "the last dial did not answer": the roster needs its own word, its +/// own colour token, and it must not borrow `stale` for it. +#[test] +fn an_invite_stale_friend_is_marked_apart_from_a_dial_stale_one() { + let row = FriendRow { + label: "alice".into(), + fingerprint: "aaaaaaaaaaaaaaaa".into(), + stale: false, + invite_stale: false, + pq: true, + }; + let invite = FriendRow { + invite_stale: true, + ..row.clone() + }; + let dial = FriendRow { + stale: true, + ..row.clone() + }; + let text = |r: &FriendRow| -> String { + roster_line(r, 40) + .spans + .iter() + .map(|s| s.content.clone()) + .collect() + }; + + let invite_text = text(&invite); + assert!( + invite_text.contains("invite stale"), + "a pre-rotation friend must say so in words: {invite_text:?}" + ); + let dial_text = text(&dial); + assert!( + !dial_text.contains("invite stale"), + "a failed dial keeps the old marker and only that: {dial_text:?}" + ); + assert!(dial_text.contains("stale"), "{dial_text:?}"); + + let invite_style = roster_line(&invite, 40).spans[0].style; + let tokens = tokens_for(color_mode()); + assert_eq!( + invite_style, tokens.invite_stale, + "invite staleness owns a colour token, not the dial-stale one" + ); + assert_ne!(tokens.invite_stale, tokens.stale); +} + +/// The hint has to render in the same place as the fingerprint mismatch banner +/// (the fail-closed alert row above the panes) and fit 80 columns. +#[test] +fn the_invite_stale_hint_renders_above_the_panes_at_80_columns() { + let hint = invite_stale_banner(); + assert!( + cell_width(hint) <= 80, + "the hint must fit 80 columns: {hint:?} is {}", + cell_width(hint) + ); + assert!(hint.contains("invite stale"), "{hint:?}"); + assert!( + hint.contains("F2") && hint.contains("F3"), + "the hint must point at sharing and re-pasting an invite: {hint:?}" + ); + + let friends = vec![ + FriendRow { + label: "alice".into(), + fingerprint: "aaaaaaaaaaaaaaaa".into(), + stale: false, + invite_stale: true, + pq: true, + }, + FriendRow { + label: "bob".into(), + fingerprint: "bbbbbbbbbbbbbbbb".into(), + stale: false, + invite_stale: false, + pq: true, + }, + ]; + let chat = vec!["hi".to_string()]; + let draw = |w: u16, h: u16| { + draw_frame(w, h, |f| { + draw_main_chrome( + f, + &MainView { + me_fp: FP, + me_onion: ONION, + phase: Some(TorPhase::Ready), + friends: &friends, + selected: 1, + focus: Pane::Chat, + chat_lines: &chat, + chat_style: ChatRowStyle::Text, + chat_name: Some("alice"), + chat_scroll: 0, + composer: "", + alert: Some(hint), + note: None, + }, + ) + }) + }; + // 80x24 is the audit size every rendered row must survive. + let narrow = draw(80, 24); + let narrow_screen = screen_of(&narrow, 80, 24); + for line in narrow_screen.lines().filter(|l| l.contains("invite")) { + println!("80-col line ({} cells): {line:?}", cell_width(line)); + } + assert!( + narrow_screen.lines().nth(1).unwrap_or_default().contains("invite stale"), + "the hint belongs in the alert row: {narrow_screen}" + ); + + let wide = draw(120, 40); + let wide_screen = screen_of(&wide, 120, 40); + assert!( + wide_screen.contains("alice invite stale"), + "the row itself must carry the marker: {wide_screen}" + ); +} + fn out_msg(id: i64, body: &str) -> Message { Message { id,