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/// Default profile used for certs unless the application passes another.
151pub fn default_profile() -> &'static Profile {
152    &WEIRDNET
153}
154
155#[cfg(test)]
156mod tests {
157    use super::*;
158    use weirdnet_net::Keypair;
159
160    fn user() -> Keypair {
161        Keypair::generate_ed25519()
162    }
163
164    #[test]
165    fn first_device_self_certifies_and_is_the_roster_of_one() {
166        let u = user();
167        let cert = Roster::self_certify(&WEIRDNET, &u, "peer-a", "desktop", 1_000).unwrap();
168        assert_eq!(cert.peer_id, "peer-a");
169        assert!(cert.active());
170        assert!(WEIRDNET.verify_cert(&u.public(), &cert));
171        let mut r = Roster::new();
172        r.upsert(cert);
173        assert_eq!(r.active().count(), 1);
174        assert_eq!(r.epoch, 0);
175    }
176
177    #[test]
178    fn revoke_bumps_the_epoch_and_rejects_that_peer() {
179        let u = user();
180        let uid = user::user_id(&u.public());
181        let mut r = Roster::new();
182        r.upsert(Roster::self_certify(&WEIRDNET, &u, "peer-a", "phone", 1).unwrap());
183        r.upsert(Roster::self_certify(&WEIRDNET, &u, "peer-b", "desktop", 2).unwrap());
184        let revoked = r.revoke(&WEIRDNET, &u, "peer-a", 3).unwrap();
185        assert_eq!(r.epoch, 1);
186        assert!(!revoked.active());
187        assert!(WEIRDNET.verify_cert(&u.public(), &revoked));
188        let check = r.check_session(
189            &WEIRDNET,
190            &u.public(),
191            &uid,
192            &SessionOffer { cert: &revoked, epoch: 1, types: &["bookmarks".into()] },
193            &["bookmarks".into()],
194        );
195        assert_eq!(check, SessionCheck::Revoked);
196        let b = r.get("peer-b").unwrap().clone();
197        assert_eq!(
198            r.check_session(&WEIRDNET, &u.public(), &uid, &SessionOffer { cert: &b, epoch: 1, types: &["bookmarks".into()] }, &["bookmarks".into()]),
199            SessionCheck::Ok
200        );
201        assert_eq!(
202            r.check_session(&WEIRDNET, &u.public(), &uid, &SessionOffer { cert: &b, epoch: 0, types: &["bookmarks".into()] }, &["bookmarks".into()]),
203            SessionCheck::EpochBehind
204        );
205        assert_eq!(
206            r.check_session(&WEIRDNET, &u.public(), &uid, &SessionOffer { cert: &b, epoch: 1, types: &["settings".into()] }, &["bookmarks".into()]),
207            SessionCheck::TypeOff
208        );
209    }
210
211    #[test]
212    fn a_foreign_user_cert_is_wrong_user() {
213        let a = user();
214        let b = user();
215        let cert = Roster::self_certify(&WEIRDNET, &b, "peer-x", "x", 1).unwrap();
216        let r = Roster::new();
217        let uid = user::user_id(&a.public());
218        assert_eq!(
219            r.check_session(
220                &WEIRDNET,
221                &a.public(),
222                &uid,
223                &SessionOffer { cert: &cert, epoch: 0, types: &["bookmarks".into()] },
224                &["bookmarks".into()]
225            ),
226            SessionCheck::WrongUser
227        );
228    }
229
230    #[test]
231    fn merge_takes_a_signed_revocation_and_the_higher_epoch() {
232        let u = user();
233        let mut a = Roster::new();
234        let mut b = Roster::new();
235        let ca = Roster::self_certify(&WEIRDNET, &u, "peer-a", "a", 1).unwrap();
236        let cb = Roster::self_certify(&WEIRDNET, &u, "peer-b", "b", 2).unwrap();
237        a.upsert(ca.clone());
238        a.upsert(cb.clone());
239        b.upsert(ca);
240        b.upsert(cb);
241        b.revoke(&WEIRDNET, &u, "peer-a", 9).unwrap();
242        a.merge(&b, &u.public(), &WEIRDNET);
243        assert_eq!(a.epoch, 1);
244        assert!(!a.get("peer-a").unwrap().active());
245        assert!(a.get("peer-b").unwrap().active());
246    }
247}