3a0944ebff
ci / check (pull_request) Has been cancelled
The relay stores files (id, upload and fetch token hashes, chunk count, uploaded hour) and chunks (file id, index, ciphertext): every chunk is 256 000 bytes, so it learns the size rounded up to 250 KiB and nothing finer, and it keeps no fetch count. Only the uploader's token puts or deletes, only the fetch token gets, a chunk never changes; per-file and relay-wide quotas answer 507; files go after 30 days, incomplete ones after 24 hours. The client pads a file to whole chunks and seals each with ChaCha20-Poly1305 in the aead crate's STREAM, under a key made for that file; the key, name, type, size and thumbnail travel only in the new `file` payload, which shares `seq` with text. Also: every route now answers a bare 413 (axum's own carried a text). PROTOCOL.md §1, §4, §5, §7, §8.
2337 lines
85 KiB
Rust
2337 lines
85 KiB
Rust
//! The Tabellarius client: MLS 1:1 conversations (OpenMLS), a mailbox per contact, invites.
|
||
//! No cryptography is written here by hand: MLS is OpenMLS, HKDF and SHA-256 are RustCrypto.
|
||
//!
|
||
//! Pairing (`.agents/features/client.md` §2):
|
||
//! 1. The inviter makes a KeyPackage and a link (invite id + secret). It also makes a *welcome
|
||
//! mailbox*, whose id and post token are derived from the secret.
|
||
//! 2. The invitee claims the KeyPackage, creates the MLS group, and posts the Welcome and an MLS
|
||
//! `hello` (its own mailbox and post token, and its name) to the welcome 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.
|
||
//!
|
||
//! **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;
|
||
|
||
mod files;
|
||
pub use files::{
|
||
chunks_for, FileRef, FileUpload, FILE_CHUNK_PLAIN, MAX_FILE_BYTES, MAX_FILE_NAME_CHARS,
|
||
MAX_MIME_BYTES, MAX_THUMB_BYTES,
|
||
};
|
||
pub use tabellarius_protocol::{FileId, FILE_CHUNK_BYTES, MAX_FILE_CHUNKS};
|
||
|
||
mod snapshot;
|
||
pub use snapshot::SNAPSHOT_VERSION;
|
||
|
||
use hkdf::Hkdf;
|
||
use openmls::prelude::tls_codec::{Deserialize as _, Serialize as _};
|
||
use openmls::prelude::*;
|
||
use openmls_basic_credential::SignatureKeyPair;
|
||
use openmls_rust_crypto::OpenMlsRustCrypto;
|
||
use serde::{Deserialize, Serialize};
|
||
use sha2::Sha256;
|
||
use snapshot::Bytes;
|
||
use std::fmt;
|
||
use tabellarius_protocol::{
|
||
blob_hash, Author, ChunkCount, CreateFile, CreateInvite, CreateMailbox, FileKey, InviteId,
|
||
KeyPackageBytes, MailboxId, PushEndpoint, Sha256Hash, Token, MAX_BLOB_BYTES,
|
||
};
|
||
pub use transport::{MemoryTransport, Transport, TransportError};
|
||
|
||
/// RFC 9420's mandatory ciphersuite.
|
||
pub const CIPHERSUITE: Ciphersuite = Ciphersuite::MLS_128_DHKEMX25519_AES128GCM_SHA256_Ed25519;
|
||
/// The longest display name sent in a `hello`.
|
||
pub const MAX_NAME_CHARS: usize = 64;
|
||
/// The longest text message, in bytes; well under a blob's limit once encrypted.
|
||
pub const MAX_TEXT_BYTES: usize = 64 * 1024;
|
||
/// The longest reaction, in bytes of UTF-8: the longest emoji ZWJ sequences are 28.
|
||
pub const MAX_EMOJI_BYTES: usize = 32;
|
||
/// The fewest and the most options a poll has.
|
||
pub const MIN_POLL_OPTIONS: usize = 2;
|
||
pub const MAX_POLL_OPTIONS: usize = 10;
|
||
/// The longest poll option, in characters.
|
||
pub const MAX_OPTION_CHARS: usize = 100;
|
||
/// The longest poll question, in characters.
|
||
pub const MAX_QUESTION_CHARS: usize = 300;
|
||
/// The payload kinds this client knows; any other kind that carries a `seq` is `Unsupported`.
|
||
const KNOWN_KINDS: [&str; 9] = [
|
||
"hello",
|
||
"text",
|
||
"receipt",
|
||
"inbox",
|
||
"reaction",
|
||
"poll",
|
||
"vote",
|
||
"pollClose",
|
||
"file",
|
||
];
|
||
|
||
const WELCOME_ID_LABEL: &[u8] = b"tabellarius v0 welcome mailbox";
|
||
const WELCOME_POST_LABEL: &[u8] = b"tabellarius v0 welcome mailbox post";
|
||
|
||
/// Why something failed. Never carries a message's text, a name, or a token.
|
||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||
pub enum ClientError {
|
||
Transport(TransportError),
|
||
/// MLS refused: a bad KeyPackage, a Welcome that is not for us, a message that does not verify.
|
||
Mls,
|
||
/// No randomness from the system.
|
||
Random,
|
||
/// A name or text over its limit.
|
||
TooLong,
|
||
/// No such contact, or a contact whose mailbox is not known yet.
|
||
UnknownContact,
|
||
/// A reply or reaction to a message that does not exist in this conversation, or an emoji
|
||
/// that is empty or has a control character.
|
||
BadReference,
|
||
/// A poll that is not well formed (an option blank or repeated, too few or too many), a vote
|
||
/// that is not (a choice out of range, repeated, or several in a single-choice poll), or a
|
||
/// close of a poll that is not ours or not in this conversation.
|
||
BadPoll,
|
||
/// A vote or a close for a poll that is already closed.
|
||
PollClosed,
|
||
/// A file that cannot be sent: empty or over [`MAX_FILE_BYTES`], a name or type outside the
|
||
/// wire's rules, a thumbnail that is not a small JPEG, or a chunk index or length that does not
|
||
/// fit the file.
|
||
BadFile,
|
||
/// A received file's chunk that does not open: tampered with, swapped, cut short, of the
|
||
/// wrong size, or with padding that is not zeros.
|
||
FileDamaged,
|
||
/// A snapshot that does not parse, has another version, or does not match OpenMLS's storage.
|
||
State,
|
||
}
|
||
|
||
impl From<TransportError> for ClientError {
|
||
fn from(e: TransportError) -> Self {
|
||
ClientError::Transport(e)
|
||
}
|
||
}
|
||
|
||
/// What the link to share carries, besides the relay's address.
|
||
#[derive(Clone, PartialEq, Eq, Debug)]
|
||
pub struct Invite {
|
||
pub id: InviteId,
|
||
pub secret: Token,
|
||
}
|
||
|
||
/// The welcome mailbox's id and post token, derived from an invite secret with HKDF-SHA256.
|
||
pub fn welcome_mailbox(secret: &Token) -> (MailboxId, Token) {
|
||
let hk = Hkdf::<Sha256>::new(None, secret.as_bytes());
|
||
let mut id = [0u8; 16];
|
||
let mut post = [0u8; 32];
|
||
// Lengths within HKDF's limit (255 × 32 bytes): expand cannot fail here.
|
||
let _ = hk.expand(WELCOME_ID_LABEL, &mut id);
|
||
let _ = hk.expand(WELCOME_POST_LABEL, &mut post);
|
||
(MailboxId::from_bytes(id), Token::from_bytes(post))
|
||
}
|
||
|
||
/// A local handle for a contact. Means nothing outside this client.
|
||
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Serialize, Deserialize)]
|
||
pub struct ContactId(pub u32);
|
||
|
||
/// What [`Client::receive`] found.
|
||
#[derive(Clone, PartialEq, Eq, Debug)]
|
||
pub enum Event {
|
||
/// 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 {
|
||
contact: ContactId,
|
||
name: String,
|
||
via: Option<InviteId>,
|
||
},
|
||
/// A text. `seq` is the author's own count; with the contact's [`Client::contact_author`] it
|
||
/// names the message, for replies and reactions. `reply_to` is a message this one answers,
|
||
/// checked to exist in this conversation (a reference that does not is left out).
|
||
Message {
|
||
contact: ContactId,
|
||
text: String,
|
||
seq: u64,
|
||
reply_to: Option<MessageRef>,
|
||
},
|
||
/// The contact's reaction to a message in this conversation: set (replacing their earlier one)
|
||
/// or, with `emoji` `None`, removed.
|
||
Reaction {
|
||
contact: ContactId,
|
||
to: MessageRef,
|
||
emoji: Option<String>,
|
||
},
|
||
/// A poll (a message: `seq` names it with the contact's author, like a text's).
|
||
Poll {
|
||
contact: ContactId,
|
||
seq: u64,
|
||
question: String,
|
||
options: Vec<String>,
|
||
multiple: bool,
|
||
},
|
||
/// The contact's vote in a poll of this conversation, replacing their earlier one; no choices
|
||
/// takes it back. Indexes into the poll's options, ascending.
|
||
Vote {
|
||
contact: ContactId,
|
||
poll: MessageRef,
|
||
choices: Vec<u8>,
|
||
},
|
||
/// The contact closed their poll. `ballots` are the final votes, ours included: show these,
|
||
/// not what was counted before.
|
||
PollClosed {
|
||
contact: ContactId,
|
||
poll: MessageRef,
|
||
ballots: Vec<Ballot>,
|
||
},
|
||
/// A file (a message: `seq` names it, like a text's). `file` fetches and opens it
|
||
/// ([`Client::get_chunk`], [`Client::download`]); `thumb` is a small JPEG, checked to start
|
||
/// like one, or `None`.
|
||
File {
|
||
contact: ContactId,
|
||
seq: u64,
|
||
file: FileRef,
|
||
name: String,
|
||
mime: String,
|
||
thumb: Option<Vec<u8>>,
|
||
},
|
||
/// A message of a kind this client does not know (a newer app's). Show that something arrived
|
||
/// that needs an update; its `seq` counts like a text's.
|
||
Unsupported { contact: ContactId, seq: u64 },
|
||
/// 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 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(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<u8>) -> Outgoing {
|
||
Outgoing(Op::Post {
|
||
to,
|
||
post,
|
||
blob: Bytes(blob),
|
||
})
|
||
}
|
||
}
|
||
|
||
impl fmt::Debug for Outgoing {
|
||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||
match &self.0 {
|
||
Op::Post { blob, .. } => write!(f, "Outgoing({} bytes)", blob.0.len()),
|
||
Op::Rotate { .. } => f.write_str("Outgoing(rotate)"),
|
||
}
|
||
}
|
||
}
|
||
|
||
/// 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, and receipts.
|
||
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")
|
||
}
|
||
}
|
||
|
||
/// A message in a conversation, named by its author and the author's own `seq` (`PROTOCOL.md` §4).
|
||
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Serialize, Deserialize)]
|
||
#[serde(deny_unknown_fields)]
|
||
pub struct MessageRef {
|
||
pub author: Author,
|
||
pub seq: u64,
|
||
}
|
||
|
||
/// One member's choices in a poll, as a close reports them.
|
||
#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
|
||
#[serde(deny_unknown_fields)]
|
||
pub struct Ballot {
|
||
pub author: Author,
|
||
pub choices: Vec<u8>,
|
||
}
|
||
|
||
/// A poll in a conversation, as this client accepted it (`.agents/features/polls.md` §2.3).
|
||
#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
|
||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||
pub(crate) struct PollState {
|
||
pub(crate) poll: MessageRef,
|
||
pub(crate) options: u8,
|
||
pub(crate) multiple: bool,
|
||
pub(crate) closed: bool,
|
||
/// Each member's current, non-empty choices.
|
||
pub(crate) ballots: Vec<Ballot>,
|
||
}
|
||
|
||
impl PollState {
|
||
/// Indexes into the options, ascending, each once; at most one unless `multiple`.
|
||
fn choices_ok(&self, choices: &[u8]) -> bool {
|
||
choices.iter().all(|&i| i < self.options)
|
||
&& choices.windows(2).all(|w| w[0] < w[1])
|
||
&& (self.multiple || choices.len() <= 1)
|
||
}
|
||
|
||
fn set_ballot(&mut self, author: Author, choices: &[u8]) {
|
||
self.ballots.retain(|b| b.author != author);
|
||
if !choices.is_empty() {
|
||
self.ballots.push(Ballot {
|
||
author,
|
||
choices: choices.to_vec(),
|
||
});
|
||
}
|
||
}
|
||
}
|
||
|
||
/// The JSON inside an MLS application message. The relay never sees it.
|
||
#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
|
||
#[serde(tag = "kind", rename_all = "camelCase", deny_unknown_fields)]
|
||
enum Payload {
|
||
#[serde(rename_all = "camelCase")]
|
||
Hello {
|
||
mailbox: MailboxId,
|
||
post_token: Token,
|
||
name: String,
|
||
},
|
||
/// `seq` counts this sender's messages to this contact, from 1. `replyTo`, when there, names
|
||
/// the message this one answers; absent, the JSON is a text's from before replies.
|
||
#[serde(rename_all = "camelCase")]
|
||
Text {
|
||
body: String,
|
||
seq: u64,
|
||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||
reply_to: Option<MessageRef>,
|
||
},
|
||
/// The sender's reaction to a message: `emoji` sets it, absent removes it. No `seq`: not a
|
||
/// message, so it is not replied to, reacted to or covered by a receipt.
|
||
Reaction {
|
||
to: MessageRef,
|
||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||
emoji: Option<String>,
|
||
},
|
||
/// A question with options; a message, sharing the sender's `seq` with texts.
|
||
#[serde(rename_all = "camelCase")]
|
||
Poll {
|
||
seq: u64,
|
||
question: String,
|
||
options: Vec<String>,
|
||
multiple: bool,
|
||
},
|
||
/// The sender's choices in `poll`, replacing their earlier ones; `[]` takes the vote back.
|
||
Vote { poll: MessageRef, choices: Vec<u8> },
|
||
/// The poll's author closed it; `ballots` are the final votes.
|
||
#[serde(rename_all = "camelCase")]
|
||
PollClose {
|
||
poll: MessageRef,
|
||
ballots: Vec<Ballot>,
|
||
},
|
||
/// A file on the relay: a message, sharing the sender's `seq` (`.agents/features/files.md`).
|
||
#[serde(rename_all = "camelCase")]
|
||
File {
|
||
seq: u64,
|
||
file: tabellarius_protocol::FileId,
|
||
fetch_token: Token,
|
||
key: FileKey,
|
||
name: String,
|
||
mime: String,
|
||
size: u64,
|
||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||
thumb: Option<Bytes>,
|
||
},
|
||
/// 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)]
|
||
struct Mailbox {
|
||
id: MailboxId,
|
||
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 {
|
||
id: ContactId,
|
||
group: MlsGroup,
|
||
name: Option<String>,
|
||
/// Where the other side posts to us. `None` on the inviter's side until our `hello` is ready.
|
||
inbox: Option<Mailbox>,
|
||
/// Where we post to the other side: their mailbox and its post token.
|
||
outbox: Option<(MailboxId, Token)>,
|
||
/// The invite this contact came through, on the inviter's side.
|
||
via: Option<InviteId>,
|
||
/// 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,
|
||
/// The polls in this conversation, ours and theirs.
|
||
polls: Vec<PollState>,
|
||
}
|
||
|
||
pub struct Client<T: Transport> {
|
||
provider: OpenMlsRustCrypto,
|
||
signer: SignatureKeyPair,
|
||
credential: CredentialWithKey,
|
||
identity: Vec<u8>,
|
||
name: String,
|
||
transport: T,
|
||
contacts: Vec<Contact>,
|
||
welcome_boxes: Vec<WelcomeBox>,
|
||
next_contact: u32,
|
||
/// Send receipts and report the other side's (reciprocal). On by default.
|
||
receipts: bool,
|
||
}
|
||
|
||
impl<T: Transport> Client<T> {
|
||
/// A new identity: an Ed25519 key and a credential holding 16 random bytes, never a name.
|
||
pub fn new(name: &str, transport: T) -> Result<Self, ClientError> {
|
||
if name.chars().count() > MAX_NAME_CHARS {
|
||
return Err(ClientError::TooLong);
|
||
}
|
||
let provider = OpenMlsRustCrypto::default();
|
||
let signer = SignatureKeyPair::new(CIPHERSUITE.signature_algorithm())
|
||
.map_err(|_| ClientError::Mls)?;
|
||
signer
|
||
.store(provider.storage())
|
||
.map_err(|_| ClientError::Mls)?;
|
||
let identity: [u8; 16] = provider
|
||
.rand()
|
||
.random_array()
|
||
.map_err(|_| ClientError::Random)?;
|
||
let credential = credential_with_key(&identity, &signer);
|
||
Ok(Self {
|
||
provider,
|
||
signer,
|
||
credential,
|
||
identity: identity.to_vec(),
|
||
name: name.to_string(),
|
||
transport,
|
||
contacts: Vec::new(),
|
||
welcome_boxes: Vec::new(),
|
||
next_contact: 0,
|
||
receipts: true,
|
||
})
|
||
}
|
||
|
||
fn random<const N: usize>(&self) -> Result<[u8; N], ClientError> {
|
||
self.provider
|
||
.rand()
|
||
.random_array()
|
||
.map_err(|_| ClientError::Random)
|
||
}
|
||
|
||
/// A fresh mailbox on the relay: we keep the fetch token, the post token goes to the contact.
|
||
fn new_mailbox(&self) -> Result<(Mailbox, Token), ClientError> {
|
||
let id = MailboxId::from_bytes(self.random()?);
|
||
let post = Token::from_bytes(self.random()?);
|
||
let fetch = Token::from_bytes(self.random()?);
|
||
self.transport.create_mailbox(&CreateMailbox {
|
||
id,
|
||
post_token_hash: post.hash(),
|
||
fetch_token_hash: fetch.hash(),
|
||
})?;
|
||
Ok((Mailbox { id, fetch }, post))
|
||
}
|
||
|
||
/// 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> {
|
||
let bundle = KeyPackage::builder()
|
||
.build(
|
||
CIPHERSUITE,
|
||
&self.provider,
|
||
&self.signer,
|
||
self.credential.clone(),
|
||
)
|
||
.map_err(|_| ClientError::Mls)?;
|
||
let kp = bundle
|
||
.key_package()
|
||
.tls_serialize_detached()
|
||
.map_err(|_| ClientError::Mls)?;
|
||
let invite = Invite {
|
||
id: InviteId::from_bytes(self.random()?),
|
||
secret: Token::from_bytes(self.random()?),
|
||
};
|
||
let (welcome_id, welcome_post) = welcome_mailbox(&invite.secret);
|
||
let fetch = Token::from_bytes(self.random()?);
|
||
self.transport.create_mailbox(&CreateMailbox {
|
||
id: welcome_id,
|
||
post_token_hash: welcome_post.hash(),
|
||
fetch_token_hash: fetch.hash(),
|
||
})?;
|
||
self.transport.create_invite(&CreateInvite {
|
||
id: invite.id,
|
||
secret_hash: invite.secret.hash(),
|
||
key_package: KeyPackageBytes::new(kp).map_err(|_| ClientError::Mls)?,
|
||
})?;
|
||
self.welcome_boxes.push(WelcomeBox {
|
||
mailbox: Mailbox {
|
||
id: welcome_id,
|
||
fetch,
|
||
},
|
||
invite: invite.id,
|
||
});
|
||
Ok(invite)
|
||
}
|
||
|
||
/// Stops fetching an invite's welcome mailbox: the invite was cancelled, or is older than the
|
||
/// 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);
|
||
}
|
||
|
||
/// Forgets a contact: its MLS group is deleted from storage, its name and tokens from the
|
||
/// client, and its mailbox is no longer fetched. The other side is not told, and anything it
|
||
/// still posts waits on the relay until it expires. Save the snapshot after it. Returns whether
|
||
/// there was such a contact.
|
||
pub fn forget_contact(&mut self, contact: ContactId) -> Result<bool, ClientError> {
|
||
let Some(index) = self.contacts.iter().position(|c| c.id == contact) else {
|
||
return Ok(false);
|
||
};
|
||
let mut c = self.contacts.remove(index);
|
||
c.group
|
||
.delete(self.provider.storage())
|
||
.map_err(|_| ClientError::State)?;
|
||
Ok(true)
|
||
}
|
||
|
||
/// 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 key_package = KeyPackageIn::tls_deserialize_exact(&kp_bytes)
|
||
.map_err(|_| ClientError::Mls)?
|
||
.validate(self.provider.crypto(), ProtocolVersion::Mls10)
|
||
.map_err(|_| ClientError::Mls)?;
|
||
let (inbox, inbox_post) = self.new_mailbox()?;
|
||
let config = MlsGroupCreateConfig::builder()
|
||
.ciphersuite(CIPHERSUITE)
|
||
.use_ratchet_tree_extension(true)
|
||
.build();
|
||
let mut group = MlsGroup::new(
|
||
&self.provider,
|
||
&self.signer,
|
||
&config,
|
||
self.credential.clone(),
|
||
)
|
||
.map_err(|_| ClientError::Mls)?;
|
||
let (_commit, welcome, _info) = group
|
||
.add_members(&self.provider, &self.signer, &[key_package])
|
||
.map_err(|_| ClientError::Mls)?;
|
||
group
|
||
.merge_pending_commit(&self.provider)
|
||
.map_err(|_| ClientError::Mls)?;
|
||
|
||
let hello = Payload::Hello {
|
||
mailbox: inbox.id,
|
||
post_token: inbox_post,
|
||
name: self.name.clone(),
|
||
};
|
||
let (welcome_id, welcome_post) = welcome_mailbox(&invite.secret);
|
||
let welcome = welcome
|
||
.tls_serialize_detached()
|
||
.map_err(|_| ClientError::Mls)?;
|
||
let hello = Self::seal(&self.provider, &self.signer, &mut group, &hello)?;
|
||
let out = vec![
|
||
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))
|
||
}
|
||
|
||
/// [`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)
|
||
}
|
||
|
||
fn add_contact(
|
||
&mut self,
|
||
group: MlsGroup,
|
||
inbox: Option<Mailbox>,
|
||
outbox: Option<(MailboxId, Token)>,
|
||
via: Option<InviteId>,
|
||
) -> ContactId {
|
||
let id = ContactId(self.next_contact);
|
||
self.next_contact += 1;
|
||
self.contacts.push(Contact {
|
||
id,
|
||
group,
|
||
name: None,
|
||
inbox,
|
||
outbox,
|
||
via,
|
||
blocked: false,
|
||
sent_seq: 0,
|
||
received_seq: 0,
|
||
polls: Vec::new(),
|
||
});
|
||
id
|
||
}
|
||
|
||
fn seal(
|
||
provider: &OpenMlsRustCrypto,
|
||
signer: &SignatureKeyPair,
|
||
group: &mut MlsGroup,
|
||
payload: &Payload,
|
||
) -> Result<Vec<u8>, ClientError> {
|
||
let json = serde_json::to_vec(payload).map_err(|_| ClientError::Mls)?;
|
||
let blob = group
|
||
.create_message(provider, signer, &json)
|
||
.map_err(|_| ClientError::Mls)?
|
||
.tls_serialize_detached()
|
||
.map_err(|_| ClientError::Mls)?;
|
||
if blob.len() > MAX_BLOB_BYTES {
|
||
return Err(ClientError::TooLong);
|
||
}
|
||
Ok(blob)
|
||
}
|
||
|
||
/// Encrypts text for a contact whose `hello` has arrived. No network: save the snapshot, then
|
||
/// [`Client::deliver`] the result.
|
||
pub fn compose(&mut self, contact: ContactId, text: &str) -> Result<Outgoing, ClientError> {
|
||
self.compose_text(contact, text, None)
|
||
}
|
||
|
||
/// [`Client::compose`], answering `reply_to`: a message in this conversation, ours or theirs,
|
||
/// that exists ([`ClientError::BadReference`] otherwise).
|
||
pub fn compose_text(
|
||
&mut self,
|
||
contact: ContactId,
|
||
text: &str,
|
||
reply_to: Option<MessageRef>,
|
||
) -> Result<Outgoing, ClientError> {
|
||
if text.len() > MAX_TEXT_BYTES {
|
||
return Err(ClientError::TooLong);
|
||
}
|
||
let index = self.index_of(contact)?;
|
||
if let Some(r) = &reply_to {
|
||
if !self.names_a_message(index, r) {
|
||
return Err(ClientError::BadReference);
|
||
}
|
||
}
|
||
let c = &mut self.contacts[index];
|
||
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,
|
||
reply_to,
|
||
},
|
||
)?;
|
||
c.sent_seq = seq;
|
||
Ok(Outgoing::post(to, post, blob))
|
||
}
|
||
|
||
/// Our reaction to a message in this conversation: `Some(emoji)` sets it (replacing our
|
||
/// earlier one), `None` removes it. No network: save the snapshot, then deliver.
|
||
pub fn react(
|
||
&mut self,
|
||
contact: ContactId,
|
||
to: MessageRef,
|
||
emoji: Option<&str>,
|
||
) -> Result<Outgoing, ClientError> {
|
||
if let Some(e) = emoji {
|
||
if e.len() > MAX_EMOJI_BYTES {
|
||
return Err(ClientError::TooLong);
|
||
}
|
||
if !emoji_ok(e) {
|
||
return Err(ClientError::BadReference);
|
||
}
|
||
}
|
||
let index = self.index_of(contact)?;
|
||
if !self.names_a_message(index, &to) {
|
||
return Err(ClientError::BadReference);
|
||
}
|
||
let c = &mut self.contacts[index];
|
||
let (out_to, post) = c.outbox.ok_or(ClientError::UnknownContact)?;
|
||
let blob = Self::seal(
|
||
&self.provider,
|
||
&self.signer,
|
||
&mut c.group,
|
||
&Payload::Reaction {
|
||
to,
|
||
emoji: emoji.map(str::to_string),
|
||
},
|
||
)?;
|
||
Ok(Outgoing::post(out_to, post, blob))
|
||
}
|
||
|
||
/// A poll for a contact: a message, named by [`Client::sent_seq`] right after. `multiple`
|
||
/// lets a vote hold several choices. No network: save the snapshot, then deliver.
|
||
pub fn compose_poll(
|
||
&mut self,
|
||
contact: ContactId,
|
||
question: &str,
|
||
options: &[String],
|
||
multiple: bool,
|
||
) -> Result<Outgoing, ClientError> {
|
||
if question.chars().count() > MAX_QUESTION_CHARS
|
||
|| options.iter().any(|o| o.chars().count() > MAX_OPTION_CHARS)
|
||
{
|
||
return Err(ClientError::TooLong);
|
||
}
|
||
if !poll_ok(question, options) {
|
||
return Err(ClientError::BadPoll);
|
||
}
|
||
let index = self.index_of(contact)?;
|
||
let author = self.author();
|
||
let c = &mut self.contacts[index];
|
||
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::Poll {
|
||
seq,
|
||
question: question.to_string(),
|
||
options: options.to_vec(),
|
||
multiple,
|
||
},
|
||
)?;
|
||
c.sent_seq = seq;
|
||
c.polls.push(PollState {
|
||
poll: MessageRef { author, seq },
|
||
// At most MAX_POLL_OPTIONS (10), checked above.
|
||
options: options.len() as u8,
|
||
multiple,
|
||
closed: false,
|
||
ballots: Vec::new(),
|
||
});
|
||
Ok(Outgoing::post(to, post, blob))
|
||
}
|
||
|
||
/// Our vote in a poll of this conversation, ours or theirs, replacing our earlier one; `[]`
|
||
/// takes it back. No network: save the snapshot, then deliver.
|
||
pub fn vote(
|
||
&mut self,
|
||
contact: ContactId,
|
||
poll: MessageRef,
|
||
choices: &[u8],
|
||
) -> Result<Outgoing, ClientError> {
|
||
let index = self.index_of(contact)?;
|
||
let author = self.author();
|
||
let c = &mut self.contacts[index];
|
||
let p = c
|
||
.polls
|
||
.iter()
|
||
.position(|p| p.poll == poll)
|
||
.ok_or(ClientError::BadPoll)?;
|
||
if c.polls[p].closed {
|
||
return Err(ClientError::PollClosed);
|
||
}
|
||
if !c.polls[p].choices_ok(choices) {
|
||
return Err(ClientError::BadPoll);
|
||
}
|
||
let (to, post) = c.outbox.ok_or(ClientError::UnknownContact)?;
|
||
let blob = Self::seal(
|
||
&self.provider,
|
||
&self.signer,
|
||
&mut c.group,
|
||
&Payload::Vote {
|
||
poll,
|
||
choices: choices.to_vec(),
|
||
},
|
||
)?;
|
||
c.polls[p].set_ballot(author, choices);
|
||
Ok(Outgoing::post(to, post, blob))
|
||
}
|
||
|
||
/// Closes our own poll. The close carries the votes this client has accepted, which become the
|
||
/// result on both sides. No network: save the snapshot, then deliver.
|
||
pub fn close_poll(
|
||
&mut self,
|
||
contact: ContactId,
|
||
poll: MessageRef,
|
||
) -> Result<Outgoing, ClientError> {
|
||
let index = self.index_of(contact)?;
|
||
if poll.author != self.author() {
|
||
return Err(ClientError::BadPoll);
|
||
}
|
||
let c = &mut self.contacts[index];
|
||
let p = c
|
||
.polls
|
||
.iter()
|
||
.position(|p| p.poll == poll)
|
||
.ok_or(ClientError::BadPoll)?;
|
||
if c.polls[p].closed {
|
||
return Err(ClientError::PollClosed);
|
||
}
|
||
let (to, post) = c.outbox.ok_or(ClientError::UnknownContact)?;
|
||
let blob = Self::seal(
|
||
&self.provider,
|
||
&self.signer,
|
||
&mut c.group,
|
||
&Payload::PollClose {
|
||
poll,
|
||
ballots: c.polls[p].ballots.clone(),
|
||
},
|
||
)?;
|
||
c.polls[p].closed = true;
|
||
Ok(Outgoing::post(to, post, blob))
|
||
}
|
||
|
||
/// A file to send, staged (`.agents/features/files.md` §2.6): a new id, an upload token, a
|
||
/// fetch token and a key, all random. No network: keep it in the outbox, then
|
||
/// [`Client::upload`] (or [`Client::create_file`] and [`Client::put_chunk`]), then
|
||
/// [`Client::compose_file`].
|
||
pub fn start_upload(&self, size: u64) -> Result<FileUpload, ClientError> {
|
||
files::chunks_for(size).ok_or(ClientError::BadFile)?;
|
||
Ok(FileUpload {
|
||
id: tabellarius_protocol::FileId::from_bytes(self.random()?),
|
||
upload_token: Token::from_bytes(self.random()?),
|
||
fetch_token: Token::from_bytes(self.random()?),
|
||
key: FileKey::from_bytes(self.random()?),
|
||
size,
|
||
})
|
||
}
|
||
|
||
/// Creates the file on the relay. Again after a crash, the relay's 409 means it is there
|
||
/// already: the id is 16 random bytes that only this upload has.
|
||
pub fn create_file(&self, up: &FileUpload) -> Result<(), ClientError> {
|
||
let chunks = ChunkCount::new(up.chunks()).map_err(|_| ClientError::BadFile)?;
|
||
let req = CreateFile {
|
||
id: up.id,
|
||
upload_token_hash: up.upload_token.hash(),
|
||
fetch_token_hash: up.fetch_token.hash(),
|
||
chunks,
|
||
};
|
||
match self.transport.create_file(&req) {
|
||
Ok(()) | Err(TransportError::Conflict) => Ok(()),
|
||
Err(e) => Err(ClientError::Transport(e)),
|
||
}
|
||
}
|
||
|
||
/// Seals and puts chunk `index` ([`FileUpload::seal`]). Again with the same bytes, the relay
|
||
/// accepts it: an upload resumes chunk by chunk.
|
||
///
|
||
/// **The bytes must be the same on every try.** A chunk is sealed under the file's one key at
|
||
/// a nonce fixed by its index, so two different plaintexts for one index would reuse a nonce
|
||
/// (the relay refuses the second with 409, but it has seen both). An app keeps the file's bytes
|
||
/// with the [`FileUpload`] until the upload is done, rather than reading the source again.
|
||
pub fn put_chunk(&self, up: &FileUpload, index: u32, plain: &[u8]) -> Result<(), ClientError> {
|
||
let chunk = up.seal(index, plain)?;
|
||
Ok(self
|
||
.transport
|
||
.put_chunk(&up.id, &up.upload_token, index, &chunk)?)
|
||
}
|
||
|
||
/// Creates the file and puts every chunk of `bytes`, the whole file.
|
||
pub fn upload(&self, up: &FileUpload, bytes: &[u8]) -> Result<(), ClientError> {
|
||
if bytes.len() as u64 != up.size {
|
||
return Err(ClientError::BadFile);
|
||
}
|
||
self.create_file(up)?;
|
||
for index in 0..up.chunks() {
|
||
let part = up.part(bytes, index).ok_or(ClientError::BadFile)?;
|
||
self.put_chunk(up, index, part)?;
|
||
}
|
||
Ok(())
|
||
}
|
||
|
||
/// The sender deletes the file from the relay before its 30 days are up.
|
||
pub fn delete_file(&self, up: &FileUpload) -> Result<(), ClientError> {
|
||
Ok(self.transport.delete_file(&up.id, &up.upload_token)?)
|
||
}
|
||
|
||
/// A `file` message for a contact: a message, named by [`Client::sent_seq`] right after. Its
|
||
/// name, type and thumbnail are checked ([`ClientError::BadFile`]). Deliver it after the upload.
|
||
pub fn compose_file(
|
||
&mut self,
|
||
contact: ContactId,
|
||
up: &FileUpload,
|
||
name: &str,
|
||
mime: &str,
|
||
thumb: Option<&[u8]>,
|
||
) -> Result<Outgoing, ClientError> {
|
||
let thumb_bad = thumb.is_some_and(|t| !files::thumb_ok(t));
|
||
if files::chunks_for(up.size).is_none()
|
||
|| !files::name_ok(name)
|
||
|| !files::mime_ok(mime)
|
||
|| thumb_bad
|
||
{
|
||
return Err(ClientError::BadFile);
|
||
}
|
||
let index = self.index_of(contact)?;
|
||
let c = &mut self.contacts[index];
|
||
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::File {
|
||
seq,
|
||
file: up.id,
|
||
fetch_token: up.fetch_token,
|
||
key: up.key,
|
||
name: name.to_string(),
|
||
mime: mime.to_string(),
|
||
size: up.size,
|
||
thumb: thumb.map(|t| Bytes(t.to_vec())),
|
||
},
|
||
)?;
|
||
c.sent_seq = seq;
|
||
Ok(Outgoing::post(to, post, blob))
|
||
}
|
||
|
||
/// Fetches and opens chunk `index` of a received file: its plaintext, without padding. A chunk
|
||
/// not on the relay (yet) is `Transport(NotFound)`; one that does not open is
|
||
/// [`ClientError::FileDamaged`].
|
||
pub fn get_chunk(&self, file: &FileRef, index: u32) -> Result<Vec<u8>, ClientError> {
|
||
if index >= file.chunks() {
|
||
return Err(ClientError::BadFile);
|
||
}
|
||
let chunk = self
|
||
.transport
|
||
.get_chunk(&file.id, &file.fetch_token, index)?;
|
||
file.open(index, &chunk)
|
||
}
|
||
|
||
/// Fetches and opens every chunk: the whole file, exactly `size` bytes.
|
||
pub fn download(&self, file: &FileRef) -> Result<Vec<u8>, ClientError> {
|
||
let mut out = Vec::with_capacity(file.size as usize);
|
||
for index in 0..file.chunks() {
|
||
out.extend(self.get_chunk(file, index)?);
|
||
}
|
||
Ok(out)
|
||
}
|
||
|
||
/// Our author name: the 16 bytes in our credential. With a `seq` it names our messages.
|
||
pub fn author(&self) -> Author {
|
||
author_of(&self.identity).unwrap_or_else(|| Author::from_bytes([0; 16]))
|
||
}
|
||
|
||
/// The contact's author name, read from the conversation's other MLS member.
|
||
pub fn contact_author(&self, contact: ContactId) -> Option<Author> {
|
||
let index = self.index_of(contact).ok()?;
|
||
self.peer_author(index)
|
||
}
|
||
|
||
fn index_of(&self, contact: ContactId) -> Result<usize, ClientError> {
|
||
self.contacts
|
||
.iter()
|
||
.position(|c| c.id == contact)
|
||
.ok_or(ClientError::UnknownContact)
|
||
}
|
||
|
||
fn peer_author(&self, index: usize) -> Option<Author> {
|
||
self.contacts[index]
|
||
.group
|
||
.members()
|
||
.filter_map(|m| BasicCredential::try_from(m.credential).ok())
|
||
.map(|c| c.identity().to_vec())
|
||
.find(|id| id != &self.identity)
|
||
.and_then(|id| author_of(&id))
|
||
}
|
||
|
||
/// Whether `r` names a message that exists in this conversation: ours up to our last `seq`,
|
||
/// theirs up to the highest `seq` received from them.
|
||
fn names_a_message(&self, index: usize, r: &MessageRef) -> bool {
|
||
let c = &self.contacts[index];
|
||
if r.seq == 0 {
|
||
return false;
|
||
}
|
||
if r.author.as_bytes()[..] == self.identity[..] {
|
||
r.seq <= c.sent_seq
|
||
} else if self.peer_author(index) == Some(r.author) {
|
||
r.seq <= c.received_seq
|
||
} else {
|
||
false
|
||
}
|
||
}
|
||
|
||
/// 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<u64> {
|
||
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> {
|
||
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()
|
||
}
|
||
|
||
/// The mailboxes this client fetches: each contact's inbox (a blocked contact's too, which
|
||
/// nothing reaches) and each open invite's welcome mailbox. For wake-ups (`PROTOCOL.md` §6): an
|
||
/// app registers one push endpoint per mailbox, so the relay cannot link them by endpoint.
|
||
pub fn inboxes(&self) -> Vec<MailboxId> {
|
||
self.contacts
|
||
.iter()
|
||
.filter_map(|c| c.inbox.map(|m| m.id))
|
||
.chain(self.welcome_boxes.iter().map(|w| w.mailbox.id))
|
||
.collect()
|
||
}
|
||
|
||
/// Where the relay wakes us when this mailbox receives (`Some`), or nowhere (`None`). Only a
|
||
/// mailbox from [`Client::inboxes`]; another is [`ClientError::UnknownContact`].
|
||
pub fn set_push(
|
||
&self,
|
||
mailbox: &MailboxId,
|
||
endpoint: Option<&PushEndpoint>,
|
||
) -> Result<(), ClientError> {
|
||
let fetch = self
|
||
.contacts
|
||
.iter()
|
||
.filter_map(|c| c.inbox)
|
||
.chain(self.welcome_boxes.iter().map(|w| w.mailbox))
|
||
.find(|m| m.id == *mailbox)
|
||
.ok_or(ClientError::UnknownContact)?
|
||
.fetch;
|
||
Ok(self.transport.set_push(mailbox, &fetch, endpoint)?)
|
||
}
|
||
|
||
/// 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<Outgoing, 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)?;
|
||
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<Vec<Outgoing>, 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)?;
|
||
self.deliver(&out)
|
||
}
|
||
|
||
/// The contact's name, once its `hello` has arrived.
|
||
pub fn contact_name(&self, contact: ContactId) -> Option<&str> {
|
||
self.contacts
|
||
.iter()
|
||
.find(|c| c.id == contact)
|
||
.and_then(|c| c.name.as_deref())
|
||
}
|
||
|
||
/// Fetches every own mailbox and processes each blob in order. Posts nothing and acknowledges
|
||
/// nothing: save the snapshot and the events, then call [`Client::finish`]. A blob that is
|
||
/// not valid MLS for one of our groups is dropped without a trace: nothing from it is shown,
|
||
/// and it is acknowledged with the rest.
|
||
///
|
||
/// If the relay fails part-way, what was processed so far is returned (with `interrupted`
|
||
/// 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(
|
||
self.contacts
|
||
.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,
|
||
Err(e) => {
|
||
got.interrupted = Some(e);
|
||
break;
|
||
}
|
||
};
|
||
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),
|
||
});
|
||
}
|
||
}
|
||
// 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::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)
|
||
}
|
||
|
||
/// 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`.
|
||
///
|
||
/// 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 {
|
||
match self.deliver(out) {
|
||
Ok(()) | Err(ClientError::Transport(TransportError::NotFound)) => {}
|
||
Err(e) => return Err(e),
|
||
}
|
||
}
|
||
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)?;
|
||
match message.extract() {
|
||
// Only a welcome mailbox carries a Welcome.
|
||
MlsMessageBodyIn::Welcome(welcome) if via.is_some() => {
|
||
let config = MlsGroupJoinConfig::builder()
|
||
.use_ratchet_tree_extension(true)
|
||
.build();
|
||
let staged =
|
||
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)
|
||
.map_err(|_| ClientError::Mls)?;
|
||
// Not a contact to show yet: the hello right behind the Welcome makes it one.
|
||
self.add_contact(group, None, None, via);
|
||
Ok(None)
|
||
}
|
||
MlsMessageBodyIn::PrivateMessage(private) => {
|
||
let protocol: ProtocolMessage = private.into();
|
||
let group_id = protocol.group_id().clone();
|
||
let index = self
|
||
.contacts
|
||
.iter()
|
||
.position(|c| c.group.group_id() == &group_id)
|
||
.ok_or(ClientError::UnknownContact)?;
|
||
let processed = self.contacts[index]
|
||
.group
|
||
.process_message(&self.provider, protocol)
|
||
.map_err(|_| ClientError::Mls)?;
|
||
let ProcessedMessageContent::ApplicationMessage(app) = processed.into_content()
|
||
else {
|
||
return Ok(None);
|
||
};
|
||
match parse_payload(&app.into_bytes())? {
|
||
Parsed::Known(payload) => self.receive_payload(index, payload),
|
||
Parsed::Unknown { seq } => self.receive_unknown(index, seq),
|
||
}
|
||
}
|
||
_ => Err(ClientError::Mls),
|
||
}
|
||
}
|
||
|
||
fn receive_payload(
|
||
&mut self,
|
||
index: usize,
|
||
payload: Payload,
|
||
) -> Result<Option<Event>, ClientError> {
|
||
match payload {
|
||
Payload::Hello {
|
||
mailbox,
|
||
post_token,
|
||
name,
|
||
} => {
|
||
if name.chars().count() > MAX_NAME_CHARS || self.contacts[index].name.is_some() {
|
||
return Err(ClientError::Mls);
|
||
}
|
||
let c = &mut self.contacts[index];
|
||
c.outbox = Some((mailbox, post_token));
|
||
c.name = Some(name.clone());
|
||
Ok(Some(Event::Joined {
|
||
contact: c.id,
|
||
name,
|
||
via: c.via,
|
||
}))
|
||
}
|
||
Payload::Text {
|
||
body,
|
||
seq,
|
||
reply_to,
|
||
} => {
|
||
let c = &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);
|
||
}
|
||
// Checked before this text counts, so a text cannot answer itself. The words are
|
||
// real even when the reference is not: the text stays, the reference goes.
|
||
let reply_to = reply_to.filter(|r| self.names_a_message(index, r));
|
||
let c = &mut self.contacts[index];
|
||
c.received_seq = c.received_seq.max(seq);
|
||
Ok(Some(Event::Message {
|
||
contact: c.id,
|
||
text: body,
|
||
seq,
|
||
reply_to,
|
||
}))
|
||
}
|
||
Payload::Reaction { to, emoji } => {
|
||
let c = &self.contacts[index];
|
||
if c.name.is_none() {
|
||
return Err(ClientError::Mls);
|
||
}
|
||
let emoji_bad = emoji
|
||
.as_deref()
|
||
.is_some_and(|e| e.len() > MAX_EMOJI_BYTES || !emoji_ok(e));
|
||
if c.blocked || emoji_bad || !self.names_a_message(index, &to) {
|
||
return Ok(None);
|
||
}
|
||
Ok(Some(Event::Reaction {
|
||
contact: c.id,
|
||
to,
|
||
emoji,
|
||
}))
|
||
}
|
||
Payload::Poll {
|
||
seq,
|
||
question,
|
||
options,
|
||
multiple,
|
||
} => self.receive_poll(index, seq, question, options, multiple),
|
||
Payload::Vote { poll, choices } => self.receive_vote(index, poll, choices),
|
||
Payload::PollClose { poll, ballots } => self.receive_close(index, poll, ballots),
|
||
Payload::File {
|
||
seq,
|
||
file,
|
||
fetch_token,
|
||
key,
|
||
name,
|
||
mime,
|
||
size,
|
||
thumb,
|
||
} => {
|
||
let c = &mut self.contacts[index];
|
||
if c.name.is_none() {
|
||
return Err(ClientError::Mls);
|
||
}
|
||
if c.blocked
|
||
|| seq == 0
|
||
|| files::chunks_for(size).is_none()
|
||
|| !files::name_ok(&name)
|
||
|| !files::mime_ok(&mime)
|
||
{
|
||
return Ok(None);
|
||
}
|
||
c.received_seq = c.received_seq.max(seq);
|
||
// The file is real even when its thumbnail is not: the file stays, the picture goes.
|
||
let thumb = thumb.map(|t| t.0).filter(|t| files::thumb_ok(t));
|
||
Ok(Some(Event::File {
|
||
contact: c.id,
|
||
seq,
|
||
file: FileRef {
|
||
id: file,
|
||
fetch_token,
|
||
key,
|
||
size,
|
||
},
|
||
name,
|
||
mime,
|
||
thumb,
|
||
}))
|
||
}
|
||
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)
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
impl<T: Transport> Client<T> {
|
||
/// A payload of a kind this client does not know, with a `seq`: a newer app's message.
|
||
fn receive_unknown(&mut self, index: usize, seq: u64) -> Result<Option<Event>, ClientError> {
|
||
let c = &mut self.contacts[index];
|
||
if c.name.is_none() {
|
||
return Err(ClientError::Mls);
|
||
}
|
||
if c.blocked {
|
||
return Ok(None);
|
||
}
|
||
c.received_seq = c.received_seq.max(seq);
|
||
Ok(Some(Event::Unsupported { contact: c.id, seq }))
|
||
}
|
||
|
||
/// The contact's poll: kept if well formed and not one we already have under that name.
|
||
fn receive_poll(
|
||
&mut self,
|
||
index: usize,
|
||
seq: u64,
|
||
question: String,
|
||
options: Vec<String>,
|
||
multiple: bool,
|
||
) -> Result<Option<Event>, ClientError> {
|
||
if self.contacts[index].name.is_none() {
|
||
return Err(ClientError::Mls);
|
||
}
|
||
let Some(author) = self.peer_author(index) else {
|
||
return Ok(None);
|
||
};
|
||
let name = MessageRef { author, seq };
|
||
let c = &mut self.contacts[index];
|
||
let fits = question.chars().count() <= MAX_QUESTION_CHARS
|
||
&& options
|
||
.iter()
|
||
.all(|o| o.chars().count() <= MAX_OPTION_CHARS);
|
||
if c.blocked
|
||
|| seq == 0
|
||
|| !fits
|
||
|| !poll_ok(&question, &options)
|
||
|| c.polls.iter().any(|p| p.poll == name)
|
||
{
|
||
return Ok(None);
|
||
}
|
||
c.received_seq = c.received_seq.max(seq);
|
||
c.polls.push(PollState {
|
||
poll: name,
|
||
// At most MAX_POLL_OPTIONS (10): poll_ok.
|
||
options: options.len() as u8,
|
||
multiple,
|
||
closed: false,
|
||
ballots: Vec::new(),
|
||
});
|
||
Ok(Some(Event::Poll {
|
||
contact: c.id,
|
||
seq,
|
||
question,
|
||
options,
|
||
multiple,
|
||
}))
|
||
}
|
||
|
||
/// The contact's vote, in a poll of this conversation that is still open.
|
||
fn receive_vote(
|
||
&mut self,
|
||
index: usize,
|
||
poll: MessageRef,
|
||
choices: Vec<u8>,
|
||
) -> Result<Option<Event>, ClientError> {
|
||
if self.contacts[index].name.is_none() {
|
||
return Err(ClientError::Mls);
|
||
}
|
||
let Some(author) = self.peer_author(index) else {
|
||
return Ok(None);
|
||
};
|
||
let c = &mut self.contacts[index];
|
||
if c.blocked {
|
||
return Ok(None);
|
||
}
|
||
let Some(p) = c.polls.iter_mut().find(|p| p.poll == poll) else {
|
||
return Ok(None);
|
||
};
|
||
if p.closed || !p.choices_ok(&choices) {
|
||
return Ok(None);
|
||
}
|
||
p.set_ballot(author, &choices);
|
||
Ok(Some(Event::Vote {
|
||
contact: c.id,
|
||
poll,
|
||
choices,
|
||
}))
|
||
}
|
||
|
||
/// The contact closed their own poll: its votes become the close's ballots, if each is a
|
||
/// member's, once, and a valid vote.
|
||
fn receive_close(
|
||
&mut self,
|
||
index: usize,
|
||
poll: MessageRef,
|
||
ballots: Vec<Ballot>,
|
||
) -> Result<Option<Event>, ClientError> {
|
||
if self.contacts[index].name.is_none() {
|
||
return Err(ClientError::Mls);
|
||
}
|
||
let Some(peer) = self.peer_author(index) else {
|
||
return Ok(None);
|
||
};
|
||
let me = self.author();
|
||
let c = &mut self.contacts[index];
|
||
if c.blocked || poll.author != peer {
|
||
return Ok(None);
|
||
}
|
||
let Some(p) = c.polls.iter_mut().find(|p| p.poll == poll) else {
|
||
return Ok(None);
|
||
};
|
||
let valid = ballots.iter().enumerate().all(|(i, b)| {
|
||
(b.author == me || b.author == peer)
|
||
&& !ballots[..i].iter().any(|o| o.author == b.author)
|
||
&& !b.choices.is_empty()
|
||
&& p.choices_ok(&b.choices)
|
||
});
|
||
if p.closed || !valid {
|
||
return Ok(None);
|
||
}
|
||
p.closed = true;
|
||
p.ballots = ballots.clone();
|
||
Ok(Some(Event::PollClosed {
|
||
contact: c.id,
|
||
poll,
|
||
ballots,
|
||
}))
|
||
}
|
||
}
|
||
|
||
enum Parsed {
|
||
Known(Payload),
|
||
Unknown { seq: u64 },
|
||
}
|
||
|
||
/// A payload of a known kind must parse exactly (`deny_unknown_fields`); one of an unknown kind is
|
||
/// `Unknown` when it carries a `seq` of at least 1, and refused otherwise.
|
||
fn parse_payload(bytes: &[u8]) -> Result<Parsed, ClientError> {
|
||
let value: serde_json::Value = serde_json::from_slice(bytes).map_err(|_| ClientError::Mls)?;
|
||
let kind = value
|
||
.get("kind")
|
||
.and_then(serde_json::Value::as_str)
|
||
.ok_or(ClientError::Mls)?;
|
||
if KNOWN_KINDS.contains(&kind) {
|
||
return serde_json::from_value(value)
|
||
.map(Parsed::Known)
|
||
.map_err(|_| ClientError::Mls);
|
||
}
|
||
match value.get("seq").and_then(serde_json::Value::as_u64) {
|
||
Some(seq) if seq >= 1 => Ok(Parsed::Unknown { seq }),
|
||
_ => Err(ClientError::Mls),
|
||
}
|
||
}
|
||
|
||
/// A poll's question and options as the wire allows them (the lengths are checked apart): 2–10
|
||
/// options, none blank, none repeated, no control characters anywhere.
|
||
fn poll_ok(question: &str, options: &[String]) -> bool {
|
||
let fine = |s: &str| !s.trim().is_empty() && !s.chars().any(char::is_control);
|
||
(MIN_POLL_OPTIONS..=MAX_POLL_OPTIONS).contains(&options.len())
|
||
&& fine(question)
|
||
&& options.iter().all(|o| fine(o))
|
||
&& options
|
||
.iter()
|
||
.enumerate()
|
||
.all(|(i, o)| !options[..i].contains(o))
|
||
}
|
||
|
||
/// An emoji as the wire allows it: not empty, no control characters (the length is checked apart,
|
||
/// as [`ClientError::TooLong`]).
|
||
fn emoji_ok(emoji: &str) -> bool {
|
||
!emoji.is_empty() && !emoji.chars().any(char::is_control)
|
||
}
|
||
|
||
fn author_of(identity: &[u8]) -> Option<Author> {
|
||
<[u8; 16]>::try_from(identity).ok().map(Author::from_bytes)
|
||
}
|
||
|
||
fn credential_with_key(identity: &[u8], signer: &SignatureKeyPair) -> CredentialWithKey {
|
||
CredentialWithKey {
|
||
credential: BasicCredential::new(identity.to_vec()).into(),
|
||
signature_key: signer.public().into(),
|
||
}
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use super::*;
|
||
|
||
/// A contact who sends a second `hello` must not redirect our messages to another mailbox,
|
||
/// nor rename themselves. Only the contact can send one (MLS authenticates it), so this guards
|
||
/// against a misbehaving contact or a replayed message.
|
||
#[test]
|
||
fn a_second_hello_changes_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");
|
||
jan.accept_invite(&invite).expect("accept");
|
||
let joined = eva.poll().expect("poll");
|
||
assert_eq!(joined.len(), 1);
|
||
let before = eva.contacts[0].outbox.map(|(m, _)| m);
|
||
|
||
let other = MailboxId::from_bytes([9; 16]);
|
||
let again = Payload::Hello {
|
||
mailbox: other,
|
||
post_token: Token::from_bytes([9; 32]),
|
||
name: "Mallory".into(),
|
||
};
|
||
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].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
|
||
}))
|
||
);
|
||
}
|
||
|
||
// Reactions and replies (`.agents/features/reactions-replies.md` §2.2).
|
||
fn paired() -> (Client<MemoryTransport>, Client<MemoryTransport>) {
|
||
let relay = MemoryTransport::default();
|
||
let mut eva = Client::new("Eva", relay.clone()).expect("eva");
|
||
let mut jan = Client::new("Jan", relay.clone()).expect("jan");
|
||
eva.set_receipts(false);
|
||
jan.set_receipts(false);
|
||
let invite = eva.create_invite().expect("invite");
|
||
jan.accept_invite(&invite).expect("accept");
|
||
eva.poll().expect("poll");
|
||
jan.poll().expect("poll");
|
||
(eva, jan)
|
||
}
|
||
|
||
/// Seals any JSON for the first contact, as a newer or misbehaving client could.
|
||
fn seal_raw(c: &mut Client<MemoryTransport>, json: &str) -> Outgoing {
|
||
let contact = &mut c.contacts[0];
|
||
let (to, post) = contact.outbox.expect("outbox");
|
||
let blob = contact
|
||
.group
|
||
.create_message(&c.provider, &c.signer, json.as_bytes())
|
||
.expect("seal")
|
||
.tls_serialize_detached()
|
||
.expect("bytes");
|
||
Outgoing::post(to, post, blob)
|
||
}
|
||
|
||
#[test]
|
||
fn a_text_without_a_reply_is_the_old_json_and_a_removal_has_no_emoji_key() {
|
||
let text = Payload::Text {
|
||
body: "x".into(),
|
||
seq: 1,
|
||
reply_to: None,
|
||
};
|
||
assert_eq!(
|
||
serde_json::to_string(&text).expect("json"),
|
||
r#"{"kind":"text","body":"x","seq":1}"#
|
||
);
|
||
let to = MessageRef {
|
||
author: Author::from_bytes([0; 16]),
|
||
seq: 3,
|
||
};
|
||
let removal = Payload::Reaction { to, emoji: None };
|
||
assert_eq!(
|
||
serde_json::to_string(&removal).expect("json"),
|
||
r#"{"kind":"reaction","to":{"author":"AAAAAAAAAAAAAAAAAAAAAA","seq":3}}"#
|
||
);
|
||
let reply = Payload::Text {
|
||
body: "y".into(),
|
||
seq: 2,
|
||
reply_to: Some(to),
|
||
};
|
||
assert!(serde_json::to_string(&reply)
|
||
.expect("json")
|
||
.contains(r#""replyTo":{"author":"#));
|
||
}
|
||
|
||
#[test]
|
||
fn an_unknown_kind_needs_a_seq_and_a_known_kind_must_parse_exactly() {
|
||
assert!(matches!(
|
||
parse_payload(br#"{"kind":"sticker","seq":4,"name":"?"}"#),
|
||
Ok(Parsed::Unknown { seq: 4 })
|
||
));
|
||
for bad in [
|
||
&br#"{"kind":"sticker","name":"?"}"#[..],
|
||
br#"{"kind":"sticker","seq":0}"#,
|
||
br#"{"kind":"sticker","seq":-1}"#,
|
||
br#"{"kind":"sticker","seq":"4"}"#,
|
||
br#"{"kind":"file","seq":4,"name":"?"}"#,
|
||
br#"{"kind":"poll","seq":4,"question":"?"}"#,
|
||
br#"{"kind":"vote","poll":{"author":"AAAAAAAAAAAAAAAAAAAAAA","seq":1},"choices":[256]}"#,
|
||
br#"{"kind":"vote","poll":{"author":"AAAAAAAAAAAAAAAAAAAAAA","seq":1},"choices":[-1]}"#,
|
||
br#"{"kind":"pollClose","poll":{"author":"AAAAAAAAAAAAAAAAAAAAAA","seq":1},"ballots":[{"author":"AAAAAAAAAAAAAAAAAAAAAA","choices":[0],"x":1}]}"#,
|
||
br#"{"seq":4}"#,
|
||
br#"{"kind":"text","body":"x","seq":1,"mentions":[]}"#,
|
||
br#"{"kind":"reaction","to":{"author":"AAAAAAAAAAAAAAAAAAAAAA","seq":1},"emoji":"x","extra":1}"#,
|
||
br#"{"kind":"reaction","to":{"author":"AAAAAAAAAAAAAAAAAAAAAA","seq":1,"x":1}}"#,
|
||
b"not json",
|
||
] {
|
||
assert!(
|
||
parse_payload(bad).is_err(),
|
||
"{}",
|
||
String::from_utf8_lossy(bad)
|
||
);
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn a_reaction_that_names_no_message_here_or_carries_a_bad_emoji_is_dropped() {
|
||
let (mut eva, mut jan) = paired();
|
||
eva.send(eva.contacts[0].id, "jedna").expect("send");
|
||
jan.poll().expect("poll");
|
||
let first = MessageRef {
|
||
author: eva.author(),
|
||
seq: 1,
|
||
};
|
||
let stranger = Author::from_bytes([7; 16]);
|
||
let reaction = |to: MessageRef, emoji: Option<&str>| Payload::Reaction {
|
||
to,
|
||
emoji: emoji.map(str::to_string),
|
||
};
|
||
let long = "😀".repeat(9);
|
||
for payload in [
|
||
reaction(MessageRef { seq: 2, ..first }, Some("👍")),
|
||
reaction(MessageRef { seq: 0, ..first }, Some("👍")),
|
||
reaction(
|
||
MessageRef {
|
||
author: stranger,
|
||
seq: 1,
|
||
},
|
||
Some("👍"),
|
||
),
|
||
// Eva's view: a reaction from Jan to Jan's message 1, which never came.
|
||
reaction(
|
||
MessageRef {
|
||
author: jan.author(),
|
||
seq: 1,
|
||
},
|
||
Some("👍"),
|
||
),
|
||
reaction(first, Some("")),
|
||
reaction(first, Some("a\u{0}")),
|
||
reaction(first, Some(&long)),
|
||
] {
|
||
assert_eq!(eva.receive_payload(0, payload), Ok(None));
|
||
}
|
||
assert!(matches!(
|
||
eva.receive_payload(0, reaction(first, Some("👍"))),
|
||
Ok(Some(Event::Reaction { .. }))
|
||
));
|
||
}
|
||
|
||
#[test]
|
||
fn a_text_whose_reference_names_nothing_here_is_shown_without_it() {
|
||
let (mut eva, _jan) = paired();
|
||
let text = |seq, reply_to| Payload::Text {
|
||
body: "words".into(),
|
||
seq,
|
||
reply_to,
|
||
};
|
||
// Their first text answering their own first text: itself.
|
||
let itself = MessageRef {
|
||
author: eva.peer_author(0).expect("author"),
|
||
seq: 1,
|
||
};
|
||
let got = eva.receive_payload(0, text(1, Some(itself)));
|
||
assert!(
|
||
matches!(
|
||
&got,
|
||
Ok(Some(Event::Message {
|
||
reply_to: None,
|
||
seq: 1,
|
||
..
|
||
}))
|
||
),
|
||
"{got:?}"
|
||
);
|
||
// Now it exists: their second text may answer it.
|
||
let got = eva.receive_payload(0, text(2, Some(itself)));
|
||
assert!(
|
||
matches!(
|
||
&got,
|
||
Ok(Some(Event::Message {
|
||
reply_to: Some(_),
|
||
..
|
||
}))
|
||
),
|
||
"{got:?}"
|
||
);
|
||
let ours = MessageRef {
|
||
author: eva.author(),
|
||
seq: 1,
|
||
};
|
||
let got = eva.receive_payload(0, text(3, Some(ours)));
|
||
assert!(
|
||
matches!(&got, Ok(Some(Event::Message { reply_to: None, text, .. })) if text == "words"),
|
||
"we sent nothing yet: {got:?}"
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn a_newer_apps_message_is_unsupported_and_counts_for_receipts() {
|
||
let (mut eva, mut jan) = paired();
|
||
eva.set_receipts(true);
|
||
let out = seal_raw(
|
||
&mut jan,
|
||
r#"{"kind":"sticker","seq":1,"mime":"image/webp"}"#,
|
||
);
|
||
jan.deliver(&out).expect("deliver");
|
||
let out = seal_raw(&mut jan, r#"{"kind":"sticker","mime":"no seq"}"#);
|
||
jan.deliver(&out).expect("deliver");
|
||
let got = eva.receive().expect("receive");
|
||
assert_eq!(
|
||
got.events,
|
||
vec![Event::Unsupported {
|
||
contact: eva.contacts[0].id,
|
||
seq: 1
|
||
}]
|
||
);
|
||
assert_eq!(eva.contacts[0].received_seq, 1);
|
||
assert_eq!(got.outgoing.len(), 1, "a receipt for it");
|
||
// From a blocked contact: dropped.
|
||
eva.contacts[0].blocked = true;
|
||
assert_eq!(eva.receive_unknown(0, 2), Ok(None));
|
||
}
|
||
|
||
// Polls (`.agents/features/polls.md` §2.4).
|
||
fn strings(xs: &[&str]) -> Vec<String> {
|
||
xs.iter().map(|x| x.to_string()).collect()
|
||
}
|
||
|
||
fn their_poll(seq: u64, options: &[&str], multiple: bool) -> Payload {
|
||
Payload::Poll {
|
||
seq,
|
||
question: "Kam?".into(),
|
||
options: strings(options),
|
||
multiple,
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn a_malformed_poll_is_refused_when_sending_and_dropped_when_received() {
|
||
let (mut eva, _jan) = paired();
|
||
let id = eva.contacts[0].id;
|
||
let long = "x".repeat(MAX_OPTION_CHARS + 1);
|
||
let eleven: Vec<String> = (0..11).map(|i| i.to_string()).collect();
|
||
let bad: [(&str, Vec<String>); 7] = [
|
||
("Kam?", strings(&["jen jedna"])),
|
||
("Kam?", eleven),
|
||
("Kam?", strings(&["a", "a"])),
|
||
("Kam?", strings(&["a", " "])),
|
||
(" ", strings(&["a", "b"])),
|
||
("Kam?\u{7}", strings(&["a", "b"])),
|
||
("Kam?", strings(&["a", "b\n"])),
|
||
];
|
||
for (question, options) in &bad {
|
||
assert_eq!(
|
||
eva.compose_poll(id, question, options, false).err(),
|
||
Some(ClientError::BadPoll),
|
||
"{question:?} {options:?}"
|
||
);
|
||
let got = eva.receive_payload(
|
||
0,
|
||
Payload::Poll {
|
||
seq: 1,
|
||
question: question.to_string(),
|
||
options: options.clone(),
|
||
multiple: false,
|
||
},
|
||
);
|
||
assert_eq!(got, Ok(None), "{question:?} {options:?}");
|
||
}
|
||
assert_eq!(
|
||
eva.compose_poll(id, "Kam?", &[long.clone(), "b".into()], false)
|
||
.err(),
|
||
Some(ClientError::TooLong)
|
||
);
|
||
let long_question = "?".repeat(MAX_QUESTION_CHARS + 1);
|
||
assert_eq!(
|
||
eva.compose_poll(id, &long_question, &strings(&["a", "b"]), false)
|
||
.err(),
|
||
Some(ClientError::TooLong)
|
||
);
|
||
assert_eq!(
|
||
eva.receive_payload(
|
||
0,
|
||
Payload::Poll {
|
||
seq: 1,
|
||
question: "Kam?".into(),
|
||
options: vec![long, "b".into()],
|
||
multiple: false,
|
||
}
|
||
),
|
||
Ok(None)
|
||
);
|
||
assert_eq!(
|
||
eva.contacts[0].received_seq, 0,
|
||
"a dropped poll does not count"
|
||
);
|
||
assert!(eva.contacts[0].polls.is_empty());
|
||
// Ten options of exactly 100 characters, and 300 of question: fits.
|
||
let ten: Vec<String> = (0..10).map(|i| format!("{i}{}", "y".repeat(99))).collect();
|
||
let q = "?".repeat(MAX_QUESTION_CHARS);
|
||
assert!(eva.compose_poll(id, &q, &ten, true).is_ok());
|
||
assert!(matches!(
|
||
eva.receive_payload(0, their_poll(1, &["a", "b"], false)),
|
||
Ok(Some(Event::Poll { seq: 1, .. }))
|
||
));
|
||
assert_eq!(
|
||
eva.receive_payload(0, their_poll(1, &["c", "d"], false)),
|
||
Ok(None),
|
||
"a second poll under the same name"
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn a_vote_that_does_not_fit_its_poll_is_refused_and_dropped() {
|
||
let (mut eva, _jan) = paired();
|
||
let id = eva.contacts[0].id;
|
||
let jan = eva.peer_author(0).expect("author");
|
||
eva.receive_payload(0, their_poll(1, &["a", "b", "c"], false))
|
||
.expect("poll");
|
||
eva.receive_payload(0, their_poll(2, &["a", "b", "c"], true))
|
||
.expect("poll");
|
||
let single = MessageRef {
|
||
author: jan,
|
||
seq: 1,
|
||
};
|
||
let multi = MessageRef {
|
||
author: jan,
|
||
seq: 2,
|
||
};
|
||
let unknown = MessageRef {
|
||
author: jan,
|
||
seq: 3,
|
||
};
|
||
let vote = |poll, choices: &[u8]| Payload::Vote {
|
||
poll,
|
||
choices: choices.to_vec(),
|
||
};
|
||
for (poll, choices) in [
|
||
(single, &[0u8, 1][..]),
|
||
(single, &[3][..]),
|
||
(multi, &[1, 0][..]),
|
||
(multi, &[1, 1][..]),
|
||
(multi, &[3][..]),
|
||
(unknown, &[0][..]),
|
||
] {
|
||
assert_eq!(
|
||
eva.vote(id, poll, choices).err(),
|
||
Some(ClientError::BadPoll),
|
||
"{poll:?} {choices:?}"
|
||
);
|
||
assert_eq!(eva.receive_payload(0, vote(poll, choices)), Ok(None));
|
||
}
|
||
assert!(eva.vote(id, multi, &[0, 2]).is_ok());
|
||
assert!(eva.vote(id, single, &[]).is_ok(), "taking back nothing");
|
||
assert!(matches!(
|
||
eva.receive_payload(0, vote(multi, &[0, 1, 2])),
|
||
Ok(Some(Event::Vote { .. }))
|
||
));
|
||
let p = &eva.contacts[0].polls[1];
|
||
assert_eq!(p.ballots.len(), 2);
|
||
// Taking it back removes the ballot.
|
||
eva.receive_payload(0, vote(multi, &[])).expect("vote");
|
||
assert_eq!(eva.contacts[0].polls[1].ballots.len(), 1);
|
||
}
|
||
|
||
#[test]
|
||
fn only_the_asker_closes_with_valid_ballots_and_then_nothing_changes_it() {
|
||
let (mut eva, _jan) = paired();
|
||
let id = eva.contacts[0].id;
|
||
let jan = eva.peer_author(0).expect("author");
|
||
let me = eva.author();
|
||
eva.receive_payload(0, their_poll(1, &["a", "b"], false))
|
||
.expect("poll");
|
||
let theirs = MessageRef {
|
||
author: jan,
|
||
seq: 1,
|
||
};
|
||
let out = eva.compose_poll(id, "Kdy?", &strings(&["pá", "so"]), false);
|
||
assert!(out.is_ok());
|
||
let ours = MessageRef { author: me, seq: 1 };
|
||
assert_eq!(
|
||
eva.close_poll(id, theirs).err(),
|
||
Some(ClientError::BadPoll),
|
||
"not ours to close"
|
||
);
|
||
let close = |poll, ballots: Vec<Ballot>| Payload::PollClose { poll, ballots };
|
||
let ballot = |author, choices: &[u8]| Ballot {
|
||
author,
|
||
choices: choices.to_vec(),
|
||
};
|
||
let stranger = Author::from_bytes([7; 16]);
|
||
for payload in [
|
||
// Jan cannot close Eva's poll.
|
||
close(ours, vec![]),
|
||
close(theirs, vec![ballot(stranger, &[0])]),
|
||
close(theirs, vec![ballot(jan, &[0]), ballot(jan, &[1])]),
|
||
close(theirs, vec![ballot(jan, &[])]),
|
||
close(theirs, vec![ballot(me, &[0, 1])]),
|
||
close(theirs, vec![ballot(me, &[2])]),
|
||
close(
|
||
MessageRef {
|
||
author: jan,
|
||
seq: 2,
|
||
},
|
||
vec![],
|
||
),
|
||
] {
|
||
assert_eq!(eva.receive_payload(0, payload), Ok(None));
|
||
}
|
||
assert!(!eva.contacts[0].polls[0].closed);
|
||
let final_ = vec![ballot(jan, &[1]), ballot(me, &[0])];
|
||
assert_eq!(
|
||
eva.receive_payload(0, close(theirs, final_.clone())),
|
||
Ok(Some(Event::PollClosed {
|
||
contact: id,
|
||
poll: theirs,
|
||
ballots: final_.clone()
|
||
}))
|
||
);
|
||
assert_eq!(eva.contacts[0].polls[0].ballots, final_);
|
||
// Closed: no vote, no second close, from either side.
|
||
assert_eq!(
|
||
eva.vote(id, theirs, &[1]).err(),
|
||
Some(ClientError::PollClosed)
|
||
);
|
||
let vote = Payload::Vote {
|
||
poll: theirs,
|
||
choices: vec![0],
|
||
};
|
||
assert_eq!(eva.receive_payload(0, vote), Ok(None));
|
||
assert_eq!(eva.receive_payload(0, close(theirs, vec![])), Ok(None));
|
||
assert_eq!(eva.contacts[0].polls[0].ballots, final_);
|
||
// Our own: closed once.
|
||
assert!(eva.close_poll(id, ours).is_ok());
|
||
assert_eq!(
|
||
eva.close_poll(id, ours).err(),
|
||
Some(ClientError::PollClosed)
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn a_blocked_contacts_poll_vote_and_close_are_dropped() {
|
||
let (mut eva, _jan) = paired();
|
||
let jan = eva.peer_author(0).expect("author");
|
||
eva.receive_payload(0, their_poll(1, &["a", "b"], false))
|
||
.expect("poll");
|
||
let poll = MessageRef {
|
||
author: jan,
|
||
seq: 1,
|
||
};
|
||
eva.contacts[0].blocked = true;
|
||
assert_eq!(
|
||
eva.receive_payload(0, their_poll(2, &["a", "b"], false)),
|
||
Ok(None)
|
||
);
|
||
let vote = Payload::Vote {
|
||
poll,
|
||
choices: vec![0],
|
||
};
|
||
assert_eq!(eva.receive_payload(0, vote), Ok(None));
|
||
let close = Payload::PollClose {
|
||
poll,
|
||
ballots: vec![],
|
||
};
|
||
assert_eq!(eva.receive_payload(0, close), Ok(None));
|
||
assert_eq!(eva.contacts[0].polls.len(), 1);
|
||
assert!(!eva.contacts[0].polls[0].closed);
|
||
assert!(eva.contacts[0].polls[0].ballots.is_empty());
|
||
}
|
||
|
||
// Files (`.agents/features/files.md` §2.5).
|
||
fn their_file(seq: u64, name: &str, mime: &str, size: u64, thumb: Option<Vec<u8>>) -> Payload {
|
||
Payload::File {
|
||
seq,
|
||
file: tabellarius_protocol::FileId::from_bytes([4; 16]),
|
||
fetch_token: Token::from_bytes([5; 32]),
|
||
key: FileKey::from_bytes([6; 32]),
|
||
name: name.into(),
|
||
mime: mime.into(),
|
||
size,
|
||
thumb: thumb.map(Bytes),
|
||
}
|
||
}
|
||
|
||
const JPEG: [u8; 4] = [0xFF, 0xD8, 0xFF, 0xE0];
|
||
|
||
#[test]
|
||
fn a_malformed_file_is_refused_when_sending_and_dropped_when_received() {
|
||
let (mut eva, _jan) = paired();
|
||
let id = eva.contacts[0].id;
|
||
let up = eva.start_upload(10).expect("upload");
|
||
let long = "x".repeat(MAX_FILE_NAME_CHARS + 1);
|
||
let bad: [(&str, &str, u64); 7] = [
|
||
("", "image/jpeg", 10),
|
||
("a/b.jpg", "image/jpeg", 10),
|
||
("a\nb", "image/jpeg", 10),
|
||
(&long, "image/jpeg", 10),
|
||
("a.jpg", "jpeg", 10),
|
||
("a.jpg", "image/jpeg", 0),
|
||
("a.jpg", "image/jpeg", MAX_FILE_BYTES + 1),
|
||
];
|
||
for (name, mime, size) in bad {
|
||
if size == 10 {
|
||
assert_eq!(
|
||
eva.compose_file(id, &up, name, mime, None).err(),
|
||
Some(ClientError::BadFile),
|
||
"{name:?} {mime:?}"
|
||
);
|
||
} else {
|
||
assert_eq!(eva.start_upload(size).err(), Some(ClientError::BadFile));
|
||
}
|
||
assert_eq!(
|
||
eva.receive_payload(0, their_file(1, name, mime, size, None)),
|
||
Ok(None),
|
||
"{name:?} {mime:?} {size}"
|
||
);
|
||
}
|
||
assert_eq!(
|
||
eva.receive_payload(0, their_file(0, "a.jpg", "image/jpeg", 10, None)),
|
||
Ok(None),
|
||
"seq 0"
|
||
);
|
||
assert_eq!(
|
||
eva.contacts[0].received_seq, 0,
|
||
"a dropped file does not count"
|
||
);
|
||
assert_eq!(
|
||
eva.compose_file(id, &up, "a.jpg", "image/jpeg", Some(b"\x89PNG"))
|
||
.err(),
|
||
Some(ClientError::BadFile),
|
||
"a thumbnail that is not a JPEG"
|
||
);
|
||
assert_eq!(eva.sent_seq(id), Some(0), "nothing was sent");
|
||
assert!(eva
|
||
.compose_file(id, &up, "a.jpg", "image/jpeg", Some(&JPEG))
|
||
.is_ok());
|
||
assert_eq!(eva.sent_seq(id), Some(1));
|
||
}
|
||
|
||
#[test]
|
||
fn a_bad_thumbnail_is_dropped_and_the_file_kept() {
|
||
let (mut eva, _jan) = paired();
|
||
let mut big = JPEG.to_vec();
|
||
big.resize(MAX_THUMB_BYTES + 1, 0);
|
||
for (seq, thumb) in [(1, b"\x89PNG".to_vec()), (2, big)] {
|
||
let got =
|
||
eva.receive_payload(0, their_file(seq, "a.jpg", "image/jpeg", 10, Some(thumb)));
|
||
assert!(
|
||
matches!(&got, Ok(Some(Event::File { thumb: None, seq: s, .. })) if *s == seq),
|
||
"{got:?}"
|
||
);
|
||
}
|
||
let got = eva.receive_payload(
|
||
0,
|
||
their_file(3, "a.jpg", "image/jpeg", 10, Some(JPEG.to_vec())),
|
||
);
|
||
assert!(matches!(&got, Ok(Some(Event::File { thumb: Some(t), .. })) if t == &JPEG));
|
||
assert_eq!(eva.contacts[0].received_seq, 3);
|
||
}
|
||
|
||
#[test]
|
||
fn a_blocked_contacts_file_is_dropped() {
|
||
let (mut eva, _jan) = paired();
|
||
eva.contacts[0].blocked = true;
|
||
assert_eq!(
|
||
eva.receive_payload(0, their_file(1, "a.jpg", "image/jpeg", 10, None)),
|
||
Ok(None)
|
||
);
|
||
assert_eq!(eva.contacts[0].received_seq, 0);
|
||
}
|
||
|
||
/// Every kind this client sends is in `KNOWN_KINDS`: a variant left out would arrive as
|
||
/// *Unsupported* at a client of the same version.
|
||
#[test]
|
||
fn every_payload_kind_is_known() {
|
||
let to = MessageRef {
|
||
author: Author::from_bytes([1; 16]),
|
||
seq: 1,
|
||
};
|
||
let all = [
|
||
Payload::Hello {
|
||
mailbox: MailboxId::from_bytes([0; 16]),
|
||
post_token: Token::from_bytes([0; 32]),
|
||
name: "x".into(),
|
||
},
|
||
Payload::Text {
|
||
body: "x".into(),
|
||
seq: 1,
|
||
reply_to: None,
|
||
},
|
||
Payload::Receipt { upto: 1 },
|
||
Payload::Inbox {
|
||
post_token: Token::from_bytes([0; 32]),
|
||
},
|
||
Payload::Reaction { to, emoji: None },
|
||
Payload::Poll {
|
||
seq: 2,
|
||
question: "?".into(),
|
||
options: vec!["a".into(), "b".into()],
|
||
multiple: false,
|
||
},
|
||
Payload::Vote {
|
||
poll: to,
|
||
choices: vec![0],
|
||
},
|
||
Payload::PollClose {
|
||
poll: to,
|
||
ballots: vec![Ballot {
|
||
author: to.author,
|
||
choices: vec![1],
|
||
}],
|
||
},
|
||
their_file(3, "a.jpg", "image/jpeg", 10, Some(JPEG.to_vec())),
|
||
];
|
||
assert_eq!(all.len(), KNOWN_KINDS.len());
|
||
for payload in all {
|
||
let json = serde_json::to_vec(&payload).expect("json");
|
||
assert!(
|
||
matches!(parse_payload(&json), Ok(Parsed::Known(p)) if p == payload),
|
||
"{}",
|
||
String::from_utf8_lossy(&json)
|
||
);
|
||
}
|
||
}
|
||
}
|