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.
6use crate::error::{Result, SyncError};
7use serde::{Deserialize, Serialize};
8use weirdnet_net::profile::{Profile, WEIRDNET};
9use weirdnet_net::user::{self, NodeCert};
10use weirdnet_net::{Keypair, PublicKey};
11
12/// The user's devices and the current sealing epoch.
13#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
14pub struct Roster {
15    pub epoch: u32,
16    pub certs: Vec<NodeCert>,
17}
18
19impl Roster {
20    pub fn new() -> Self {
21        Self::default()
22    }
23
24    /// The first device to hold an identity self-certifies and is the initial roster of one.
25    pub fn self_certify(profile: &Profile, user: &Keypair, peer_id: &str, label: &str, at_ms: i64) -> Result<NodeCert> {
26        let uid = user::user_id(&user.public());
27        Ok(profile.certify(user, &uid, peer_id, label, at_ms)?)
28    }
29
30    /// Insert or replace the cert for this peer id. Does not change the epoch.
31    pub fn upsert(&mut self, cert: NodeCert) {
32        if let Some(existing) = self.certs.iter_mut().find(|c| c.peer_id == cert.peer_id) {
33            *existing = cert;
34        } else {
35            self.certs.push(cert);
36        }
37    }
38
39    pub fn get(&self, peer_id: &str) -> Option<&NodeCert> {
40        self.certs.iter().find(|c| c.peer_id == peer_id)
41    }
42
43    pub fn active(&self) -> impl Iterator<Item = &NodeCert> {
44        self.certs.iter().filter(|c| c.active())
45    }
46
47    /// Sign a revocation, attach it to the cert, and bump the key epoch so the revoked
48    /// node cannot decrypt later pages even if it still has an old `SyncKey`.
49    pub fn revoke(&mut self, profile: &Profile, user: &Keypair, peer_id: &str, at_ms: i64) -> Result<NodeCert> {
50        let uid = user::user_id(&user.public());
51        let sig = profile.revoke(user, &uid, peer_id, at_ms)?;
52        let cert = self.certs.iter_mut().find(|c| c.peer_id == peer_id).ok_or_else(|| SyncError::Protocol(format!("no cert for {peer_id}")))?;
53        if cert.user_id != uid {
54            return Err(SyncError::Protocol("revocation user does not match the cert".into()));
55        }
56        cert.revoked_at = Some(at_ms);
57        cert.revocation = Some(sig);
58        self.epoch = self.epoch.saturating_add(1);
59        Ok(cert.clone())
60    }
61
62    /// Merge another replica's certs. A signed revocation wins over a still-active copy
63    /// of the same cert. The epoch is the max of the two.
64    pub fn merge(&mut self, other: &Roster, key: &PublicKey, profile: &Profile) {
65        self.epoch = self.epoch.max(other.epoch);
66        for c in &other.certs {
67            if !profile.verify_cert(key, c) {
68                continue;
69            }
70            match self.certs.iter_mut().find(|x| x.peer_id == c.peer_id) {
71                Some(existing) => {
72                    if !existing.active() {
73                        continue;
74                    }
75                    if !c.active() {
76                        *existing = c.clone();
77                    }
78                }
79                None => self.certs.push(c.clone()),
80            }
81        }
82    }
83}
84
85/// Why a hello is refused, as sent on the wire.
86#[derive(Debug, Clone, Copy, PartialEq, Eq)]
87pub enum SessionCheck {
88    Ok,
89    WrongUser,
90    Revoked,
91    EpochBehind,
92    TypeOff,
93}
94
95impl SessionCheck {
96    pub fn reason(self) -> Option<&'static str> {
97        match self {
98            SessionCheck::Ok => None,
99            SessionCheck::WrongUser => Some("wrong-user"),
100            SessionCheck::Revoked => Some("revoked"),
101            SessionCheck::EpochBehind => Some("epoch-behind"),
102            SessionCheck::TypeOff => Some("type-off"),
103        }
104    }
105}
106
107/// What a peer presents in Hello, for [`Roster::check_session`].
108pub struct SessionOffer<'a> {
109    pub cert: &'a NodeCert,
110    pub epoch: u32,
111    pub types: &'a [String],
112}
113
114impl Roster {
115    /// Accept a session only if the cert is for `user_id`, verifies, is not revoked, and
116    /// the peer's epoch is not behind ours. `offered_types` must intersect `our_types`.
117    pub fn check_session(
118        &self,
119        profile: &Profile,
120        user_key: &PublicKey,
121        user_id: &str,
122        offer: &SessionOffer<'_>,
123        our_types: &[String],
124    ) -> SessionCheck {
125        let cert = offer.cert;
126        if cert.user_id != user_id || user::user_id(user_key) != user_id || !profile.verify_cert(user_key, cert) {
127            return SessionCheck::WrongUser;
128        }
129        let revoked_here = self.get(&cert.peer_id).is_some_and(|c| !c.active()) || !cert.active();
130        if revoked_here || !profile.verify_cert(user_key, cert) {
131            return SessionCheck::Revoked;
132        }
133        if offer.epoch < self.epoch {
134            return SessionCheck::EpochBehind;
135        }
136        if !offer.types.iter().any(|t| our_types.iter().any(|o| o == t)) {
137            return SessionCheck::TypeOff;
138        }
139        SessionCheck::Ok
140    }
141}
142
143/// Default profile used for certs unless the application passes another.
144pub fn default_profile() -> &'static Profile {
145    &WEIRDNET
146}
147
148#[cfg(test)]
149mod tests {
150    use super::*;
151    use weirdnet_net::Keypair;
152
153    fn user() -> Keypair {
154        Keypair::generate_ed25519()
155    }
156
157    #[test]
158    fn first_device_self_certifies_and_is_the_roster_of_one() {
159        let u = user();
160        let cert = Roster::self_certify(&WEIRDNET, &u, "peer-a", "desktop", 1_000).unwrap();
161        assert_eq!(cert.peer_id, "peer-a");
162        assert!(cert.active());
163        assert!(WEIRDNET.verify_cert(&u.public(), &cert));
164        let mut r = Roster::new();
165        r.upsert(cert);
166        assert_eq!(r.active().count(), 1);
167        assert_eq!(r.epoch, 0);
168    }
169
170    #[test]
171    fn revoke_bumps_the_epoch_and_rejects_that_peer() {
172        let u = user();
173        let uid = user::user_id(&u.public());
174        let mut r = Roster::new();
175        r.upsert(Roster::self_certify(&WEIRDNET, &u, "peer-a", "phone", 1).unwrap());
176        r.upsert(Roster::self_certify(&WEIRDNET, &u, "peer-b", "desktop", 2).unwrap());
177        let revoked = r.revoke(&WEIRDNET, &u, "peer-a", 3).unwrap();
178        assert_eq!(r.epoch, 1);
179        assert!(!revoked.active());
180        assert!(WEIRDNET.verify_cert(&u.public(), &revoked));
181        let check = r.check_session(
182            &WEIRDNET,
183            &u.public(),
184            &uid,
185            &SessionOffer { cert: &revoked, epoch: 1, types: &["bookmarks".into()] },
186            &["bookmarks".into()],
187        );
188        assert_eq!(check, SessionCheck::Revoked);
189        let b = r.get("peer-b").unwrap().clone();
190        assert_eq!(
191            r.check_session(&WEIRDNET, &u.public(), &uid, &SessionOffer { cert: &b, epoch: 1, types: &["bookmarks".into()] }, &["bookmarks".into()]),
192            SessionCheck::Ok
193        );
194        assert_eq!(
195            r.check_session(&WEIRDNET, &u.public(), &uid, &SessionOffer { cert: &b, epoch: 0, types: &["bookmarks".into()] }, &["bookmarks".into()]),
196            SessionCheck::EpochBehind
197        );
198        assert_eq!(
199            r.check_session(&WEIRDNET, &u.public(), &uid, &SessionOffer { cert: &b, epoch: 1, types: &["settings".into()] }, &["bookmarks".into()]),
200            SessionCheck::TypeOff
201        );
202    }
203
204    #[test]
205    fn a_foreign_user_cert_is_wrong_user() {
206        let a = user();
207        let b = user();
208        let cert = Roster::self_certify(&WEIRDNET, &b, "peer-x", "x", 1).unwrap();
209        let r = Roster::new();
210        let uid = user::user_id(&a.public());
211        assert_eq!(
212            r.check_session(
213                &WEIRDNET,
214                &a.public(),
215                &uid,
216                &SessionOffer { cert: &cert, epoch: 0, types: &["bookmarks".into()] },
217                &["bookmarks".into()]
218            ),
219            SessionCheck::WrongUser
220        );
221    }
222
223    #[test]
224    fn merge_takes_a_signed_revocation_and_the_higher_epoch() {
225        let u = user();
226        let mut a = Roster::new();
227        let mut b = Roster::new();
228        let ca = Roster::self_certify(&WEIRDNET, &u, "peer-a", "a", 1).unwrap();
229        let cb = Roster::self_certify(&WEIRDNET, &u, "peer-b", "b", 2).unwrap();
230        a.upsert(ca.clone());
231        a.upsert(cb.clone());
232        b.upsert(ca);
233        b.upsert(cb);
234        b.revoke(&WEIRDNET, &u, "peer-a", 9).unwrap();
235        a.merge(&b, &u.public(), &WEIRDNET);
236        assert_eq!(a.epoch, 1);
237        assert!(!a.get("peer-a").unwrap().active());
238        assert!(a.get("peer-b").unwrap().active());
239    }
240}