From cfabc97d201040137b2e567578ef7289a21e4431 Mon Sep 17 00:00:00 2001 From: mnovak Date: Tue, 17 Nov 2026 12:01:32 +0100 Subject: [PATCH] [client] F24: block and unblock as staged rotates, receipts with seq, readdress; payloads in PROTOCOL.md --- .agents/features/block-and-receipts.md | 68 ++++++ crates/client/src/lib.rs | 299 +++++++++++++++++++++---- crates/client/src/snapshot.rs | 21 ++ crates/client/src/transport.rs | 22 ++ crates/client/tests/block.rs | 215 ++++++++++++++++++ crates/client/tests/pairing.rs | 3 + crates/client/tests/real_relay.rs | 16 ++ crates/client/tests/state.rs | 52 +++-- docs/PROTOCOL.md | 13 ++ 9 files changed, 652 insertions(+), 57 deletions(-) create mode 100644 .agents/features/block-and-receipts.md create mode 100644 crates/client/tests/block.rs diff --git a/.agents/features/block-and-receipts.md b/.agents/features/block-and-receipts.md new file mode 100644 index 0000000..9c0395b --- /dev/null +++ b/.agents/features/block-and-receipts.md @@ -0,0 +1,68 @@ +# F24 — Block, unblock, and *delivered* + +Analysis, 2026-11-17. Issues Amicitia #52 (F24). It builds on F21/F22a (`client.md`, +`client-state.md`). `PROTOCOL.md` §3 already says what block is: *the owner rotates the post token; +the old one is refused. The blocked person is not told.* The relay route exists (§8, `PUT +…/post-token`); the client never used it. + +## 1. Why and what +- **Block:** someone who turns hostile can no longer put anything in your mailbox. Nothing is sent + to them, so they are not told. What they posted before the block, and what you already fetched, + is dropped and never shown. +- **Unblock:** a mistake can be undone. A fresh post token goes to them inside MLS, and their + client switches to it, including for what waited in their outbox. +- ***Delivered*:** you see when your message reached the other person's app (fetched and saved + there). Each text carries a sequence number; the receiving client answers with a **receipt** + `upto = n` once it has saved them. **Reciprocal and switchable:** with receipts off, a client + neither sends them nor reports the other side's. The cost is said where the switch is: a + receipt tells the sender roughly when your app was open. + +## 2. Design +### Everything is a staged step +F22a's rule holds: nothing reaches the relay before the app has saved. So `Outgoing` grows from +"one blob to post" to **one relay operation**: post a blob, or rotate a post token. +| Call | Local change | Returned for the app to deliver after saving | +|:--|:--|:--| +| `block(contact)` | marks the contact blocked | a **rotate** to the hash of a fresh random token, which nobody gets | +| `unblock(contact)` | clears the mark | a **rotate** to a new token, then a **post** of `inbox {postToken}` to them, inside MLS | +| `compose` | `seq` + 1 for that contact | the text, now with its `seq` | +| `receive` | texts from a blocked contact dropped; the highest `seq` received per contact | a **receipt** per contact that sent texts (receipts on, not blocked) | +- `deliver` performs either operation. A rotate delivered twice is harmless: the same hash again. +- `readdress(&Outgoing)`: a post waiting in an app's outbox carries the token it was sealed with. + After an `inbox` payload changed the token, `readdress` swaps in the current one. The sealed + blob does not change. Apps call it before delivering from the outbox. +- An app learns a message's `seq` from `sent_seq(contact)` right after `compose`. + +### Payloads inside MLS *(documented in `PROTOCOL.md` §4, new: `seq`, `receipt`, `inbox`)* +```json +{"kind":"hello","mailbox":"…","postToken":"…","name":"…"} +{"kind":"text","body":"…","seq":7} +{"kind":"receipt","upto":7} +{"kind":"inbox","postToken":"…"} +``` +- `inbox` changes only the token for the mailbox we already know: the sender cannot redirect us to + another mailbox (F21's *second hello* rule still holds). MLS authenticates that it is theirs. +- A `receipt` with `upto` above what we sent is capped to what we sent; it cannot mark the future. +- The relay sees none of this: all of it is MLS ciphertext, and a rotate is §8's existing route. + +### What the blocked person can tell +Their posts get **404**: the same answer as any wrong token. Their app keeps the message as *not +sent yet* and retries. Nothing in the protocol tells them it was a block rather than, say, an +expired mailbox. Their client cannot ask. Stated: someone whose messages never leave the outbox +may guess. + +## 3. Tests — written first +1. Block: the blocked side's next post is refused (404); nothing reaches us; what they posted + just before the block, still waiting, is fetched, dropped, never shown, and acknowledged. +2. Block works offline: the rotate waits as an `Outgoing`, and after a restart from the snapshot it + still applies. +3. Unblock: they get the new token, their waiting outbox post is readdressed and arrives, and new + texts flow both ways. +4. Receipts: Eva sends 3, Jan receives, Eva gets `Delivered{upto: 3}`. Receipts off on Jan: none + sent. Off on Eva: Jan's receipts are ignored. A receipt `upto` above what was sent is capped. +5. A snapshot from before F24 (no `blocked`, `seq`, `receipts`) still restores, with receipts on. +6. `inbox` cannot change the mailbox, only the token. + +Planted bugs: block that also posts something to the blocked person; texts from a blocked contact +shown; the rotate done inside `block` (not staged); receipts sent while off; a receipt marking +beyond what was sent; `readdress` leaving the old token. diff --git a/crates/client/src/lib.rs b/crates/client/src/lib.rs index ed42938..0a4a582 100644 --- a/crates/client/src/lib.rs +++ b/crates/client/src/lib.rs @@ -106,22 +106,55 @@ pub enum Event { contact: ContactId, text: String, }, + /// The other side's app has saved our texts up to `upto` (a `seq` from + /// [`Client::sent_seq`]). Only while receipts are on ([`Client::set_receipts`]). + Delivered { + contact: ContactId, + upto: u64, + }, } -/// One blob for the relay, to deliver once the app has saved the snapshot. An app may keep it in -/// an outbox and deliver it again after a crash: a second copy is refused by MLS as a replay. -/// `Debug` shows neither the post token nor the bytes. +/// One operation for the relay, to deliver once the app has saved the snapshot: a blob to post, +/// or a post token to rotate (block, unblock). An app may keep it in an outbox and deliver it +/// again after a crash: a second post is refused by MLS as a replay, a second rotate changes +/// nothing. `Debug` shows no token and no bytes. #[derive(Clone, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -pub struct Outgoing { - to: MailboxId, - post: Token, - blob: Bytes, +#[serde(transparent)] +pub struct Outgoing(Op); + +#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "op", rename_all = "camelCase", deny_unknown_fields)] +enum Op { + #[serde(rename_all = "camelCase")] + Post { + to: MailboxId, + post: Token, + blob: Bytes, + }, + #[serde(rename_all = "camelCase")] + Rotate { + mailbox: MailboxId, + fetch: Token, + post_token_hash: Sha256Hash, + }, +} + +impl Outgoing { + fn post(to: MailboxId, post: Token, blob: Vec) -> Outgoing { + Outgoing(Op::Post { + to, + post, + blob: Bytes(blob), + }) + } } impl fmt::Debug for Outgoing { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "Outgoing({} bytes)", self.blob.0.len()) + match &self.0 { + Op::Post { blob, .. } => write!(f, "Outgoing({} bytes)", blob.0.len()), + Op::Rotate { .. } => f.write_str("Outgoing(rotate)"), + } } } @@ -138,7 +171,7 @@ struct Ack { #[derive(Debug)] pub struct Received { pub events: Vec, - /// Our answering `hello`s. + /// Our answering `hello`s, and receipts. pub outgoing: Vec, /// The relay failed part-way: what was fetched before it is here, the rest waits there. pub interrupted: Option, @@ -161,9 +194,13 @@ enum Payload { post_token: Token, name: String, }, - Text { - body: String, - }, + /// `seq` counts this sender's texts to this contact, from 1. + Text { body: String, seq: u64 }, + /// The receiver has saved our texts up to `upto`. + Receipt { upto: u64 }, + /// A new post token for the mailbox the receiver already knows (unblock). + #[serde(rename_all = "camelCase")] + Inbox { post_token: Token }, } #[derive(Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] @@ -189,6 +226,12 @@ struct Contact { outbox: Option<(MailboxId, Token)>, /// The invite this contact came through, on the inviter's side. via: Option, + /// Blocked: their mailbox token rotated away; what still arrives from them is dropped. + blocked: bool, + /// The `seq` of our last text to them. + sent_seq: u64, + /// The highest `seq` of their texts we have received. + received_seq: u64, } pub struct Client { @@ -201,6 +244,8 @@ pub struct Client { contacts: Vec, welcome_boxes: Vec, next_contact: u32, + /// Send receipts and report the other side's (reciprocal). On by default. + receipts: bool, } impl Client { @@ -230,6 +275,7 @@ impl Client { contacts: Vec::new(), welcome_boxes: Vec::new(), next_contact: 0, + receipts: true, }) } @@ -355,16 +401,8 @@ impl Client { .map_err(|_| ClientError::Mls)?; let hello = Self::seal(&self.provider, &self.signer, &mut group, &hello)?; let out = vec![ - Outgoing { - to: welcome_id, - post: welcome_post, - blob: Bytes(welcome), - }, - Outgoing { - to: welcome_id, - post: welcome_post, - blob: Bytes(hello), - }, + Outgoing::post(welcome_id, welcome_post, welcome), + Outgoing::post(welcome_id, welcome_post, hello), ]; let id = self.add_contact(group, Some(inbox), None, None); Ok((id, out)) @@ -395,6 +433,9 @@ impl Client { inbox, outbox, via, + blocked: false, + sent_seq: 0, + received_seq: 0, }); id } @@ -429,27 +470,118 @@ impl Client { .find(|c| c.id == contact) .ok_or(ClientError::UnknownContact)?; let (to, post) = c.outbox.ok_or(ClientError::UnknownContact)?; + let seq = c.sent_seq + 1; let blob = Self::seal( &self.provider, &self.signer, &mut c.group, &Payload::Text { body: text.to_string(), + seq, }, )?; - Ok(Outgoing { - to, - post, - blob: Bytes(blob), - }) + c.sent_seq = seq; + Ok(Outgoing::post(to, post, blob)) } - /// Posts one blob to the relay. + /// The `seq` of our last text to a contact: right after [`Client::compose`], the one it made. + pub fn sent_seq(&self, contact: ContactId) -> Option { + self.contacts + .iter() + .find(|c| c.id == contact) + .map(|c| c.sent_seq) + } + + /// Performs one operation on the relay: posts a blob, or rotates a post token. pub fn deliver(&self, out: &Outgoing) -> Result<(), ClientError> { - self.transport.post(&out.to, &out.post, &out.blob.0)?; + match &out.0 { + Op::Post { to, post, blob } => self.transport.post(to, post, &blob.0)?, + Op::Rotate { + mailbox, + fetch, + post_token_hash, + } => self + .transport + .rotate_post_token(mailbox, fetch, post_token_hash)?, + } Ok(()) } + /// A post waiting in an app's outbox, with the contact's current post token: after an + /// unblock on their side, the token it was sealed with is refused. The blob is unchanged. + pub fn readdress(&self, out: &Outgoing) -> Outgoing { + if let Op::Post { to, blob, .. } = &out.0 { + if let Some((_, post)) = self + .contacts + .iter() + .filter_map(|c| c.outbox) + .find(|(mailbox, _)| mailbox == to) + { + return Outgoing::post(*to, post, blob.0.clone()); + } + } + out.clone() + } + + /// Blocks a contact, staged: they are marked, and their way into our mailbox is closed by a + /// rotate to the hash of a fresh token that nobody gets. Nothing is sent to them. Save the + /// snapshot, then deliver the result. + pub fn block(&mut self, contact: ContactId) -> Result { + let token = Token::from_bytes(self.random()?); + let c = self + .contacts + .iter_mut() + .find(|c| c.id == contact) + .ok_or(ClientError::UnknownContact)?; + let inbox = c.inbox.ok_or(ClientError::UnknownContact)?; + c.blocked = true; + Ok(Outgoing(Op::Rotate { + mailbox: inbox.id, + fetch: inbox.fetch, + post_token_hash: token.hash(), + })) + } + + /// Unblocks, staged: a rotate to a new token, then that token to them inside MLS. + pub fn unblock(&mut self, contact: ContactId) -> Result, ClientError> { + let token = Token::from_bytes(self.random()?); + let c = self + .contacts + .iter_mut() + .find(|c| c.id == contact) + .ok_or(ClientError::UnknownContact)?; + let inbox = c.inbox.ok_or(ClientError::UnknownContact)?; + let (to, post) = c.outbox.ok_or(ClientError::UnknownContact)?; + let blob = Self::seal( + &self.provider, + &self.signer, + &mut c.group, + &Payload::Inbox { post_token: token }, + )?; + c.blocked = false; + Ok(vec![ + Outgoing(Op::Rotate { + mailbox: inbox.id, + fetch: inbox.fetch, + post_token_hash: token.hash(), + }), + Outgoing::post(to, post, blob), + ]) + } + + pub fn is_blocked(&self, contact: ContactId) -> bool { + self.contacts.iter().any(|c| c.id == contact && c.blocked) + } + + /// Receipts on or off: off, we send none and report none of theirs. Save the snapshot after. + pub fn set_receipts(&mut self, on: bool) { + self.receipts = on; + } + + pub fn receipts(&self) -> bool { + self.receipts + } + /// [`Client::compose`] and [`Client::deliver`] at once, for use without persistence. pub fn send(&mut self, contact: ContactId, text: &str) -> Result<(), ClientError> { let out = self.compose(contact, text)?; @@ -488,6 +620,11 @@ impl Client { .iter() .filter_map(|c| c.inbox.map(|m| (m, None))), ); + let before: Vec<(ContactId, u64)> = self + .contacts + .iter() + .map(|c| (c.id, c.received_seq)) + .collect(); for (mailbox, via) in sources { let blobs = match self.transport.fetch(&mailbox.id, &mailbox.fetch) { Ok(blobs) => blobs, @@ -531,16 +668,31 @@ impl Client { continue; }; c.inbox = Some(inbox); - got.outgoing.push(Outgoing { - to, - post, - blob: Bytes(blob), - }); + got.outgoing.push(Outgoing::post(to, post, blob)); } Err(ClientError::Transport(e)) => got.interrupted = Some(e), Err(_) => continue, } } + // Receipts, for every contact whose texts arrived now. Delivered by `finish`, so only + // after the app has saved the texts. + if self.receipts { + for (id, was) in before { + let Some(c) = self.contacts.iter_mut().find(|c| c.id == id) else { + continue; + }; + let Some((to, post)) = c.outbox else { continue }; + if c.received_seq == was || c.blocked { + continue; + } + let receipt = Payload::Receipt { + upto: c.received_seq, + }; + if let Ok(blob) = Self::seal(&self.provider, &self.signer, &mut c.group, &receipt) { + got.outgoing.push(Outgoing::post(to, post, blob)); + } + } + } Ok(got) } @@ -551,9 +703,16 @@ impl Client { /// is never fetched. Not before: a snapshot saved between `receive` and `finish` must still /// know the mailbox, so that a restored client fetches its blobs again and acknowledges them. /// Save the snapshot again after `finish`. + /// + /// A post the relay refuses with 404 is skipped: that mailbox's token is gone (we may be + /// blocked), and trying again cannot help. Without the skip, one refused receipt would keep + /// everything fetched from being acknowledged, for ever. pub fn finish(&mut self, received: &Received) -> Result<(), ClientError> { for out in &received.outgoing { - self.deliver(out)?; + match self.deliver(out) { + Ok(()) | Err(ClientError::Transport(TransportError::NotFound)) => {} + Err(e) => return Err(e), + } } for ack in &received.acks { self.transport @@ -653,17 +812,42 @@ impl Client { via: c.via, })) } - Payload::Text { body } => { - let c = &self.contacts[index]; + Payload::Text { body, seq } => { + let c = &mut self.contacts[index]; if c.name.is_none() { // Text before hello: not from a conversation that has been set up. return Err(ClientError::Mls); } + if c.blocked { + // Posted before the block, or fetched after it: dropped, never shown. + return Ok(None); + } + c.received_seq = c.received_seq.max(seq); Ok(Some(Event::Message { contact: c.id, text: body, })) } + Payload::Receipt { upto } => { + let c = &self.contacts[index]; + if !self.receipts || c.name.is_none() || c.blocked { + return Ok(None); + } + // A receipt cannot mark what was never sent. + Ok(Some(Event::Delivered { + contact: c.id, + upto: upto.min(c.sent_seq), + })) + } + Payload::Inbox { post_token } => { + let c = &mut self.contacts[index]; + // Only the token changes: the mailbox stays the one their hello named. + let Some((mailbox, _)) = c.outbox else { + return Err(ClientError::Mls); + }; + c.outbox = Some((mailbox, post_token)); + Ok(None) + } } } } @@ -703,4 +887,43 @@ mod tests { assert_eq!(eva.contacts[0].outbox.map(|(m, _)| m), before); assert_eq!(eva.contacts[0].name.as_deref(), Some("Jan")); } + + /// `inbox` (unblock) changes only the token for the mailbox their hello named. + #[test] + fn an_inbox_payload_changes_the_token_not_the_mailbox() { + let relay = MemoryTransport::default(); + let mut eva = Client::new("Eva", relay.clone()).expect("eva"); + let mut jan = Client::new("Jan", relay.clone()).expect("jan"); + let invite = eva.create_invite().expect("invite"); + jan.accept_invite(&invite).expect("accept"); + eva.poll().expect("poll"); + let (mailbox, before) = eva.contacts[0].outbox.expect("outbox"); + let fresh = Token::from_bytes([5; 32]); + let inbox = Payload::Inbox { post_token: fresh }; + assert_eq!(eva.receive_payload(0, inbox), Ok(None)); + let (still, after) = eva.contacts[0].outbox.expect("outbox"); + assert_eq!(still, mailbox); + assert_ne!(after.hash(), before.hash()); + assert_eq!(after.hash(), fresh.hash()); + } + + /// A receipt cannot mark texts that were never sent. + #[test] + fn a_receipt_is_capped_at_what_was_sent() { + let relay = MemoryTransport::default(); + let mut eva = Client::new("Eva", relay.clone()).expect("eva"); + let mut jan = Client::new("Jan", relay.clone()).expect("jan"); + let invite = eva.create_invite().expect("invite"); + jan.accept_invite(&invite).expect("accept"); + eva.poll().expect("poll"); + eva.send(eva.contacts[0].id, "jedna").expect("send"); + let got = eva.receive_payload(0, Payload::Receipt { upto: 99 }); + assert_eq!( + got, + Ok(Some(Event::Delivered { + contact: eva.contacts[0].id, + upto: 1 + })) + ); + } } diff --git a/crates/client/src/snapshot.rs b/crates/client/src/snapshot.rs index 2ce4bc4..b429f80 100644 --- a/crates/client/src/snapshot.rs +++ b/crates/client/src/snapshot.rs @@ -47,6 +47,17 @@ struct ContactState { inbox: Option, outbox: Option<(MailboxId, Token)>, via: Option, + // F24; absent in older snapshots. + #[serde(default)] + blocked: bool, + #[serde(default)] + sent_seq: u64, + #[serde(default)] + received_seq: u64, +} + +fn yes() -> bool { + true } #[derive(Serialize, Deserialize)] @@ -59,6 +70,8 @@ struct State { contacts: Vec, welcome_boxes: Vec, next_contact: u32, + #[serde(default = "yes")] + receipts: bool, /// OpenMLS's storage: every key and value, sorted by key so equal states give equal bytes. storage: Vec<(Bytes, Bytes)>, } @@ -91,10 +104,14 @@ impl Client { inbox: c.inbox, outbox: c.outbox, via: c.via, + blocked: c.blocked, + sent_seq: c.sent_seq, + received_seq: c.received_seq, }) .collect(), welcome_boxes: self.welcome_boxes.clone(), next_contact: self.next_contact, + receipts: self.receipts, storage, }; serde_json::to_vec(&state).map_err(|_| ClientError::State) @@ -143,6 +160,9 @@ impl Client { inbox: c.inbox, outbox: c.outbox, via: c.via, + blocked: c.blocked, + sent_seq: c.sent_seq, + received_seq: c.received_seq, }); } Ok(Client { @@ -155,6 +175,7 @@ impl Client { contacts, welcome_boxes: state.welcome_boxes, next_contact: state.next_contact, + receipts: state.receipts, }) } } diff --git a/crates/client/src/transport.rs b/crates/client/src/transport.rs index 21ca5ae..b9d7e8e 100644 --- a/crates/client/src/transport.rs +++ b/crates/client/src/transport.rs @@ -32,6 +32,13 @@ pub trait Transport { hash: &Sha256Hash, ) -> Result<(), TransportError>; fn create_invite(&self, req: &CreateInvite) -> Result<(), TransportError>; + /// Block: the mailbox's post token becomes `new_hash`'s; the old one is refused from now on. + fn rotate_post_token( + &self, + id: &MailboxId, + fetch: &Token, + new_hash: &Sha256Hash, + ) -> Result<(), TransportError>; /// The KeyPackage, once. fn claim_invite(&self, id: &InviteId, secret: &Token) -> Result, TransportError>; } @@ -129,6 +136,21 @@ impl Transport for MemoryTransport { } } + fn rotate_post_token( + &self, + id: &MailboxId, + fetch: &Token, + new_hash: &Sha256Hash, + ) -> Result<(), TransportError> { + match self.boxes().mailboxes.get_mut(id) { + Some((post, f, _)) if *f == fetch.hash() => { + *post = *new_hash; + Ok(()) + } + _ => Err(TransportError::NotFound), + } + } + fn create_invite(&self, req: &CreateInvite) -> Result<(), TransportError> { let mut b = self.boxes(); if b.invites.contains_key(&req.id) { diff --git a/crates/client/tests/block.rs b/crates/client/tests/block.rs new file mode 100644 index 0000000..f0bee76 --- /dev/null +++ b/crates/client/tests/block.rs @@ -0,0 +1,215 @@ +//! Block, unblock and receipts (`.agents/features/block-and-receipts.md` §3). No I/O: runs on the +//! Android emulator too. + +use tabellarius_client::*; + +type C = Client; + +fn pair(relay: &MemoryTransport) -> (C, ContactId, C, ContactId) { + let mut eva = Client::new("Eva", relay.clone()).expect("eva"); + let mut jan = Client::new("Jan", relay.clone()).expect("jan"); + let invite = eva.create_invite().expect("invite"); + let jan_side = jan.accept_invite(&invite).expect("accept"); + let Some(Event::Joined { + contact: eva_side, .. + }) = eva.poll().expect("poll").first().cloned() + else { + panic!("no join") + }; + jan.poll().expect("poll"); + (eva, eva_side, jan, jan_side) +} + +fn texts(events: &[Event]) -> Vec { + events + .iter() + .filter_map(|e| match e { + Event::Message { text, .. } => Some(text.clone()), + _ => None, + }) + .collect() +} + +#[test] +fn a_blocked_contact_reaches_us_no_more_and_is_not_told() { + let relay = MemoryTransport::default(); + let (mut eva, eva_side, mut jan, jan_side) = pair(&relay); + // Jan writes once before the block; it waits on the relay. + jan.send(jan_side, "před blokem").expect("send"); + let waiting = relay.waiting_blobs(); + + let rotate = eva.block(eva_side).expect("block"); + assert_eq!( + relay.waiting_blobs(), + waiting, + "block posts nothing to anyone" + ); + eva.deliver(&rotate).expect("rotate"); + assert!(eva.is_blocked(eva_side)); + + // Jan's next post is refused, the same 404 as any wrong token. + assert_eq!( + jan.send(jan_side, "po bloku"), + Err(ClientError::Transport(TransportError::NotFound)) + ); + // What he posted before the block is fetched, dropped, never shown, and acknowledged. + let events = eva.poll().expect("poll"); + assert!(texts(&events).is_empty(), "{events:?}"); + assert_eq!(relay.waiting_blobs(), 0); + // Eva can still write to him: block closes her mailbox, not his. His receipt for it is + // refused, and that does not stop his app from acknowledging what it fetched. + assert!(jan.receipts()); + eva.send(eva_side, "jen já tobě").expect("send"); + assert_eq!(texts(&jan.poll().expect("poll")), ["jen já tobě"]); +} + +#[test] +fn a_block_made_offline_waits_and_survives_a_restart() { + let relay = MemoryTransport::default(); + let (mut eva, eva_side, mut jan, jan_side) = pair(&relay); + let rotate = eva.block(eva_side).expect("block"); + // Staged: nothing reached the relay, so Jan can still post until the rotate is delivered. + jan.send(jan_side, "ještě to prošlo") + .expect("not blocked on the relay yet"); + let saved = eva.snapshot().expect("snapshot"); + let kept = serde_json::to_vec(&rotate).expect("outbox"); + drop(eva); // the relay was away; the app closes + + let eva = Client::restore(&saved, relay.clone()).expect("restore"); + assert!(eva.is_blocked(eva_side)); + let rotate: Outgoing = serde_json::from_slice(&kept).expect("outbox"); + assert_eq!(format!("{rotate:?}"), "Outgoing(rotate)"); + eva.deliver(&rotate).expect("rotate"); + eva.deliver(&rotate).expect("a second time changes nothing"); + assert!(jan.send(jan_side, "x").is_err()); +} + +#[test] +fn unblocking_readdresses_what_waited_and_both_can_talk_again() { + let relay = MemoryTransport::default(); + let (mut eva, eva_side, mut jan, jan_side) = pair(&relay); + let rotate = eva.block(eva_side).expect("block"); + eva.deliver(&rotate).expect("rotate"); + // Jan's app keeps what it could not send in its outbox. + let stuck = jan.compose(jan_side, "čekalo to").expect("compose"); + assert!(jan.deliver(&stuck).is_err()); + + for out in eva.unblock(eva_side).expect("unblock") { + eva.deliver(&out).expect("deliver"); + } + assert!(!eva.is_blocked(eva_side)); + jan.poll().expect("Jan receives the new token"); + // The old token is still refused; readdressed, the same sealed message goes through. + assert!(jan.deliver(&stuck).is_err()); + jan.deliver(&jan.readdress(&stuck)).expect("readdressed"); + jan.send(jan_side, "a teď nová").expect("send"); + assert_eq!( + texts(&eva.poll().expect("poll")), + ["čekalo to", "a teď nová"] + ); + eva.send(eva_side, "vítej zpátky").expect("send"); + assert_eq!(texts(&jan.poll().expect("poll")), ["vítej zpátky"]); +} + +#[test] +fn receipts_say_what_arrived_and_only_while_both_want_them() { + let relay = MemoryTransport::default(); + let (mut eva, eva_side, mut jan, jan_side) = pair(&relay); + for t in ["jedna", "dvě", "tři"] { + eva.send(eva_side, t).expect("send"); + } + assert_eq!(eva.sent_seq(eva_side), Some(3)); + assert_eq!(texts(&jan.poll().expect("poll")).len(), 3); + assert!(eva.poll().expect("poll").contains(&Event::Delivered { + contact: eva_side, + upto: 3 + })); + + // Jan turns them off: he sends none. + jan.set_receipts(false); + eva.send(eva_side, "čtyři").expect("send"); + jan.poll().expect("poll"); + assert!(!eva + .poll() + .expect("poll") + .iter() + .any(|e| matches!(e, Event::Delivered { .. }))); + + // Eva turns them off: Jan's are ignored (reciprocal). + jan.set_receipts(true); + eva.set_receipts(false); + eva.send(eva_side, "pět").expect("send"); + jan.poll().expect("poll"); + assert!(!eva + .poll() + .expect("poll") + .iter() + .any(|e| matches!(e, Event::Delivered { .. }))); + // And she sends none for Jan's. + jan.send(jan_side, "ahoj").expect("send"); + eva.poll().expect("poll"); + assert!(!jan + .poll() + .expect("poll") + .iter() + .any(|e| matches!(e, Event::Delivered { .. }))); +} + +#[test] +fn a_blocked_contact_gets_no_receipt() { + let relay = MemoryTransport::default(); + let (mut eva, eva_side, mut jan, jan_side) = pair(&relay); + jan.send(jan_side, "x").expect("send"); + let rotate = eva.block(eva_side).expect("block"); + eva.deliver(&rotate).expect("rotate"); + eva.poll().expect("poll"); + assert!(!jan + .poll() + .expect("poll") + .iter() + .any(|e| matches!(e, Event::Delivered { .. }))); +} + +#[test] +fn receipts_are_kept_across_a_restart_and_default_to_on() { + let relay = MemoryTransport::default(); + let (mut eva, eva_side, _jan, _) = pair(&relay); + assert!(eva.receipts()); + eva.set_receipts(false); + eva.send(eva_side, "x").expect("send"); + let saved = eva.snapshot().expect("snapshot"); + let eva = Client::restore(&saved, relay.clone()).expect("restore"); + assert!(!eva.receipts()); + assert_eq!(eva.sent_seq(eva_side), Some(1)); + + // A snapshot from before F24 has none of the new fields: it restores, receipts on. + let mut old: serde_json::Value = serde_json::from_slice(&saved).expect("json"); + old.as_object_mut().expect("object").remove("receipts"); + for c in old["contacts"].as_array_mut().expect("contacts") { + let c = c.as_object_mut().expect("contact"); + for f in ["blocked", "sentSeq", "receivedSeq"] { + c.remove(f); + } + } + let old = serde_json::to_vec(&old).expect("json"); + let eva = Client::restore(&old, relay.clone()).expect("an old snapshot"); + assert!(eva.receipts()); + assert!(!eva.is_blocked(eva_side)); +} + +#[test] +fn a_refused_receipt_does_not_keep_the_blocked_side_from_acknowledging() { + let relay = MemoryTransport::default(); + let (mut eva, eva_side, mut jan, _) = pair(&relay); + let rotate = eva.block(eva_side).expect("block"); + eva.deliver(&rotate).expect("rotate"); + eva.send(eva_side, "jedna").expect("send"); + eva.send(eva_side, "dvě").expect("send"); + assert_eq!(texts(&jan.poll().expect("poll")), ["jedna", "dvě"]); + assert_eq!( + relay.waiting_blobs(), + 0, + "acknowledged, the refused receipt skipped" + ); + assert!(jan.poll().expect("poll").is_empty()); +} diff --git a/crates/client/tests/pairing.rs b/crates/client/tests/pairing.rs index d7bacb8..88ff06f 100644 --- a/crates/client/tests/pairing.rs +++ b/crates/client/tests/pairing.rs @@ -19,6 +19,9 @@ fn pair( ) { let mut eva = Client::new("Eva Nováková", relay.clone()).expect("eva"); let mut jan = Client::new("Jan", relay.clone()).expect("jan"); + // Receipts (F24) have their own tests; here they would only add events and blobs. + eva.set_receipts(false); + jan.set_receipts(false); let invite = eva.create_invite().expect("invite"); let jan_side = jan.accept_invite(&invite).expect("accept"); let eva_events = eva.poll().expect("eva polls"); diff --git a/crates/client/tests/real_relay.rs b/crates/client/tests/real_relay.rs index 659ebe6..0678382 100644 --- a/crates/client/tests/real_relay.rs +++ b/crates/client/tests/real_relay.rs @@ -98,6 +98,20 @@ impl Transport for Http { self.call("DELETE", &path, Some(fetch), &[], false) .map(|_| ()) } + fn rotate_post_token( + &self, + id: &MailboxId, + fetch: &Token, + new_hash: &Sha256Hash, + ) -> Result<(), TransportError> { + let body = serde_json::to_vec(&RotatePostToken { + post_token_hash: *new_hash, + }) + .map_err(|_| TransportError::Failed)?; + let path = format!("/v0/mailboxes/{}/post-token", id.to_wire()); + self.call("PUT", &path, Some(fetch), &body, true) + .map(|_| ()) + } fn create_invite(&self, req: &CreateInvite) -> Result<(), TransportError> { let body = serde_json::to_vec(req).map_err(|_| TransportError::Failed)?; self.call("POST", "/v0/invites", None, &body, true) @@ -152,6 +166,8 @@ fn pair_and_talk_through_a_real_relay_which_never_sees_a_name_or_a_word() { let mut eva = Client::new("Eva Nováková", relay.clone()).expect("eva"); let mut jan = Client::new("Jan Dvořák", relay.clone()).expect("jan"); + eva.set_receipts(false); + jan.set_receipts(false); let invite = eva.create_invite().expect("invite"); // While the invite waits, the relay holds Eva's KeyPackage: it must not carry her name. let invited = std::fs::read(&db).expect("db"); diff --git a/crates/client/tests/state.rs b/crates/client/tests/state.rs index 4ede982..7a04136 100644 --- a/crates/client/tests/state.rs +++ b/crates/client/tests/state.rs @@ -5,10 +5,16 @@ use tabellarius_client::*; type C = Client; +/// Receipts off: these tests count events and waiting blobs, and receipts (F24) have their own. +fn quiet(mut c: Client) -> Client { + c.set_receipts(false); + c +} + /// Pairs Eva (inviter) and Jan through the staged calls, saving nothing. Returns both sides' ids. fn pair(relay: &MemoryTransport) -> (C, ContactId, C, ContactId) { - let mut eva = Client::new("Eva", relay.clone()).expect("eva"); - let mut jan = Client::new("Jan", relay.clone()).expect("jan"); + let mut eva = quiet(Client::new("Eva", relay.clone()).expect("eva")); + let mut jan = quiet(Client::new("Jan", relay.clone()).expect("jan")); let invite = eva.create_invite().expect("invite"); let jan_side = jan.accept_invite(&invite).expect("accept"); let events = eva.poll().expect("poll"); @@ -39,7 +45,7 @@ fn texts(events: Vec) -> Vec { .into_iter() .filter_map(|e| match e { Event::Message { text, .. } => Some(text), - Event::Joined { .. } => None, + _ => None, }) .collect() } @@ -64,8 +70,8 @@ fn both_sides_restart_mid_conversation_and_keep_talking() { #[test] fn an_invite_waiting_survives_a_restart() { let relay = MemoryTransport::default(); - let mut eva = Client::new("Eva", relay.clone()).expect("eva"); - let mut jan = Client::new("Jan", relay.clone()).expect("jan"); + let mut eva = quiet(Client::new("Eva", relay.clone()).expect("eva")); + let mut jan = quiet(Client::new("Jan", relay.clone()).expect("jan")); let invite = eva.create_invite().expect("invite"); let mut eva = restart(&eva, &relay); let jan_side = jan.accept_invite(&invite).expect("accept"); @@ -84,7 +90,7 @@ fn a_restored_client_gives_a_new_contact_a_new_id() { let relay = MemoryTransport::default(); let (eva, eva_side, _jan, _) = pair(&relay); let mut eva = restart(&eva, &relay); - let mut petr = Client::new("Petr", relay.clone()).expect("petr"); + let mut petr = quiet(Client::new("Petr", relay.clone()).expect("petr")); let invite = eva.create_invite().expect("invite"); petr.accept_invite(&invite).expect("accept"); let events = eva.poll().expect("poll"); @@ -99,8 +105,8 @@ fn a_restored_client_gives_a_new_contact_a_new_id() { #[test] fn the_staged_calls_post_nothing_and_acknowledge_nothing() { let relay = MemoryTransport::default(); - let mut eva = Client::new("Eva", relay.clone()).expect("eva"); - let mut jan = Client::new("Jan", relay.clone()).expect("jan"); + let mut eva = quiet(Client::new("Eva", relay.clone()).expect("eva")); + let mut jan = quiet(Client::new("Jan", relay.clone()).expect("jan")); let invite = eva.create_invite().expect("invite"); let (jan_side, out) = jan.accept(&invite).expect("accept"); @@ -137,8 +143,8 @@ fn the_staged_calls_post_nothing_and_acknowledge_nothing() { #[test] fn a_crash_between_receive_and_finish_loses_nothing_and_shows_nothing_twice() { let relay = MemoryTransport::default(); - let mut eva = Client::new("Eva", relay.clone()).expect("eva"); - let mut jan = Client::new("Jan", relay.clone()).expect("jan"); + let mut eva = quiet(Client::new("Eva", relay.clone()).expect("eva")); + let mut jan = quiet(Client::new("Jan", relay.clone()).expect("jan")); let invite = eva.create_invite().expect("invite"); let jan_side = jan.accept_invite(&invite).expect("accept"); // Jan cannot write before Eva's hello gives him her mailbox. @@ -317,6 +323,14 @@ impl Transport for Flaky { fn create_invite(&self, r: &tabellarius_protocol::CreateInvite) -> Result<(), TransportError> { self.inner.create_invite(r) } + fn rotate_post_token( + &self, + id: &tabellarius_protocol::MailboxId, + fetch: &tabellarius_protocol::Token, + new_hash: &tabellarius_protocol::Sha256Hash, + ) -> Result<(), TransportError> { + self.inner.rotate_post_token(id, fetch, new_hash) + } fn claim_invite( &self, id: &tabellarius_protocol::InviteId, @@ -332,8 +346,8 @@ impl Transport for Flaky { fn finish_acknowledges_nothing_when_delivering_fails() { let relay = MemoryTransport::default(); let flaky = Flaky::new(&relay); - let mut eva = Client::new("Eva", flaky.clone()).expect("eva"); - let mut jan = Client::new("Jan", relay.clone()).expect("jan"); + let mut eva = quiet(Client::new("Eva", flaky.clone()).expect("eva")); + let mut jan = quiet(Client::new("Jan", relay.clone()).expect("jan")); let invite = eva.create_invite().expect("invite"); let jan_side = jan.accept_invite(&invite).expect("accept"); @@ -362,10 +376,10 @@ fn finish_acknowledges_nothing_when_delivering_fails() { fn a_relay_failing_part_way_returns_what_was_processed() { let relay = MemoryTransport::default(); let flaky = Flaky::new(&relay); - let mut eva = Client::new("Eva", flaky.clone()).expect("eva"); + let mut eva = quiet(Client::new("Eva", flaky.clone()).expect("eva")); let mut friends = Vec::new(); for name in ["Jan", "Petr"] { - let mut friend = Client::new(name, relay.clone()).expect("friend"); + let mut friend = quiet(Client::new(name, relay.clone()).expect("friend")); let invite = eva.create_invite().expect("invite"); let side = friend.accept_invite(&invite).expect("accept"); friends.push((friend, side)); @@ -398,8 +412,8 @@ fn a_relay_failing_part_way_returns_what_was_processed() { #[test] fn a_used_welcome_mailbox_is_no_longer_fetched() { let relay = MemoryTransport::default(); - let mut eva = Client::new("Eva", relay.clone()).expect("eva"); - let mut jan = Client::new("Jan", relay.clone()).expect("jan"); + let mut eva = quiet(Client::new("Eva", relay.clone()).expect("eva")); + let mut jan = quiet(Client::new("Jan", relay.clone()).expect("jan")); let invite = eva.create_invite().expect("invite"); jan.accept_invite(&invite).expect("accept"); eva.poll().expect("poll"); @@ -415,8 +429,8 @@ fn a_used_welcome_mailbox_is_no_longer_fetched() { #[test] fn a_forgotten_invite_is_no_longer_fetched() { let relay = MemoryTransport::default(); - let mut eva = Client::new("Eva", relay.clone()).expect("eva"); - let mut jan = Client::new("Jan", relay.clone()).expect("jan"); + let mut eva = quiet(Client::new("Eva", relay.clone()).expect("eva")); + let mut jan = quiet(Client::new("Jan", relay.clone()).expect("jan")); let invite = eva.create_invite().expect("invite"); eva.forget_invite(&invite.id); let mut eva = restart(&eva, &relay); @@ -439,7 +453,7 @@ fn contains(haystack: &[u8], needle: &[u8]) -> bool { fn a_forgotten_contact_leaves_nothing_behind() { let relay = MemoryTransport::default(); let (mut eva, eva_side, mut jan, jan_side) = pair(&relay); - let mut petr = Client::new("Petr Zapomenutý", relay.clone()).expect("petr"); + let mut petr = quiet(Client::new("Petr Zapomenutý", relay.clone()).expect("petr")); let invite = eva.create_invite().expect("invite"); let petr_side = petr.accept_invite(&invite).expect("accept"); let Some(Event::Joined { diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.md index b3267dc..70bff33 100644 --- a/docs/PROTOCOL.md +++ b/docs/PROTOCOL.md @@ -46,6 +46,19 @@ MLS**. To the relay, the welcome mailbox is an ordinary mailbox. *(Changed 2026-11-14, approved by Mark, from "the invitee replies with their own KeyPackage": the invitee needs no KeyPackage, because it creates the group itself.)* +### Payloads inside MLS *(added 2026-11-17, F24; `.agents/features/block-and-receipts.md`)* +Every MLS application message carries one JSON object. The relay sees none of it. +| `kind` | Fields | Meaning | +|:--|:--|:--| +| `hello` | `mailbox`, `postToken`, `name` | where and how to post to the sender; once per conversation | +| `text` | `body`, `seq` | a message; `seq` counts the sender's texts to this contact from 1 | +| `receipt` | `upto` | the receiver has saved the sender's texts up to `upto`. Sent only by a client with receipts on; a client with them off also ignores them | +| `inbox` | `postToken` | a new post token for the mailbox the receiver already knows (after an unblock). It cannot name another mailbox | + +**Block** (§3) is a rotate of the post token to the hash of a token nobody gets. Nothing is sent to +the blocked person: their posts get §8's ordinary 404. What they posted before is fetched and +dropped. **Unblock** rotates again and sends the new token in an `inbox` payload. + ## 5. What the relay stores — the complete list | Table | Columns | |:--|:--|