[client] F22a: snapshot and restore, and staged calls that send nothing before the app has saved
This commit is contained in:
+277
-63
@@ -9,9 +9,19 @@
|
||||
//! 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 snapshot;
|
||||
pub use snapshot::SNAPSHOT_VERSION;
|
||||
|
||||
use hkdf::Hkdf;
|
||||
use openmls::prelude::tls_codec::{Deserialize as _, Serialize as _};
|
||||
use openmls::prelude::*;
|
||||
@@ -19,9 +29,11 @@ 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, CreateInvite, CreateMailbox, InviteId, KeyPackageBytes, MailboxId, Token,
|
||||
MAX_BLOB_BYTES,
|
||||
blob_hash, CreateInvite, CreateMailbox, InviteId, KeyPackageBytes, MailboxId, Sha256Hash,
|
||||
Token, MAX_BLOB_BYTES,
|
||||
};
|
||||
pub use transport::{MemoryTransport, Transport, TransportError};
|
||||
|
||||
@@ -47,6 +59,8 @@ pub enum ClientError {
|
||||
TooLong,
|
||||
/// No such contact, or a contact whose mailbox is not known yet.
|
||||
UnknownContact,
|
||||
/// A snapshot that does not parse, has another version, or does not match OpenMLS's storage.
|
||||
State,
|
||||
}
|
||||
|
||||
impl From<TransportError> for ClientError {
|
||||
@@ -74,16 +88,19 @@ pub fn welcome_mailbox(secret: &Token) -> (MailboxId, Token) {
|
||||
}
|
||||
|
||||
/// A local handle for a contact. Means nothing outside this client.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Serialize, Deserialize)]
|
||||
pub struct ContactId(pub u32);
|
||||
|
||||
/// What [`Client::poll`] found.
|
||||
/// 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.
|
||||
/// 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>,
|
||||
},
|
||||
Message {
|
||||
contact: ContactId,
|
||||
@@ -91,6 +108,49 @@ pub enum Event {
|
||||
},
|
||||
}
|
||||
|
||||
/// One blob for the relay, to deliver once the app has saved the snapshot. An app may keep it in
|
||||
/// an outbox and deliver it again after a crash: a second copy is refused by MLS as a replay.
|
||||
/// `Debug` shows neither the post token nor the bytes.
|
||||
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct Outgoing {
|
||||
to: MailboxId,
|
||||
post: Token,
|
||||
blob: Bytes,
|
||||
}
|
||||
|
||||
impl fmt::Debug for Outgoing {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "Outgoing({} bytes)", self.blob.0.len())
|
||||
}
|
||||
}
|
||||
|
||||
/// A fetched blob to acknowledge once the app has saved what it produced.
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
struct Ack {
|
||||
mailbox: MailboxId,
|
||||
fetch: Token,
|
||||
hash: Sha256Hash,
|
||||
}
|
||||
|
||||
/// What one [`Client::receive`] produced. Save the snapshot and the events, keep the `outgoing`
|
||||
/// blobs if the app has an outbox, then call [`Client::finish`].
|
||||
#[derive(Debug)]
|
||||
pub struct Received {
|
||||
pub events: Vec<Event>,
|
||||
/// Our answering `hello`s.
|
||||
pub outgoing: Vec<Outgoing>,
|
||||
/// The relay failed part-way: what was fetched before it is here, the rest waits there.
|
||||
pub interrupted: Option<TransportError>,
|
||||
acks: Vec<Ack>,
|
||||
}
|
||||
|
||||
impl fmt::Debug for Ack {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str("Ack")
|
||||
}
|
||||
}
|
||||
|
||||
/// The JSON inside an MLS application message. The relay never sees it.
|
||||
#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
|
||||
#[serde(tag = "kind", rename_all = "camelCase", deny_unknown_fields)]
|
||||
@@ -106,29 +166,40 @@ enum Payload {
|
||||
},
|
||||
}
|
||||
|
||||
#[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.
|
||||
/// 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>,
|
||||
}
|
||||
|
||||
pub struct Client<T: Transport> {
|
||||
provider: OpenMlsRustCrypto,
|
||||
signer: SignatureKeyPair,
|
||||
credential: CredentialWithKey,
|
||||
identity: Vec<u8>,
|
||||
name: String,
|
||||
transport: T,
|
||||
contacts: Vec<Contact>,
|
||||
welcome_boxes: Vec<Mailbox>,
|
||||
welcome_boxes: Vec<WelcomeBox>,
|
||||
next_contact: u32,
|
||||
}
|
||||
|
||||
@@ -148,14 +219,12 @@ impl<T: Transport> Client<T> {
|
||||
.rand()
|
||||
.random_array()
|
||||
.map_err(|_| ClientError::Random)?;
|
||||
let credential = CredentialWithKey {
|
||||
credential: BasicCredential::new(identity.to_vec()).into(),
|
||||
signature_key: signer.public().into(),
|
||||
};
|
||||
let credential = credential_with_key(&identity, &signer);
|
||||
Ok(Self {
|
||||
provider,
|
||||
signer,
|
||||
credential,
|
||||
identity: identity.to_vec(),
|
||||
name: name.to_string(),
|
||||
transport,
|
||||
contacts: Vec::new(),
|
||||
@@ -184,7 +253,8 @@ impl<T: Transport> Client<T> {
|
||||
Ok((Mailbox { id, fetch }, post))
|
||||
}
|
||||
|
||||
/// Step 1: a KeyPackage on the relay and a welcome mailbox. Share the result as a link.
|
||||
/// Step 1: a KeyPackage on the relay and a welcome mailbox. Save the snapshot, then share the
|
||||
/// result as a link.
|
||||
pub fn create_invite(&mut self) -> Result<Invite, ClientError> {
|
||||
let bundle = KeyPackage::builder()
|
||||
.build(
|
||||
@@ -214,20 +284,26 @@ impl<T: Transport> Client<T> {
|
||||
secret_hash: invite.secret.hash(),
|
||||
key_package: KeyPackageBytes::new(kp).map_err(|_| ClientError::Mls)?,
|
||||
})?;
|
||||
self.welcome_boxes.push(Mailbox {
|
||||
id: welcome_id,
|
||||
fetch,
|
||||
self.welcome_boxes.push(WelcomeBox {
|
||||
mailbox: Mailbox {
|
||||
id: welcome_id,
|
||||
fetch,
|
||||
},
|
||||
invite: invite.id,
|
||||
});
|
||||
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> {
|
||||
/// 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)
|
||||
@@ -246,7 +322,6 @@ impl<T: Transport> Client<T> {
|
||||
.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,
|
||||
@@ -257,10 +332,28 @@ impl<T: Transport> Client<T> {
|
||||
.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 out = vec![
|
||||
Outgoing {
|
||||
to: welcome_id,
|
||||
post: welcome_post,
|
||||
blob: Bytes(welcome),
|
||||
},
|
||||
Outgoing {
|
||||
to: welcome_id,
|
||||
post: welcome_post,
|
||||
blob: Bytes(hello),
|
||||
},
|
||||
];
|
||||
let id = self.add_contact(group, Some(inbox), None, None);
|
||||
Ok((id, out))
|
||||
}
|
||||
|
||||
let id = self.add_contact(group, Some(inbox), None);
|
||||
/// [`Client::accept`] and delivering at once, for use without persistence.
|
||||
pub fn accept_invite(&mut self, invite: &Invite) -> Result<ContactId, ClientError> {
|
||||
let (id, out) = self.accept(invite)?;
|
||||
for o in &out {
|
||||
self.deliver(o)?;
|
||||
}
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
@@ -269,6 +362,7 @@ impl<T: Transport> Client<T> {
|
||||
group: MlsGroup,
|
||||
inbox: Option<Mailbox>,
|
||||
outbox: Option<(MailboxId, Token)>,
|
||||
via: Option<InviteId>,
|
||||
) -> ContactId {
|
||||
let id = ContactId(self.next_contact);
|
||||
self.next_contact += 1;
|
||||
@@ -278,6 +372,7 @@ impl<T: Transport> Client<T> {
|
||||
name: None,
|
||||
inbox,
|
||||
outbox,
|
||||
via,
|
||||
});
|
||||
id
|
||||
}
|
||||
@@ -300,8 +395,9 @@ impl<T: Transport> Client<T> {
|
||||
Ok(blob)
|
||||
}
|
||||
|
||||
/// Sends text to a contact whose `hello` has arrived.
|
||||
pub fn send(&mut self, contact: ContactId, text: &str) -> Result<(), ClientError> {
|
||||
/// 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> {
|
||||
if text.len() > MAX_TEXT_BYTES {
|
||||
return Err(ClientError::TooLong);
|
||||
}
|
||||
@@ -319,10 +415,25 @@ impl<T: Transport> Client<T> {
|
||||
body: text.to_string(),
|
||||
},
|
||||
)?;
|
||||
self.transport.post(&to, &post, &blob)?;
|
||||
Ok(Outgoing {
|
||||
to,
|
||||
post,
|
||||
blob: Bytes(blob),
|
||||
})
|
||||
}
|
||||
|
||||
/// Posts one blob to the relay.
|
||||
pub fn deliver(&self, out: &Outgoing) -> Result<(), ClientError> {
|
||||
self.transport.post(&out.to, &out.post, &out.blob.0)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// [`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
|
||||
@@ -331,43 +442,146 @@ impl<T: Transport> Client<T> {
|
||||
.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();
|
||||
/// 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.as_ref().map(|m| (m.id, m.fetch))),
|
||||
.filter_map(|c| c.inbox.map(|m| (m, None))),
|
||||
);
|
||||
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);
|
||||
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;
|
||||
}
|
||||
self.transport.acknowledge(&id, &fetch, &blob_hash(&blob))?;
|
||||
};
|
||||
for blob in blobs {
|
||||
// A failure to understand one blob must not stop the rest, nor be shown.
|
||||
if let Ok(Some(event)) = self.process(&blob, via) {
|
||||
got.events.push(event);
|
||||
}
|
||||
got.acks.push(Ack {
|
||||
mailbox: mailbox.id,
|
||||
fetch: mailbox.fetch,
|
||||
hash: blob_hash(&blob),
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(events)
|
||||
// The inviter's side: each contact whose `hello` arrived gets ours, with a new mailbox. A
|
||||
// relay that fails here leaves the contact owing its answer until the next receive.
|
||||
for index in 0..self.contacts.len() {
|
||||
let c = &self.contacts[index];
|
||||
let Some((to, post)) = c.outbox else { continue };
|
||||
if c.inbox.is_some() || got.interrupted.is_some() {
|
||||
continue;
|
||||
}
|
||||
match self.new_mailbox() {
|
||||
Ok((inbox, inbox_post)) => {
|
||||
let hello = Payload::Hello {
|
||||
mailbox: inbox.id,
|
||||
post_token: inbox_post,
|
||||
name: self.name.clone(),
|
||||
};
|
||||
let c = &mut self.contacts[index];
|
||||
// Failing to seal leaves the answer owed, like a relay failure: the events
|
||||
// already processed must still reach the app.
|
||||
let Ok(blob) = Self::seal(&self.provider, &self.signer, &mut c.group, &hello)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
c.inbox = Some(inbox);
|
||||
got.outgoing.push(Outgoing {
|
||||
to,
|
||||
post,
|
||||
blob: Bytes(blob),
|
||||
});
|
||||
}
|
||||
Err(ClientError::Transport(e)) => got.interrupted = Some(e),
|
||||
Err(_) => continue,
|
||||
}
|
||||
}
|
||||
Ok(got)
|
||||
}
|
||||
|
||||
fn process(&mut self, blob: &[u8]) -> Result<Option<Event>, ClientError> {
|
||||
/// After saving: delivers the `outgoing` blobs, then acknowledges the fetched ones. On an
|
||||
/// error, call it again later; anything delivered twice is refused by MLS as a replay.
|
||||
///
|
||||
/// Then a welcome mailbox whose contact has said hello is dropped, so junk posted to it later
|
||||
/// is never fetched. Not before: a snapshot saved between `receive` and `finish` must still
|
||||
/// know the mailbox, so that a restored client fetches its blobs again and acknowledges them.
|
||||
/// Save the snapshot again after `finish`.
|
||||
pub fn finish(&mut self, received: &Received) -> Result<(), ClientError> {
|
||||
for out in &received.outgoing {
|
||||
self.deliver(out)?;
|
||||
}
|
||||
for ack in &received.acks {
|
||||
self.transport
|
||||
.acknowledge(&ack.mailbox, &ack.fetch, &ack.hash)?;
|
||||
}
|
||||
let joined: Vec<InviteId> = self
|
||||
.contacts
|
||||
.iter()
|
||||
.filter(|c| c.name.is_some())
|
||||
.filter_map(|c| c.via)
|
||||
.collect();
|
||||
self.welcome_boxes.retain(|w| !joined.contains(&w.invite));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// [`Client::receive`] and [`Client::finish`] at once, for use without persistence.
|
||||
pub fn poll(&mut self) -> Result<Vec<Event>, ClientError> {
|
||||
let got = self.receive()?;
|
||||
self.finish(&got)?;
|
||||
match got.interrupted {
|
||||
Some(e) if got.events.is_empty() => Err(ClientError::Transport(e)),
|
||||
_ => Ok(got.events),
|
||||
}
|
||||
}
|
||||
|
||||
fn process(
|
||||
&mut self,
|
||||
blob: &[u8],
|
||||
via: Option<InviteId>,
|
||||
) -> Result<Option<Event>, ClientError> {
|
||||
let message = MlsMessageIn::tls_deserialize_exact(blob).map_err(|_| ClientError::Mls)?;
|
||||
match message.extract() {
|
||||
MlsMessageBodyIn::Welcome(welcome) => {
|
||||
// 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 group = StagedWelcome::new_from_welcome(&self.provider, &config, welcome, None)
|
||||
.map_err(|_| ClientError::Mls)?
|
||||
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);
|
||||
self.add_contact(group, None, None, via);
|
||||
Ok(None)
|
||||
}
|
||||
MlsMessageBodyIn::PrivateMessage(private) => {
|
||||
@@ -388,13 +602,17 @@ impl<T: Transport> Client<T> {
|
||||
};
|
||||
let payload: Payload =
|
||||
serde_json::from_slice(&app.into_bytes()).map_err(|_| ClientError::Mls)?;
|
||||
self.receive(index, payload)
|
||||
self.receive_payload(index, payload)
|
||||
}
|
||||
_ => Err(ClientError::Mls),
|
||||
}
|
||||
}
|
||||
|
||||
fn receive(&mut self, index: usize, payload: Payload) -> Result<Option<Event>, ClientError> {
|
||||
fn receive_payload(
|
||||
&mut self,
|
||||
index: usize,
|
||||
payload: Payload,
|
||||
) -> Result<Option<Event>, ClientError> {
|
||||
match payload {
|
||||
Payload::Hello {
|
||||
mailbox,
|
||||
@@ -404,24 +622,13 @@ impl<T: Transport> Client<T> {
|
||||
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)?;
|
||||
}
|
||||
let c = &mut self.contacts[index];
|
||||
c.outbox = Some((mailbox, post_token));
|
||||
c.name = Some(name.clone());
|
||||
Ok(Some(Event::Joined {
|
||||
contact: self.contacts[index].id,
|
||||
contact: c.id,
|
||||
name,
|
||||
via: c.via,
|
||||
}))
|
||||
}
|
||||
Payload::Text { body } => {
|
||||
@@ -439,6 +646,13 @@ impl<T: Transport> Client<T> {
|
||||
}
|
||||
}
|
||||
|
||||
fn credential_with_key(identity: &[u8], signer: &SignatureKeyPair) -> CredentialWithKey {
|
||||
CredentialWithKey {
|
||||
credential: BasicCredential::new(identity.to_vec()).into(),
|
||||
signature_key: signer.public().into(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -463,7 +677,7 @@ mod tests {
|
||||
post_token: Token::from_bytes([9; 32]),
|
||||
name: "Mallory".into(),
|
||||
};
|
||||
assert_eq!(eva.receive(0, again), Err(ClientError::Mls));
|
||||
assert_eq!(eva.receive_payload(0, again), Err(ClientError::Mls));
|
||||
assert_eq!(eva.contacts[0].outbox.map(|(m, _)| m), before);
|
||||
assert_eq!(eva.contacts[0].name.as_deref(), Some("Jan"));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
//! The client's whole state as bytes, for the app's encrypted store
|
||||
//! (`.agents/features/client-state.md` §2). It holds every secret of the identity: MLS private
|
||||
//! keys, fetch tokens and post tokens. `Debug` is not implemented for any of it.
|
||||
|
||||
use crate::{
|
||||
credential_with_key, Client, ClientError, Contact, ContactId, Mailbox, Transport, WelcomeBox,
|
||||
CIPHERSUITE, MAX_NAME_CHARS,
|
||||
};
|
||||
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
|
||||
use base64::Engine as _;
|
||||
use openmls::prelude::{GroupId, MlsGroup, OpenMlsProvider as _};
|
||||
use openmls_basic_credential::SignatureKeyPair;
|
||||
use openmls_rust_crypto::OpenMlsRustCrypto;
|
||||
use serde::{Deserialize, Deserializer, Serialize, Serializer};
|
||||
use std::collections::HashSet;
|
||||
use tabellarius_protocol::{InviteId, MailboxId, Token};
|
||||
|
||||
/// The snapshot format's version. Another number is refused, never guessed at.
|
||||
pub const SNAPSHOT_VERSION: u32 = 1;
|
||||
|
||||
/// Bytes as unpadded base64url in JSON.
|
||||
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub(crate) struct Bytes(pub(crate) Vec<u8>);
|
||||
|
||||
impl Serialize for Bytes {
|
||||
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
|
||||
s.serialize_str(&URL_SAFE_NO_PAD.encode(&self.0))
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for Bytes {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
let s = String::deserialize(d)?;
|
||||
URL_SAFE_NO_PAD
|
||||
.decode(s.as_bytes())
|
||||
.map(Bytes)
|
||||
.map_err(serde::de::Error::custom)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
struct ContactState {
|
||||
id: ContactId,
|
||||
group: Bytes,
|
||||
name: Option<String>,
|
||||
inbox: Option<Mailbox>,
|
||||
outbox: Option<(MailboxId, Token)>,
|
||||
via: Option<InviteId>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
struct State {
|
||||
v: u32,
|
||||
name: String,
|
||||
identity: Bytes,
|
||||
signer_public: Bytes,
|
||||
contacts: Vec<ContactState>,
|
||||
welcome_boxes: Vec<WelcomeBox>,
|
||||
next_contact: u32,
|
||||
/// OpenMLS's storage: every key and value, sorted by key so equal states give equal bytes.
|
||||
storage: Vec<(Bytes, Bytes)>,
|
||||
}
|
||||
|
||||
impl<T: Transport> Client<T> {
|
||||
/// The whole state, to keep in the app's encrypted store. Secret: never log it, never send it.
|
||||
pub fn snapshot(&self) -> Result<Vec<u8>, ClientError> {
|
||||
let mut storage: Vec<(Bytes, Bytes)> = self
|
||||
.provider
|
||||
.storage()
|
||||
.values
|
||||
.read()
|
||||
.map_err(|_| ClientError::State)?
|
||||
.iter()
|
||||
.map(|(k, v)| (Bytes(k.clone()), Bytes(v.clone())))
|
||||
.collect();
|
||||
storage.sort();
|
||||
let state = State {
|
||||
v: SNAPSHOT_VERSION,
|
||||
name: self.name.clone(),
|
||||
identity: Bytes(self.identity.clone()),
|
||||
signer_public: Bytes(self.signer.to_public_vec()),
|
||||
contacts: self
|
||||
.contacts
|
||||
.iter()
|
||||
.map(|c| ContactState {
|
||||
id: c.id,
|
||||
group: Bytes(c.group.group_id().as_slice().to_vec()),
|
||||
name: c.name.clone(),
|
||||
inbox: c.inbox,
|
||||
outbox: c.outbox,
|
||||
via: c.via,
|
||||
})
|
||||
.collect(),
|
||||
welcome_boxes: self.welcome_boxes.clone(),
|
||||
next_contact: self.next_contact,
|
||||
storage,
|
||||
};
|
||||
serde_json::to_vec(&state).map_err(|_| ClientError::State)
|
||||
}
|
||||
|
||||
/// A client from a snapshot. All or nothing: a snapshot that does not parse, has another
|
||||
/// version, or does not match its own storage is refused with [`ClientError::State`].
|
||||
pub fn restore(snapshot: &[u8], transport: T) -> Result<Self, ClientError> {
|
||||
let state: State = serde_json::from_slice(snapshot).map_err(|_| ClientError::State)?;
|
||||
if state.v != SNAPSHOT_VERSION || state.name.chars().count() > MAX_NAME_CHARS {
|
||||
return Err(ClientError::State);
|
||||
}
|
||||
let provider = OpenMlsRustCrypto::default();
|
||||
{
|
||||
let mut values = provider
|
||||
.storage()
|
||||
.values
|
||||
.write()
|
||||
.map_err(|_| ClientError::State)?;
|
||||
for (k, v) in state.storage {
|
||||
values.insert(k.0, v.0);
|
||||
}
|
||||
}
|
||||
let signer = SignatureKeyPair::read(
|
||||
provider.storage(),
|
||||
&state.signer_public.0,
|
||||
CIPHERSUITE.signature_algorithm(),
|
||||
)
|
||||
.ok_or(ClientError::State)?;
|
||||
let credential = credential_with_key(&state.identity.0, &signer);
|
||||
|
||||
let mut ids = HashSet::new();
|
||||
let mut contacts = Vec::with_capacity(state.contacts.len());
|
||||
for c in state.contacts {
|
||||
// Ids are unique and below the next one, or two contacts could end up sharing one.
|
||||
if c.id.0 >= state.next_contact || !ids.insert(c.id) {
|
||||
return Err(ClientError::State);
|
||||
}
|
||||
let group = MlsGroup::load(provider.storage(), &GroupId::from_slice(&c.group.0))
|
||||
.map_err(|_| ClientError::State)?
|
||||
.ok_or(ClientError::State)?;
|
||||
contacts.push(Contact {
|
||||
id: c.id,
|
||||
group,
|
||||
name: c.name,
|
||||
inbox: c.inbox,
|
||||
outbox: c.outbox,
|
||||
via: c.via,
|
||||
});
|
||||
}
|
||||
Ok(Client {
|
||||
provider,
|
||||
signer,
|
||||
credential,
|
||||
identity: state.identity.0,
|
||||
name: state.name,
|
||||
transport,
|
||||
contacts,
|
||||
welcome_boxes: state.welcome_boxes,
|
||||
next_contact: state.next_contact,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn bytes_round_trip_as_base64url() {
|
||||
let b = Bytes(vec![0, 1, 254, 255]);
|
||||
let json = serde_json::to_string(&b).expect("json");
|
||||
assert_eq!(json, "\"AAH-_w\"");
|
||||
let back: Bytes = serde_json::from_str(&json).expect("back");
|
||||
assert!(back == b);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user