Skip to main content

weirdnet_sync/
protocol.rs

1//! `weirdnet-sync/v1` messages and length-prefixed CBOR framing.
2//!
3//! After the authenticated channel is up, payloads that carry records, cursors or
4//! certificates are sealed under [`crate::sync_key`]. An [`Envelope`] carries the type and
5//! epoch in the clear so the receiver can pick the key; the body is sealed.
6use crate::error::{Result, SyncError};
7use crate::hlc::{Hlc, NodeId};
8use crate::log::{LogEntry, Page as LogPage};
9use crate::rotation::KeyChain;
10use crate::seal::{open_page, page_aad_keyed, rotated_sync_key, seal_page, sync_key};
11use serde::{Deserialize, Serialize};
12use weirdnet_keys::{Key32, Sealed};
13use weirdnet_net::profile::{Profile, WEIRDNET};
14use weirdnet_net::user::NodeCert;
15use zeroize::Zeroizing;
16
17/// Request-response protocol id, same style as `/weirdnet/link/1`.
18pub const PROTOCOL: &str = "/weirdnet/sync/1";
19
20/// Largest sealed page (and the reply cap to set on a sync node). Still under weirdnet-net's 8 MiB default.
21pub const PAGE_MAX: usize = 256 * 1024;
22
23/// Plaintext budget for the ops in one page. The sealed body is hex in the envelope, and
24/// weirdnet-net's request-response CBOR sends the envelope bytes as an array of integers
25/// (two bytes each for hex digits), so a page is about four times its plaintext on the
26/// wire. This keeps a full page under [`PAGE_MAX`], which is also what a 0.3 puller accepts.
27pub const PAGE_BUDGET: usize = (PAGE_MAX - 16 * 1024) / 4;
28
29/// Identifier profile: `/weirdnet/sync/1` for request-response, otherwise [`WEIRDNET`].
30pub static SYNC_PROFILE: Profile = Profile { protocol: PROTOCOL, thread: "weirdnet-sync", ..WEIRDNET };
31
32/// Last seq applied from each node, as sent in Hello.
33pub type Cursors = Vec<(NodeId, u64)>;
34
35#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
36pub struct Hello {
37    pub cert: NodeCert,
38    pub user_id: String,
39    pub epoch: u32,
40    pub types: Vec<String>,
41    pub our_cursors: Cursors,
42    pub our_hlc: Hlc,
43    /// The sender's key chain, so device keys and rotations spread. Absent from 0.2.
44    #[serde(default)]
45    pub chain: KeyChain,
46}
47
48#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
49pub struct HelloOk {
50    pub cert: NodeCert,
51    pub epoch: u32,
52    pub cursors: Cursors,
53    pub revocations: Vec<NodeCert>,
54    #[serde(default)]
55    pub chain: KeyChain,
56}
57
58#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
59pub struct Refuse {
60    pub reason: String,
61}
62
63impl Refuse {
64    pub fn new(reason: &'static str) -> Self {
65        Self { reason: reason.into() }
66    }
67}
68
69pub type RefuseReason = Refuse;
70
71#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
72pub struct Pull {
73    pub node_id: NodeId,
74    pub after_seq: u64,
75    pub typ: String,
76    pub limit: u32,
77}
78
79#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
80pub struct Page {
81    pub typ: String,
82    pub page: LogPage,
83}
84
85#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
86pub struct Ack {
87    pub node_id: NodeId,
88    pub last_seq: u64,
89}
90
91#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
92pub struct RosterMsg {
93    pub certs: Vec<NodeCert>,
94    pub epoch: u32,
95    /// Device keys, rotations (with the sealed epoch keys) and admissions.
96    #[serde(default)]
97    pub chain: KeyChain,
98}
99
100/// Application-level message, before sealing.
101#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
102#[serde(tag = "kind", rename_all = "kebab-case")]
103pub enum Message {
104    Hello(Hello),
105    HelloOk(HelloOk),
106    Refuse(Refuse),
107    Pull(Pull),
108    Page(Page),
109    Ack(Ack),
110    Roster(RosterMsg),
111}
112
113/// What goes on the request-response wire: type, epoch and (after a rotation) the
114/// rotation id in the clear, body sealed.
115#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
116pub struct Envelope {
117    pub typ: String,
118    pub epoch: u32,
119    /// Rotation id of the epoch key; `None` for the seed-derived key.
120    #[serde(default, skip_serializing_if = "Option::is_none")]
121    pub key: Option<String>,
122    pub sealed: Sealed,
123}
124
125/// Which key an envelope is sealed under: the seed-derived one at `epoch`, or the
126/// rotated one with this id.
127#[derive(Debug, Clone, PartialEq, Eq)]
128pub struct KeyRef {
129    pub epoch: u32,
130    pub id: Option<String>,
131}
132
133impl KeyRef {
134    pub fn seed(epoch: u32) -> Self {
135        Self { epoch, id: None }
136    }
137}
138
139impl Envelope {
140    /// Seal under a rotated epoch key (rotation `id`).
141    pub fn seal_keyed(epoch_key: &Key32, id: &str, user_id: &str, typ: &str, epoch: u32, asking_peer: &str, msg: &Message) -> Result<Self> {
142        let key = rotated_sync_key(epoch_key, user_id, typ, epoch, id)?;
143        let plain = encode(msg)?;
144        let sealed = weirdnet_keys::seal(&key, &plain, &page_aad_keyed(typ, epoch, id, asking_peer))?;
145        Ok(Self { typ: typ.into(), epoch, key: Some(id.into()), sealed })
146    }
147
148    pub fn open_keyed(&self, epoch_key: &Key32, user_id: &str, asking_peer: &str) -> Result<Message> {
149        let id = self.key.as_deref().ok_or_else(|| SyncError::Crypto("not sealed under a rotated key".into()))?;
150        let key = rotated_sync_key(epoch_key, user_id, &self.typ, self.epoch, id)?;
151        let plain: Zeroizing<Vec<u8>> = weirdnet_keys::open(&key, &self.sealed, &page_aad_keyed(&self.typ, self.epoch, id, asking_peer))?;
152        decode(&plain)
153    }
154
155    pub fn seal(seed: &[u8], user_id: &str, typ: &str, epoch: u32, asking_peer: &str, msg: &Message) -> Result<Self> {
156        let key = sync_key(seed, user_id, typ, epoch)?;
157        let plain = encode(msg)?;
158        let sealed = seal_page(&key, typ, epoch, asking_peer, &plain)?;
159        Ok(Self { typ: typ.into(), epoch, key: None, sealed })
160    }
161
162    /// Open a seed-sealed envelope. One sealed under a rotated key fails here.
163    pub fn open(&self, seed: &[u8], user_id: &str, asking_peer: &str) -> Result<Message> {
164        if self.key.is_some() {
165            return Err(SyncError::Crypto("sealed under a rotated key".into()));
166        }
167        let key = sync_key(seed, user_id, &self.typ, self.epoch)?;
168        let plain: Zeroizing<Vec<u8>> = open_page(&key, &self.typ, self.epoch, asking_peer, &self.sealed)?;
169        decode(&plain)
170    }
171}
172
173/// Length-prefixed CBOR (u32 big-endian length, then the item). For a raw stream;
174/// `Node::request` already frames [`Envelope`] as CBOR through libp2p.
175pub fn encode<T: Serialize>(v: &T) -> Result<Vec<u8>> {
176    cbor4ii::serde::to_vec(Vec::new(), v).map_err(|e| SyncError::Codec(e.to_string()))
177}
178
179pub fn decode<'a, T: Deserialize<'a>>(bytes: &'a [u8]) -> Result<T> {
180    cbor4ii::serde::from_slice(bytes).map_err(|e| SyncError::Codec(e.to_string()))
181}
182
183pub fn encode_framed<T: Serialize>(v: &T) -> Result<Vec<u8>> {
184    let body = encode(v)?;
185    if body.len() > u32::MAX as usize {
186        return Err(SyncError::Codec("frame too large".into()));
187    }
188    let mut out = Vec::with_capacity(4 + body.len());
189    out.extend_from_slice(&(body.len() as u32).to_be_bytes());
190    out.extend_from_slice(&body);
191    Ok(out)
192}
193
194pub fn decode_framed<'a, T: Deserialize<'a>>(bytes: &'a [u8]) -> Result<T> {
195    if bytes.len() < 4 {
196        return Err(SyncError::Codec("short frame".into()));
197    }
198    let n = u32::from_be_bytes(bytes[..4].try_into().unwrap()) as usize;
199    if bytes.len() != 4 + n {
200        return Err(SyncError::Codec(format!("frame length {n} does not match {}", bytes.len().saturating_sub(4))));
201    }
202    decode(&bytes[4..])
203}
204
205/// Build a `Page` message from a log page, dropping ops whose typ does not match (they
206/// stay in the log for a later pull of that type).
207pub fn page_for_type(typ: &str, page: LogPage) -> Page {
208    let ops: Vec<LogEntry> = page.ops.into_iter().filter(|e| e.typ == typ).collect();
209    let from_seq = ops.first().map(|e| e.seq).unwrap_or(page.from_seq);
210    let to_seq = ops.last().map(|e| e.seq).unwrap_or(page.to_seq);
211    Page { typ: typ.into(), page: LogPage { node_id: page.node_id, from_seq, to_seq, ops } }
212}
213
214#[cfg(test)]
215mod tests {
216    use super::*;
217    use crate::hlc::Hlc;
218    use crate::roster::Roster;
219    use weirdnet_net::Keypair;
220    use weirdnet_net::user;
221
222    const SEED: [u8; 32] = *b"CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC";
223
224    fn hello() -> (Message, String, Keypair) {
225        let u = Keypair::generate_ed25519();
226        let uid = user::user_id(&u.public());
227        let cert = Roster::self_certify(&WEIRDNET, &u, "peer-a", "a", 1).unwrap();
228        let msg = Message::Hello(Hello {
229            cert,
230            user_id: uid.clone(),
231            epoch: 0,
232            types: vec!["bookmarks".into()],
233            our_cursors: vec![(NodeId::new("peer-a"), 3)],
234            our_hlc: Hlc::new(10, 0, NodeId::new("peer-a")),
235            chain: Default::default(),
236        });
237        (msg, uid, u)
238    }
239
240    #[test]
241    fn a_full_page_fits_the_reply_cap_once_sealed() {
242        use crate::log::OpLog;
243        let (_, uid, _) = hello();
244        let mut log = OpLog::new();
245        let node = NodeId::new("peer-a");
246        for i in 0..400u64 {
247            log.append(node.clone(), Hlc::new(i, 0, node.clone()), "bookmarks", format!("r{i}"), vec![7u8; 1500]);
248        }
249        let known = log.cursor_for(&node, "bookmarks");
250        let page = log.page_of_type(&node, "bookmarks", 0, known, 4096);
251        assert!(page.ops.len() > 10 && page.to_seq < 400, "the budget split the stream");
252        let msg = Message::Page(Page { typ: "bookmarks".into(), page });
253        let env = Envelope::seal(&SEED, &uid, "bookmarks", 0, "peer-b", &msg).unwrap();
254        // What the request-response codec sends: the envelope bytes as a CBOR value.
255        let wire = |env: &Envelope| encode(&encode(env).unwrap()).unwrap().len();
256        assert!(wire(&env) <= PAGE_MAX, "sealed page is {} bytes on the wire, cap {PAGE_MAX}", wire(&env));
257        assert!(wire(&env) > PAGE_MAX / 2, "the budget is not far too small");
258        let page = log.page(&node, 0, 4096);
259        let env = Envelope::seal(&SEED, &uid, "bookmarks", 0, "peer-b", &Message::Page(Page { typ: "bookmarks".into(), page })).unwrap();
260        assert!(wire(&env) <= PAGE_MAX);
261    }
262
263    #[test]
264    fn framed_cbor_round_trips_and_rejects_a_truncated_frame() {
265        let (msg, _, _) = hello();
266        let bytes = encode_framed(&msg).unwrap();
267        assert_eq!(u32::from_be_bytes(bytes[..4].try_into().unwrap()) as usize, bytes.len() - 4);
268        let back: Message = decode_framed(&bytes).unwrap();
269        assert_eq!(back, msg);
270        assert!(decode_framed::<Message>(&bytes[..3]).is_err());
271        assert!(decode_framed::<Message>(&bytes[..bytes.len() - 1]).is_err());
272    }
273
274    #[test]
275    fn a_sealed_hello_opens_for_the_same_seed_and_user_only() {
276        let (msg, uid, _) = hello();
277        let env = Envelope::seal(&SEED, &uid, "bookmarks", 0, "peer-b", &msg).unwrap();
278        let opened = env.open(&SEED, &uid, "peer-b").unwrap();
279        assert_eq!(opened, msg);
280        assert!(env.open(&SEED, "other-user", "peer-b").is_err());
281        assert!(env.open(&SEED, &uid, "peer-c").is_err());
282        assert!(Envelope { typ: "history".into(), ..env.clone() }.open(&SEED, &uid, "peer-b").is_err());
283    }
284
285    #[test]
286    fn seed_envelopes_and_rosters_keep_the_0_2_wire_shape() {
287        #[derive(Serialize, Deserialize, PartialEq, Debug)]
288        struct EnvelopeV02 {
289            typ: String,
290            epoch: u32,
291            sealed: Sealed,
292        }
293        let (msg, uid, _) = hello();
294        let env = Envelope::seal(&SEED, &uid, "bookmarks", 0, "peer-b", &msg).unwrap();
295        let old: EnvelopeV02 = decode(&encode(&env).unwrap()).unwrap();
296        assert_eq!(encode(&old).unwrap(), encode(&env).unwrap(), "no key field on a seed envelope");
297        let back: Envelope = decode(&encode(&old).unwrap()).unwrap();
298        assert_eq!(back.key, None);
299        #[derive(Serialize)]
300        #[serde(tag = "kind", rename_all = "kebab-case")]
301        enum OldMessage {
302            Roster { certs: Vec<NodeCert>, epoch: u32 },
303        }
304        let old = encode(&OldMessage::Roster { certs: vec![], epoch: 3 }).unwrap();
305        assert_eq!(decode::<Message>(&old).unwrap(), Message::Roster(RosterMsg { certs: vec![], epoch: 3, chain: KeyChain::default() }));
306        // A keyed envelope never opens as a seed one.
307        let k = Key32::random().unwrap();
308        let keyed = Envelope::seal_keyed(&k, "r1", &uid, "bookmarks", 1, "peer-b", &msg).unwrap();
309        assert!(keyed.open(&SEED, &uid, "peer-b").is_err());
310        assert_eq!(keyed.open_keyed(&k, &uid, "peer-b").unwrap(), msg);
311        assert!(keyed.open_keyed(&k, &uid, "peer-c").is_err());
312        assert!(Envelope { key: Some("r2".into()), ..keyed.clone() }.open_keyed(&k, &uid, "peer-b").is_err());
313    }
314}