Skip to main content

weirdnet_sync/
net.rs

1//! The pull protocol running on a [`weirdnet_net::Node`] (`/weirdnet/sync/1`).
2//!
3//! The official WeirdBrains relay must not store pages; this module only exchanges
4//! sealed envelopes between the user's own nodes.
5use crate::error::{Result, SyncError};
6use crate::hlc::{Hlc, NodeId};
7use crate::log::OpLog;
8use crate::protocol::{Ack, Envelope, Hello, HelloOk, KeyRef, Message, PAGE_MAX, Pull, Refuse, RosterMsg, SYNC_PROFILE, decode, encode};
9use crate::roster::{Roster, SessionCheck};
10use crate::rotation::{Device, EpochKeys, KeyChain};
11use std::sync::{Arc, Mutex};
12use weirdnet_net::user::NodeCert;
13use weirdnet_net::{Handler, Keypair, Multiaddr, Node, NodeConfig, PeerId, PublicKey, WEIRDNET};
14
15/// Mutable state a sync node answers from and applies pages into.
16pub struct SyncState {
17    pub seed: Vec<u8>,
18    pub user_id: String,
19    pub user_key: PublicKey,
20    pub our_cert: NodeCert,
21    pub our_node: NodeId,
22    pub types: Vec<String>,
23    pub roster: Roster,
24    pub log: OpLog,
25    pub clock: Option<Hlc>,
26    /// This device's node and exchange secrets. Without them the state stays on
27    /// seed-derived keys and cannot rotate or open a rotated key.
28    pub device: Option<Device>,
29    /// Rotated epoch keys this device holds (secret; persist encrypted).
30    pub keys: EpochKeys,
31    /// Make the first rotation automatically once it is due (see
32    /// [`SyncState::first_rotation_due`]): right after the first link, and once after an
33    /// upgrade from seed-only keys. On in [`SyncState::new`].
34    pub auto_first_rotation: bool,
35}
36
37impl SyncState {
38    /// A state for this device. With `node_key`, it publishes its device key so
39    /// rotations can include it.
40    pub fn new(seed: Vec<u8>, user_key: PublicKey, our_cert: NodeCert, node_key: Option<&Keypair>, types: Vec<String>) -> Result<Self> {
41        let device = node_key.map(Device::from_node_key).transpose()?;
42        let mut roster = Roster::new();
43        roster.upsert(our_cert.clone());
44        let mut st = Self {
45            seed,
46            user_id: our_cert.user_id.clone(),
47            user_key,
48            our_node: NodeId::new(our_cert.peer_id.clone()),
49            our_cert,
50            types,
51            roster,
52            log: OpLog::new(),
53            clock: None,
54            device,
55            keys: EpochKeys::new(),
56            auto_first_rotation: true,
57        };
58        if st.device.is_some() {
59            st.publish_device_key(st.our_cert.issued_at)?;
60        }
61        Ok(st)
62    }
63
64    /// The key new envelopes are sealed with: the head epoch key when we hold it,
65    /// otherwise the seed-derived key (enough to catch up and be re-admitted).
66    pub fn current_key(&self) -> KeyRef {
67        match self.roster.head_id() {
68            Some(id) if self.keys.has(&id) => {
69                let epoch = self.roster.chain_view().head().map(|h| h.epoch).unwrap_or(self.roster.epoch);
70                KeyRef { epoch, id: Some(id) }
71            }
72            _ => KeyRef::seed(self.roster.epoch),
73        }
74    }
75
76    pub fn seal_envelope(&self, key: &KeyRef, typ: &str, peer: &str, msg: &Message) -> Result<Envelope> {
77        match &key.id {
78            None => Envelope::seal(&self.seed, &self.user_id, typ, key.epoch, peer, msg),
79            Some(id) => {
80                let k = self.keys.get(id).ok_or_else(|| SyncError::Crypto("unknown epoch key".into()))?;
81                Envelope::seal_keyed(k, id, &self.user_id, typ, key.epoch, peer, msg)
82            }
83        }
84    }
85
86    pub fn open_envelope(&self, env: &Envelope, peer: &str) -> Result<Message> {
87        match &env.key {
88            None => env.open(&self.seed, &self.user_id, peer),
89            Some(id) => {
90                let k = self.keys.get(id).ok_or_else(|| SyncError::Crypto("unknown epoch key".into()))?;
91                env.open_keyed(k, &self.user_id, peer)
92            }
93        }
94    }
95
96    fn roster_msg(&self) -> Message {
97        Message::Roster(RosterMsg { certs: self.roster.certs.clone(), epoch: self.roster.epoch, chain: self.roster.chain.shared() })
98    }
99
100    /// Merge certs, epoch and chain from a peer, then open any key sealed to us.
101    fn absorb(&mut self, certs: Vec<NodeCert>, epoch: u32, chain: KeyChain) {
102        let key = self.user_key.clone();
103        self.roster.merge(&Roster { epoch, certs, chain }, &key, &WEIRDNET);
104        self.refresh_keys();
105    }
106
107    /// Take the epoch keys (and adopted root) another copy of this state picked up,
108    /// for apps that pull into a snapshot and fold it back. Merge the roster as well.
109    pub fn take_keys_from(&mut self, other: &SyncState) {
110        self.keys.merge(&other.keys);
111        if self.roster.chain.root.is_none() {
112            self.roster.chain.root = other.roster.chain.root.clone();
113        }
114    }
115
116    fn is_revoked(&self, peer: &str) -> bool {
117        self.roster.get(peer).is_some_and(|c| !c.active())
118    }
119
120    pub fn handle(&mut self, from: &str, env: Envelope) -> Result<Envelope> {
121        let key = KeyRef { epoch: env.epoch, id: env.key.clone() };
122        // Open with our keys and user id; a foreign user fails here (wrong-user).
123        let msg = match self.open_envelope(&env, from) {
124            Ok(m) => m,
125            // Sealed under a rotation we don't hold: we are behind. Say so under the seed
126            // key, so the asker sends us its roster.
127            Err(_) if env.key.is_some() => return self.refuse(from, &env.typ, env.epoch, "unknown-key"),
128            Err(_) => return self.refuse(from, &env.typ, env.epoch, "wrong-user"),
129        };
130        let head = self.roster.head_id();
131        // After a rotation only the head key carries data; older and seed-derived keys
132        // (which a revoked device may hold) only get the roster.
133        let at_head = head.is_none() || env.key == head;
134        let reply = match msg {
135            Message::Hello(h) => self.on_hello(from, h, at_head),
136            Message::Pull(_) if !at_head => Message::Refuse(Refuse::new("epoch-behind")),
137            Message::Pull(_) if self.is_revoked(from) => Message::Refuse(Refuse::new("revoked")),
138            Message::Pull(p) => self.on_pull(p),
139            // An ack is the puller's progress, not ours: it must not move our cursors.
140            Message::Ack(a) => Message::Ack(Ack { node_id: a.node_id, last_seq: a.last_seq }),
141            Message::Roster(r) => {
142                self.absorb(r.certs, r.epoch, r.chain);
143                self.roster_msg()
144            }
145            Message::HelloOk(_) | Message::Page(_) | Message::Refuse(_) => {
146                return Err(SyncError::Protocol("unexpected request".into()));
147            }
148        };
149        // Answer under the key the request came in, so a peer behind us can read it.
150        self.seal_envelope(&key, &env.typ, from, &reply)
151    }
152
153    fn refuse(&self, from: &str, typ: &str, epoch: u32, reason: &'static str) -> Result<Envelope> {
154        Envelope::seal(&self.seed, &self.user_id, typ, epoch, from, &Message::Refuse(Refuse::new(reason)))
155    }
156
157    fn on_hello(&mut self, _from: &str, h: Hello, at_head: bool) -> Message {
158        let rotated = self.roster.head_id().is_some();
159        // After a rotation the key decides who is current, not the epoch number.
160        let epoch = if rotated { self.roster.epoch } else { h.epoch };
161        let check = self.roster.check_session(
162            &WEIRDNET,
163            &self.user_key,
164            &self.user_id,
165            &crate::roster::SessionOffer { cert: &h.cert, epoch, types: &h.types },
166            &self.types,
167        );
168        if matches!(check, SessionCheck::WrongUser | SessionCheck::Revoked) {
169            return Message::Refuse(Refuse::new(check.reason().unwrap_or("wrong-user")));
170        }
171        // Learn the peer's device key and rotations (signed; checked on merge).
172        if !h.chain.is_empty() {
173            self.roster.chain.merge(&h.chain);
174            self.refresh_keys();
175            // A device the user approved here, saying hello for the first time: admit it
176            // now, so the roster reply below already carries its admission.
177            self.admit_approved(now_ms() as i64);
178        }
179        if (rotated && !at_head) || check == SessionCheck::EpochBehind {
180            // A valid, unrevoked device of this user that missed a revocation or a
181            // rotation, or one waiting to be re-admitted: send the roster (user-signed
182            // certs and revocations, and the key chain) so it can catch up and retry.
183            return self.roster_msg();
184        }
185        if check != SessionCheck::Ok {
186            return Message::Refuse(Refuse::new(check.reason().unwrap_or("wrong-user")));
187        }
188        let cursors = self.log.cursors().into_iter().collect();
189        let revocations = self.roster.certs.iter().filter(|c| !c.active()).cloned().collect();
190        Message::HelloOk(HelloOk { cert: self.our_cert.clone(), epoch: self.roster.epoch, cursors, revocations, chain: self.roster.chain.shared() })
191    }
192
193    fn on_pull(&self, p: Pull) -> Message {
194        if !self.types.iter().any(|t| t == &p.typ) {
195            return Message::Refuse(Refuse::new("type-off"));
196        }
197        let limit = (p.limit as usize).clamp(1, 4096);
198        let known = self.log.cursor_for(&p.node_id, &p.typ);
199        let page = self.log.page_of_type(&p.node_id, &p.typ, p.after_seq, known, limit);
200        Message::Page(crate::protocol::Page { typ: p.typ, page })
201    }
202
203    /// A local write: tick the clock, append one log op.
204    pub fn local_op(&mut self, now_ms: u64, typ: &str, record_id: &str, op: Vec<u8>) {
205        let hlc = Hlc::tick(self.clock.as_ref(), now_ms, self.our_node.clone());
206        self.clock = Some(hlc.clone());
207        self.log.append(self.our_node.clone(), hlc, typ, record_id, op);
208    }
209}
210
211/// Request-response handler that talks [`Envelope`] on [`SYNC_PROFILE`].
212pub struct SyncHandler {
213    pub state: Arc<Mutex<SyncState>>,
214}
215
216impl Handler<Vec<u8>, Vec<u8>> for SyncHandler {
217    fn request(&self, from: &PeerId, req: Vec<u8>) -> Vec<u8> {
218        let env: Envelope = match decode(&req) {
219            Ok(e) => e,
220            Err(e) => return error_bytes(&e.to_string()),
221        };
222        let mut st = self.state.lock().expect("sync state");
223        match st.handle(&from.to_string(), env) {
224            Ok(reply) => encode(&reply).unwrap_or_else(|e| error_bytes(&e.to_string())),
225            Err(e) => error_bytes(&e.to_string()),
226        }
227    }
228}
229
230fn error_bytes(msg: &str) -> Vec<u8> {
231    encode(&Message::Refuse(Refuse { reason: format!("codec:{msg}") })).unwrap_or_default()
232}
233
234/// Listen with the in-memory transport (tests) or the caller's config, 256 KiB caps.
235pub fn node_config(listen_memory: bool) -> NodeConfig {
236    NodeConfig {
237        listen: if listen_memory { vec!["/memory/0".parse().expect("memory addr")] } else { Vec::new() },
238        memory: listen_memory,
239        request_max: PAGE_MAX as u64,
240        response_max: PAGE_MAX as u64,
241        label: "sync".into(),
242        ..Default::default()
243    }
244}
245
246/// Start a sync node on [`SYNC_PROFILE`].
247pub fn start_node(key: Keypair, cfg: NodeConfig, state: Arc<Mutex<SyncState>>) -> Result<Node<Vec<u8>, Vec<u8>>> {
248    Ok(Node::start(&SYNC_PROFILE, key, cfg, Arc::new(SyncHandler { state }))?)
249}
250
251/// Hello then pull every roster member the peer advertised, applying pages and acking.
252///
253/// Catches up on revocations and rotations both ways, and replaces a head rotation
254/// that still includes a revoked device. Fails with `Refused("needs-admission")` when
255/// the chain has moved on without this device (restored from the seed): another device
256/// has to [`SyncState::admit`] it.
257pub fn pull_from(state: &mut SyncState, node: &Node<Vec<u8>, Vec<u8>>, peer: PeerId, addrs: &[Multiaddr], typ_name: &str) -> Result<usize> {
258    let from = node.peer_id().to_string();
259    let mut catch_ups = 0;
260    let mut pushed = false;
261    let ok = loop {
262        let key = state.current_key();
263        let hello = Message::Hello(Hello {
264            cert: state.our_cert.clone(),
265            user_id: state.user_id.clone(),
266            epoch: key.epoch,
267            types: state.types.clone(),
268            our_cursors: state.log.cursors().into_iter().collect(),
269            our_hlc: state.clock.clone().unwrap_or_else(|| Hlc::new(0, 0, state.our_node.clone())),
270            chain: state.roster.chain.shared(),
271        });
272        let env = state.seal_envelope(&key, typ_name, &from, &hello)?;
273        let reply = request(node, peer, addrs, &env)?;
274        match state.open_envelope(&reply, &from)? {
275            Message::HelloOk(ok) => break ok,
276            // We are behind a revocation or rotation: take the peer's signed roster and
277            // chain, then hello again.
278            Message::Roster(r) if catch_ups < 3 => {
279                state.absorb(r.certs, r.epoch, r.chain);
280                if !state.roster.get(&state.our_cert.peer_id).is_none_or(|c| c.active()) {
281                    return Err(SyncError::Refused("revoked".into()));
282                }
283                if state.current_key() == key {
284                    let reason = if state.needs_admission() { "needs-admission" } else { "epoch-behind" };
285                    return Err(SyncError::Refused(reason.into()));
286                }
287                catch_ups += 1;
288            }
289            // The peer missed a rotation we hold: hand it our roster under the seed key
290            // (the chain is public; the epoch keys inside are sealed), then hello again.
291            Message::Refuse(r) if r.reason == "unknown-key" && !pushed => {
292                let env = state.seal_envelope(&KeyRef::seed(state.roster.epoch), typ_name, &from, &state.roster_msg())?;
293                if let Ok(Message::Roster(back)) = request(node, peer, addrs, &env).and_then(|e| state.open_envelope(&e, &from)) {
294                    state.absorb(back.certs, back.epoch, back.chain);
295                }
296                pushed = true;
297            }
298            Message::Refuse(r) => return Err(SyncError::Refused(r.reason)),
299            _ => return Err(SyncError::Protocol("expected HelloOk".into())),
300        }
301    };
302    let behind = ok.epoch < state.roster.epoch;
303    state.absorb(ok.revocations.into_iter().chain([ok.cert]).collect(), ok.epoch, ok.chain);
304    let key = state.current_key();
305    if behind {
306        // The peer missed a revocation we hold: hand it our roster so it can catch up.
307        let env = state.seal_envelope(&key, typ_name, &from, &state.roster_msg())?;
308        let _ = request(node, peer, addrs, &env)?;
309    }
310    let mut applied = 0;
311    let mut to_pull: Vec<(NodeId, u64)> = ok.cursors;
312    // Also pull the peer's own node if it wasn't in cursors yet.
313    if !to_pull.iter().any(|(n, _)| n.0 == peer.to_string()) {
314        to_pull.push((NodeId(peer.to_string()), 0));
315    }
316    for (nid, _their) in to_pull {
317        loop {
318            // Resume per type: a pull of another type over the same stream must not
319            // move this type's position.
320            let after = state.log.cursor_for(&nid, typ_name);
321            let pull = Message::Pull(Pull { node_id: nid.clone(), after_seq: after, typ: typ_name.into(), limit: 512 });
322            let env = state.seal_envelope(&key, typ_name, &from, &pull)?;
323            let reply = request(node, peer, addrs, &env)?;
324            match state.open_envelope(&reply, &from)? {
325                Message::Page(p) => {
326                    let last = p.page.to_seq;
327                    if p.typ != typ_name || p.page.node_id != nid || p.page.ops.iter().any(|e| e.typ != typ_name) {
328                        return Err(SyncError::Protocol("page of another type or node".into()));
329                    }
330                    if last <= after {
331                        break;
332                    }
333                    applied += state.log.integrate(&p.page);
334                    state.log.set_cursor_for(&nid, typ_name, last);
335                    if last > state.log.cursor(&nid) {
336                        state.log.set_cursor(&nid, last);
337                    }
338                    let ack = Message::Ack(Ack { node_id: nid.clone(), last_seq: last });
339                    let env = state.seal_envelope(&key, typ_name, &from, &ack)?;
340                    let _ = request(node, peer, addrs, &env)?;
341                }
342                Message::Refuse(r) => return Err(SyncError::Refused(r.reason)),
343                _ => return Err(SyncError::Protocol("expected Page".into())),
344            }
345        }
346    }
347    observe(state, now_ms());
348    if state.auto_first_rotation && state.first_rotation_due() {
349        // Linked devices still on seed-derived keys, all with device keys: start the
350        // chain while every device is trusted.
351        state.rotate(now_ms() as i64)?;
352    } else if state.needs_rotation() {
353        // The head still includes a device that has since been revoked (say, revoked
354        // on a device without a node key): replace it.
355        state.rotate(now_ms() as i64)?;
356    }
357    Ok(applied)
358}
359
360/// Advance our clock past the newest op held, so the next local write orders after
361/// everything this node has seen (a visit after a remote clear, say).
362pub fn observe(state: &mut SyncState, wall_ms: u64) {
363    if let Some(h) = state.log.newest_hlc().cloned()
364        && state.clock.as_ref().is_none_or(|c| h.cmp_total(c).is_gt())
365    {
366        state.clock = Some(Hlc::receive(state.clock.as_ref(), &h, wall_ms, state.our_node.clone()));
367    }
368}
369
370fn now_ms() -> u64 {
371    std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0)
372}
373
374fn request(node: &Node<Vec<u8>, Vec<u8>>, peer: PeerId, addrs: &[Multiaddr], env: &Envelope) -> Result<Envelope> {
375    let bytes = encode(env)?;
376    let reply = node.request(peer, addrs, bytes)?;
377    decode(&reply)
378}
379
380#[cfg(test)]
381mod tests {
382    use super::*;
383    use crate::roster::Roster;
384    use crate::rotation::KeyStatus;
385    use crate::seal::typ;
386    use weirdnet_net::user;
387
388    const SEED: [u8; 32] = *b"DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD";
389
390    fn addrs(n: &Node<Vec<u8>, Vec<u8>>) -> Vec<Multiaddr> {
391        n.reachable_addrs().into_iter().map(|s| s.parse().expect("addr")).collect()
392    }
393
394    fn pair() -> (Keypair, Keypair, Keypair, String) {
395        let user = Keypair::generate_ed25519();
396        let a = Keypair::generate_ed25519();
397        let b = Keypair::generate_ed25519();
398        let uid = user::user_id(&user.public());
399        (user, a, b, uid)
400    }
401
402    fn state(user: &Keypair, node_key: &Keypair, uid: &str, label: &str, types: &[&str]) -> (Arc<Mutex<SyncState>>, NodeId) {
403        let peer = node_key.public().to_peer_id().to_string();
404        let cert = Roster::self_certify(&WEIRDNET, user, &peer, label, 1).unwrap();
405        let mut roster = Roster::new();
406        roster.upsert(cert.clone());
407        let node = NodeId(peer.clone());
408        let st = SyncState {
409            seed: SEED.to_vec(),
410            user_id: uid.into(),
411            user_key: user.public(),
412            our_cert: cert,
413            our_node: node.clone(),
414            types: types.iter().map(|s| s.to_string()).collect(),
415            roster,
416            log: OpLog::new(),
417            clock: None,
418            device: Some(Device::from_node_key(node_key).unwrap()),
419            keys: EpochKeys::new(),
420            auto_first_rotation: false,
421        };
422        let mut st = st;
423        st.publish_device_key(1).unwrap();
424        (Arc::new(Mutex::new(st)), node)
425    }
426
427    #[test]
428    fn two_memory_nodes_hello_and_pull_a_bookmark_op() {
429        let (user, ka, kb, uid) = pair();
430        let (sa, _) = state(&user, &ka, &uid, "a", &["bookmarks"]);
431        let (sb, _) = state(&user, &kb, &uid, "b", &["bookmarks"]);
432        // Each roster starts as one; at hello they learn the other.
433        {
434            let mut a = sa.lock().unwrap();
435            a.local_op(1_000, typ::BOOKMARKS, "bm-1", b"{\"title\":\"Rust\"}".to_vec());
436            a.local_op(1_001, typ::HISTORY, "v-1", b"https://example".to_vec());
437            a.local_op(1_002, typ::BOOKMARKS, "bm-2", b"{}".to_vec());
438        }
439        let na = start_node(ka, node_config(true), sa.clone()).unwrap();
440        let nb = start_node(kb, node_config(true), sb.clone()).unwrap();
441        // Put each other in the roster (as a QR link would, plus hello).
442        {
443            let ca = sa.lock().unwrap().our_cert.clone();
444            let cb = sb.lock().unwrap().our_cert.clone();
445            sa.lock().unwrap().roster.upsert(cb);
446            sb.lock().unwrap().roster.upsert(ca);
447        }
448        let mut st_b = sb.lock().unwrap();
449        let applied = pull_from(&mut st_b, &nb, na.peer_id(), &addrs(&na), typ::BOOKMARKS).unwrap();
450        assert!(applied >= 1, "applied {applied}");
451        let entry = st_b.log.get(&NodeId(na.peer_id().to_string()), 1).expect("bookmark op");
452        assert_eq!(entry.typ, typ::BOOKMARKS);
453        assert_eq!(entry.record_id, "bm-1");
454        assert_eq!(entry.op, b"{\"title\":\"Rust\"}");
455        let hist_visible = st_b.log.iter_node(&NodeId(na.peer_id().to_string())).any(|e| e.typ == typ::HISTORY);
456        assert!(!hist_visible, "a bookmarks pull must not apply history ops");
457        assert!(st_b.clock.as_ref().is_some_and(|c| c.physical_ms >= 1_000), "the clock moved past what was pulled");
458
459        // The history op sits between two bookmarks on one stream: a later history pull
460        // must still find it (0.1.0 lost it because the bookmarks pull moved one cursor
461        // past it).
462        let a_node = NodeId(na.peer_id().to_string());
463        assert_eq!(st_b.log.get(&a_node, 3).expect("second bookmark").record_id, "bm-2");
464        st_b.types.push(typ::HISTORY.into());
465        sa.lock().unwrap().types.push(typ::HISTORY.into());
466        let applied = pull_from(&mut st_b, &nb, na.peer_id(), &addrs(&na), typ::HISTORY).unwrap();
467        assert_eq!(applied, 1);
468        assert_eq!(st_b.log.get(&a_node, 2).expect("history op").record_id, "v-1");
469        assert_eq!(pull_from(&mut st_b, &nb, na.peer_id(), &addrs(&na), typ::BOOKMARKS).unwrap(), 0);
470        assert_eq!(st_b.log.cursor_for(&a_node, typ::HISTORY), 3, "contiguous after both types");
471        assert_eq!(pull_from(&mut st_b, &nb, na.peer_id(), &addrs(&na), typ::HISTORY).unwrap(), 0);
472        assert_eq!(sa.lock().unwrap().log.cursor_for(&a_node, typ::BOOKMARKS), 3, "acks never move the server's cursors");
473        drop(st_b);
474
475        // A revoked B cannot pull after A revokes B and bumps the epoch.
476        {
477            let mut a = sa.lock().unwrap();
478            let b_peer = nb.peer_id().to_string();
479            a.roster.revoke(&WEIRDNET, &user, &b_peer, 9).unwrap();
480        }
481        let mut st_b = sb.lock().unwrap();
482        let err = pull_from(&mut st_b, &nb, na.peer_id(), &addrs(&na), typ::BOOKMARKS).unwrap_err();
483        match err {
484            SyncError::Refused(r) => assert!(r == "revoked" || r == "epoch-behind" || r == "wrong-user", "got {r}"),
485            other => panic!("expected refuse, got {other}"),
486        }
487    }
488
489    #[test]
490    fn a_revocation_reaches_the_other_devices_both_ways() {
491        let user = Keypair::generate_ed25519();
492        let uid = user::user_id(&user.public());
493        let (ka, kb, kc, kd) = (Keypair::generate_ed25519(), Keypair::generate_ed25519(), Keypair::generate_ed25519(), Keypair::generate_ed25519());
494        let types = ["bookmarks"];
495        let (sa, _) = state(&user, &ka, &uid, "a", &types);
496        let (sb, _) = state(&user, &kb, &uid, "b", &types);
497        let (sc, _) = state(&user, &kc, &uid, "c", &types);
498        let (sd, _) = state(&user, &kd, &uid, "d", &types);
499        let all = [&sa, &sb, &sc, &sd];
500        let certs: Vec<_> = all.iter().map(|s| s.lock().unwrap().our_cert.clone()).collect();
501        for s in all {
502            for c in &certs {
503                s.lock().unwrap().roster.upsert(c.clone());
504            }
505        }
506        sa.lock().unwrap().local_op(1, typ::BOOKMARKS, "a-1", vec![1]);
507        let na = start_node(ka, node_config(true), sa.clone()).unwrap();
508        let nb = start_node(kb, node_config(true), sb.clone()).unwrap();
509        let nc = start_node(kc, node_config(true), sc.clone()).unwrap();
510        let nd = start_node(kd, node_config(true), sd.clone()).unwrap();
511        let c_peer = nc.peer_id().to_string();
512        sa.lock().unwrap().roster.revoke(&WEIRDNET, &user, &c_peer, 9).unwrap();
513
514        // B is a revocation behind A: A answers with its roster, B catches up and pulls.
515        let applied = pull_from(&mut sb.lock().unwrap(), &nb, na.peer_id(), &addrs(&na), typ::BOOKMARKS).unwrap();
516        assert_eq!(applied, 1);
517        {
518            let b = sb.lock().unwrap();
519            assert_eq!(b.roster.epoch, 1);
520            assert!(!b.roster.get(&c_peer).unwrap().active());
521        }
522        // A pulls from D (still behind): A pushes its roster to D.
523        pull_from(&mut sa.lock().unwrap(), &na, nd.peer_id(), &addrs(&nd), typ::BOOKMARKS).unwrap();
524        assert_eq!(sd.lock().unwrap().roster.epoch, 1);
525        assert!(!sd.lock().unwrap().roster.get(&c_peer).unwrap().active());
526        // C is refused everywhere that learned, and a roster reply never lets it back in.
527        for (n, label) in [(&nb, "b"), (&nd, "d"), (&na, "a")] {
528            let err = pull_from(&mut sc.lock().unwrap(), &nc, n.peer_id(), &addrs(n), typ::BOOKMARKS).unwrap_err();
529            assert!(matches!(err, SyncError::Refused(ref r) if r == "revoked"), "{label}: {err}");
530        }
531    }
532
533    #[test]
534    fn a_foreign_user_is_refused() {
535        let (user_a, ka, _, uid_a) = pair();
536        let (user_b, kb, _, uid_b) = pair();
537        let (sa, _) = state(&user_a, &ka, &uid_a, "a", &["bookmarks"]);
538        let (sb, _) = state(&user_b, &kb, &uid_b, "b", &["bookmarks"]);
539        let na = start_node(ka, node_config(true), sa.clone()).unwrap();
540        let nb = start_node(kb, node_config(true), sb.clone()).unwrap();
541        let mut st_b = sb.lock().unwrap();
542        let err = pull_from(&mut st_b, &nb, na.peer_id(), &addrs(&na), typ::BOOKMARKS).unwrap_err();
543        match err {
544            SyncError::Refused(r) => assert_eq!(r, "wrong-user"),
545            // Opening the reply can also fail if A sealed a refuse under A's user id.
546            SyncError::Crypto(_) => {}
547            other => panic!("expected wrong-user, got {other}"),
548        }
549    }
550
551    type Sn = (Arc<Mutex<SyncState>>, Node<Vec<u8>, Vec<u8>>);
552
553    /// `n` linked devices of one user: every roster holds every cert, every chain every
554    /// device key (as one round of sync would leave them), each on a memory node.
555    fn linked(user: &Keypair, labels: &[&str]) -> Vec<Sn> {
556        let uid = user::user_id(&user.public());
557        let made: Vec<(Arc<Mutex<SyncState>>, Keypair)> = labels
558            .iter()
559            .map(|l| {
560                let k = Keypair::generate_ed25519();
561                (state(user, &k, &uid, l, &["bookmarks"]).0, k)
562            })
563            .collect();
564        let certs: Vec<_> = made.iter().map(|(s, _)| s.lock().unwrap().our_cert.clone()).collect();
565        let chains: Vec<_> = made.iter().map(|(s, _)| s.lock().unwrap().roster.chain.clone()).collect();
566        for (s, _) in &made {
567            let mut st = s.lock().unwrap();
568            for c in &certs {
569                st.roster.upsert(c.clone());
570            }
571            for ch in &chains {
572                st.roster.chain.merge(ch);
573            }
574        }
575        made.into_iter().map(|(s, k)| (s.clone(), start_node(k, node_config(true), s).unwrap())).collect()
576    }
577
578    fn pull(a: &Sn, b: &Sn) -> Result<usize> {
579        pull_from(&mut a.0.lock().unwrap(), &a.1, b.1.peer_id(), &addrs(&b.1), typ::BOOKMARKS)
580    }
581
582    fn head(s: &Sn) -> Option<String> {
583        s.0.lock().unwrap().roster.head_id()
584    }
585
586    fn records(s: &Sn) -> Vec<String> {
587        let st = s.0.lock().unwrap();
588        let mut v: Vec<String> = st.log.cursors().keys().flat_map(|n| st.log.iter_node(n).map(|e| e.record_id.clone()).collect::<Vec<_>>()).collect();
589        v.sort();
590        v
591    }
592
593    fn peer(s: &Sn) -> String {
594        s.1.peer_id().to_string()
595    }
596
597    #[test]
598    fn a_revoked_device_cannot_read_ops_written_after_the_rotation() {
599        let user = Keypair::generate_ed25519();
600        let g = linked(&user, &["a", "b", "c"]);
601        let (a, b, c) = (&g[0], &g[1], &g[2]);
602        a.0.lock().unwrap().local_op(1, typ::BOOKMARKS, "before", vec![1]);
603        assert_eq!(pull(c, a).unwrap(), 1, "c reads what was written before");
604
605        let rot = {
606            let mut st = a.0.lock().unwrap();
607            st.revoke(&user, &peer(c), 9).unwrap();
608            st.local_op(10, typ::BOOKMARKS, "after", vec![2]);
609            st.roster.head_id().unwrap()
610        };
611        {
612            let st = a.0.lock().unwrap();
613            let view = st.roster.chain_view();
614            let h = view.head().unwrap();
615            assert!(h.members.contains(&peer(a)) && h.members.contains(&peer(b)));
616            assert!(!h.members.contains(&peer(c)), "the revoked device is not sealed a copy");
617            assert_eq!(st.key_status(), KeyStatus::Current { epoch: h.epoch });
618        }
619
620        // B catches up through the roster reply and reads the new op.
621        assert_eq!(pull(b, a).unwrap(), 2);
622        assert_eq!(head(b).as_deref(), Some(rot.as_str()));
623        assert!(b.0.lock().unwrap().keys.has(&rot));
624
625        // C is refused, and learning the whole chain gives it no key.
626        assert!(matches!(pull(c, a), Err(SyncError::Refused(ref r)) if r == "revoked"));
627        let chain = a.0.lock().unwrap().roster.clone();
628        {
629            let mut st = c.0.lock().unwrap();
630            let key = st.user_key.clone();
631            st.roster.merge(&chain, &key, &WEIRDNET);
632            st.refresh_keys();
633            assert!(!st.keys.has(&rot));
634            assert_eq!(st.key_status(), KeyStatus::Revoked);
635        }
636
637        // B's page with the post-rotation op, as it crosses the wire.
638        let a_node = NodeId(peer(a));
639        let page_env = {
640            let bs = b.0.lock().unwrap();
641            let pull = Message::Pull(Pull { node_id: a_node.clone(), after_seq: 0, typ: typ::BOOKMARKS.into(), limit: 10 });
642            let env = bs.seal_envelope(&bs.current_key(), typ::BOOKMARKS, &peer(b), &pull).unwrap();
643            a.0.lock().unwrap().handle(&peer(b), env).unwrap()
644        };
645        match b.0.lock().unwrap().open_envelope(&page_env, &peer(b)).unwrap() {
646            Message::Page(p) => assert!(p.page.ops.iter().any(|e| e.record_id == "after")),
647            other => panic!("expected a page, got {other:?}"),
648        }
649        let cs = c.0.lock().unwrap();
650        assert!(cs.open_envelope(&page_env, &peer(b)).is_err(), "c holds the seed and every old key, and still cannot open it");
651        assert!(page_env.open(&cs.seed, &cs.user_id, &peer(b)).is_err());
652        // Nor can it pull with the seed-derived key, as itself or claiming to be B.
653        for (from, label) in [(peer(c), "as c"), (peer(b), "as b")] {
654            let pull = Message::Pull(Pull { node_id: a_node.clone(), after_seq: 0, typ: typ::BOOKMARKS.into(), limit: 10 });
655            let env = cs.seal_envelope(&KeyRef::seed(cs.roster.epoch), typ::BOOKMARKS, &from, &pull).unwrap();
656            let reply = a.0.lock().unwrap().handle(&from, env).unwrap();
657            match cs.open_envelope(&reply, &from).unwrap() {
658                Message::Refuse(r) => assert_eq!(r.reason, "epoch-behind", "{label}"),
659                other => panic!("{label}: expected a refusal, got {other:?}"),
660            }
661        }
662        drop(cs);
663
664        // A new node certified with the seed's user key (what a revoked holder can mint)
665        // gets the roster, not the key.
666        let mint = Keypair::generate_ed25519();
667        let uid = user::user_id(&user.public());
668        let (ms, _) = state(&user, &mint, &uid, "minted", &["bookmarks"]);
669        let mn = start_node(mint, node_config(true), ms.clone()).unwrap();
670        let minted = (ms, mn);
671        assert!(matches!(pull(&minted, a), Err(SyncError::Refused(ref r)) if r == "needs-admission"));
672        assert!(!records(&minted).contains(&"after".to_string()));
673    }
674
675    #[test]
676    fn the_remaining_devices_converge_after_a_rotation() {
677        let user = Keypair::generate_ed25519();
678        let g = linked(&user, &["a", "b", "c", "d"]);
679        let (a, b, c, d) = (&g[0], &g[1], &g[2], &g[3]);
680        a.0.lock().unwrap().local_op(1, typ::BOOKMARKS, "a-1", vec![1]);
681        a.0.lock().unwrap().revoke(&user, &peer(c), 5).unwrap();
682        a.0.lock().unwrap().local_op(6, typ::BOOKMARKS, "a-2", vec![2]);
683        // A pulls from B, which has not heard: B cannot open A's hello, A hands it the
684        // roster, and the pull goes through under the new key.
685        b.0.lock().unwrap().local_op(7, typ::BOOKMARKS, "b-1", vec![3]);
686        assert_eq!(pull(a, b).unwrap(), 1);
687        assert_eq!(head(b), head(a));
688        // D was offline; it catches up from B, not from A.
689        assert_eq!(pull(d, b).unwrap(), 1);
690        assert_eq!(head(d), head(a));
691        d.0.lock().unwrap().local_op(8, typ::BOOKMARKS, "d-1", vec![4]);
692        assert_eq!(pull(a, d).unwrap(), 1);
693        assert_eq!(pull(b, d).unwrap(), 1);
694        pull(b, a).unwrap();
695        pull(d, a).unwrap();
696        let want = vec!["a-1", "a-2", "b-1", "d-1"];
697        for (s, label) in [(a, "a"), (b, "b"), (d, "d")] {
698            assert_eq!(records(s), want, "{label}");
699            assert!(matches!(s.0.lock().unwrap().key_status(), KeyStatus::Current { .. }), "{label}");
700        }
701        assert!(matches!(pull(c, d), Err(SyncError::Refused(ref r)) if r == "revoked"));
702    }
703
704    #[test]
705    fn a_restored_device_is_re_admitted_and_catches_up() {
706        let user = Keypair::generate_ed25519();
707        let g = linked(&user, &["a", "b", "c"]);
708        let (a, b, c) = (&g[0], &g[1], &g[2]);
709        a.0.lock().unwrap().local_op(1, typ::BOOKMARKS, "old", vec![1]);
710        let first = {
711            let mut st = a.0.lock().unwrap();
712            st.revoke(&user, &peer(c), 2).unwrap();
713            st.roster.head_id().unwrap()
714        };
715        let second = a.0.lock().unwrap().rotate(3).unwrap();
716        a.0.lock().unwrap().local_op(4, typ::BOOKMARKS, "new", vec![2]);
717        pull(b, a).unwrap();
718
719        // Restored from the recovery words: same seed and user, a new node key.
720        let uid = user::user_id(&user.public());
721        let rk = Keypair::generate_ed25519();
722        let (rs, _) = state(&user, &rk, &uid, "restored", &["bookmarks"]);
723        let r = (rs.clone(), start_node(rk, node_config(true), rs).unwrap());
724        assert!(matches!(pull(&r, a), Err(SyncError::Refused(ref x)) if x == "needs-admission"));
725        assert_eq!(r.0.lock().unwrap().key_status(), KeyStatus::NeedsAdmission);
726        assert!(r.0.lock().unwrap().roster.head_id().is_some(), "it knows the chain moved on");
727
728        // On A the user approves it (as when linking). A learned its device key from the hello.
729        let cert = r.0.lock().unwrap().our_cert.clone();
730        let fp = r.0.lock().unwrap().roster.chain.device(&peer(&r)).unwrap().fingerprint();
731        assert_eq!(a.0.lock().unwrap().roster.chain.device(&peer(&r)).unwrap().fingerprint(), fp);
732        assert!(a.0.lock().unwrap().admit(cert, 5).unwrap());
733
734        assert_eq!(pull(&r, a).unwrap(), 2);
735        assert_eq!(records(&r), vec!["new", "old"]);
736        {
737            let st = r.0.lock().unwrap();
738            assert!(st.keys.has(&first) && st.keys.has(&second), "older epochs come along for history");
739            assert!(matches!(st.key_status(), KeyStatus::Current { .. }));
740        }
741        // It writes; B learns of it from A and then pulls from it directly.
742        r.0.lock().unwrap().local_op(6, typ::BOOKMARKS, "restored-1", vec![3]);
743        pull(b, a).unwrap();
744        assert_eq!(pull(b, &r).unwrap(), 1);
745        // A device approved before its key is known (the link flow) is admitted by its
746        // first hello and catches up in that same pull.
747        let rk2 = Keypair::generate_ed25519();
748        let (rs2, _) = state(&user, &rk2, &uid, "restored-2", &["bookmarks"]);
749        let r2 = (rs2.clone(), start_node(rk2, node_config(true), rs2).unwrap());
750        let cert2 = r2.0.lock().unwrap().our_cert.clone();
751        assert!(!a.0.lock().unwrap().approve(cert2, 8).unwrap(), "no device key yet");
752        assert_eq!(a.0.lock().unwrap().roster.chain.approved, vec![peer(&r2)]);
753        assert_eq!(pull(&r2, a).unwrap(), 2);
754        assert!(a.0.lock().unwrap().roster.chain.approved.is_empty());
755        assert!(a.0.lock().unwrap().roster.chain_view().head().unwrap().members.contains(&peer(&r2)));
756        // A revoked device cannot be admitted again.
757        let c_cert = c.0.lock().unwrap().our_cert.clone();
758        assert!(matches!(a.0.lock().unwrap().admit(c_cert, 7), Err(SyncError::Refused(ref x)) if x == "revoked"));
759    }
760
761    #[test]
762    fn concurrent_rotations_settle_on_one_head() {
763        let user = Keypair::generate_ed25519();
764        let g = linked(&user, &["a", "b"]);
765        let (a, b) = (&g[0], &g[1]);
766        a.0.lock().unwrap().rotate(1).unwrap();
767        pull(b, a).unwrap();
768        let ra = a.0.lock().unwrap().rotate(2).unwrap();
769        let rb = b.0.lock().unwrap().rotate(2).unwrap();
770        assert_ne!(ra, rb);
771        a.0.lock().unwrap().local_op(3, typ::BOOKMARKS, "a-1", vec![1]);
772        assert_eq!(pull(b, a).unwrap(), 1);
773        pull(a, b).unwrap();
774        let h = head(a).unwrap();
775        assert_eq!(head(b).as_deref(), Some(h.as_str()));
776        assert_eq!(h, ra.clone().min(rb.clone()), "the lower id wins a tie");
777        assert!(a.0.lock().unwrap().keys.has(&ra) && a.0.lock().unwrap().keys.has(&rb));
778    }
779
780    #[test]
781    fn a_late_root_and_a_revoked_creator_do_not_move_the_head() {
782        let user = Keypair::generate_ed25519();
783        let g = linked(&user, &["a", "b", "c"]);
784        let (a, b, c) = (&g[0], &g[1], &g[2]);
785        a.0.lock().unwrap().rotate(1).unwrap();
786        pull(b, a).unwrap();
787        pull(c, a).unwrap();
788        a.0.lock().unwrap().revoke(&user, &peer(c), 2).unwrap();
789        let h = head(a).unwrap();
790        // C, unaware, rotates off the root it still holds. Its rotation stops counting
791        // once its revocation is known, so it never becomes the head.
792        c.0.lock().unwrap().rotate(3).unwrap();
793        c.0.lock().unwrap().rotate(4).unwrap();
794        assert!(c.0.lock().unwrap().roster.chain_view().head().unwrap().epoch > a.0.lock().unwrap().roster.chain_view().head().unwrap().epoch);
795        // A seed holder with a fresh node starts its own root that includes everyone.
796        let uid = user::user_id(&user.public());
797        let mk = Keypair::generate_ed25519();
798        let (ms, _) = state(&user, &mk, &uid, "minted", &["bookmarks"]);
799        {
800            let mut m = ms.lock().unwrap();
801            let r = a.0.lock().unwrap().roster.clone();
802            let mut plain =
803                Roster { epoch: r.epoch, certs: r.certs.clone(), chain: KeyChain { devices: r.chain.devices.clone(), ..Default::default() } };
804            plain.certs.retain(|x| x.active());
805            let key = m.user_key.clone();
806            m.roster.merge(&plain, &key, &WEIRDNET);
807            m.rotate(1).unwrap();
808            assert!(m.roster.chain_view().head().unwrap().epoch > 2, "it outnumbers the real head");
809        }
810        let minted_cert = ms.lock().unwrap().our_cert.clone();
811        let minted_chain = ms.lock().unwrap().roster.chain.clone();
812        let c_roster = c.0.lock().unwrap().roster.clone();
813        {
814            let mut st = a.0.lock().unwrap();
815            let key = st.user_key.clone();
816            st.roster.merge(&c_roster, &key, &WEIRDNET);
817            st.roster.upsert(minted_cert);
818            st.roster.chain.merge(&minted_chain);
819            st.refresh_keys();
820            assert_eq!(st.roster.head_id().as_deref(), Some(h.as_str()));
821            assert!(!st.needs_rotation());
822        }
823    }
824
825    #[test]
826    fn a_head_that_still_includes_a_revoked_device_is_replaced() {
827        let user = Keypair::generate_ed25519();
828        let g = linked(&user, &["a", "b", "c"]);
829        let (a, b, c) = (&g[0], &g[1], &g[2]);
830        let root = a.0.lock().unwrap().rotate(1).unwrap();
831        pull(b, a).unwrap();
832        // Revoked without a rotation (a 0.2 device, or one without its node key).
833        b.0.lock().unwrap().roster.revoke(&WEIRDNET, &user, &peer(c), 2).unwrap();
834        assert!(b.0.lock().unwrap().needs_rotation());
835        pull(b, a).unwrap();
836        let h = head(b).unwrap();
837        assert_ne!(h, root);
838        assert!(!b.0.lock().unwrap().needs_rotation());
839        pull(a, b).unwrap();
840        assert_eq!(head(a).as_deref(), Some(h.as_str()));
841        assert!(!a.0.lock().unwrap().roster.chain_view().head().unwrap().members.contains(&peer(c)));
842    }
843
844    #[test]
845    fn the_first_rotation_starts_once_every_linked_device_has_a_key() {
846        let user = Keypair::generate_ed25519();
847        let uid = user::user_id(&user.public());
848        let (ka, kb) = (Keypair::generate_ed25519(), Keypair::generate_ed25519());
849        let (sa, _) = state(&user, &ka, &uid, "a", &["bookmarks"]);
850        let (sb, _) = state(&user, &kb, &uid, "b", &["bookmarks"]);
851        for s in [&sa, &sb] {
852            s.lock().unwrap().auto_first_rotation = true;
853        }
854        assert!(!sa.lock().unwrap().first_rotation_due(), "one device: nothing to rotate for");
855        let a = (sa.clone(), start_node(ka, node_config(true), sa.clone()).unwrap());
856        let b = (sb.clone(), start_node(kb, node_config(true), sb.clone()).unwrap());
857        // The first link: each learns the other's cert, not yet its device key.
858        let (ca, cb) = (sa.lock().unwrap().our_cert.clone(), sb.lock().unwrap().our_cert.clone());
859        sa.lock().unwrap().roster.upsert(cb);
860        sb.lock().unwrap().roster.upsert(ca);
861        for s in [&sa, &sb] {
862            let st = s.lock().unwrap();
863            assert!(!st.first_rotation_due());
864            assert_eq!(st.devices_without_key().len(), 1, "the other device has no key yet");
865        }
866        let (low, high) = if peer(&a) < peer(&b) { (&a, &b) } else { (&b, &a) };
867        sa.lock().unwrap().local_op(1, typ::BOOKMARKS, "a-1", vec![1]);
868        // The higher peer pulls first: it learns the lower one's key, but leaves the
869        // first rotation to it.
870        pull(high, low).unwrap();
871        assert_eq!(head(high), None);
872        assert!(low.0.lock().unwrap().first_rotation_due(), "the hello brought the other key");
873        pull(low, high).unwrap();
874        let root = head(low).expect("the lowest peer started the chain");
875        assert!(!low.0.lock().unwrap().first_rotation_due());
876        pull(high, low).unwrap();
877        assert_eq!(head(high).as_deref(), Some(root.as_str()));
878        assert!(matches!(high.0.lock().unwrap().key_status(), KeyStatus::Current { .. }));
879        assert_eq!(records(&b), vec!["a-1"]);
880        // Never again: later passes keep the same head.
881        pull(low, high).unwrap();
882        pull(high, low).unwrap();
883        assert_eq!(head(low).as_deref(), Some(root.as_str()));
884        assert_eq!(head(high).as_deref(), Some(root.as_str()));
885    }
886
887    #[test]
888    fn an_upgrade_rotates_once_and_waits_for_every_device_key() {
889        let user = Keypair::generate_ed25519();
890        let g = linked(&user, &["a", "b", "c"]);
891        // C has not upgraded yet: drop its device key everywhere.
892        let c_peer = peer(&g[2]);
893        for s in &g {
894            let mut st = s.0.lock().unwrap();
895            st.roster.chain.devices.retain(|d| d.peer_id != c_peer);
896            st.auto_first_rotation = true;
897        }
898        for x in &g[..2] {
899            let st = x.0.lock().unwrap();
900            assert_eq!(st.devices_without_key().iter().map(|c| c.peer_id.clone()).collect::<Vec<_>>(), vec![c_peer.clone()]);
901            assert!(!st.first_rotation_due());
902        }
903        assert_eq!(g[0].0.lock().unwrap().rotate_if_first_due(1).unwrap(), None);
904        // C upgrades: its key spreads with its hellos, and the lowest peer rotates once.
905        g[2].0.lock().unwrap().publish_device_key(2).unwrap();
906        for i in 0..3 {
907            for j in 0..3 {
908                if i != j {
909                    let _ = pull(&g[i], &g[j]);
910                }
911            }
912        }
913        for _ in 0..2 {
914            for i in 0..3 {
915                for j in 0..3 {
916                    if i != j {
917                        pull(&g[i], &g[j]).unwrap();
918                    }
919                }
920            }
921        }
922        let heads: Vec<_> = g.iter().map(head).collect();
923        assert!(heads[0].is_some() && heads.iter().all(|h| *h == heads[0]), "{heads:?}");
924        for s in &g {
925            let st = s.0.lock().unwrap();
926            assert_eq!(st.roster.chain.rotations.len(), 1, "exactly one first rotation");
927            assert!(matches!(st.key_status(), KeyStatus::Current { .. }));
928        }
929    }
930}