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::{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        let plain = encode(msg)?;
192        let sealed = weirdnet_keys::seal(&key, &plain, &page_aad_keyed(typ, epoch, id, asking_peer))?;
193        Ok(Self { typ: typ.into(), epoch, key: Some(id.into()), sealed, clear: false })
194    }
195
196    pub fn open_keyed(&self, epoch_key: &Key32, user_id: &str, asking_peer: &str) -> Result<Message> {
197        let id = self.key.as_deref().ok_or_else(|| SyncError::Crypto("not sealed under a rotated key".into()))?;
198        let key = rotated_sync_key(epoch_key, user_id, &self.typ, self.epoch, id)?;
199        let plain: Zeroizing<Vec<u8>> = weirdnet_keys::open(&key, &self.sealed, &page_aad_keyed(&self.typ, self.epoch, id, asking_peer))?;
200        decode(&plain)
201    }
202
203    pub fn seal(seed: &[u8], user_id: &str, typ: &str, epoch: u32, asking_peer: &str, msg: &Message) -> Result<Self> {
204        let key = sync_key(seed, user_id, typ, epoch)?;
205        let plain = encode(msg)?;
206        let sealed = seal_page(&key, typ, epoch, asking_peer, &plain)?;
207        Ok(Self { typ: typ.into(), epoch, key: None, sealed, clear: false })
208    }
209
210    /// Open a seed-sealed envelope. One sealed under a rotated key fails here.
211    pub fn open(&self, seed: &[u8], user_id: &str, asking_peer: &str) -> Result<Message> {
212        if self.key.is_some() || self.clear {
213            return Err(SyncError::Crypto("sealed under a rotated key".into()));
214        }
215        let key = sync_key(seed, user_id, &self.typ, self.epoch)?;
216        let plain: Zeroizing<Vec<u8>> = open_page(&key, &self.typ, self.epoch, asking_peer, &self.sealed)?;
217        decode(&plain)
218    }
219}
220
221/// Length-prefixed CBOR (u32 big-endian length, then the item). For a raw stream;
222/// `Node::request` already frames [`Envelope`] as CBOR through libp2p.
223pub fn encode<T: Serialize>(v: &T) -> Result<Vec<u8>> {
224    cbor4ii::serde::to_vec(Vec::new(), v).map_err(|e| SyncError::Codec(e.to_string()))
225}
226
227pub fn decode<'a, T: Deserialize<'a>>(bytes: &'a [u8]) -> Result<T> {
228    cbor4ii::serde::from_slice(bytes).map_err(|e| SyncError::Codec(e.to_string()))
229}
230
231pub fn encode_framed<T: Serialize>(v: &T) -> Result<Vec<u8>> {
232    let body = encode(v)?;
233    if body.len() > u32::MAX as usize {
234        return Err(SyncError::Codec("frame too large".into()));
235    }
236    let mut out = Vec::with_capacity(4 + body.len());
237    out.extend_from_slice(&(body.len() as u32).to_be_bytes());
238    out.extend_from_slice(&body);
239    Ok(out)
240}
241
242pub fn decode_framed<'a, T: Deserialize<'a>>(bytes: &'a [u8]) -> Result<T> {
243    if bytes.len() < 4 {
244        return Err(SyncError::Codec("short frame".into()));
245    }
246    let n = u32::from_be_bytes(bytes[..4].try_into().unwrap()) as usize;
247    if bytes.len() != 4 + n {
248        return Err(SyncError::Codec(format!("frame length {n} does not match {}", bytes.len().saturating_sub(4))));
249    }
250    decode(&bytes[4..])
251}
252
253/// Build a `Page` message from a log page, dropping ops whose typ does not match (they
254/// stay in the log for a later pull of that type).
255pub fn page_for_type(typ: &str, page: LogPage) -> Page {
256    let ops: Vec<LogEntry> = page.ops.into_iter().filter(|e| e.typ == typ).collect();
257    let from_seq = ops.first().map(|e| e.seq).unwrap_or(page.from_seq);
258    let to_seq = ops.last().map(|e| e.seq).unwrap_or(page.to_seq);
259    Page { typ: typ.into(), page: LogPage { node_id: page.node_id, from_seq, to_seq, ops } }
260}
261
262#[cfg(test)]
263mod tests {
264    use super::*;
265    use crate::hlc::Hlc;
266    use crate::roster::Roster;
267    use weirdnet_net::Keypair;
268    use weirdnet_net::user;
269
270    const SEED: [u8; 32] = *b"CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC";
271
272    fn hello() -> (Message, String, Keypair) {
273        let u = Keypair::generate_ed25519();
274        let uid = user::user_id(&u.public());
275        let cert = Roster::self_certify(&WEIRDNET, &u, "peer-a", "a", 1).unwrap();
276        let msg = Message::Hello(Hello {
277            cert,
278            user_id: uid.clone(),
279            epoch: 0,
280            types: vec!["bookmarks".into()],
281            our_cursors: vec![(NodeId::new("peer-a"), 3)],
282            our_hlc: Hlc::new(10, 0, NodeId::new("peer-a")),
283            chain: Default::default(),
284        });
285        (msg, uid, u)
286    }
287
288    #[test]
289    fn a_full_page_fits_the_reply_cap_once_sealed() {
290        use crate::log::OpLog;
291        let (_, uid, _) = hello();
292        let mut log = OpLog::new();
293        let node = NodeId::new("peer-a");
294        for i in 0..400u64 {
295            log.append(node.clone(), Hlc::new(i, 0, node.clone()), "bookmarks", format!("r{i}"), vec![7u8; 1500]);
296        }
297        let known = log.cursor_for(&node, "bookmarks");
298        let page = log.page_of_type(&node, "bookmarks", 0, known, 4096);
299        assert!(page.ops.len() > 10 && page.to_seq < 400, "the budget split the stream");
300        let msg = Message::Page(Page { typ: "bookmarks".into(), page });
301        let env = Envelope::seal(&SEED, &uid, "bookmarks", 0, "peer-b", &msg).unwrap();
302        // What weirdnet-net 0.8 sends: the envelope bytes as one CBOR byte string.
303        let wire = |env: &Envelope| weirdnet_net::wire::to_vec(&encode(env).unwrap()).unwrap().len();
304        assert!(wire(&env) <= PAGE_MAX, "sealed page is {} bytes on the wire, cap {PAGE_MAX}", wire(&env));
305        assert!(wire(&env) > PAGE_MAX / 2, "the budget is not far too small ({})", wire(&env));
306        assert!(wire(&env) <= PAGE_MAX - 16 * 1024, "keeps a 16 KiB safety margin ({})", wire(&env));
307        let page = log.page(&node, 0, 4096);
308        let env = Envelope::seal(&SEED, &uid, "bookmarks", 0, "peer-b", &Message::Page(Page { typ: "bookmarks".into(), page })).unwrap();
309        assert!(wire(&env) <= PAGE_MAX);
310    }
311
312    #[test]
313    fn framed_cbor_round_trips_and_rejects_a_truncated_frame() {
314        let (msg, _, _) = hello();
315        let bytes = encode_framed(&msg).unwrap();
316        assert_eq!(u32::from_be_bytes(bytes[..4].try_into().unwrap()) as usize, bytes.len() - 4);
317        let back: Message = decode_framed(&bytes).unwrap();
318        assert_eq!(back, msg);
319        assert!(decode_framed::<Message>(&bytes[..3]).is_err());
320        assert!(decode_framed::<Message>(&bytes[..bytes.len() - 1]).is_err());
321    }
322
323    #[test]
324    fn a_sealed_hello_opens_for_the_same_seed_and_user_only() {
325        let (msg, uid, _) = hello();
326        let env = Envelope::seal(&SEED, &uid, "bookmarks", 0, "peer-b", &msg).unwrap();
327        let opened = env.open(&SEED, &uid, "peer-b").unwrap();
328        assert_eq!(opened, msg);
329        assert!(env.open(&SEED, "other-user", "peer-b").is_err());
330        assert!(env.open(&SEED, &uid, "peer-c").is_err());
331        assert!(Envelope { typ: "history".into(), ..env.clone() }.open(&SEED, &uid, "peer-b").is_err());
332    }
333
334    #[test]
335    fn seed_envelopes_and_rosters_keep_the_0_2_wire_shape() {
336        #[derive(Serialize, Deserialize, PartialEq, Debug)]
337        struct EnvelopeV02 {
338            typ: String,
339            epoch: u32,
340            sealed: Sealed,
341        }
342        let (msg, uid, _) = hello();
343        let env = Envelope::seal(&SEED, &uid, "bookmarks", 0, "peer-b", &msg).unwrap();
344        let old: EnvelopeV02 = decode(&encode(&env).unwrap()).unwrap();
345        assert_eq!(encode(&old).unwrap(), encode(&env).unwrap(), "no key field on a seed envelope");
346        let back: Envelope = decode(&encode(&old).unwrap()).unwrap();
347        assert_eq!(back.key, None);
348        #[derive(Serialize)]
349        #[serde(tag = "kind", rename_all = "kebab-case")]
350        enum OldMessage {
351            Roster { certs: Vec<NodeCert>, epoch: u32 },
352        }
353        let old = encode(&OldMessage::Roster { certs: vec![], epoch: 3 }).unwrap();
354        assert_eq!(
355            decode::<Message>(&old).unwrap(),
356            Message::Roster(RosterMsg { certs: vec![], epoch: 3, chain: KeyChain::default(), grants: vec![] })
357        );
358        // A keyed envelope never opens as a seed one.
359        let k = Key32::random().unwrap();
360        let keyed = Envelope::seal_keyed(&k, "r1", &uid, "bookmarks", 1, "peer-b", &msg).unwrap();
361        assert!(keyed.open(&SEED, &uid, "peer-b").is_err());
362        assert_eq!(keyed.open_keyed(&k, &uid, "peer-b").unwrap(), msg);
363        assert!(keyed.open_keyed(&k, &uid, "peer-c").is_err());
364        assert!(Envelope { key: Some("r2".into()), ..keyed.clone() }.open_keyed(&k, &uid, "peer-b").is_err());
365    }
366}