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