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