Skip to main content

weirdnet_sync/
roster.rs

1//! Device roster: self-issued [`NodeCert`]s, revocations and the key epoch.
2//!
3//! Certificates themselves are created and checked by [`weirdnet_net::user`] /
4//! [`Profile::certify`]. This module keeps the set, bumps the epoch on revoke, and
5//! decides whether a peer may start a sync session. The key chain ([`KeyChain`]: device
6//! keys, rotations and admissions) travels with the roster; see [`crate::rotation`].
7use crate::error::{Result, SyncError};
8use crate::rotation::KeyChain;
9use serde::{Deserialize, Serialize};
10use weirdnet_net::profile::{Profile, WEIRDNET};
11use weirdnet_net::user::{self, NodeCert};
12use weirdnet_net::{Keypair, PublicKey};
13
14/// The user's devices and the current sealing epoch.
15#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
16pub struct Roster {
17    pub epoch: u32,
18    pub certs: Vec<NodeCert>,
19    /// Device keys, rotations and admissions (public; sealed epoch keys inside).
20    #[serde(default, skip_serializing_if = "KeyChain::is_empty_and_rootless")]
21    pub chain: KeyChain,
22}
23
24impl Roster {
25    pub fn new() -> Self {
26        Self::default()
27    }
28
29    /// The first device to hold an identity self-certifies and is the initial roster of one.
30    pub fn self_certify(profile: &Profile, user: &Keypair, peer_id: &str, label: &str, at_ms: i64) -> Result<NodeCert> {
31        let uid = user::user_id(&user.public());
32        Ok(profile.certify(user, &uid, peer_id, label, at_ms)?)
33    }
34
35    /// Insert or replace the cert for this peer id. Does not change the epoch.
36    pub fn upsert(&mut self, cert: NodeCert) {
37        if let Some(existing) = self.certs.iter_mut().find(|c| c.peer_id == cert.peer_id) {
38            *existing = cert;
39        } else {
40            self.certs.push(cert);
41        }
42    }
43
44    pub fn get(&self, peer_id: &str) -> Option<&NodeCert> {
45        self.certs.iter().find(|c| c.peer_id == peer_id)
46    }
47
48    pub fn active(&self) -> impl Iterator<Item = &NodeCert> {
49        self.certs.iter().filter(|c| c.active())
50    }
51
52    /// Sign a revocation, attach it to the cert, and bump the key epoch. This alone does
53    /// not shut out a device that holds the seed: use [`crate::SyncState::revoke`], which
54    /// also rotates to a random epoch key.
55    pub fn revoke(&mut self, profile: &Profile, user: &Keypair, peer_id: &str, at_ms: i64) -> Result<NodeCert> {
56        let uid = user::user_id(&user.public());
57        let sig = profile.revoke(user, &uid, peer_id, at_ms)?;
58        let cert = self.certs.iter_mut().find(|c| c.peer_id == peer_id).ok_or_else(|| SyncError::Protocol(format!("no cert for {peer_id}")))?;
59        if cert.user_id != uid {
60            return Err(SyncError::Protocol("revocation user does not match the cert".into()));
61        }
62        cert.revoked_at = Some(at_ms);
63        cert.revocation = Some(sig);
64        self.epoch = self.epoch.saturating_add(1);
65        Ok(cert.clone())
66    }
67
68    /// Merge another replica's certs and key chain. A signed revocation wins over a
69    /// still-active copy of the same cert. The epoch is the max of the two.
70    pub fn merge(&mut self, other: &Roster, key: &PublicKey, profile: &Profile) {
71        self.epoch = self.epoch.max(other.epoch);
72        self.chain.merge(&other.chain);
73        for c in &other.certs {
74            if !profile.verify_cert(key, c) {
75                continue;
76            }
77            match self.certs.iter_mut().find(|x| x.peer_id == c.peer_id) {
78                Some(existing) => {
79                    if !existing.active() {
80                        continue;
81                    }
82                    if !c.active() {
83                        *existing = c.clone();
84                    }
85                }
86                None => self.certs.push(c.clone()),
87            }
88        }
89    }
90}
91
92/// Why a hello is refused, as sent on the wire.
93#[derive(Debug, Clone, Copy, PartialEq, Eq)]
94pub enum SessionCheck {
95    Ok,
96    WrongUser,
97    Revoked,
98    EpochBehind,
99    TypeOff,
100}
101
102impl SessionCheck {
103    pub fn reason(self) -> Option<&'static str> {
104        match self {
105            SessionCheck::Ok => None,
106            SessionCheck::WrongUser => Some("wrong-user"),
107            SessionCheck::Revoked => Some("revoked"),
108            SessionCheck::EpochBehind => Some("epoch-behind"),
109            SessionCheck::TypeOff => Some("type-off"),
110        }
111    }
112}
113
114/// What a peer presents in Hello, for [`Roster::check_session`].
115pub struct SessionOffer<'a> {
116    pub cert: &'a NodeCert,
117    pub epoch: u32,
118    pub types: &'a [String],
119}
120
121impl Roster {
122    /// Accept a session only if the cert is for `user_id`, verifies, is not revoked, and
123    /// the peer's epoch is not behind ours. `offered_types` must intersect `our_types`.
124    pub fn check_session(
125        &self,
126        profile: &Profile,
127        user_key: &PublicKey,
128        user_id: &str,
129        offer: &SessionOffer<'_>,
130        our_types: &[String],
131    ) -> SessionCheck {
132        let cert = offer.cert;
133        if cert.user_id != user_id || user::user_id(user_key) != user_id || !profile.verify_cert(user_key, cert) {
134            return SessionCheck::WrongUser;
135        }
136        let revoked_here = self.get(&cert.peer_id).is_some_and(|c| !c.active()) || !cert.active();
137        if revoked_here || !profile.verify_cert(user_key, cert) {
138            return SessionCheck::Revoked;
139        }
140        if offer.epoch < self.epoch {
141            return SessionCheck::EpochBehind;
142        }
143        if !offer.types.iter().any(|t| our_types.iter().any(|o| o == t)) {
144            return SessionCheck::TypeOff;
145        }
146        SessionCheck::Ok
147    }
148}
149
150/// What [`Roster::check_caller`] decided about a caller.
151#[derive(Debug, Clone, Copy, PartialEq, Eq)]
152pub enum CallerCheck {
153    /// An active, verified device of this user, in the key chain's head once there is one.
154    Linked,
155    /// No cert for this peer in the roster. A cert the caller presents is not enough: anyone
156    /// holding the seed (a revoked device too) can mint one.
157    Unknown,
158    /// Revoked here, or the caller presented a revoked cert.
159    Revoked,
160    /// The cert is for another user or another peer, or does not verify.
161    WrongUser,
162    /// In the roster but not a member of the current key chain's head (not yet admitted).
163    NotAdmitted,
164}
165
166impl CallerCheck {
167    /// The refusal reason to send back, `None` for [`CallerCheck::Linked`].
168    pub fn reason(self) -> Option<&'static str> {
169        match self {
170            CallerCheck::Linked => None,
171            CallerCheck::Unknown => Some("unknown-device"),
172            CallerCheck::Revoked => Some("revoked"),
173            CallerCheck::WrongUser => Some("wrong-user"),
174            CallerCheck::NotAdmitted => Some("needs-admission"),
175        }
176    }
177}
178
179impl Roster {
180    /// Whether the caller of an app call or stream served by this device is one of the
181    /// user's linked devices. `peer` must be the transport-authenticated peer id (Noise),
182    /// never one the caller sent. `presented` is the cert the caller sent with the call, if
183    /// any; it must match `peer` and the user, and a revoked one is refused, but only this
184    /// roster's own cert admits a caller.
185    pub fn check_caller(&self, profile: &Profile, user_key: &PublicKey, peer: &str, presented: Option<&NodeCert>) -> CallerCheck {
186        let uid = user::user_id(user_key);
187        if let Some(p) = presented {
188            if p.peer_id != peer || p.user_id != uid || !profile.verify_cert(user_key, p) {
189                return CallerCheck::WrongUser;
190            }
191            if !p.active() {
192                return CallerCheck::Revoked;
193            }
194        }
195        let Some(cert) = self.get(peer) else { return CallerCheck::Unknown };
196        if !cert.active() {
197            return CallerCheck::Revoked;
198        }
199        if cert.user_id != uid || !profile.verify_cert(user_key, cert) {
200            return CallerCheck::WrongUser;
201        }
202        if self.chain_view().head().is_some_and(|h| !h.members.contains(peer)) {
203            return CallerCheck::NotAdmitted;
204        }
205        CallerCheck::Linked
206    }
207}
208
209/// Default profile used for certs unless the application passes another.
210pub fn default_profile() -> &'static Profile {
211    &WEIRDNET
212}
213
214#[cfg(test)]
215mod tests {
216    use super::*;
217    use weirdnet_net::Keypair;
218
219    fn user() -> Keypair {
220        Keypair::generate_ed25519()
221    }
222
223    #[test]
224    fn first_device_self_certifies_and_is_the_roster_of_one() {
225        let u = user();
226        let cert = Roster::self_certify(&WEIRDNET, &u, "peer-a", "desktop", 1_000).unwrap();
227        assert_eq!(cert.peer_id, "peer-a");
228        assert!(cert.active());
229        assert!(WEIRDNET.verify_cert(&u.public(), &cert));
230        let mut r = Roster::new();
231        r.upsert(cert);
232        assert_eq!(r.active().count(), 1);
233        assert_eq!(r.epoch, 0);
234    }
235
236    #[test]
237    fn revoke_bumps_the_epoch_and_rejects_that_peer() {
238        let u = user();
239        let uid = user::user_id(&u.public());
240        let mut r = Roster::new();
241        r.upsert(Roster::self_certify(&WEIRDNET, &u, "peer-a", "phone", 1).unwrap());
242        r.upsert(Roster::self_certify(&WEIRDNET, &u, "peer-b", "desktop", 2).unwrap());
243        let revoked = r.revoke(&WEIRDNET, &u, "peer-a", 3).unwrap();
244        assert_eq!(r.epoch, 1);
245        assert!(!revoked.active());
246        assert!(WEIRDNET.verify_cert(&u.public(), &revoked));
247        let check = r.check_session(
248            &WEIRDNET,
249            &u.public(),
250            &uid,
251            &SessionOffer { cert: &revoked, epoch: 1, types: &["bookmarks".into()] },
252            &["bookmarks".into()],
253        );
254        assert_eq!(check, SessionCheck::Revoked);
255        let b = r.get("peer-b").unwrap().clone();
256        assert_eq!(
257            r.check_session(&WEIRDNET, &u.public(), &uid, &SessionOffer { cert: &b, epoch: 1, types: &["bookmarks".into()] }, &["bookmarks".into()]),
258            SessionCheck::Ok
259        );
260        assert_eq!(
261            r.check_session(&WEIRDNET, &u.public(), &uid, &SessionOffer { cert: &b, epoch: 0, types: &["bookmarks".into()] }, &["bookmarks".into()]),
262            SessionCheck::EpochBehind
263        );
264        assert_eq!(
265            r.check_session(&WEIRDNET, &u.public(), &uid, &SessionOffer { cert: &b, epoch: 1, types: &["settings".into()] }, &["bookmarks".into()]),
266            SessionCheck::TypeOff
267        );
268    }
269
270    #[test]
271    fn a_foreign_user_cert_is_wrong_user() {
272        let a = user();
273        let b = user();
274        let cert = Roster::self_certify(&WEIRDNET, &b, "peer-x", "x", 1).unwrap();
275        let r = Roster::new();
276        let uid = user::user_id(&a.public());
277        assert_eq!(
278            r.check_session(
279                &WEIRDNET,
280                &a.public(),
281                &uid,
282                &SessionOffer { cert: &cert, epoch: 0, types: &["bookmarks".into()] },
283                &["bookmarks".into()]
284            ),
285            SessionCheck::WrongUser
286        );
287    }
288
289    #[test]
290    fn callers_are_checked_against_the_roster() {
291        let u = user();
292        let mut r = Roster::new();
293        r.upsert(Roster::self_certify(&WEIRDNET, &u, "peer-a", "desktop", 1).unwrap());
294        r.upsert(Roster::self_certify(&WEIRDNET, &u, "peer-b", "phone", 2).unwrap());
295        let a = r.get("peer-a").unwrap().clone();
296        let check = |r: &Roster, peer: &str, presented: Option<&NodeCert>| r.check_caller(&WEIRDNET, &u.public(), peer, presented);
297        assert_eq!(check(&r, "peer-a", None), CallerCheck::Linked);
298        assert_eq!(check(&r, "peer-a", Some(&a)), CallerCheck::Linked);
299        assert_eq!(check(&r, "peer-b", Some(&a)), CallerCheck::WrongUser, "a cert for another peer");
300        // A cert minted with the user key for a peer this roster never had.
301        let minted = Roster::self_certify(&WEIRDNET, &u, "peer-m", "minted", 3).unwrap();
302        assert_eq!(check(&r, "peer-m", Some(&minted)), CallerCheck::Unknown);
303        assert_eq!(check(&r, "peer-x", None), CallerCheck::Unknown);
304        // Another user's device.
305        let other = user();
306        let foreign = Roster::self_certify(&WEIRDNET, &other, "peer-a", "x", 1).unwrap();
307        assert_eq!(check(&r, "peer-a", Some(&foreign)), CallerCheck::WrongUser);
308        let mut theirs = Roster::new();
309        theirs.upsert(foreign);
310        assert_eq!(check(&theirs, "peer-a", None), CallerCheck::WrongUser);
311        // Revoked here, and a revoked cert presented to a roster that has not heard.
312        let stale = r.clone();
313        let revoked = r.revoke(&WEIRDNET, &u, "peer-b", 4).unwrap();
314        assert_eq!(check(&r, "peer-b", None), CallerCheck::Revoked);
315        assert_eq!(check(&stale, "peer-b", Some(&revoked)), CallerCheck::Revoked);
316        assert_eq!(CallerCheck::Revoked.reason(), Some("revoked"));
317        assert_eq!(CallerCheck::Linked.reason(), None);
318    }
319
320    #[test]
321    fn merge_takes_a_signed_revocation_and_the_higher_epoch() {
322        let u = user();
323        let mut a = Roster::new();
324        let mut b = Roster::new();
325        let ca = Roster::self_certify(&WEIRDNET, &u, "peer-a", "a", 1).unwrap();
326        let cb = Roster::self_certify(&WEIRDNET, &u, "peer-b", "b", 2).unwrap();
327        a.upsert(ca.clone());
328        a.upsert(cb.clone());
329        b.upsert(ca);
330        b.upsert(cb);
331        b.revoke(&WEIRDNET, &u, "peer-a", 9).unwrap();
332        a.merge(&b, &u.public(), &WEIRDNET);
333        assert_eq!(a.epoch, 1);
334        assert!(!a.get("peer-a").unwrap().active());
335        assert!(a.get("peer-b").unwrap().active());
336    }
337}