Skip to main content

weirdnet_sync/
rotation.rs

1//! Real key rotation: random epoch keys sealed to each remaining device.
2//!
3//! Every device holds the identity seed, so a seed-derived key can never shut a revoked
4//! device out. A rotation therefore makes a fresh random epoch key and seals one copy to
5//! each remaining device's exchange key (X25519, derived from its node key). The sealed
6//! copies travel in the roster ([`Roster::chain`]). A device that is not a recipient,
7//! revoked or restored from the seed alone, cannot open the new key; a restored device
8//! is let back in by an [`Admission`] from a device that holds the key.
9//!
10//! Rules (all checked on every device, so they converge):
11//!
12//! - A [`DeviceKey`] is signed by the device's own node key, so no other device (even
13//!   one holding the user key) can swap in its own exchange key.
14//! - A [`Rotation`] is signed by its creator's node key. It is valid when the creator has
15//!   an active cert and is a member of the parent rotation, and its epoch is the parent's
16//!   plus one. A root (no parent) is valid when its creator has an active cert. A
17//!   revoked creator's rotations stop counting, with everything built on them.
18//! - Once a device holds a key from a root it keeps that root ([`KeyChain::root`]); a
19//!   later root from someone holding only the seed is ignored.
20//! - The members of a rotation are its recipients plus devices admitted to it by a
21//!   member. The head is the valid rotation with the highest epoch, then one with no
22//!   revoked member, then the lowest id. A head with a revoked member needs another
23//!   rotation; [`crate::pull_from`] makes it.
24use crate::error::{Result, SyncError};
25use crate::net::SyncState;
26use crate::protocol::{decode, encode};
27use crate::roster::Roster;
28use serde::{Deserialize, Serialize};
29use std::collections::{BTreeMap, BTreeSet};
30use weirdnet_keys::exchange::{self, ExchangeSecret};
31use weirdnet_keys::mac::HmacSha256;
32use weirdnet_keys::{Key32, Sealed, kdf, open, seal};
33use weirdnet_net::profile::WEIRDNET;
34use weirdnet_net::user::NodeCert;
35use weirdnet_net::{Keypair, PeerId, PublicKey};
36use zeroize::{Zeroize, Zeroizing};
37
38const DEVICE_KEY: &str = "weirdnet-sync/v1/device-key";
39const ROTATION: &str = "weirdnet-sync/v1/rotation";
40const ADMISSION: &str = "weirdnet-sync/v1/admission";
41const SEAL_KEY: &[u8] = b"weirdnet-sync/v1/seal-key";
42const SEAL_SAS: &[u8] = b"weirdnet-sync/v1/seal-sas";
43
44/// The node public key inside an Ed25519 (identity-multihash) peer id.
45pub fn peer_public(peer: &str) -> Option<PublicKey> {
46    let pid: PeerId = peer.parse().ok()?;
47    let bytes = pid.to_bytes();
48    if bytes.len() < 2 || bytes[0] != 0 || bytes.len() != 2 + bytes[1] as usize {
49        return None;
50    }
51    let key = PublicKey::try_decode_protobuf(&bytes[2..]).ok()?;
52    (key.to_peer_id() == pid).then_some(key)
53}
54
55fn hash_hex(domain: &[u8], data: &[u8], n: usize) -> String {
56    let mut h = HmacSha256::new(domain);
57    h.update(data);
58    hex::encode(&h.finalize()[..n])
59}
60
61fn key_check(key: &Key32) -> String {
62    let mut h = HmacSha256::new(&key.0);
63    h.update(b"weirdnet-sync/v1/key-check");
64    hex::encode(&h.finalize()[..16])
65}
66
67fn crypto(msg: impl Into<String>) -> SyncError {
68    SyncError::Crypto(msg.into())
69}
70
71/// A device's public exchange key, signed by the device's node key.
72#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
73pub struct DeviceKey {
74    pub peer_id: String,
75    /// X25519 public key, hex.
76    pub exchange: String,
77    pub at_ms: i64,
78    pub sig: Vec<u8>,
79}
80
81impl DeviceKey {
82    fn signing_bytes(peer: &str, exchange: &str, at: i64) -> Vec<u8> {
83        format!("{DEVICE_KEY}\n{peer}\n{exchange}\n{at}").into_bytes()
84    }
85
86    /// The signature is the device's own and the key is well formed.
87    pub fn verify(&self) -> bool {
88        self.public().is_some()
89            && peer_public(&self.peer_id).is_some_and(|k| k.verify(&Self::signing_bytes(&self.peer_id, &self.exchange, self.at_ms), &self.sig))
90    }
91
92    pub fn public(&self) -> Option<[u8; 32]> {
93        hex::decode(&self.exchange).ok()?.try_into().ok()
94    }
95
96    /// A short code to compare on both screens before re-admitting a device.
97    pub fn fingerprint(&self) -> String {
98        let h = hash_hex(b"weirdnet-sync/v1/fingerprint", format!("{}|{}", self.peer_id, self.exchange).as_bytes(), 6);
99        format!("{}-{}-{}", &h[..4], &h[4..8], &h[8..])
100    }
101}
102
103/// This device's signing and exchange secrets. The exchange secret is derived from the
104/// node key, so nothing new has to be stored.
105pub struct Device {
106    node: Keypair,
107    exchange: ExchangeSecret,
108}
109
110impl Clone for Device {
111    fn clone(&self) -> Self {
112        Self { node: self.node.clone(), exchange: ExchangeSecret::from_bytes(*self.exchange.to_bytes()) }
113    }
114}
115
116impl std::fmt::Debug for Device {
117    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
118        write!(f, "Device({})", self.peer_id())
119    }
120}
121
122impl Device {
123    pub fn from_node_key(node: &Keypair) -> Result<Self> {
124        let bytes = Zeroizing::new(node.to_protobuf_encoding().map_err(|e| crypto(format!("node key: {e}")))?);
125        let k = kdf::hkdf(&bytes, Some(b"weirdnet-sync/v1"), b"weirdnet-sync/v1/exchange")?;
126        Ok(Self { node: node.clone(), exchange: ExchangeSecret::from_bytes(k.0) })
127    }
128
129    pub fn peer_id(&self) -> String {
130        self.node.public().to_peer_id().to_string()
131    }
132
133    pub fn device_key(&self, at_ms: i64) -> Result<DeviceKey> {
134        let peer = self.peer_id();
135        let exchange = hex::encode(self.exchange.public());
136        let sig = self.sign(&DeviceKey::signing_bytes(&peer, &exchange, at_ms))?;
137        Ok(DeviceKey { peer_id: peer, exchange, at_ms, sig })
138    }
139
140    fn sign(&self, bytes: &[u8]) -> Result<Vec<u8>> {
141        self.node.sign(bytes).map_err(|e| crypto(format!("sign: {e}")))
142    }
143}
144
145/// One recipient's copy of an epoch key.
146#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
147pub struct SealedKey {
148    pub peer_id: String,
149    pub sealed: Sealed,
150}
151
152/// A new random epoch key, sealed to each remaining device.
153#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
154pub struct Rotation {
155    pub epoch: u32,
156    /// The rotation this one replaces; `None` for the first one (out of seed-derived keys).
157    pub parent: Option<String>,
158    pub by: String,
159    pub at_ms: i64,
160    /// Ephemeral X25519 public key, hex.
161    pub eph: String,
162    /// Commitment to the key, so every holder can tell it got the same one.
163    pub check: String,
164    pub keys: Vec<SealedKey>,
165    pub sig: Vec<u8>,
166}
167
168impl Rotation {
169    fn body(&self) -> Vec<u8> {
170        encode(&(ROTATION, self.epoch, &self.parent, &self.by, self.at_ms, &self.eph, &self.check, &self.keys)).unwrap_or_default()
171    }
172
173    pub fn id(&self) -> String {
174        hash_hex(ROTATION.as_bytes(), &self.body(), 16)
175    }
176
177    fn signed(&self) -> bool {
178        peer_public(&self.by).is_some_and(|k| k.verify(&self.body(), &self.sig))
179    }
180
181    pub fn recipients(&self) -> impl Iterator<Item = &str> {
182        self.keys.iter().map(|k| k.peer_id.as_str())
183    }
184
185    fn transcript(&self, recipient: &str, recipient_pub: &[u8; 32]) -> Vec<u8> {
186        let parent = self.parent.as_deref().unwrap_or("-");
187        format!("{ROTATION}|e{}|{parent}|{}|{recipient}|{}|{}", self.epoch, self.by, self.eph, hex::encode(recipient_pub)).into_bytes()
188    }
189}
190
191/// A member's grant of the current key (and the older ones it holds) to a device,
192/// such as one restored from the seed.
193#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
194pub struct Admission {
195    pub rotation: String,
196    pub peer_id: String,
197    pub by: String,
198    pub at_ms: i64,
199    pub eph: String,
200    pub sealed: Sealed,
201    pub sig: Vec<u8>,
202}
203
204impl Admission {
205    fn body(&self) -> Vec<u8> {
206        encode(&(ADMISSION, &self.rotation, &self.peer_id, &self.by, self.at_ms, &self.eph, &self.sealed)).unwrap_or_default()
207    }
208
209    pub fn id(&self) -> String {
210        hash_hex(ADMISSION.as_bytes(), &self.body(), 16)
211    }
212
213    fn signed(&self) -> bool {
214        peer_public(&self.by).is_some_and(|k| k.verify(&self.body(), &self.sig))
215    }
216
217    fn transcript(&self, recipient_pub: &[u8; 32]) -> Vec<u8> {
218        format!("{ADMISSION}|{}|{}|{}|{}|{}", self.rotation, self.peer_id, self.by, self.eph, hex::encode(recipient_pub)).into_bytes()
219    }
220}
221
222/// The public part of rotation: device keys, rotations and admissions. Gossiped with the
223/// roster; holds no secret.
224#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
225pub struct KeyChain {
226    #[serde(default)]
227    pub devices: Vec<DeviceKey>,
228    #[serde(default)]
229    pub rotations: Vec<Rotation>,
230    #[serde(default)]
231    pub admissions: Vec<Admission>,
232    /// The root this device follows, once it holds a key from it. Local; never merged.
233    #[serde(default, skip_serializing_if = "Option::is_none")]
234    pub root: Option<String>,
235    /// Devices the user approved on this device (by linking) that wait for an
236    /// admission. Local; never merged.
237    #[serde(default, skip_serializing_if = "Vec::is_empty")]
238    pub approved: Vec<String>,
239}
240
241impl KeyChain {
242    pub fn is_empty(&self) -> bool {
243        self.devices.is_empty() && self.rotations.is_empty() && self.admissions.is_empty()
244    }
245
246    pub fn is_empty_and_rootless(&self) -> bool {
247        self.is_empty() && self.root.is_none() && self.approved.is_empty()
248    }
249
250    pub fn device(&self, peer_id: &str) -> Option<&DeviceKey> {
251        self.devices.iter().find(|d| d.peer_id == peer_id)
252    }
253
254    /// Add or replace (newer `at_ms`) a device key. Returns false if it does not verify.
255    pub fn add_device(&mut self, dk: DeviceKey) -> bool {
256        if !dk.verify() {
257            return false;
258        }
259        match self.devices.iter_mut().find(|d| d.peer_id == dk.peer_id) {
260            Some(d) if d.at_ms < dk.at_ms => *d = dk,
261            Some(_) => {}
262            None => self.devices.push(dk),
263        }
264        true
265    }
266
267    /// Take another replica's device keys, rotations and admissions (signed ones only).
268    /// `root` stays ours.
269    pub fn merge(&mut self, other: &KeyChain) {
270        for d in &other.devices {
271            self.add_device(d.clone());
272        }
273        let have: BTreeSet<String> = self.rotations.iter().map(Rotation::id).collect();
274        for r in &other.rotations {
275            if !have.contains(&r.id()) && r.signed() {
276                self.rotations.push(r.clone());
277            }
278        }
279        let have: BTreeSet<String> = self.admissions.iter().map(Admission::id).collect();
280        for a in &other.admissions {
281            if !have.contains(&a.id()) && a.signed() {
282                self.admissions.push(a.clone());
283            }
284        }
285    }
286
287    /// This chain without the local `root` and `approved`, for the wire.
288    pub fn shared(&self) -> KeyChain {
289        KeyChain { root: None, approved: Vec::new(), ..self.clone() }
290    }
291}
292
293/// A rotation that counts, with its members.
294#[derive(Debug, Clone)]
295pub struct ValidRotation {
296    pub id: String,
297    pub epoch: u32,
298    pub members: BTreeSet<String>,
299    pub clean: bool,
300}
301
302/// The chain as this roster sees it: valid rotations from the root, and the head.
303#[derive(Debug, Clone, Default)]
304pub struct ChainView {
305    pub root: Option<String>,
306    pub valid: BTreeMap<String, ValidRotation>,
307    pub admissions: Vec<String>,
308    pub head: Option<String>,
309}
310
311impl ChainView {
312    pub fn head(&self) -> Option<&ValidRotation> {
313        self.head.as_ref().and_then(|h| self.valid.get(h))
314    }
315
316    /// The head has a member that has since been revoked.
317    pub fn dirty(&self) -> bool {
318        self.head().is_some_and(|h| !h.clean)
319    }
320}
321
322impl Roster {
323    fn revoked_set(&self) -> BTreeSet<&str> {
324        self.certs.iter().filter(|c| !c.active()).map(|c| c.peer_id.as_str()).collect()
325    }
326
327    fn active_set(&self) -> BTreeSet<&str> {
328        self.active().map(|c| c.peer_id.as_str()).collect()
329    }
330
331    /// Work out which rotations count, their members, and the head.
332    pub fn chain_view(&self) -> ChainView {
333        let revoked = self.revoked_set();
334        let active = self.active_set();
335        let rots: Vec<(String, &Rotation)> =
336            self.chain.rotations.iter().filter(|r| active.contains(r.by.as_str()) && r.signed()).map(|r| (r.id(), r)).collect();
337        let adms: Vec<(String, &Admission)> =
338            self.chain.admissions.iter().filter(|a| active.contains(a.by.as_str()) && a.signed()).map(|a| (a.id(), a)).collect();
339
340        let roots: Vec<&(String, &Rotation)> = rots.iter().filter(|(_, r)| r.parent.is_none() && r.recipients().any(|p| p == r.by)).collect();
341        let root = match &self.chain.root {
342            Some(id) => roots.iter().find(|(rid, _)| rid == id),
343            None => roots.iter().min_by(|a, b| (a.1.epoch, &a.0).cmp(&(b.1.epoch, &b.0))),
344        };
345        let mut view = ChainView::default();
346        let Some((root_id, root_rot)) = root else { return view };
347        view.root = Some(root_id.clone());
348
349        let members_of = |id: &str, r: &Rotation, admitted: &mut Vec<String>| -> BTreeSet<String> {
350            let mut m: BTreeSet<String> = r.recipients().map(str::to_string).collect();
351            loop {
352                let mut grew = false;
353                for (aid, a) in adms.iter().filter(|(_, a)| a.rotation == id) {
354                    if m.contains(&a.by) && !revoked.contains(a.by.as_str()) && !m.contains(&a.peer_id) {
355                        m.insert(a.peer_id.clone());
356                        admitted.push(aid.clone());
357                        grew = true;
358                    }
359                }
360                if !grew {
361                    return m;
362                }
363            }
364        };
365        let mut admitted = Vec::new();
366        let add = |view: &mut ChainView, id: &str, r: &Rotation, admitted: &mut Vec<String>| {
367            let members = members_of(id, r, admitted);
368            let clean = !members.iter().any(|m| revoked.contains(m.as_str()));
369            view.valid.insert(id.to_string(), ValidRotation { id: id.to_string(), epoch: r.epoch, members, clean });
370        };
371        add(&mut view, root_id, root_rot, &mut admitted);
372        loop {
373            let mut grew = false;
374            for (id, r) in &rots {
375                if view.valid.contains_key(id) {
376                    continue;
377                }
378                let Some(p) = r.parent.as_ref().and_then(|p| view.valid.get(p)) else { continue };
379                if r.epoch == p.epoch.saturating_add(1) && p.members.contains(&r.by) && r.recipients().any(|x| x == r.by) {
380                    add(&mut view, id, r, &mut admitted);
381                    grew = true;
382                }
383            }
384            if !grew {
385                break;
386            }
387        }
388        view.admissions = admitted;
389        view.head = view
390            .valid
391            .values()
392            .max_by(|a, b| (a.epoch, a.clean, std::cmp::Reverse(&a.id)).cmp(&(b.epoch, b.clean, std::cmp::Reverse(&b.id))))
393            .map(|v| v.id.clone());
394        view
395    }
396
397    /// The head rotation id, if the chain has started.
398    pub fn head_id(&self) -> Option<String> {
399        self.chain_view().head
400    }
401}
402
403/// The epoch keys this device holds, by rotation id. Secret: the application stores it
404/// encrypted ([`EpochKeys::export`]) and never logs it.
405#[derive(Clone, Default, PartialEq)]
406pub struct EpochKeys {
407    keys: BTreeMap<String, (u32, Key32)>,
408}
409
410impl std::fmt::Debug for EpochKeys {
411    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
412        write!(f, "EpochKeys({} keys)", self.keys.len())
413    }
414}
415
416#[derive(Serialize, Deserialize)]
417struct KeyEntry {
418    id: String,
419    epoch: u32,
420    key: [u8; 32],
421}
422
423impl EpochKeys {
424    pub fn new() -> Self {
425        Self::default()
426    }
427    pub fn get(&self, id: &str) -> Option<&Key32> {
428        self.keys.get(id).map(|(_, k)| k)
429    }
430    pub fn has(&self, id: &str) -> bool {
431        self.keys.contains_key(id)
432    }
433    pub fn insert(&mut self, id: String, epoch: u32, key: Key32) {
434        self.keys.insert(id, (epoch, key));
435    }
436    pub fn len(&self) -> usize {
437        self.keys.len()
438    }
439    pub fn is_empty(&self) -> bool {
440        self.keys.is_empty()
441    }
442    pub fn ids(&self) -> impl Iterator<Item = (&str, u32)> {
443        self.keys.iter().map(|(id, (e, _))| (id.as_str(), *e))
444    }
445    /// Take keys held by another copy of this state (keys are never dropped).
446    pub fn merge(&mut self, other: &EpochKeys) {
447        for (id, v) in &other.keys {
448            self.keys.entry(id.clone()).or_insert_with(|| v.clone());
449        }
450    }
451
452    fn entries(&self, only: impl Fn(&str) -> bool) -> Zeroizing<Vec<u8>> {
453        let mut list: Vec<KeyEntry> =
454            self.keys.iter().filter(|(id, _)| only(id)).map(|(id, (e, k))| KeyEntry { id: id.clone(), epoch: *e, key: k.0 }).collect();
455        let out = Zeroizing::new(encode(&list).unwrap_or_default());
456        for e in &mut list {
457            e.key.zeroize();
458        }
459        out
460    }
461
462    fn absorb(&mut self, bytes: &[u8], accept: impl Fn(&str, &Key32) -> bool) -> Result<usize> {
463        let mut list: Vec<KeyEntry> = decode(bytes)?;
464        let mut n = 0;
465        for e in &mut list {
466            let key = Key32(e.key);
467            e.key.zeroize();
468            if !self.has(&e.id) && accept(&e.id, &key) {
469                self.keys.insert(e.id.clone(), (e.epoch, key));
470                n += 1;
471            }
472        }
473        Ok(n)
474    }
475
476    /// CBOR for the application's encrypted store.
477    pub fn export(&self) -> Zeroizing<Vec<u8>> {
478        self.entries(|_| true)
479    }
480
481    pub fn import(bytes: &[u8]) -> Result<Self> {
482        let mut k = Self::new();
483        k.absorb(bytes, |_, _| true)?;
484        Ok(k)
485    }
486}
487
488fn seal_to(eph: &ExchangeSecret, to: &[u8; 32], transcript: &[u8], plain: &[u8]) -> Result<Sealed> {
489    let shared = eph.agree(to).ok_or_else(|| crypto("low-order device key"))?;
490    let (k, _) = exchange::derive(&shared, transcript, SEAL_KEY, SEAL_SAS)?;
491    Ok(seal(&k, plain, transcript)?)
492}
493
494fn open_from(me: &ExchangeSecret, eph_hex: &str, transcript: &[u8], sealed: &Sealed) -> Result<Zeroizing<Vec<u8>>> {
495    let eph: [u8; 32] = hex::decode(eph_hex).ok().and_then(|b| b.try_into().ok()).ok_or_else(|| crypto("bad ephemeral key"))?;
496    let shared = me.agree(&eph).ok_or_else(|| crypto("low-order ephemeral key"))?;
497    let (k, _) = exchange::derive(&shared, transcript, SEAL_KEY, SEAL_SAS)?;
498    Ok(open(&k, sealed, transcript)?)
499}
500
501/// Where this device stands with rotated keys.
502#[derive(Debug, Clone, PartialEq, Eq)]
503pub enum KeyStatus {
504    /// No rotation yet: keys come from the seed, as in 0.2.
505    Seed,
506    /// Holding the head key at this epoch.
507    Current { epoch: u32 },
508    /// The chain has moved on and this device was not given the key: another device
509    /// must re-admit it (for example after a restore from the recovery words).
510    NeedsAdmission,
511    /// This device has been revoked.
512    Revoked,
513}
514
515impl SyncState {
516    /// Put this device's exchange key in the roster so rotations can include it.
517    pub fn publish_device_key(&mut self, at_ms: i64) -> Result<()> {
518        let device = self.device.as_ref().ok_or_else(|| SyncError::Protocol("no device key".into()))?;
519        if self.roster.chain.device(&device.peer_id()).is_none() {
520            let dk = device.device_key(at_ms)?;
521            self.roster.chain.add_device(dk);
522        }
523        Ok(())
524    }
525
526    pub fn key_status(&self) -> KeyStatus {
527        if self.roster.get(&self.our_cert.peer_id).is_some_and(|c| !c.active()) || !self.our_cert.active() {
528            return KeyStatus::Revoked;
529        }
530        let view = self.roster.chain_view();
531        match view.head() {
532            None => KeyStatus::Seed,
533            Some(h) if self.keys.has(&h.id) => KeyStatus::Current { epoch: h.epoch },
534            Some(_) => KeyStatus::NeedsAdmission,
535        }
536    }
537
538    pub fn needs_admission(&self) -> bool {
539        self.key_status() == KeyStatus::NeedsAdmission
540    }
541
542    /// Active devices that have not published a device key yet (not upgraded, or not
543    /// synced since). A rotation now leaves them out; they would need re-admission.
544    /// Apps warn before revoking while this is not empty.
545    pub fn devices_without_key(&self) -> Vec<NodeCert> {
546        self.roster.active().filter(|c| self.roster.chain.device(&c.peer_id).is_none_or(|d| !d.verify())).cloned().collect()
547    }
548
549    /// The first rotation should happen now, on this device: there is no rotation yet,
550    /// at least two devices are linked, every active device has published its device
551    /// key, and this device has the lowest peer id among them (so only one device
552    /// starts the chain). Covers both "right after the first link" and "once after an
553    /// upgrade from seed-only keys". [`crate::pull_from`] does it when
554    /// [`SyncState::auto_first_rotation`] is on; apps may also call
555    /// [`SyncState::rotate_if_first_due`].
556    pub fn first_rotation_due(&self) -> bool {
557        let Some(device) = &self.device else { return false };
558        if self.key_status() != KeyStatus::Seed {
559            return false;
560        }
561        let active: Vec<&NodeCert> = self.roster.active().collect();
562        let me = device.peer_id();
563        active.len() >= 2 && active.iter().any(|c| c.peer_id == me) && self.devices_without_key().is_empty() && active.iter().all(|c| c.peer_id >= me)
564    }
565
566    /// Make the first rotation if [`SyncState::first_rotation_due`]. Returns its id.
567    pub fn rotate_if_first_due(&mut self, at_ms: i64) -> Result<Option<String>> {
568        if self.first_rotation_due() { self.rotate(at_ms).map(Some) } else { Ok(None) }
569    }
570
571    /// The head has a revoked member and this device can replace it.
572    pub fn needs_rotation(&self) -> bool {
573        let view = self.roster.chain_view();
574        self.device.is_some() && view.dirty() && view.head().is_some_and(|h| self.keys.has(&h.id)) && self.key_status() != KeyStatus::Revoked
575    }
576
577    /// Open every key sealed or admitted to this device and adopt the root. Returns how
578    /// many keys were new.
579    pub fn refresh_keys(&mut self) -> usize {
580        let Some(device) = self.device.clone() else { return 0 };
581        let me = device.peer_id();
582        let Some(my_pub) = self.roster.chain.device(&me).and_then(DeviceKey::public) else { return 0 };
583        let view = self.roster.chain_view();
584        let mut n = 0;
585        let checks: BTreeMap<String, String> = self.roster.chain.rotations.iter().map(|r| (r.id(), r.check.clone())).collect();
586        for r in &self.roster.chain.rotations {
587            let id = r.id();
588            if !view.valid.contains_key(&id) || self.keys.has(&id) {
589                continue;
590            }
591            let Some(sk) = r.keys.iter().find(|k| k.peer_id == me) else { continue };
592            if let Ok(plain) = open_from(&device.exchange, &r.eph, &r.transcript(&me, &my_pub), &sk.sealed)
593                && let Ok(key) = Key32::from_slice(&plain)
594                && key_check(&key) == r.check
595            {
596                self.keys.insert(id, r.epoch, key);
597                n += 1;
598            }
599        }
600        for a in &self.roster.chain.admissions {
601            if a.peer_id != me || !view.admissions.contains(&a.id()) {
602                continue;
603            }
604            if let Ok(plain) = open_from(&device.exchange, &a.eph, &a.transcript(&my_pub), &a.sealed) {
605                n += self
606                    .keys
607                    .absorb(&plain, |id, key| view.valid.contains_key(id) && checks.get(id).is_some_and(|c| *c == key_check(key)))
608                    .unwrap_or(0);
609            }
610        }
611        if self.roster.chain.root.is_none()
612            && let Some(root) = &view.root
613            && view.valid.keys().any(|id| self.keys.has(id))
614        {
615            self.roster.chain.root = Some(root.clone());
616        }
617        if let Some(h) = view.head() {
618            self.roster.epoch = self.roster.epoch.max(h.epoch);
619        }
620        n
621    }
622
623    /// Make a fresh random epoch key and seal it to every remaining device that has
624    /// published a device key. Returns the new rotation id.
625    pub fn rotate(&mut self, at_ms: i64) -> Result<String> {
626        let device = self.device.clone().ok_or_else(|| SyncError::Protocol("no device key".into()))?;
627        let me = device.peer_id();
628        self.publish_device_key(at_ms)?;
629        if self.key_status() == KeyStatus::Revoked {
630            return Err(SyncError::Refused("revoked".into()));
631        }
632        let view = self.roster.chain_view();
633        let active: BTreeSet<String> = self.roster.active().map(|c| c.peer_id.clone()).collect();
634        let (parent, epoch, mut candidates): (Option<String>, u32, BTreeSet<String>) = match view.head() {
635            Some(h) if !self.keys.has(&h.id) => return Err(SyncError::Refused("needs-admission".into())),
636            Some(h) => (Some(h.id.clone()), h.epoch.saturating_add(1), h.members.clone()),
637            None => (None, self.roster.epoch.saturating_add(1), active.clone()),
638        };
639        candidates.extend(self.roster.chain.approved.iter().cloned());
640        let key = Key32::random()?;
641        let eph = ExchangeSecret::generate();
642        let mut r = Rotation {
643            epoch,
644            parent,
645            by: me.clone(),
646            at_ms,
647            eph: hex::encode(eph.public()),
648            check: key_check(&key),
649            keys: Vec::new(),
650            sig: Vec::new(),
651        };
652        let mut recipients: Vec<String> = candidates.into_iter().filter(|p| active.contains(p)).collect();
653        if !recipients.contains(&me) {
654            recipients.push(me.clone());
655        }
656        for peer in recipients {
657            let Some(public) = self.roster.chain.device(&peer).and_then(DeviceKey::public) else { continue };
658            let sealed = seal_to(&eph, &public, &r.transcript(&peer, &public), &key.0)?;
659            r.keys.push(SealedKey { peer_id: peer, sealed });
660        }
661        r.sig = device.sign(&r.body())?;
662        let id = r.id();
663        if r.parent.is_none() {
664            self.roster.chain.root = Some(id.clone());
665        }
666        self.roster.chain.rotations.push(r);
667        self.keys.insert(id.clone(), epoch, key);
668        self.roster.epoch = self.roster.epoch.max(epoch);
669        Ok(id)
670    }
671
672    /// Revoke a device and, when this state has a device key, rotate so the revoked
673    /// device cannot read anything written afterwards even though it holds the seed.
674    pub fn revoke(&mut self, user: &Keypair, peer_id: &str, at_ms: i64) -> Result<NodeCert> {
675        let cert = self.roster.revoke(&WEIRDNET, user, peer_id, at_ms)?;
676        if self.device.is_some() {
677            self.rotate(at_ms)?;
678        }
679        Ok(cert)
680    }
681
682    /// The user approved this device here (as when linking it). It is admitted now if
683    /// its device key is known, otherwise as soon as one of its hellos brings the key.
684    /// Returns whether it was admitted now.
685    pub fn approve(&mut self, cert: NodeCert, at_ms: i64) -> Result<bool> {
686        if !WEIRDNET.verify_cert(&self.user_key, &cert) || !cert.active() || cert.user_id != self.user_id {
687            return Err(SyncError::Refused("wrong-user".into()));
688        }
689        if self.roster.get(&cert.peer_id).is_some_and(|c| !c.active()) {
690            return Err(SyncError::Refused("revoked".into()));
691        }
692        let peer = cert.peer_id.clone();
693        self.roster.upsert(cert);
694        if !self.roster.chain.approved.contains(&peer) {
695            self.roster.chain.approved.push(peer.clone());
696        }
697        Ok(self.admit_approved(at_ms).contains(&peer))
698    }
699
700    /// Admit every approved device whose device key is known and that is not yet a
701    /// member of the head. Members and revoked devices leave the list. Returns the
702    /// devices admitted.
703    pub fn admit_approved(&mut self, at_ms: i64) -> Vec<String> {
704        let mut admitted = Vec::new();
705        if self.roster.chain.approved.is_empty() || self.device.is_none() {
706            return admitted;
707        }
708        for peer in self.roster.chain.approved.clone() {
709            let view = self.roster.chain_view();
710            let Some(head) = view.head() else { break };
711            if !self.keys.has(&head.id) {
712                break;
713            }
714            let done = head.members.contains(&peer) || self.roster.get(&peer).is_none_or(|c| !c.active());
715            if !done
716                && self.roster.chain.device(&peer).is_some()
717                && let Some(cert) = self.roster.get(&peer).cloned()
718                && self.admit(cert, at_ms).unwrap_or(false)
719            {
720                admitted.push(peer.clone());
721            }
722            if done || admitted.contains(&peer) {
723                self.roster.chain.approved.retain(|p| p != &peer);
724            }
725        }
726        admitted
727    }
728
729    /// Let a device back in (after the user approved it on this device, as when
730    /// linking; [`SyncState::approve`] waits for its device key): seal the head key and the older keys this device holds to its device
731    /// key. Returns false when there is nothing to admit to (no rotation yet: the seed
732    /// is enough).
733    pub fn admit(&mut self, cert: NodeCert, at_ms: i64) -> Result<bool> {
734        if !WEIRDNET.verify_cert(&self.user_key, &cert) || !cert.active() || cert.user_id != self.user_id {
735            return Err(SyncError::Refused("wrong-user".into()));
736        }
737        if self.roster.get(&cert.peer_id).is_some_and(|c| !c.active()) {
738            return Err(SyncError::Refused("revoked".into()));
739        }
740        let device = self.device.clone().ok_or_else(|| SyncError::Protocol("no device key".into()))?;
741        let peer = cert.peer_id.clone();
742        self.roster.upsert(cert);
743        let view = self.roster.chain_view();
744        let Some(head) = view.head() else { return Ok(false) };
745        if !self.keys.has(&head.id) {
746            return Err(SyncError::Refused("needs-admission".into()));
747        }
748        let public = self
749            .roster
750            .chain
751            .device(&peer)
752            .and_then(DeviceKey::public)
753            .ok_or_else(|| SyncError::Protocol(format!("no device key for {peer} yet")))?;
754        let eph = ExchangeSecret::generate();
755        let mut a = Admission {
756            rotation: head.id.clone(),
757            peer_id: peer,
758            by: device.peer_id(),
759            at_ms,
760            eph: hex::encode(eph.public()),
761            sealed: Sealed { nonce: String::new(), ct: String::new() },
762            sig: Vec::new(),
763        };
764        let plain = self.keys.entries(|id| view.valid.contains_key(id));
765        a.sealed = seal_to(&eph, &public, &a.transcript(&public), &plain)?;
766        a.sig = device.sign(&a.body())?;
767        self.roster.chain.admissions.push(a);
768        Ok(true)
769    }
770}
771
772#[cfg(test)]
773mod tests {
774    use super::*;
775
776    #[test]
777    fn a_device_key_verifies_only_for_its_own_node() {
778        let node = Keypair::generate_ed25519();
779        let d = Device::from_node_key(&node).unwrap();
780        let dk = d.device_key(5).unwrap();
781        assert!(dk.verify());
782        assert_eq!(dk.peer_id, node.public().to_peer_id().to_string());
783        // Same node key, same exchange key (nothing new to store).
784        assert_eq!(Device::from_node_key(&node).unwrap().device_key(5).unwrap().exchange, dk.exchange);
785        let other = Device::from_node_key(&Keypair::generate_ed25519()).unwrap().device_key(5).unwrap();
786        assert!(!DeviceKey { exchange: other.exchange.clone(), ..dk.clone() }.verify(), "a swapped exchange key fails");
787        assert!(!DeviceKey { peer_id: other.peer_id.clone(), ..dk.clone() }.verify());
788        assert_eq!(dk.fingerprint().len(), 14);
789        assert!(format!("{d:?}").starts_with("Device(12D3"));
790    }
791
792    #[test]
793    fn epoch_keys_export_and_import() {
794        let mut k = EpochKeys::new();
795        k.insert("a".into(), 1, Key32::random().unwrap());
796        k.insert("b".into(), 2, Key32::random().unwrap());
797        let back = EpochKeys::import(&k.export()).unwrap();
798        assert_eq!(back, k);
799        assert_eq!(format!("{k:?}"), "EpochKeys(2 keys)");
800    }
801
802    #[test]
803    fn a_sealed_copy_opens_only_for_its_recipient() {
804        let a = Device::from_node_key(&Keypair::generate_ed25519()).unwrap();
805        let b = Device::from_node_key(&Keypair::generate_ed25519()).unwrap();
806        let eph = ExchangeSecret::generate();
807        let to = a.exchange.public();
808        let s = seal_to(&eph, &to, b"t", b"key").unwrap();
809        let eph_hex = hex::encode(eph.public());
810        assert_eq!(&open_from(&a.exchange, &eph_hex, b"t", &s).unwrap()[..], b"key");
811        assert!(open_from(&b.exchange, &eph_hex, b"t", &s).is_err());
812        assert!(open_from(&a.exchange, &eph_hex, b"other", &s).is_err());
813    }
814
815    #[test]
816    fn peer_public_round_trips() {
817        let k = Keypair::generate_ed25519();
818        let pid = k.public().to_peer_id().to_string();
819        assert_eq!(peer_public(&pid).unwrap(), k.public());
820        assert!(peer_public("not-a-peer").is_none());
821    }
822}