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.
208 lines
6.9 KiB
Rust
208 lines
6.9 KiB
Rust
//! 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, PollState, 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>);
|
|
|
|
/// Shows the length only: these bytes are a group's state or a thumbnail.
|
|
impl std::fmt::Debug for Bytes {
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
write!(f, "Bytes({})", self.0.len())
|
|
}
|
|
}
|
|
|
|
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>,
|
|
// F24; absent in older snapshots.
|
|
#[serde(default)]
|
|
blocked: bool,
|
|
#[serde(default)]
|
|
sent_seq: u64,
|
|
#[serde(default)]
|
|
received_seq: u64,
|
|
// F28 (`.agents/features/polls.md` §2.3); absent in older snapshots.
|
|
#[serde(default)]
|
|
polls: Vec<PollState>,
|
|
}
|
|
|
|
fn yes() -> bool {
|
|
true
|
|
}
|
|
|
|
#[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,
|
|
#[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)>,
|
|
}
|
|
|
|
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,
|
|
blocked: c.blocked,
|
|
sent_seq: c.sent_seq,
|
|
received_seq: c.received_seq,
|
|
polls: c.polls.clone(),
|
|
})
|
|
.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)
|
|
}
|
|
|
|
/// 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,
|
|
blocked: c.blocked,
|
|
sent_seq: c.sent_seq,
|
|
received_seq: c.received_seq,
|
|
polls: c.polls,
|
|
});
|
|
}
|
|
Ok(Client {
|
|
provider,
|
|
signer,
|
|
credential,
|
|
identity: state.identity.0,
|
|
name: state.name,
|
|
transport,
|
|
contacts,
|
|
welcome_boxes: state.welcome_boxes,
|
|
next_contact: state.next_contact,
|
|
receipts: state.receipts,
|
|
})
|
|
}
|
|
}
|
|
|
|
#[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);
|
|
}
|
|
}
|