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::roster::DeviceGrant;
10use crate::rotation::KeyChain;
11use crate::seal::{SyncKey, open_page, page_aad_keyed, rotated_sync_key, seal_page, sync_key};
12use serde::{Deserialize, Serialize};
13use weirdnet_keys::{Key32, Sealed};
14use weirdnet_net::profile::{Profile, WEIRDNET};
15use weirdnet_net::user::NodeCert;
16use zeroize::Zeroizing;
17
18/// Request-response protocol id. `/2` since weirdnet-net 0.8 sends byte fields as CBOR byte
19/// strings; a 0.4 (`/1`) node fails to negotiate instead of failing to decode.
20pub const PROTOCOL: &str = "/weirdnet/sync/2";
21
22/// Largest sealed page on the wire (and the request and reply cap to set on a sync node).
23pub const PAGE_MAX: usize = 256 * 1024;
24
25/// Plaintext budget for the ops in one page. The sealed body is hex in the envelope (two
26/// bytes per plaintext byte), and weirdnet-net 0.8 sends the encoded envelope as one CBOR
27/// byte string (one byte per byte, a few bytes of header). So a page is about twice its
28/// plaintext on the wire, plus the envelope fields. This reserves 16 KiB for those and for
29/// the gap between [`LogEntry::wire_size`](crate::log::LogEntry::wire_size) and the real
30/// encoding (which is an estimate), then halves the rest: a full page is about 120 KiB
31/// plus slack under [`PAGE_MAX`]. (Through 0.4 this was a quarter, because 0.7 sent the
32/// bytes as integer arrays.)
33pub const PAGE_BUDGET: usize = (PAGE_MAX - 16 * 1024) / 2 - 8 * 1024;
34
35/// Identifier profile: `/weirdnet/sync/2` for request-response, otherwise [`WEIRDNET`].
36pub static SYNC_PROFILE: Profile = Profile { protocol: PROTOCOL, thread: "weirdnet-sync", ..WEIRDNET };
37
38/// Last seq applied from each node, as sent in Hello.
39pub type Cursors = Vec<(NodeId, u64)>;
40
41#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
42pub struct Hello {
43    pub cert: NodeCert,
44    pub user_id: String,
45    pub epoch: u32,
46    pub types: Vec<String>,
47    pub our_cursors: Cursors,
48    pub our_hlc: Hlc,
49    /// The sender's key chain, so device keys and rotations spread. Absent from 0.2.
50    #[serde(default)]
51    pub chain: KeyChain,
52}
53
54#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
55pub struct HelloOk {
56    pub cert: NodeCert,
57    pub epoch: u32,
58    pub cursors: Cursors,
59    /// The answering node's certs. Since 0.5.2 every cert, active and revoked (the name
60    /// is kept for the wire); before that only the revoked ones.
61    pub revocations: Vec<NodeCert>,
62    #[serde(default)]
63    pub chain: KeyChain,
64    /// The answering node's device grants (roles, service class). Absent before 0.7.
65    #[serde(default, skip_serializing_if = "Vec::is_empty")]
66    pub grants: Vec<DeviceGrant>,
67}
68
69#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
70pub struct Refuse {
71    pub reason: String,
72}
73
74impl Refuse {
75    pub fn new(reason: &'static str) -> Self {
76        Self { reason: reason.into() }
77    }
78}
79
80pub type RefuseReason = Refuse;
81
82#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
83pub struct Pull {
84    pub node_id: NodeId,
85    pub after_seq: u64,
86    pub typ: String,
87    pub limit: u32,
88}
89
90#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
91pub struct Page {
92    pub typ: String,
93    pub page: LogPage,
94}
95
96#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
97pub struct Ack {
98    pub node_id: NodeId,
99    pub last_seq: u64,
100}
101
102#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
103pub struct RosterMsg {
104    pub certs: Vec<NodeCert>,
105    pub epoch: u32,
106    /// Device keys, rotations (with the sealed epoch keys) and admissions.
107    #[serde(default)]
108    pub chain: KeyChain,
109    /// Device grants (roles, service class). Absent before 0.7.
110    #[serde(default, skip_serializing_if = "Vec::is_empty")]
111    pub grants: Vec<DeviceGrant>,
112}
113
114/// Application-level message, before sealing.
115#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
116#[serde(tag = "kind", rename_all = "kebab-case")]
117pub enum Message {
118    Hello(Hello),
119    HelloOk(HelloOk),
120    Refuse(Refuse),
121    Pull(Pull),
122    Page(Page),
123    Ack(Ack),
124    Roster(RosterMsg),
125    /// Leases (0.8): a candidate's ask, a voter's grant or denial, a release.
126    LeaseAsk(crate::lease::LeaseAsk),
127    LeaseGrant(crate::lease::LeaseGrant),
128    LeaseDeny(crate::lease::LeaseDeny),
129    LeaseFree(crate::lease::LeaseFree),
130}
131
132/// What goes on the request-response wire: type, epoch and (after a rotation) the
133/// rotation id in the clear, body sealed.
134#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
135pub struct Envelope {
136    pub typ: String,
137    pub epoch: u32,
138    /// Rotation id of the epoch key; `None` for the seed-derived key.
139    #[serde(default, skip_serializing_if = "Option::is_none")]
140    pub key: Option<String>,
141    pub sealed: Sealed,
142    /// Since 0.7: the body is not sealed (`sealed.ct` is the hex CBOR message). Only a
143    /// [`Message::Roster`] or a [`Message::Refuse`] travels this way: the roster is public
144    /// (every part verifies under the user key) and a refusal is a reason code, over a
145    /// stream Noise already authenticated. Service devices, which hold no seed, use it to
146    /// refuse and to fetch the roster. A 0.6 peer cannot open it.
147    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
148    pub clear: bool,
149}
150
151/// Which key an envelope is sealed under: the seed-derived one at `epoch`, or the
152/// rotated one with this id.
153#[derive(Debug, Clone, PartialEq, Eq)]
154pub struct KeyRef {
155    pub epoch: u32,
156    pub id: Option<String>,
157}
158
159impl KeyRef {
160    pub fn seed(epoch: u32) -> Self {
161        Self { epoch, id: None }
162    }
163}
164
165impl Envelope {
166    /// An unsealed envelope (see [`Envelope::clear`]). Only a roster or a refusal may be sent so.
167    pub fn clear(typ: &str, epoch: u32, msg: &Message) -> Result<Self> {
168        if !matches!(msg, Message::Roster(_) | Message::Refuse(_)) {
169            return Err(SyncError::Protocol("only a roster or a refusal travels unsealed".into()));
170        }
171        let plain = encode(msg)?;
172        Ok(Self { typ: typ.into(), epoch, key: None, sealed: Sealed { nonce: String::new(), ct: hex::encode(plain) }, clear: true })
173    }
174
175    /// The message of an unsealed envelope. Anything but a roster or a refusal is refused.
176    pub fn open_clear(&self) -> Result<Message> {
177        if !self.clear {
178            return Err(SyncError::Crypto("sealed envelope".into()));
179        }
180        let plain = hex::decode(&self.sealed.ct).map_err(|e| SyncError::Codec(e.to_string()))?;
181        let msg: Message = decode(&plain)?;
182        if !matches!(msg, Message::Roster(_) | Message::Refuse(_)) {
183            return Err(SyncError::Protocol("only a roster or a refusal travels unsealed".into()));
184        }
185        Ok(msg)
186    }
187
188    /// Seal under a rotated epoch key (rotation `id`).
189    pub fn seal_keyed(epoch_key: &Key32, id: &str, user_id: &str, typ: &str, epoch: u32, asking_peer: &str, msg: &Message) -> Result<Self> {
190        let key = rotated_sync_key(epoch_key, user_id, typ, epoch, id)?;
191        Self::seal_scoped(&key, id, typ, epoch, asking_peer, msg)
192    }
193
194    pub fn open_keyed(&self, epoch_key: &Key32, user_id: &str, asking_peer: &str) -> Result<Message> {
195        let id = self.key.as_deref().ok_or_else(|| SyncError::Crypto("not sealed under a rotated key".into()))?;
196        let key = rotated_sync_key(epoch_key, user_id, &self.typ, self.epoch, id)?;
197        self.open_scoped(&key, asking_peer)
198    }
199
200    /// Seal under a type-scoped key (since 0.8.3): `typ`'s [`SyncKey`] under rotation `id`,
201    /// as [`rotated_sync_key`] derives it from the epoch key and as a service device holds
202    /// it ([`crate::EpochKeys::get_scoped`]). The envelope is byte-for-byte the shape
203    /// [`Envelope::seal_keyed`] makes, so either side may hold the epoch key or the scoped key.
204    pub fn seal_scoped(key: &SyncKey, id: &str, typ: &str, epoch: u32, asking_peer: &str, msg: &Message) -> Result<Self> {
205        let plain = Zeroizing::new(encode(msg)?);
206        let sealed = weirdnet_keys::seal(key, &plain, &page_aad_keyed(typ, epoch, id, asking_peer))?;
207        Ok(Self { typ: typ.into(), epoch, key: Some(id.into()), sealed, clear: false })
208    }
209
210    /// Open an envelope sealed under a rotated key with its type-scoped key (since 0.8.3).
211    pub fn open_scoped(&self, key: &SyncKey, asking_peer: &str) -> Result<Message> {
212        let id = self.key.as_deref().ok_or_else(|| SyncError::Crypto("not sealed under a rotated key".into()))?;
213        let plain: Zeroizing<Vec<u8>> = weirdnet_keys::open(key, &self.sealed, &page_aad_keyed(&self.typ, self.epoch, id, asking_peer))?;
214        decode(&plain)
215    }
216
217    pub fn seal(seed: &[u8], user_id: &str, typ: &str, epoch: u32, asking_peer: &str, msg: &Message) -> Result<Self> {
218        let key = sync_key(seed, user_id, typ, epoch)?;
219        let plain = encode(msg)?;
220        let sealed = seal_page(&key, typ, epoch, asking_peer, &plain)?;
221        Ok(Self { typ: typ.into(), epoch, key: None, sealed, clear: false })
222    }
223
224    /// Open a seed-sealed envelope. One sealed under a rotated key fails here.
225    pub fn open(&self, seed: &[u8], user_id: &str, asking_peer: &str) -> Result<Message> {
226        if self.key.is_some() || self.clear {
227            return Err(SyncError::Crypto("sealed under a rotated key".into()));
228        }
229        let key = sync_key(seed, user_id, &self.typ, self.epoch)?;
230        let plain: Zeroizing<Vec<u8>> = open_page(&key, &self.typ, self.epoch, asking_peer, &self.sealed)?;
231        decode(&plain)
232    }
233}
234
235/// Length-prefixed CBOR (u32 big-endian length, then the item). For a raw stream;
236/// `Node::request` already frames [`Envelope`] as CBOR through libp2p.
237pub fn encode<T: Serialize>(v: &T) -> Result<Vec<u8>> {
238    cbor4ii::serde::to_vec(Vec::new(), v).map_err(|e| SyncError::Codec(e.to_string()))
239}
240
241pub fn decode<'a, T: Deserialize<'a>>(bytes: &'a [u8]) -> Result<T> {
242    cbor4ii::serde::from_slice(bytes).map_err(|e| SyncError::Codec(e.to_string()))
243}
244
245pub fn encode_framed<T: Serialize>(v: &T) -> Result<Vec<u8>> {
246    let body = encode(v)?;
247    if body.len() > u32::MAX as usize {
248        return Err(SyncError::Codec("frame too large".into()));
249    }
250    let mut out = Vec::with_capacity(4 + body.len());
251    out.extend_from_slice(&(body.len() as u32).to_be_bytes());
252    out.extend_from_slice(&body);
253    Ok(out)
254}
255
256pub fn decode_framed<'a, T: Deserialize<'a>>(bytes: &'a [u8]) -> Result<T> {
257    if bytes.len() < 4 {
258        return Err(SyncError::Codec("short frame".into()));
259    }
260    let n = u32::from_be_bytes(bytes[..4].try_into().unwrap()) as usize;
261    if bytes.len() != 4 + n {
262        return Err(SyncError::Codec(format!("frame length {n} does not match {}", bytes.len().saturating_sub(4))));
263    }
264    decode(&bytes[4..])
265}
266
267/// Build a `Page` message from a log page, dropping ops whose typ does not match (they
268/// stay in the log for a later pull of that type).
269pub fn page_for_type(typ: &str, page: LogPage) -> Page {
270    let ops: Vec<LogEntry> = page.ops.into_iter().filter(|e| e.typ == typ).collect();
271    let from_seq = ops.first().map(|e| e.seq).unwrap_or(page.from_seq);
272    let to_seq = ops.last().map(|e| e.seq).unwrap_or(page.to_seq);
273    Page { typ: typ.into(), page: LogPage { node_id: page.node_id, from_seq, to_seq, ops } }
274}
275
276#[cfg(test)]
277mod tests {
278    use super::*;
279    use crate::hlc::Hlc;
280    use crate::roster::Roster;
281    use weirdnet_net::Keypair;
282    use weirdnet_net::user;
283
284    const SEED: [u8; 32] = *b"CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC";
285
286    fn hello() -> (Message, String, Keypair) {
287        let u = Keypair::generate_ed25519();
288        let uid = user::user_id(&u.public());
289        let cert = Roster::self_certify(&WEIRDNET, &u, "peer-a", "a", 1).unwrap();
290        let msg = Message::Hello(Hello {
291            cert,
292            user_id: uid.clone(),
293            epoch: 0,
294            types: vec!["bookmarks".into()],
295            our_cursors: vec![(NodeId::new("peer-a"), 3)],
296            our_hlc: Hlc::new(10, 0, NodeId::new("peer-a")),
297            chain: Default::default(),
298        });
299        (msg, uid, u)
300    }
301
302    #[test]
303    fn a_full_page_fits_the_reply_cap_once_sealed() {
304        use crate::log::OpLog;
305        let (_, uid, _) = hello();
306        let mut log = OpLog::new();
307        let node = NodeId::new("peer-a");
308        for i in 0..400u64 {
309            log.append(node.clone(), Hlc::new(i, 0, node.clone()), "bookmarks", format!("r{i}"), vec![7u8; 1500]);
310        }
311        let known = log.cursor_for(&node, "bookmarks");
312        let page = log.page_of_type(&node, "bookmarks", 0, known, 4096);
313        assert!(page.ops.len() > 10 && page.to_seq < 400, "the budget split the stream");
314        let msg = Message::Page(Page { typ: "bookmarks".into(), page });
315        let env = Envelope::seal(&SEED, &uid, "bookmarks", 0, "peer-b", &msg).unwrap();
316        // What weirdnet-net 0.8 sends: the envelope bytes as one CBOR byte string.
317        let wire = |env: &Envelope| weirdnet_net::wire::to_vec(&encode(env).unwrap()).unwrap().len();
318        assert!(wire(&env) <= PAGE_MAX, "sealed page is {} bytes on the wire, cap {PAGE_MAX}", wire(&env));
319        assert!(wire(&env) > PAGE_MAX / 2, "the budget is not far too small ({})", wire(&env));
320        assert!(wire(&env) <= PAGE_MAX - 16 * 1024, "keeps a 16 KiB safety margin ({})", wire(&env));
321        let page = log.page(&node, 0, 4096);
322        let env = Envelope::seal(&SEED, &uid, "bookmarks", 0, "peer-b", &Message::Page(Page { typ: "bookmarks".into(), page })).unwrap();
323        assert!(wire(&env) <= PAGE_MAX);
324    }
325
326    #[test]
327    fn framed_cbor_round_trips_and_rejects_a_truncated_frame() {
328        let (msg, _, _) = hello();
329        let bytes = encode_framed(&msg).unwrap();
330        assert_eq!(u32::from_be_bytes(bytes[..4].try_into().unwrap()) as usize, bytes.len() - 4);
331        let back: Message = decode_framed(&bytes).unwrap();
332        assert_eq!(back, msg);
333        assert!(decode_framed::<Message>(&bytes[..3]).is_err());
334        assert!(decode_framed::<Message>(&bytes[..bytes.len() - 1]).is_err());
335    }
336
337    #[test]
338    fn a_sealed_hello_opens_for_the_same_seed_and_user_only() {
339        let (msg, uid, _) = hello();
340        let env = Envelope::seal(&SEED, &uid, "bookmarks", 0, "peer-b", &msg).unwrap();
341        let opened = env.open(&SEED, &uid, "peer-b").unwrap();
342        assert_eq!(opened, msg);
343        assert!(env.open(&SEED, "other-user", "peer-b").is_err());
344        assert!(env.open(&SEED, &uid, "peer-c").is_err());
345        assert!(Envelope { typ: "history".into(), ..env.clone() }.open(&SEED, &uid, "peer-b").is_err());
346    }
347
348    #[test]
349    fn seed_envelopes_and_rosters_keep_the_0_2_wire_shape() {
350        #[derive(Serialize, Deserialize, PartialEq, Debug)]
351        struct EnvelopeV02 {
352            typ: String,
353            epoch: u32,
354            sealed: Sealed,
355        }
356        let (msg, uid, _) = hello();
357        let env = Envelope::seal(&SEED, &uid, "bookmarks", 0, "peer-b", &msg).unwrap();
358        let old: EnvelopeV02 = decode(&encode(&env).unwrap()).unwrap();
359        assert_eq!(encode(&old).unwrap(), encode(&env).unwrap(), "no key field on a seed envelope");
360        let back: Envelope = decode(&encode(&old).unwrap()).unwrap();
361        assert_eq!(back.key, None);
362        #[derive(Serialize)]
363        #[serde(tag = "kind", rename_all = "kebab-case")]
364        enum OldMessage {
365            Roster { certs: Vec<NodeCert>, epoch: u32 },
366        }
367        let old = encode(&OldMessage::Roster { certs: vec![], epoch: 3 }).unwrap();
368        assert_eq!(
369            decode::<Message>(&old).unwrap(),
370            Message::Roster(RosterMsg { certs: vec![], epoch: 3, chain: KeyChain::default(), grants: vec![] })
371        );
372        // A keyed envelope never opens as a seed one.
373        let k = Key32::random().unwrap();
374        let keyed = Envelope::seal_keyed(&k, "r1", &uid, "bookmarks", 1, "peer-b", &msg).unwrap();
375        assert!(keyed.open(&SEED, &uid, "peer-b").is_err());
376        assert_eq!(keyed.open_keyed(&k, &uid, "peer-b").unwrap(), msg);
377        assert!(keyed.open_keyed(&k, &uid, "peer-c").is_err());
378        assert!(Envelope { key: Some("r2".into()), ..keyed.clone() }.open_keyed(&k, &uid, "peer-b").is_err());
379    }
380}