Compare commits

..

3 Commits

Author SHA1 Message Date
mnovak 6f939be758 [client] F22a: forget_invite, so an unclaimed invite's mailbox is not fetched for ever
ci / check (pull_request) Has been cancelled
2026-11-16 01:02:29 +01:00
mnovak 21bee2d633 [client] F22a: snapshot and restore, and staged calls that send nothing before the app has saved 2026-11-16 00:59:25 +01:00
mnovak 47ed9eef18 [client] F21: merge feature/client — MLS 1:1 over OpenMLS, mailboxes, invites
ci / check (push) Has been cancelled
PROTOCOL.md section 4 revised as built (approved by Mark, 2026-11-14). Self-review: PR #14.
41 tests: client 10, protocol 14, relay 17.
2026-11-14 15:00:19 +01:00
8 changed files with 997 additions and 64 deletions
+102
View File
@@ -0,0 +1,102 @@
# F22a — The client survives a restart, and never sends what it has not saved
Analysis, 2026-11-16. Part of F22 (chat in Amicitia, `../amicitia/.agents/features/chat.md`). It
builds on F21 (`client.md`), whose state lived in memory only (its review, finding F6).
## 1. Why and what
An app must be able to close and reopen without losing a conversation, and must never get into a
state that MLS cannot recover from. Two things are needed:
1. **A snapshot.** `Client::snapshot()` gives the whole client state as bytes, and
`Client::restore(bytes, transport)` brings it back. The app keeps the bytes in its own encrypted
store (Amicitia: the SQLCipher database). The library never writes a file.
2. **Save before the network sees it.** Everything that reaches the relay after a state change goes
out only after the app has saved the snapshot. Otherwise a crash can leave the relay ahead of the
saved state.
### What goes wrong without step 2
| Crash between… | Then, after restoring the older snapshot |
|:--|:--|
| a text posted and the snapshot saved | the next text reuses the same MLS generation; the other side cannot decrypt it, and every later one fails too |
| the blobs acknowledged and the snapshot saved | the messages are gone from the relay and from the app |
| the inviter's `hello` posted and the snapshot saved | the inviter joins again from the same Welcome and sends a second `hello` with a new mailbox; the other side refuses it (F21's *second hello* rule) and posts to a mailbox the inviter no longer knows |
## 2. Design
### The staged calls
Each call that changes state does its **local** work and returns what still has to reach the relay:
| Call | Network inside the call | Returned for the app to deliver after saving |
|:--|:--|:--|
| `compose(contact, text)` | none | one `Outgoing` |
| `accept(invite)` | claim the KeyPackage; create our mailbox | `ContactId`, and the Welcome and `hello` as `Outgoing`s |
| `receive()` | fetch; create our mailbox when a `hello` asks us to answer | a `Received`: the events, our answering `hello`s as `Outgoing`s, and the blobs to acknowledge |
| `create_invite()` | create the welcome mailbox and the invite | the `Invite` (the app shows the link only after saving) |
Then `deliver(&Outgoing)` posts one blob, and `finish(&Received)` delivers its `Outgoing`s, then
acknowledges its blobs, then drops each welcome mailbox whose contact has said hello. The app saves
the snapshot again after `finish`. The drop waits for `finish` on purpose. A snapshot saved between
`receive` and `finish` must still know the welcome mailbox, so that a restored client fetches its
blobs again and acknowledges them. Dropping it inside `receive` left the Welcome and the `hello` on
the relay for 30 days; test 3 found that while this was being built. `Outgoing` is serialisable, so an app can keep it in an outbox and deliver
it again after a crash.
The F21 calls stay, for apps and tests without persistence: `send` = `compose` + `deliver`,
`accept_invite` = `accept` + deliver, `poll` = `receive` + `finish`.
### Why a crash is now harmless
| Crash after saving, before… | What happens on the next start |
|:--|:--|
| delivering an `Outgoing` | the app delivers it from its outbox. If the crash came after the post, the blob arrives twice; MLS refuses the second copy as a replay, and it is dropped |
| acknowledging | the blobs are fetched again; MLS refuses them as already processed, and the client drops them and acknowledges them. The events were saved with the snapshot, so nothing is shown twice |
| saving at all | nothing reached the relay, apart from a mailbox or an invite nobody knows about: no harm. A claimed invite is used up (the link says *ask for a new one*) |
### The snapshot
- JSON, versioned (`"v": 1`). It contains:
- our name and the 16 identity bytes;
- the signature public key; the private key is in OpenMLS's storage;
- each contact: id, MLS group id, name, our mailbox and fetch token, their mailbox and post token;
- the welcome mailboxes;
- **all of OpenMLS's storage** (`MemoryStorage::values`, a public map of keys and values,
base64url).
- Restoring rebuilds the provider with that map. It loads each group with `MlsGroup::load` and the
signer with `SignatureKeyPair::read`. A snapshot that does not parse, has another version, or
names a group that is not in the storage is refused (`ClientError::State`). A half-restored client
is never returned.
- **It holds every secret of the identity**: MLS private keys, fetch tokens, post tokens. It must
live only in encrypted storage. The library never logs it, and its `Debug` prints no bytes.
- **Size:** a few KB per contact (two MLS epochs of secrets). Writing it whole after each change is
fine for 1:1 chats with dozens of people. A table per key would scale better; that is for later,
when measured.
## 3. Tests — written first
1. **Restart both sides mid-conversation:** pair, talk, snapshot both, restore both into new clients,
then talk both ways.
2. **Restart with an invite waiting:** create an invite, snapshot, restore; the invitee accepts; the
restored inviter joins.
3. **Crash between receive and finish** (on the inviter's side, when the `hello` is answered): save
the snapshot with the `Received`, drop the client, restore, deliver the saved `Outgoing`s, receive
again. The pairing completes, and no event is shown twice.
4. **Crash after deliver, before marking it delivered:** the blob is posted twice; the receiver shows
the text once.
5. **Nothing reaches the relay before the app saves.** `compose` and `receive` post nothing (the
relay's blob count is unchanged), and `receive` acknowledges nothing.
6. **A bad snapshot is refused:** truncated, wrong version, or a contact whose group is missing.
7. **The snapshot carries no name in clear on the relay:** not a relay test. The relay never sees a
snapshot, and the F21 tests still hold.
8. **The relay fails:** `finish` acknowledges nothing when delivering fails (an app without an
outbox depends on that). A `receive` whose relay fails part-way returns what it processed,
because the client's state already includes it.
9. **A used welcome mailbox is no longer fetched**, even after a restart. Neither is a forgotten
invite's: `forget_invite(id)`, which the app calls when an invite is cancelled or older than the
relay's 7 days (the library has no clock). Without it an unclaimed invite's mailbox is fetched
for ever.
Planted bugs, for the review: `receive` acknowledges inside the call; `compose` posts; `restore`
skips the storage map; `finish` acknowledges before it delivers; a restored client starts
`next_contact` at 0, so two contacts share an id.
## 4. Not in this part
- How Amicitia stores the snapshot, events and outbox in one transaction (F22b).
- Several devices per identity (Phase 2 has one; HANDOVER).
- Encrypting the snapshot inside the library: the app's store is already encrypted, and a second
key would have to live somewhere too.
Generated
+1
View File
@@ -2245,6 +2245,7 @@ name = "tabellarius-client"
version = "0.0.0" version = "0.0.0"
dependencies = [ dependencies = [
"axum", "axum",
"base64",
"hkdf 0.12.4", "hkdf 0.12.4",
"openmls", "openmls",
"openmls_basic_credential", "openmls_basic_credential",
+2
View File
@@ -18,6 +18,8 @@ hkdf = "0.12"
sha2 = "0.10" sha2 = "0.10"
serde = { version = "1", features = ["derive"] } serde = { version = "1", features = ["derive"] }
serde_json = "1" serde_json = "1"
# The snapshot's byte fields (already in the tree through the protocol crate).
base64 = "0.22"
[dev-dependencies] [dev-dependencies]
# The real relay, for the end-to-end test only. `check-deps.sh` checks normal edges: the client # The real relay, for the end-to-end test only. `check-deps.sh` checks normal edges: the client
+284 -63
View File
@@ -9,9 +9,19 @@
//! 3. The inviter joins, and answers with its own `hello` to the invitee's mailbox. //! 3. The inviter joins, and answers with its own `hello` to the invitee's mailbox.
//! //!
//! The relay only ever holds MLS ciphertext, KeyPackages, ids and token hashes. //! The relay only ever holds MLS ciphertext, KeyPackages, ids and token hashes.
//!
//! **An app that keeps the client across restarts** (`.agents/features/client-state.md`) uses the
//! staged calls — [`Client::compose`], [`Client::accept`], [`Client::receive`] — then saves
//! [`Client::snapshot`] together with what they returned, and only then calls [`Client::deliver`]
//! or [`Client::finish`]. Nothing reaches the relay after a state change before the app has saved
//! it. [`Client::send`], [`Client::accept_invite`] and [`Client::poll`] do both steps at once, for
//! use without persistence.
pub mod transport; pub mod transport;
mod snapshot;
pub use snapshot::SNAPSHOT_VERSION;
use hkdf::Hkdf; use hkdf::Hkdf;
use openmls::prelude::tls_codec::{Deserialize as _, Serialize as _}; use openmls::prelude::tls_codec::{Deserialize as _, Serialize as _};
use openmls::prelude::*; use openmls::prelude::*;
@@ -19,9 +29,11 @@ use openmls_basic_credential::SignatureKeyPair;
use openmls_rust_crypto::OpenMlsRustCrypto; use openmls_rust_crypto::OpenMlsRustCrypto;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use sha2::Sha256; use sha2::Sha256;
use snapshot::Bytes;
use std::fmt;
use tabellarius_protocol::{ use tabellarius_protocol::{
blob_hash, CreateInvite, CreateMailbox, InviteId, KeyPackageBytes, MailboxId, Token, blob_hash, CreateInvite, CreateMailbox, InviteId, KeyPackageBytes, MailboxId, Sha256Hash,
MAX_BLOB_BYTES, Token, MAX_BLOB_BYTES,
}; };
pub use transport::{MemoryTransport, Transport, TransportError}; pub use transport::{MemoryTransport, Transport, TransportError};
@@ -47,6 +59,8 @@ pub enum ClientError {
TooLong, TooLong,
/// No such contact, or a contact whose mailbox is not known yet. /// No such contact, or a contact whose mailbox is not known yet.
UnknownContact, UnknownContact,
/// A snapshot that does not parse, has another version, or does not match OpenMLS's storage.
State,
} }
impl From<TransportError> for ClientError { impl From<TransportError> for ClientError {
@@ -74,16 +88,19 @@ pub fn welcome_mailbox(secret: &Token) -> (MailboxId, Token) {
} }
/// A local handle for a contact. Means nothing outside this client. /// A local handle for a contact. Means nothing outside this client.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Serialize, Deserialize)]
pub struct ContactId(pub u32); pub struct ContactId(pub u32);
/// What [`Client::poll`] found. /// What [`Client::receive`] found.
#[derive(Clone, PartialEq, Eq, Debug)] #[derive(Clone, PartialEq, Eq, Debug)]
pub enum Event { pub enum Event {
/// The other side's `hello` arrived: the conversation can be used both ways. /// The other side's `hello` arrived: the conversation can be used both ways. On the
/// inviter's side, `via` is the invite it came through; on the invitee's side it is `None`
/// (the app already knows the contact from [`Client::accept`]).
Joined { Joined {
contact: ContactId, contact: ContactId,
name: String, name: String,
via: Option<InviteId>,
}, },
Message { Message {
contact: ContactId, contact: ContactId,
@@ -91,6 +108,49 @@ pub enum Event {
}, },
} }
/// 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.
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Outgoing {
to: MailboxId,
post: Token,
blob: Bytes,
}
impl fmt::Debug for Outgoing {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Outgoing({} bytes)", self.blob.0.len())
}
}
/// A fetched blob to acknowledge once the app has saved what it produced.
#[derive(Clone, PartialEq, Eq)]
struct Ack {
mailbox: MailboxId,
fetch: Token,
hash: Sha256Hash,
}
/// What one [`Client::receive`] produced. Save the snapshot and the events, keep the `outgoing`
/// blobs if the app has an outbox, then call [`Client::finish`].
#[derive(Debug)]
pub struct Received {
pub events: Vec<Event>,
/// Our answering `hello`s.
pub outgoing: Vec<Outgoing>,
/// The relay failed part-way: what was fetched before it is here, the rest waits there.
pub interrupted: Option<TransportError>,
acks: Vec<Ack>,
}
impl fmt::Debug for Ack {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("Ack")
}
}
/// The JSON inside an MLS application message. The relay never sees it. /// The JSON inside an MLS application message. The relay never sees it.
#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
#[serde(tag = "kind", rename_all = "camelCase", deny_unknown_fields)] #[serde(tag = "kind", rename_all = "camelCase", deny_unknown_fields)]
@@ -106,29 +166,40 @@ enum Payload {
}, },
} }
#[derive(Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
struct Mailbox { struct Mailbox {
id: MailboxId, id: MailboxId,
fetch: Token, fetch: Token,
} }
/// A welcome mailbox and the invite it belongs to.
#[derive(Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
struct WelcomeBox {
mailbox: Mailbox,
invite: InviteId,
}
struct Contact { struct Contact {
id: ContactId, id: ContactId,
group: MlsGroup, group: MlsGroup,
name: Option<String>, name: Option<String>,
/// Where the other side posts to us. /// Where the other side posts to us. `None` on the inviter's side until our `hello` is ready.
inbox: Option<Mailbox>, inbox: Option<Mailbox>,
/// Where we post to the other side: their mailbox and its post token. /// Where we post to the other side: their mailbox and its post token.
outbox: Option<(MailboxId, Token)>, outbox: Option<(MailboxId, Token)>,
/// The invite this contact came through, on the inviter's side.
via: Option<InviteId>,
} }
pub struct Client<T: Transport> { pub struct Client<T: Transport> {
provider: OpenMlsRustCrypto, provider: OpenMlsRustCrypto,
signer: SignatureKeyPair, signer: SignatureKeyPair,
credential: CredentialWithKey, credential: CredentialWithKey,
identity: Vec<u8>,
name: String, name: String,
transport: T, transport: T,
contacts: Vec<Contact>, contacts: Vec<Contact>,
welcome_boxes: Vec<Mailbox>, welcome_boxes: Vec<WelcomeBox>,
next_contact: u32, next_contact: u32,
} }
@@ -148,14 +219,12 @@ impl<T: Transport> Client<T> {
.rand() .rand()
.random_array() .random_array()
.map_err(|_| ClientError::Random)?; .map_err(|_| ClientError::Random)?;
let credential = CredentialWithKey { let credential = credential_with_key(&identity, &signer);
credential: BasicCredential::new(identity.to_vec()).into(),
signature_key: signer.public().into(),
};
Ok(Self { Ok(Self {
provider, provider,
signer, signer,
credential, credential,
identity: identity.to_vec(),
name: name.to_string(), name: name.to_string(),
transport, transport,
contacts: Vec::new(), contacts: Vec::new(),
@@ -184,7 +253,8 @@ impl<T: Transport> Client<T> {
Ok((Mailbox { id, fetch }, post)) Ok((Mailbox { id, fetch }, post))
} }
/// Step 1: a KeyPackage on the relay and a welcome mailbox. Share the result as a link. /// Step 1: a KeyPackage on the relay and a welcome mailbox. Save the snapshot, then share the
/// result as a link.
pub fn create_invite(&mut self) -> Result<Invite, ClientError> { pub fn create_invite(&mut self) -> Result<Invite, ClientError> {
let bundle = KeyPackage::builder() let bundle = KeyPackage::builder()
.build( .build(
@@ -214,20 +284,33 @@ impl<T: Transport> Client<T> {
secret_hash: invite.secret.hash(), secret_hash: invite.secret.hash(),
key_package: KeyPackageBytes::new(kp).map_err(|_| ClientError::Mls)?, key_package: KeyPackageBytes::new(kp).map_err(|_| ClientError::Mls)?,
})?; })?;
self.welcome_boxes.push(Mailbox { self.welcome_boxes.push(WelcomeBox {
id: welcome_id, mailbox: Mailbox {
fetch, id: welcome_id,
fetch,
},
invite: invite.id,
}); });
Ok(invite) Ok(invite)
} }
/// Step 2, on the other device: claim the KeyPackage, make the group, send Welcome and hello. /// Stops fetching an invite's welcome mailbox: the invite was cancelled, or is older than the
pub fn accept_invite(&mut self, invite: &Invite) -> Result<ContactId, ClientError> { /// relay keeps unclaimed invites (7 days; the app has the clock, the library has none).
/// Otherwise an unclaimed invite's mailbox is fetched for ever. Save the snapshot after it.
pub fn forget_invite(&mut self, invite: &InviteId) {
self.welcome_boxes.retain(|w| w.invite != *invite);
}
/// Step 2, on the other device, staged: claims the KeyPackage (which uses the link up) and
/// creates our mailbox, then makes the group. The Welcome and our `hello` come back for the
/// app to deliver after saving.
pub fn accept(&mut self, invite: &Invite) -> Result<(ContactId, Vec<Outgoing>), ClientError> {
let kp_bytes = self.transport.claim_invite(&invite.id, &invite.secret)?; let kp_bytes = self.transport.claim_invite(&invite.id, &invite.secret)?;
let key_package = KeyPackageIn::tls_deserialize_exact(&kp_bytes) let key_package = KeyPackageIn::tls_deserialize_exact(&kp_bytes)
.map_err(|_| ClientError::Mls)? .map_err(|_| ClientError::Mls)?
.validate(self.provider.crypto(), ProtocolVersion::Mls10) .validate(self.provider.crypto(), ProtocolVersion::Mls10)
.map_err(|_| ClientError::Mls)?; .map_err(|_| ClientError::Mls)?;
let (inbox, inbox_post) = self.new_mailbox()?;
let config = MlsGroupCreateConfig::builder() let config = MlsGroupCreateConfig::builder()
.ciphersuite(CIPHERSUITE) .ciphersuite(CIPHERSUITE)
.use_ratchet_tree_extension(true) .use_ratchet_tree_extension(true)
@@ -246,7 +329,6 @@ impl<T: Transport> Client<T> {
.merge_pending_commit(&self.provider) .merge_pending_commit(&self.provider)
.map_err(|_| ClientError::Mls)?; .map_err(|_| ClientError::Mls)?;
let (inbox, inbox_post) = self.new_mailbox()?;
let hello = Payload::Hello { let hello = Payload::Hello {
mailbox: inbox.id, mailbox: inbox.id,
post_token: inbox_post, post_token: inbox_post,
@@ -257,10 +339,28 @@ impl<T: Transport> Client<T> {
.tls_serialize_detached() .tls_serialize_detached()
.map_err(|_| ClientError::Mls)?; .map_err(|_| ClientError::Mls)?;
let hello = Self::seal(&self.provider, &self.signer, &mut group, &hello)?; let hello = Self::seal(&self.provider, &self.signer, &mut group, &hello)?;
self.transport.post(&welcome_id, &welcome_post, &welcome)?; let out = vec![
self.transport.post(&welcome_id, &welcome_post, &hello)?; Outgoing {
to: welcome_id,
post: welcome_post,
blob: Bytes(welcome),
},
Outgoing {
to: welcome_id,
post: welcome_post,
blob: Bytes(hello),
},
];
let id = self.add_contact(group, Some(inbox), None, None);
Ok((id, out))
}
let id = self.add_contact(group, Some(inbox), None); /// [`Client::accept`] and delivering at once, for use without persistence.
pub fn accept_invite(&mut self, invite: &Invite) -> Result<ContactId, ClientError> {
let (id, out) = self.accept(invite)?;
for o in &out {
self.deliver(o)?;
}
Ok(id) Ok(id)
} }
@@ -269,6 +369,7 @@ impl<T: Transport> Client<T> {
group: MlsGroup, group: MlsGroup,
inbox: Option<Mailbox>, inbox: Option<Mailbox>,
outbox: Option<(MailboxId, Token)>, outbox: Option<(MailboxId, Token)>,
via: Option<InviteId>,
) -> ContactId { ) -> ContactId {
let id = ContactId(self.next_contact); let id = ContactId(self.next_contact);
self.next_contact += 1; self.next_contact += 1;
@@ -278,6 +379,7 @@ impl<T: Transport> Client<T> {
name: None, name: None,
inbox, inbox,
outbox, outbox,
via,
}); });
id id
} }
@@ -300,8 +402,9 @@ impl<T: Transport> Client<T> {
Ok(blob) Ok(blob)
} }
/// Sends text to a contact whose `hello` has arrived. /// Encrypts text for a contact whose `hello` has arrived. No network: save the snapshot, then
pub fn send(&mut self, contact: ContactId, text: &str) -> Result<(), ClientError> { /// [`Client::deliver`] the result.
pub fn compose(&mut self, contact: ContactId, text: &str) -> Result<Outgoing, ClientError> {
if text.len() > MAX_TEXT_BYTES { if text.len() > MAX_TEXT_BYTES {
return Err(ClientError::TooLong); return Err(ClientError::TooLong);
} }
@@ -319,10 +422,25 @@ impl<T: Transport> Client<T> {
body: text.to_string(), body: text.to_string(),
}, },
)?; )?;
self.transport.post(&to, &post, &blob)?; Ok(Outgoing {
to,
post,
blob: Bytes(blob),
})
}
/// Posts one blob to the relay.
pub fn deliver(&self, out: &Outgoing) -> Result<(), ClientError> {
self.transport.post(&out.to, &out.post, &out.blob.0)?;
Ok(()) Ok(())
} }
/// [`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)?;
self.deliver(&out)
}
/// The contact's name, once its `hello` has arrived. /// The contact's name, once its `hello` has arrived.
pub fn contact_name(&self, contact: ContactId) -> Option<&str> { pub fn contact_name(&self, contact: ContactId) -> Option<&str> {
self.contacts self.contacts
@@ -331,43 +449,146 @@ impl<T: Transport> Client<T> {
.and_then(|c| c.name.as_deref()) .and_then(|c| c.name.as_deref())
} }
/// Fetches every own mailbox, processes each blob in order, and acknowledges it, whether it /// Fetches every own mailbox and processes each blob in order. Posts nothing and acknowledges
/// was understood or refused. A blob that is not valid MLS for one of our groups is dropped /// nothing: save the snapshot and the events, then call [`Client::finish`]. A blob that is
/// without a trace: nothing from it is shown. /// not valid MLS for one of our groups is dropped without a trace: nothing from it is shown,
pub fn poll(&mut self) -> Result<Vec<Event>, ClientError> { /// and it is acknowledged with the rest.
let mut events = Vec::new(); ///
let mut sources: Vec<(MailboxId, Token)> = /// If the relay fails part-way, what was processed so far is returned (with `interrupted`
self.welcome_boxes.iter().map(|m| (m.id, m.fetch)).collect(); /// set), because the client's state already includes it.
pub fn receive(&mut self) -> Result<Received, ClientError> {
let mut got = Received {
events: Vec::new(),
outgoing: Vec::new(),
interrupted: None,
acks: Vec::new(),
};
let mut sources: Vec<(Mailbox, Option<InviteId>)> = self
.welcome_boxes
.iter()
.map(|w| (w.mailbox, Some(w.invite)))
.collect();
sources.extend( sources.extend(
self.contacts self.contacts
.iter() .iter()
.filter_map(|c| c.inbox.as_ref().map(|m| (m.id, m.fetch))), .filter_map(|c| c.inbox.map(|m| (m, None))),
); );
for (id, fetch) in sources { for (mailbox, via) in sources {
for blob in self.transport.fetch(&id, &fetch)? { let blobs = match self.transport.fetch(&mailbox.id, &mailbox.fetch) {
// A failure to understand one blob must not stop the rest, nor be shown. Ok(blobs) => blobs,
if let Ok(Some(event)) = self.process(&blob) { Err(e) => {
events.push(event); got.interrupted = Some(e);
break;
} }
self.transport.acknowledge(&id, &fetch, &blob_hash(&blob))?; };
for blob in blobs {
// A failure to understand one blob must not stop the rest, nor be shown.
if let Ok(Some(event)) = self.process(&blob, via) {
got.events.push(event);
}
got.acks.push(Ack {
mailbox: mailbox.id,
fetch: mailbox.fetch,
hash: blob_hash(&blob),
});
} }
} }
Ok(events) // The inviter's side: each contact whose `hello` arrived gets ours, with a new mailbox. A
// relay that fails here leaves the contact owing its answer until the next receive.
for index in 0..self.contacts.len() {
let c = &self.contacts[index];
let Some((to, post)) = c.outbox else { continue };
if c.inbox.is_some() || got.interrupted.is_some() {
continue;
}
match self.new_mailbox() {
Ok((inbox, inbox_post)) => {
let hello = Payload::Hello {
mailbox: inbox.id,
post_token: inbox_post,
name: self.name.clone(),
};
let c = &mut self.contacts[index];
// Failing to seal leaves the answer owed, like a relay failure: the events
// already processed must still reach the app.
let Ok(blob) = Self::seal(&self.provider, &self.signer, &mut c.group, &hello)
else {
continue;
};
c.inbox = Some(inbox);
got.outgoing.push(Outgoing {
to,
post,
blob: Bytes(blob),
});
}
Err(ClientError::Transport(e)) => got.interrupted = Some(e),
Err(_) => continue,
}
}
Ok(got)
} }
fn process(&mut self, blob: &[u8]) -> Result<Option<Event>, ClientError> { /// After saving: delivers the `outgoing` blobs, then acknowledges the fetched ones. On an
/// error, call it again later; anything delivered twice is refused by MLS as a replay.
///
/// Then a welcome mailbox whose contact has said hello is dropped, so junk posted to it later
/// 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`.
pub fn finish(&mut self, received: &Received) -> Result<(), ClientError> {
for out in &received.outgoing {
self.deliver(out)?;
}
for ack in &received.acks {
self.transport
.acknowledge(&ack.mailbox, &ack.fetch, &ack.hash)?;
}
let joined: Vec<InviteId> = self
.contacts
.iter()
.filter(|c| c.name.is_some())
.filter_map(|c| c.via)
.collect();
self.welcome_boxes.retain(|w| !joined.contains(&w.invite));
Ok(())
}
/// [`Client::receive`] and [`Client::finish`] at once, for use without persistence.
pub fn poll(&mut self) -> Result<Vec<Event>, ClientError> {
let got = self.receive()?;
self.finish(&got)?;
match got.interrupted {
Some(e) if got.events.is_empty() => Err(ClientError::Transport(e)),
_ => Ok(got.events),
}
}
fn process(
&mut self,
blob: &[u8],
via: Option<InviteId>,
) -> Result<Option<Event>, ClientError> {
let message = MlsMessageIn::tls_deserialize_exact(blob).map_err(|_| ClientError::Mls)?; let message = MlsMessageIn::tls_deserialize_exact(blob).map_err(|_| ClientError::Mls)?;
match message.extract() { match message.extract() {
MlsMessageBodyIn::Welcome(welcome) => { // Only a welcome mailbox carries a Welcome.
MlsMessageBodyIn::Welcome(welcome) if via.is_some() => {
let config = MlsGroupJoinConfig::builder() let config = MlsGroupJoinConfig::builder()
.use_ratchet_tree_extension(true) .use_ratchet_tree_extension(true)
.build(); .build();
let group = StagedWelcome::new_from_welcome(&self.provider, &config, welcome, None) let staged =
.map_err(|_| ClientError::Mls)? StagedWelcome::new_from_welcome(&self.provider, &config, welcome, None)
.map_err(|_| ClientError::Mls)?;
// The same group twice (a Welcome fetched again after a crash): refused.
let group_id = staged.group_context().group_id();
if self.contacts.iter().any(|c| c.group.group_id() == group_id) {
return Err(ClientError::Mls);
}
let group = staged
.into_group(&self.provider) .into_group(&self.provider)
.map_err(|_| ClientError::Mls)?; .map_err(|_| ClientError::Mls)?;
// Not a contact to show yet: the hello right behind the Welcome makes it one. // Not a contact to show yet: the hello right behind the Welcome makes it one.
self.add_contact(group, None, None); self.add_contact(group, None, None, via);
Ok(None) Ok(None)
} }
MlsMessageBodyIn::PrivateMessage(private) => { MlsMessageBodyIn::PrivateMessage(private) => {
@@ -388,13 +609,17 @@ impl<T: Transport> Client<T> {
}; };
let payload: Payload = let payload: Payload =
serde_json::from_slice(&app.into_bytes()).map_err(|_| ClientError::Mls)?; serde_json::from_slice(&app.into_bytes()).map_err(|_| ClientError::Mls)?;
self.receive(index, payload) self.receive_payload(index, payload)
} }
_ => Err(ClientError::Mls), _ => Err(ClientError::Mls),
} }
} }
fn receive(&mut self, index: usize, payload: Payload) -> Result<Option<Event>, ClientError> { fn receive_payload(
&mut self,
index: usize,
payload: Payload,
) -> Result<Option<Event>, ClientError> {
match payload { match payload {
Payload::Hello { Payload::Hello {
mailbox, mailbox,
@@ -404,24 +629,13 @@ impl<T: Transport> Client<T> {
if name.chars().count() > MAX_NAME_CHARS || self.contacts[index].name.is_some() { if name.chars().count() > MAX_NAME_CHARS || self.contacts[index].name.is_some() {
return Err(ClientError::Mls); return Err(ClientError::Mls);
} }
self.contacts[index].outbox = Some((mailbox, post_token)); let c = &mut self.contacts[index];
self.contacts[index].name = Some(name.clone()); c.outbox = Some((mailbox, post_token));
// The inviter's side: answer with our own mailbox, inside MLS. c.name = Some(name.clone());
if self.contacts[index].inbox.is_none() {
let (inbox, inbox_post) = self.new_mailbox()?;
let hello = Payload::Hello {
mailbox: inbox.id,
post_token: inbox_post,
name: self.name.clone(),
};
let c = &mut self.contacts[index];
let blob = Self::seal(&self.provider, &self.signer, &mut c.group, &hello)?;
c.inbox = Some(inbox);
self.transport.post(&mailbox, &post_token, &blob)?;
}
Ok(Some(Event::Joined { Ok(Some(Event::Joined {
contact: self.contacts[index].id, contact: c.id,
name, name,
via: c.via,
})) }))
} }
Payload::Text { body } => { Payload::Text { body } => {
@@ -439,6 +653,13 @@ impl<T: Transport> Client<T> {
} }
} }
fn credential_with_key(identity: &[u8], signer: &SignatureKeyPair) -> CredentialWithKey {
CredentialWithKey {
credential: BasicCredential::new(identity.to_vec()).into(),
signature_key: signer.public().into(),
}
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
@@ -463,7 +684,7 @@ mod tests {
post_token: Token::from_bytes([9; 32]), post_token: Token::from_bytes([9; 32]),
name: "Mallory".into(), name: "Mallory".into(),
}; };
assert_eq!(eva.receive(0, again), Err(ClientError::Mls)); assert_eq!(eva.receive_payload(0, again), Err(ClientError::Mls));
assert_eq!(eva.contacts[0].outbox.map(|(m, _)| m), before); assert_eq!(eva.contacts[0].outbox.map(|(m, _)| m), before);
assert_eq!(eva.contacts[0].name.as_deref(), Some("Jan")); assert_eq!(eva.contacts[0].name.as_deref(), Some("Jan"));
} }
+174
View File
@@ -0,0 +1,174 @@
//! The client's whole state as bytes, for the app's encrypted store
//! (`.agents/features/client-state.md` §2). It holds every secret of the identity: MLS private
//! keys, fetch tokens and post tokens. `Debug` is not implemented for any of it.
use crate::{
credential_with_key, Client, ClientError, Contact, ContactId, Mailbox, Transport, WelcomeBox,
CIPHERSUITE, MAX_NAME_CHARS,
};
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use base64::Engine as _;
use openmls::prelude::{GroupId, MlsGroup, OpenMlsProvider as _};
use openmls_basic_credential::SignatureKeyPair;
use openmls_rust_crypto::OpenMlsRustCrypto;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::collections::HashSet;
use tabellarius_protocol::{InviteId, MailboxId, Token};
/// The snapshot format's version. Another number is refused, never guessed at.
pub const SNAPSHOT_VERSION: u32 = 1;
/// Bytes as unpadded base64url in JSON.
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) struct Bytes(pub(crate) Vec<u8>);
impl Serialize for Bytes {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
s.serialize_str(&URL_SAFE_NO_PAD.encode(&self.0))
}
}
impl<'de> Deserialize<'de> for Bytes {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let s = String::deserialize(d)?;
URL_SAFE_NO_PAD
.decode(s.as_bytes())
.map(Bytes)
.map_err(serde::de::Error::custom)
}
}
#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct ContactState {
id: ContactId,
group: Bytes,
name: Option<String>,
inbox: Option<Mailbox>,
outbox: Option<(MailboxId, Token)>,
via: Option<InviteId>,
}
#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct State {
v: u32,
name: String,
identity: Bytes,
signer_public: Bytes,
contacts: Vec<ContactState>,
welcome_boxes: Vec<WelcomeBox>,
next_contact: u32,
/// OpenMLS's storage: every key and value, sorted by key so equal states give equal bytes.
storage: Vec<(Bytes, Bytes)>,
}
impl<T: Transport> Client<T> {
/// The whole state, to keep in the app's encrypted store. Secret: never log it, never send it.
pub fn snapshot(&self) -> Result<Vec<u8>, ClientError> {
let mut storage: Vec<(Bytes, Bytes)> = self
.provider
.storage()
.values
.read()
.map_err(|_| ClientError::State)?
.iter()
.map(|(k, v)| (Bytes(k.clone()), Bytes(v.clone())))
.collect();
storage.sort();
let state = State {
v: SNAPSHOT_VERSION,
name: self.name.clone(),
identity: Bytes(self.identity.clone()),
signer_public: Bytes(self.signer.to_public_vec()),
contacts: self
.contacts
.iter()
.map(|c| ContactState {
id: c.id,
group: Bytes(c.group.group_id().as_slice().to_vec()),
name: c.name.clone(),
inbox: c.inbox,
outbox: c.outbox,
via: c.via,
})
.collect(),
welcome_boxes: self.welcome_boxes.clone(),
next_contact: self.next_contact,
storage,
};
serde_json::to_vec(&state).map_err(|_| ClientError::State)
}
/// A client from a snapshot. All or nothing: a snapshot that does not parse, has another
/// version, or does not match its own storage is refused with [`ClientError::State`].
pub fn restore(snapshot: &[u8], transport: T) -> Result<Self, ClientError> {
let state: State = serde_json::from_slice(snapshot).map_err(|_| ClientError::State)?;
if state.v != SNAPSHOT_VERSION || state.name.chars().count() > MAX_NAME_CHARS {
return Err(ClientError::State);
}
let provider = OpenMlsRustCrypto::default();
{
let mut values = provider
.storage()
.values
.write()
.map_err(|_| ClientError::State)?;
for (k, v) in state.storage {
values.insert(k.0, v.0);
}
}
let signer = SignatureKeyPair::read(
provider.storage(),
&state.signer_public.0,
CIPHERSUITE.signature_algorithm(),
)
.ok_or(ClientError::State)?;
let credential = credential_with_key(&state.identity.0, &signer);
let mut ids = HashSet::new();
let mut contacts = Vec::with_capacity(state.contacts.len());
for c in state.contacts {
// Ids are unique and below the next one, or two contacts could end up sharing one.
if c.id.0 >= state.next_contact || !ids.insert(c.id) {
return Err(ClientError::State);
}
let group = MlsGroup::load(provider.storage(), &GroupId::from_slice(&c.group.0))
.map_err(|_| ClientError::State)?
.ok_or(ClientError::State)?;
contacts.push(Contact {
id: c.id,
group,
name: c.name,
inbox: c.inbox,
outbox: c.outbox,
via: c.via,
});
}
Ok(Client {
provider,
signer,
credential,
identity: state.identity.0,
name: state.name,
transport,
contacts,
welcome_boxes: state.welcome_boxes,
next_contact: state.next_contact,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn bytes_round_trip_as_base64url() {
let b = Bytes(vec![0, 1, 254, 255]);
let json = serde_json::to_string(&b).expect("json");
assert_eq!(json, "\"AAH-_w\"");
let back: Bytes = serde_json::from_str(&json).expect("back");
assert!(back == b);
}
}
+3 -1
View File
@@ -25,6 +25,7 @@ fn pair(
let Some(Event::Joined { let Some(Event::Joined {
contact: eva_side, contact: eva_side,
name, name,
..
}) = eva_events.first().cloned() }) = eva_events.first().cloned()
else { else {
panic!("Eva did not see Jan join: {eva_events:?}"); panic!("Eva did not see Jan join: {eva_events:?}");
@@ -35,7 +36,8 @@ fn pair(
jan_events, jan_events,
vec![Event::Joined { vec![Event::Joined {
contact: jan_side, contact: jan_side,
name: "Eva Nováková".into() name: "Eva Nováková".into(),
via: None,
}] }]
); );
(eva, eva_side, jan, jan_side) (eva, eva_side, jan, jan_side)
+1
View File
@@ -160,6 +160,7 @@ fn pair_and_talk_through_a_real_relay_which_never_sees_a_name_or_a_word() {
let Some(Event::Joined { let Some(Event::Joined {
contact: eva_side, contact: eva_side,
name, name,
..
}) = events.first().cloned() }) = events.first().cloned()
else { else {
panic!("no join: {events:?}"); panic!("no join: {events:?}");
+430
View File
@@ -0,0 +1,430 @@
//! The client survives a restart, and nothing reaches the relay before the app has saved
//! (`.agents/features/client-state.md` §3). No I/O: runs on the Android emulator too.
use tabellarius_client::*;
type C = Client<MemoryTransport>;
/// 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 invite = eva.create_invite().expect("invite");
let jan_side = jan.accept_invite(&invite).expect("accept");
let events = eva.poll().expect("poll");
let Some(Event::Joined {
contact: eva_side,
via,
..
}) = events.first().cloned()
else {
panic!("no join: {events:?}");
};
assert_eq!(
via,
Some(invite.id),
"the inviter learns which invite was used"
);
assert_eq!(jan.poll().expect("poll").len(), 1);
(eva, eva_side, jan, jan_side)
}
fn restart(client: &C, relay: &MemoryTransport) -> C {
let saved = client.snapshot().expect("snapshot");
Client::restore(&saved, relay.clone()).expect("restore")
}
fn texts(events: Vec<Event>) -> Vec<String> {
events
.into_iter()
.filter_map(|e| match e {
Event::Message { text, .. } => Some(text),
Event::Joined { .. } => None,
})
.collect()
}
#[test]
fn both_sides_restart_mid_conversation_and_keep_talking() {
let relay = MemoryTransport::default();
let (mut eva, eva_side, mut jan, jan_side) = pair(&relay);
eva.send(eva_side, "před restartem").expect("send");
assert_eq!(texts(jan.poll().expect("poll")), ["před restartem"]);
let mut eva = restart(&eva, &relay);
let mut jan = restart(&jan, &relay);
assert_eq!(eva.contact_name(eva_side), Some("Jan"));
eva.send(eva_side, "po restartu").expect("send");
jan.send(jan_side, "taky po restartu").expect("send");
assert_eq!(texts(jan.poll().expect("poll")), ["po restartu"]);
assert_eq!(texts(eva.poll().expect("poll")), ["taky po restartu"]);
assert_eq!(relay.waiting_blobs(), 0);
}
#[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 invite = eva.create_invite().expect("invite");
let mut eva = restart(&eva, &relay);
let jan_side = jan.accept_invite(&invite).expect("accept");
let events = eva.poll().expect("poll");
assert!(
matches!(&events[..], [Event::Joined { name, via, .. }] if name == "Jan" && *via == Some(invite.id)),
"{events:?}"
);
jan.poll().expect("poll");
jan.send(jan_side, "ahoj").expect("send");
assert_eq!(texts(eva.poll().expect("poll")), ["ahoj"]);
}
#[test]
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 invite = eva.create_invite().expect("invite");
petr.accept_invite(&invite).expect("accept");
let events = eva.poll().expect("poll");
let Some(Event::Joined { contact, .. }) = events.first() else {
panic!("no join: {events:?}");
};
assert_ne!(*contact, eva_side);
assert_eq!(eva.contact_name(eva_side), Some("Jan"));
assert_eq!(eva.contact_name(*contact), Some("Petr"));
}
#[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 invite = eva.create_invite().expect("invite");
let (jan_side, out) = jan.accept(&invite).expect("accept");
assert_eq!(out.len(), 2, "the Welcome and the hello");
assert_eq!(relay.waiting_blobs(), 0, "accept posts nothing");
out.iter().for_each(|o| jan.deliver(o).expect("deliver"));
assert_eq!(relay.waiting_blobs(), 2);
let got = eva.receive().expect("receive");
assert_eq!(got.events.len(), 1);
assert_eq!(got.outgoing.len(), 1, "Eva's answering hello");
assert_eq!(
relay.waiting_blobs(),
2,
"receive acknowledges nothing and posts nothing"
);
eva.finish(&got).expect("finish");
assert_eq!(
relay.waiting_blobs(),
1,
"Welcome and hello acknowledged; Eva's hello waits"
);
jan.poll().expect("poll");
let text = jan.compose(jan_side, "ještě neodesláno").expect("compose");
assert_eq!(relay.waiting_blobs(), 0, "compose posts nothing");
jan.deliver(&text).expect("deliver");
assert_eq!(relay.waiting_blobs(), 1);
}
/// The inviter answers a `hello` inside `receive`. Crash after saving, before `finish`: the saved
/// answer is delivered from the outbox, the same blobs are fetched again and dropped, and the pair
/// works with nothing shown twice.
#[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 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.
assert_eq!(jan.send(jan_side, "x"), Err(ClientError::UnknownContact));
let got = eva.receive().expect("receive");
assert_eq!(got.events.len(), 1);
let saved = eva.snapshot().expect("snapshot");
let outbox = got.outgoing.clone();
drop(eva); // the crash: finish never ran
let mut eva = Client::restore(&saved, relay.clone()).expect("restore");
outbox.iter().for_each(|o| eva.deliver(o).expect("deliver"));
let again = eva.poll().expect("poll again");
assert!(
again.is_empty(),
"the Welcome and hello are not shown twice: {again:?}"
);
assert_eq!(relay.waiting_blobs(), 1, "only Eva's hello to Jan waits");
assert_eq!(jan.poll().expect("poll").len(), 1, "Jan sees Eva join");
jan.send(jan_side, "funguje to").expect("send");
let Event::Joined { contact, .. } = got.events[0].clone() else {
unreachable!()
};
assert_eq!(
eva.poll().expect("poll"),
[Event::Message {
contact,
text: "funguje to".into()
}]
);
}
#[test]
fn a_blob_delivered_twice_is_shown_once() {
let relay = MemoryTransport::default();
let (mut eva, eva_side, mut jan, _) = pair(&relay);
let out = eva.compose(eva_side, "jednou").expect("compose");
eva.deliver(&out).expect("deliver");
eva.deliver(&out).expect("deliver again, after a crash");
assert_eq!(texts(jan.poll().expect("poll")), ["jednou"]);
assert_eq!(relay.waiting_blobs(), 0, "the copy is acknowledged too");
}
#[test]
fn an_outgoing_survives_the_outbox() {
// An app keeps undelivered blobs in its outbox as JSON; Debug shows no token and no bytes.
let relay = MemoryTransport::default();
let (mut eva, eva_side, mut jan, _) = pair(&relay);
let out = eva.compose(eva_side, "z outboxu").expect("compose");
let kept = serde_json::to_vec(&out).expect("json");
let back: Outgoing = serde_json::from_slice(&kept).expect("back");
assert_eq!(back, out);
assert!(format!("{back:?}").starts_with("Outgoing("));
eva.deliver(&back).expect("deliver");
assert_eq!(texts(jan.poll().expect("poll")), ["z outboxu"]);
}
#[test]
fn a_bad_snapshot_is_refused() {
let relay = MemoryTransport::default();
let (eva, _, _jan, _) = pair(&relay);
let good = eva.snapshot().expect("snapshot");
let mut json: serde_json::Value = serde_json::from_slice(&good).expect("json");
let refused =
|bytes: &[u8]| matches!(C::restore(bytes, relay.clone()), Err(ClientError::State));
assert!(refused(&good[..good.len() / 2]), "truncated");
assert!(refused(b"{}"), "empty");
let mut other = json.clone();
other["v"] = 2.into();
assert!(
refused(&serde_json::to_vec(&other).expect("json")),
"another version"
);
let mut no_storage = json.clone();
no_storage["storage"] = serde_json::json!([]);
assert!(
refused(&serde_json::to_vec(&no_storage).expect("json")),
"storage missing"
);
let mut wrong_group = json.clone();
wrong_group["contacts"][0]["group"] = "AAAA".into();
assert!(
refused(&serde_json::to_vec(&wrong_group).expect("json")),
"group missing"
);
let mut id_too_high = json.clone();
id_too_high["nextContact"] = 0.into();
assert!(
refused(&serde_json::to_vec(&id_too_high).expect("json")),
"ids would repeat"
);
json["unexpected"] = true.into();
assert!(
refused(&serde_json::to_vec(&json).expect("json")),
"unknown field"
);
}
#[test]
fn equal_states_give_equal_snapshots() {
let relay = MemoryTransport::default();
let (eva, _, _jan, _) = pair(&relay);
let once = eva.snapshot().expect("snapshot");
let restored = Client::restore(&once, relay.clone()).expect("restore");
assert_eq!(restored.snapshot().expect("snapshot"), once);
}
/// A relay that can be told to fail: posts, or every fetch after the first `n`.
#[derive(Clone, Default)]
struct Flaky {
inner: MemoryTransport,
fail_posts: std::sync::Arc<std::sync::atomic::AtomicBool>,
fetches_left: std::sync::Arc<std::sync::atomic::AtomicI32>,
}
impl Flaky {
fn new(inner: &MemoryTransport) -> Flaky {
let f = Flaky {
inner: inner.clone(),
..Flaky::default()
};
f.fetches_left
.store(i32::MAX, std::sync::atomic::Ordering::SeqCst);
f
}
}
impl Transport for Flaky {
fn create_mailbox(
&self,
r: &tabellarius_protocol::CreateMailbox,
) -> Result<(), TransportError> {
self.inner.create_mailbox(r)
}
fn post(
&self,
id: &tabellarius_protocol::MailboxId,
post: &tabellarius_protocol::Token,
blob: &[u8],
) -> Result<(), TransportError> {
if self.fail_posts.load(std::sync::atomic::Ordering::SeqCst) {
return Err(TransportError::Failed);
}
self.inner.post(id, post, blob)
}
fn fetch(
&self,
id: &tabellarius_protocol::MailboxId,
fetch: &tabellarius_protocol::Token,
) -> Result<Vec<Vec<u8>>, TransportError> {
if self
.fetches_left
.fetch_sub(1, std::sync::atomic::Ordering::SeqCst)
<= 0
{
return Err(TransportError::Failed);
}
self.inner.fetch(id, fetch)
}
fn acknowledge(
&self,
id: &tabellarius_protocol::MailboxId,
fetch: &tabellarius_protocol::Token,
hash: &tabellarius_protocol::Sha256Hash,
) -> Result<(), TransportError> {
self.inner.acknowledge(id, fetch, hash)
}
fn create_invite(&self, r: &tabellarius_protocol::CreateInvite) -> Result<(), TransportError> {
self.inner.create_invite(r)
}
fn claim_invite(
&self,
id: &tabellarius_protocol::InviteId,
secret: &tabellarius_protocol::Token,
) -> Result<Vec<u8>, TransportError> {
self.inner.claim_invite(id, secret)
}
}
/// Without an outbox (`poll`), the answering hello must be delivered before anything is
/// acknowledged: if delivering fails, the blobs stay on the relay and the next try answers again.
#[test]
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 invite = eva.create_invite().expect("invite");
let jan_side = jan.accept_invite(&invite).expect("accept");
let got = eva.receive().expect("receive");
flaky
.fail_posts
.store(true, std::sync::atomic::Ordering::SeqCst);
assert!(eva.finish(&got).is_err());
assert_eq!(relay.waiting_blobs(), 2, "nothing acknowledged");
flaky
.fail_posts
.store(false, std::sync::atomic::Ordering::SeqCst);
eva.finish(&got).expect("finish, again");
assert_eq!(
relay.waiting_blobs(),
1,
"now acknowledged; Eva's hello waits"
);
assert_eq!(jan.poll().expect("poll").len(), 1);
jan.send(jan_side, "ok").expect("send");
assert_eq!(texts(eva.poll().expect("poll")), ["ok"]);
}
/// The relay fails after the first mailbox: what was processed comes back, the rest waits.
#[test]
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 friends = Vec::new();
for name in ["Jan", "Petr"] {
let mut friend = 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));
}
assert_eq!(eva.poll().expect("poll").len(), 2);
for (friend, side) in &mut friends {
friend.poll().expect("poll");
friend.send(*side, "zpráva").expect("send");
}
flaky
.fetches_left
.store(1, std::sync::atomic::Ordering::SeqCst);
let got = eva.receive().expect("partial, not an error");
assert_eq!(texts(got.events.clone()), ["zpráva"]);
assert_eq!(got.interrupted, Some(TransportError::Failed));
eva.finish(&got).expect("finish");
flaky
.fetches_left
.store(i32::MAX, std::sync::atomic::Ordering::SeqCst);
assert_eq!(
texts(eva.poll().expect("poll")),
["zpráva"],
"the other one, now"
);
assert_eq!(relay.waiting_blobs(), 0);
}
/// Once its contact has said hello, a welcome mailbox is no longer fetched: whoever still holds the
/// link can post to it, but it is never read again (it expires on the relay).
#[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 invite = eva.create_invite().expect("invite");
jan.accept_invite(&invite).expect("accept");
eva.poll().expect("poll");
jan.poll().expect("poll");
let (welcome, post) = welcome_mailbox(&invite.secret);
relay.post(&welcome, &post, b"later junk").expect("post");
let mut eva = restart(&eva, &relay);
assert!(eva.poll().expect("poll").is_empty());
assert_eq!(relay.waiting_blobs(), 1, "the junk was never fetched");
}
/// A forgotten invite's mailbox is no longer fetched, even if someone uses the link afterwards.
#[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 invite = eva.create_invite().expect("invite");
eva.forget_invite(&invite.id);
let mut eva = restart(&eva, &relay);
jan.accept_invite(&invite).expect("the relay still has it");
assert!(eva.poll().expect("poll").is_empty());
assert_eq!(
relay.waiting_blobs(),
2,
"the Welcome and hello wait, never fetched"
);
}