Files
Amicitia-Tabellarius/crates/client/src/lib.rs
T

471 lines
17 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! 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.
pub mod transport;
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 tabellarius_protocol::{
blob_hash, CreateInvite, CreateMailbox, InviteId, KeyPackageBytes, MailboxId, 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;
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,
}
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)]
pub struct ContactId(pub u32);
/// What [`Client::poll`] found.
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum Event {
/// The other side's `hello` arrived: the conversation can be used both ways.
Joined {
contact: ContactId,
name: String,
},
Message {
contact: ContactId,
text: String,
},
}
/// 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,
},
Text {
body: String,
},
}
struct Mailbox {
id: MailboxId,
fetch: Token,
}
struct Contact {
id: ContactId,
group: MlsGroup,
name: Option<String>,
/// Where the other side posts to us.
inbox: Option<Mailbox>,
/// Where we post to the other side: their mailbox and its post token.
outbox: Option<(MailboxId, Token)>,
}
pub struct Client<T: Transport> {
provider: OpenMlsRustCrypto,
signer: SignatureKeyPair,
credential: CredentialWithKey,
name: String,
transport: T,
contacts: Vec<Contact>,
welcome_boxes: Vec<Mailbox>,
next_contact: u32,
}
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 = CredentialWithKey {
credential: BasicCredential::new(identity.to_vec()).into(),
signature_key: signer.public().into(),
};
Ok(Self {
provider,
signer,
credential,
name: name.to_string(),
transport,
contacts: Vec::new(),
welcome_boxes: Vec::new(),
next_contact: 0,
})
}
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. 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(Mailbox {
id: welcome_id,
fetch,
});
Ok(invite)
}
/// Step 2, on the other device: claim the KeyPackage, make the group, send Welcome and hello.
pub fn accept_invite(&mut self, invite: &Invite) -> Result<ContactId, 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 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 (inbox, inbox_post) = self.new_mailbox()?;
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)?;
self.transport.post(&welcome_id, &welcome_post, &welcome)?;
self.transport.post(&welcome_id, &welcome_post, &hello)?;
let id = self.add_contact(group, Some(inbox), None);
Ok(id)
}
fn add_contact(
&mut self,
group: MlsGroup,
inbox: Option<Mailbox>,
outbox: Option<(MailboxId, Token)>,
) -> ContactId {
let id = ContactId(self.next_contact);
self.next_contact += 1;
self.contacts.push(Contact {
id,
group,
name: None,
inbox,
outbox,
});
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)
}
/// Sends text to a contact whose `hello` has arrived.
pub fn send(&mut self, contact: ContactId, text: &str) -> Result<(), ClientError> {
if text.len() > MAX_TEXT_BYTES {
return Err(ClientError::TooLong);
}
let c = self
.contacts
.iter_mut()
.find(|c| c.id == contact)
.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::Text {
body: text.to_string(),
},
)?;
self.transport.post(&to, &post, &blob)?;
Ok(())
}
/// 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, processes each blob in order, and acknowledges it, whether it
/// was understood or refused. A blob that is 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> {
let mut events = Vec::new();
let mut sources: Vec<(MailboxId, Token)> =
self.welcome_boxes.iter().map(|m| (m.id, m.fetch)).collect();
sources.extend(
self.contacts
.iter()
.filter_map(|c| c.inbox.as_ref().map(|m| (m.id, m.fetch))),
);
for (id, fetch) in sources {
for blob in self.transport.fetch(&id, &fetch)? {
// A failure to understand one blob must not stop the rest, nor be shown.
if let Ok(Some(event)) = self.process(&blob) {
events.push(event);
}
self.transport.acknowledge(&id, &fetch, &blob_hash(&blob))?;
}
}
Ok(events)
}
fn process(&mut self, blob: &[u8]) -> Result<Option<Event>, ClientError> {
let message = MlsMessageIn::tls_deserialize_exact(blob).map_err(|_| ClientError::Mls)?;
match message.extract() {
MlsMessageBodyIn::Welcome(welcome) => {
let config = MlsGroupJoinConfig::builder()
.use_ratchet_tree_extension(true)
.build();
let group = StagedWelcome::new_from_welcome(&self.provider, &config, welcome, None)
.map_err(|_| ClientError::Mls)?
.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);
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);
};
let payload: Payload =
serde_json::from_slice(&app.into_bytes()).map_err(|_| ClientError::Mls)?;
self.receive(index, payload)
}
_ => Err(ClientError::Mls),
}
}
fn receive(&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);
}
self.contacts[index].outbox = Some((mailbox, post_token));
self.contacts[index].name = Some(name.clone());
// The inviter's side: answer with our own mailbox, inside MLS.
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 {
contact: self.contacts[index].id,
name,
}))
}
Payload::Text { body } => {
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);
}
Ok(Some(Event::Message {
contact: c.id,
text: body,
}))
}
}
}
}
#[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(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"));
}
}