[client] F24: block and unblock as staged rotates, receipts with seq, readdress; payloads in PROTOCOL.md
ci / check (pull_request) Has been cancelled
ci / check (pull_request) Has been cancelled
This commit is contained in:
+261
-38
@@ -106,22 +106,55 @@ pub enum Event {
|
||||
contact: ContactId,
|
||||
text: String,
|
||||
},
|
||||
/// The other side's app has saved our texts up to `upto` (a `seq` from
|
||||
/// [`Client::sent_seq`]). Only while receipts are on ([`Client::set_receipts`]).
|
||||
Delivered {
|
||||
contact: ContactId,
|
||||
upto: u64,
|
||||
},
|
||||
}
|
||||
|
||||
/// One blob for the relay, to deliver once the app has saved the snapshot. An app may keep it in
|
||||
/// an outbox and deliver it again after a crash: a second copy is refused by MLS as a replay.
|
||||
/// `Debug` shows neither the post token nor the bytes.
|
||||
/// One operation for the relay, to deliver once the app has saved the snapshot: a blob to post,
|
||||
/// or a post token to rotate (block, unblock). An app may keep it in an outbox and deliver it
|
||||
/// again after a crash: a second post is refused by MLS as a replay, a second rotate changes
|
||||
/// nothing. `Debug` shows no token and no bytes.
|
||||
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct Outgoing {
|
||||
to: MailboxId,
|
||||
post: Token,
|
||||
blob: Bytes,
|
||||
#[serde(transparent)]
|
||||
pub struct Outgoing(Op);
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(tag = "op", rename_all = "camelCase", deny_unknown_fields)]
|
||||
enum Op {
|
||||
#[serde(rename_all = "camelCase")]
|
||||
Post {
|
||||
to: MailboxId,
|
||||
post: Token,
|
||||
blob: Bytes,
|
||||
},
|
||||
#[serde(rename_all = "camelCase")]
|
||||
Rotate {
|
||||
mailbox: MailboxId,
|
||||
fetch: Token,
|
||||
post_token_hash: Sha256Hash,
|
||||
},
|
||||
}
|
||||
|
||||
impl Outgoing {
|
||||
fn post(to: MailboxId, post: Token, blob: Vec<u8>) -> Outgoing {
|
||||
Outgoing(Op::Post {
|
||||
to,
|
||||
post,
|
||||
blob: Bytes(blob),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for Outgoing {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "Outgoing({} bytes)", self.blob.0.len())
|
||||
match &self.0 {
|
||||
Op::Post { blob, .. } => write!(f, "Outgoing({} bytes)", blob.0.len()),
|
||||
Op::Rotate { .. } => f.write_str("Outgoing(rotate)"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -138,7 +171,7 @@ struct Ack {
|
||||
#[derive(Debug)]
|
||||
pub struct Received {
|
||||
pub events: Vec<Event>,
|
||||
/// Our answering `hello`s.
|
||||
/// 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>,
|
||||
@@ -161,9 +194,13 @@ enum Payload {
|
||||
post_token: Token,
|
||||
name: String,
|
||||
},
|
||||
Text {
|
||||
body: String,
|
||||
},
|
||||
/// `seq` counts this sender's texts to this contact, from 1.
|
||||
Text { body: String, seq: u64 },
|
||||
/// The receiver has saved our texts up to `upto`.
|
||||
Receipt { upto: u64 },
|
||||
/// A new post token for the mailbox the receiver already knows (unblock).
|
||||
#[serde(rename_all = "camelCase")]
|
||||
Inbox { post_token: Token },
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
@@ -189,6 +226,12 @@ struct Contact {
|
||||
outbox: Option<(MailboxId, Token)>,
|
||||
/// The invite this contact came through, on the inviter's side.
|
||||
via: Option<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,
|
||||
}
|
||||
|
||||
pub struct Client<T: Transport> {
|
||||
@@ -201,6 +244,8 @@ pub struct Client<T: Transport> {
|
||||
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> {
|
||||
@@ -230,6 +275,7 @@ impl<T: Transport> Client<T> {
|
||||
contacts: Vec::new(),
|
||||
welcome_boxes: Vec::new(),
|
||||
next_contact: 0,
|
||||
receipts: true,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -355,16 +401,8 @@ impl<T: Transport> Client<T> {
|
||||
.map_err(|_| ClientError::Mls)?;
|
||||
let hello = Self::seal(&self.provider, &self.signer, &mut group, &hello)?;
|
||||
let out = vec![
|
||||
Outgoing {
|
||||
to: welcome_id,
|
||||
post: welcome_post,
|
||||
blob: Bytes(welcome),
|
||||
},
|
||||
Outgoing {
|
||||
to: welcome_id,
|
||||
post: welcome_post,
|
||||
blob: Bytes(hello),
|
||||
},
|
||||
Outgoing::post(welcome_id, welcome_post, welcome),
|
||||
Outgoing::post(welcome_id, welcome_post, hello),
|
||||
];
|
||||
let id = self.add_contact(group, Some(inbox), None, None);
|
||||
Ok((id, out))
|
||||
@@ -395,6 +433,9 @@ impl<T: Transport> Client<T> {
|
||||
inbox,
|
||||
outbox,
|
||||
via,
|
||||
blocked: false,
|
||||
sent_seq: 0,
|
||||
received_seq: 0,
|
||||
});
|
||||
id
|
||||
}
|
||||
@@ -429,27 +470,118 @@ impl<T: Transport> Client<T> {
|
||||
.find(|c| c.id == contact)
|
||||
.ok_or(ClientError::UnknownContact)?;
|
||||
let (to, post) = c.outbox.ok_or(ClientError::UnknownContact)?;
|
||||
let seq = c.sent_seq + 1;
|
||||
let blob = Self::seal(
|
||||
&self.provider,
|
||||
&self.signer,
|
||||
&mut c.group,
|
||||
&Payload::Text {
|
||||
body: text.to_string(),
|
||||
seq,
|
||||
},
|
||||
)?;
|
||||
Ok(Outgoing {
|
||||
to,
|
||||
post,
|
||||
blob: Bytes(blob),
|
||||
})
|
||||
c.sent_seq = seq;
|
||||
Ok(Outgoing::post(to, post, blob))
|
||||
}
|
||||
|
||||
/// Posts one blob to the relay.
|
||||
/// The `seq` of our last text to a contact: right after [`Client::compose`], the one it made.
|
||||
pub fn sent_seq(&self, contact: ContactId) -> Option<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> {
|
||||
self.transport.post(&out.to, &out.post, &out.blob.0)?;
|
||||
match &out.0 {
|
||||
Op::Post { to, post, blob } => self.transport.post(to, post, &blob.0)?,
|
||||
Op::Rotate {
|
||||
mailbox,
|
||||
fetch,
|
||||
post_token_hash,
|
||||
} => self
|
||||
.transport
|
||||
.rotate_post_token(mailbox, fetch, post_token_hash)?,
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A post waiting in an app's outbox, with the contact's current post token: after an
|
||||
/// unblock on their side, the token it was sealed with is refused. The blob is unchanged.
|
||||
pub fn readdress(&self, out: &Outgoing) -> Outgoing {
|
||||
if let Op::Post { to, blob, .. } = &out.0 {
|
||||
if let Some((_, post)) = self
|
||||
.contacts
|
||||
.iter()
|
||||
.filter_map(|c| c.outbox)
|
||||
.find(|(mailbox, _)| mailbox == to)
|
||||
{
|
||||
return Outgoing::post(*to, post, blob.0.clone());
|
||||
}
|
||||
}
|
||||
out.clone()
|
||||
}
|
||||
|
||||
/// Blocks a contact, staged: they are marked, and their way into our mailbox is closed by a
|
||||
/// rotate to the hash of a fresh token that nobody gets. Nothing is sent to them. Save the
|
||||
/// snapshot, then deliver the result.
|
||||
pub fn block(&mut self, contact: ContactId) -> Result<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)?;
|
||||
@@ -488,6 +620,11 @@ impl<T: Transport> Client<T> {
|
||||
.iter()
|
||||
.filter_map(|c| c.inbox.map(|m| (m, None))),
|
||||
);
|
||||
let before: Vec<(ContactId, u64)> = self
|
||||
.contacts
|
||||
.iter()
|
||||
.map(|c| (c.id, c.received_seq))
|
||||
.collect();
|
||||
for (mailbox, via) in sources {
|
||||
let blobs = match self.transport.fetch(&mailbox.id, &mailbox.fetch) {
|
||||
Ok(blobs) => blobs,
|
||||
@@ -531,16 +668,31 @@ impl<T: Transport> Client<T> {
|
||||
continue;
|
||||
};
|
||||
c.inbox = Some(inbox);
|
||||
got.outgoing.push(Outgoing {
|
||||
to,
|
||||
post,
|
||||
blob: Bytes(blob),
|
||||
});
|
||||
got.outgoing.push(Outgoing::post(to, post, blob));
|
||||
}
|
||||
Err(ClientError::Transport(e)) => got.interrupted = Some(e),
|
||||
Err(_) => continue,
|
||||
}
|
||||
}
|
||||
// Receipts, for every contact whose texts arrived now. Delivered by `finish`, so only
|
||||
// after the app has saved the texts.
|
||||
if self.receipts {
|
||||
for (id, was) in before {
|
||||
let Some(c) = self.contacts.iter_mut().find(|c| c.id == id) else {
|
||||
continue;
|
||||
};
|
||||
let Some((to, post)) = c.outbox else { continue };
|
||||
if c.received_seq == was || c.blocked {
|
||||
continue;
|
||||
}
|
||||
let receipt = Payload::Receipt {
|
||||
upto: c.received_seq,
|
||||
};
|
||||
if let Ok(blob) = Self::seal(&self.provider, &self.signer, &mut c.group, &receipt) {
|
||||
got.outgoing.push(Outgoing::post(to, post, blob));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(got)
|
||||
}
|
||||
|
||||
@@ -551,9 +703,16 @@ impl<T: Transport> Client<T> {
|
||||
/// is never fetched. Not before: a snapshot saved between `receive` and `finish` must still
|
||||
/// know the mailbox, so that a restored client fetches its blobs again and acknowledges them.
|
||||
/// Save the snapshot again after `finish`.
|
||||
///
|
||||
/// A post the relay refuses with 404 is skipped: that mailbox's token is gone (we may be
|
||||
/// blocked), and trying again cannot help. Without the skip, one refused receipt would keep
|
||||
/// everything fetched from being acknowledged, for ever.
|
||||
pub fn finish(&mut self, received: &Received) -> Result<(), ClientError> {
|
||||
for out in &received.outgoing {
|
||||
self.deliver(out)?;
|
||||
match self.deliver(out) {
|
||||
Ok(()) | Err(ClientError::Transport(TransportError::NotFound)) => {}
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
}
|
||||
for ack in &received.acks {
|
||||
self.transport
|
||||
@@ -653,17 +812,42 @@ impl<T: Transport> Client<T> {
|
||||
via: c.via,
|
||||
}))
|
||||
}
|
||||
Payload::Text { body } => {
|
||||
let c = &self.contacts[index];
|
||||
Payload::Text { body, seq } => {
|
||||
let c = &mut self.contacts[index];
|
||||
if c.name.is_none() {
|
||||
// Text before hello: not from a conversation that has been set up.
|
||||
return Err(ClientError::Mls);
|
||||
}
|
||||
if c.blocked {
|
||||
// Posted before the block, or fetched after it: dropped, never shown.
|
||||
return Ok(None);
|
||||
}
|
||||
c.received_seq = c.received_seq.max(seq);
|
||||
Ok(Some(Event::Message {
|
||||
contact: c.id,
|
||||
text: body,
|
||||
}))
|
||||
}
|
||||
Payload::Receipt { upto } => {
|
||||
let c = &self.contacts[index];
|
||||
if !self.receipts || c.name.is_none() || c.blocked {
|
||||
return Ok(None);
|
||||
}
|
||||
// A receipt cannot mark what was never sent.
|
||||
Ok(Some(Event::Delivered {
|
||||
contact: c.id,
|
||||
upto: upto.min(c.sent_seq),
|
||||
}))
|
||||
}
|
||||
Payload::Inbox { post_token } => {
|
||||
let c = &mut self.contacts[index];
|
||||
// Only the token changes: the mailbox stays the one their hello named.
|
||||
let Some((mailbox, _)) = c.outbox else {
|
||||
return Err(ClientError::Mls);
|
||||
};
|
||||
c.outbox = Some((mailbox, post_token));
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -703,4 +887,43 @@ mod tests {
|
||||
assert_eq!(eva.contacts[0].outbox.map(|(m, _)| m), before);
|
||||
assert_eq!(eva.contacts[0].name.as_deref(), Some("Jan"));
|
||||
}
|
||||
|
||||
/// `inbox` (unblock) changes only the token for the mailbox their hello named.
|
||||
#[test]
|
||||
fn an_inbox_payload_changes_the_token_not_the_mailbox() {
|
||||
let relay = MemoryTransport::default();
|
||||
let mut eva = Client::new("Eva", relay.clone()).expect("eva");
|
||||
let mut jan = Client::new("Jan", relay.clone()).expect("jan");
|
||||
let invite = eva.create_invite().expect("invite");
|
||||
jan.accept_invite(&invite).expect("accept");
|
||||
eva.poll().expect("poll");
|
||||
let (mailbox, before) = eva.contacts[0].outbox.expect("outbox");
|
||||
let fresh = Token::from_bytes([5; 32]);
|
||||
let inbox = Payload::Inbox { post_token: fresh };
|
||||
assert_eq!(eva.receive_payload(0, inbox), Ok(None));
|
||||
let (still, after) = eva.contacts[0].outbox.expect("outbox");
|
||||
assert_eq!(still, mailbox);
|
||||
assert_ne!(after.hash(), before.hash());
|
||||
assert_eq!(after.hash(), fresh.hash());
|
||||
}
|
||||
|
||||
/// A receipt cannot mark texts that were never sent.
|
||||
#[test]
|
||||
fn a_receipt_is_capped_at_what_was_sent() {
|
||||
let relay = MemoryTransport::default();
|
||||
let mut eva = Client::new("Eva", relay.clone()).expect("eva");
|
||||
let mut jan = Client::new("Jan", relay.clone()).expect("jan");
|
||||
let invite = eva.create_invite().expect("invite");
|
||||
jan.accept_invite(&invite).expect("accept");
|
||||
eva.poll().expect("poll");
|
||||
eva.send(eva.contacts[0].id, "jedna").expect("send");
|
||||
let got = eva.receive_payload(0, Payload::Receipt { upto: 99 });
|
||||
assert_eq!(
|
||||
got,
|
||||
Ok(Some(Event::Delivered {
|
||||
contact: eva.contacts[0].id,
|
||||
upto: 1
|
||||
}))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,6 +47,17 @@ struct ContactState {
|
||||
inbox: Option<Mailbox>,
|
||||
outbox: Option<(MailboxId, Token)>,
|
||||
via: Option<InviteId>,
|
||||
// F24; absent in older snapshots.
|
||||
#[serde(default)]
|
||||
blocked: bool,
|
||||
#[serde(default)]
|
||||
sent_seq: u64,
|
||||
#[serde(default)]
|
||||
received_seq: u64,
|
||||
}
|
||||
|
||||
fn yes() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
@@ -59,6 +70,8 @@ struct State {
|
||||
contacts: Vec<ContactState>,
|
||||
welcome_boxes: Vec<WelcomeBox>,
|
||||
next_contact: u32,
|
||||
#[serde(default = "yes")]
|
||||
receipts: bool,
|
||||
/// OpenMLS's storage: every key and value, sorted by key so equal states give equal bytes.
|
||||
storage: Vec<(Bytes, Bytes)>,
|
||||
}
|
||||
@@ -91,10 +104,14 @@ impl<T: Transport> Client<T> {
|
||||
inbox: c.inbox,
|
||||
outbox: c.outbox,
|
||||
via: c.via,
|
||||
blocked: c.blocked,
|
||||
sent_seq: c.sent_seq,
|
||||
received_seq: c.received_seq,
|
||||
})
|
||||
.collect(),
|
||||
welcome_boxes: self.welcome_boxes.clone(),
|
||||
next_contact: self.next_contact,
|
||||
receipts: self.receipts,
|
||||
storage,
|
||||
};
|
||||
serde_json::to_vec(&state).map_err(|_| ClientError::State)
|
||||
@@ -143,6 +160,9 @@ impl<T: Transport> Client<T> {
|
||||
inbox: c.inbox,
|
||||
outbox: c.outbox,
|
||||
via: c.via,
|
||||
blocked: c.blocked,
|
||||
sent_seq: c.sent_seq,
|
||||
received_seq: c.received_seq,
|
||||
});
|
||||
}
|
||||
Ok(Client {
|
||||
@@ -155,6 +175,7 @@ impl<T: Transport> Client<T> {
|
||||
contacts,
|
||||
welcome_boxes: state.welcome_boxes,
|
||||
next_contact: state.next_contact,
|
||||
receipts: state.receipts,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,6 +32,13 @@ pub trait Transport {
|
||||
hash: &Sha256Hash,
|
||||
) -> Result<(), TransportError>;
|
||||
fn create_invite(&self, req: &CreateInvite) -> Result<(), TransportError>;
|
||||
/// Block: the mailbox's post token becomes `new_hash`'s; the old one is refused from now on.
|
||||
fn rotate_post_token(
|
||||
&self,
|
||||
id: &MailboxId,
|
||||
fetch: &Token,
|
||||
new_hash: &Sha256Hash,
|
||||
) -> Result<(), TransportError>;
|
||||
/// The KeyPackage, once.
|
||||
fn claim_invite(&self, id: &InviteId, secret: &Token) -> Result<Vec<u8>, TransportError>;
|
||||
}
|
||||
@@ -129,6 +136,21 @@ impl Transport for MemoryTransport {
|
||||
}
|
||||
}
|
||||
|
||||
fn rotate_post_token(
|
||||
&self,
|
||||
id: &MailboxId,
|
||||
fetch: &Token,
|
||||
new_hash: &Sha256Hash,
|
||||
) -> Result<(), TransportError> {
|
||||
match self.boxes().mailboxes.get_mut(id) {
|
||||
Some((post, f, _)) if *f == fetch.hash() => {
|
||||
*post = *new_hash;
|
||||
Ok(())
|
||||
}
|
||||
_ => Err(TransportError::NotFound),
|
||||
}
|
||||
}
|
||||
|
||||
fn create_invite(&self, req: &CreateInvite) -> Result<(), TransportError> {
|
||||
let mut b = self.boxes();
|
||||
if b.invites.contains_key(&req.id) {
|
||||
|
||||
Reference in New Issue
Block a user