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