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
14const GRANT: &str = "weirdnet-sync/v1/grant";
15/// Most roles one grant carries.
16pub const MAX_GRANT_ROLES: usize = 16;
17/// Most sync types one grant scopes.
18pub const MAX_GRANT_TYPES: usize = 64;
19const MAX_NAME: usize = 128;
20
21/// What kind of device a [`DeviceGrant`] makes a cert.
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
23#[serde(rename_all = "kebab-case")]
24pub enum DeviceClass {
25    /// Holds (or may hold) the identity seed: admits, revokes, grants and rotates.
26    Full,
27    /// Linked with a certificate only, never the seed (a server such as a model or
28    /// inference node). It cannot admit, revoke, grant or rotate, and its rotations and
29    /// admissions are ignored. With no `types` it gets no data keys at all.
30    Service,
31}
32
33/// The user's signed statement of what a device is: its class, its roles and, for a
34/// service device, the sync types it may hold keys for. Signed by the user key, so only
35/// a device holding the seed can make one; it travels in the roster with the certs.
36///
37/// Roles are application strings (`ymir.inference`, `ymir.model`, …): what a device may
38/// do, as opposed to the role toggles an app announces about itself, which anyone can
39/// claim. Per device the newest grant (by `issued_at`) that verifies wins; a grant for a
40/// revoked cert counts for nothing.
41#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
42pub struct DeviceGrant {
43    pub user_id: String,
44    pub peer_id: String,
45    pub class: DeviceClass,
46    #[serde(default)]
47    pub roles: Vec<String>,
48    #[serde(default)]
49    pub types: Vec<String>,
50    pub issued_at: i64,
51    #[serde(with = "crate::bytes")]
52    pub sig: Vec<u8>,
53}
54
55fn valid_name(s: &str) -> bool {
56    !s.is_empty() && s.len() <= MAX_NAME && s.bytes().all(|b| b.is_ascii_alphanumeric() || b".-_:/+#".contains(&b))
57}
58
59impl DeviceGrant {
60    fn signing_bytes(&self) -> Vec<u8> {
61        let mut out = format!("{GRANT}\n").into_bytes();
62        out.extend(
63            crate::protocol::encode(&(&self.user_id, &self.peer_id, self.class, &self.roles, &self.types, self.issued_at)).unwrap_or_default(),
64        );
65        out
66    }
67
68    /// A grant for `peer_id`, signed by the user key. Roles and types are sorted and
69    /// deduplicated; names are 1..=128 of `A-Z a-z 0-9 . - _ : / + #`.
70    pub fn sign(user: &Keypair, peer_id: &str, class: DeviceClass, roles: &[String], types: &[String], issued_at: i64) -> Result<Self> {
71        let norm = |v: &[String], max: usize, what: &str| -> Result<Vec<String>> {
72            let mut v: Vec<String> = v.to_vec();
73            v.sort();
74            v.dedup();
75            if v.len() > max || !v.iter().all(|s| valid_name(s)) {
76                return Err(SyncError::Protocol(format!("grant: bad {what}")));
77            }
78            Ok(v)
79        };
80        let mut g = Self {
81            user_id: user::user_id(&user.public()),
82            peer_id: peer_id.into(),
83            class,
84            roles: norm(roles, MAX_GRANT_ROLES, "roles")?,
85            types: norm(types, MAX_GRANT_TYPES, "types")?,
86            issued_at,
87            sig: Vec::new(),
88        };
89        g.sig = user.sign(&g.signing_bytes()).map_err(|e| SyncError::Crypto(format!("grant: {e}")))?;
90        Ok(g)
91    }
92
93    /// Signed by this user key, for this user, and well formed.
94    pub fn verify(&self, user_key: &PublicKey) -> bool {
95        user::user_id(user_key) == self.user_id
96            && self.roles.len() <= MAX_GRANT_ROLES
97            && self.types.len() <= MAX_GRANT_TYPES
98            && self.roles.iter().chain(&self.types).all(|s| valid_name(s))
99            && user_key.verify(&self.signing_bytes(), &self.sig)
100    }
101
102    pub fn has_role(&self, role: &str) -> bool {
103        self.roles.iter().any(|r| r == role)
104    }
105
106    /// A service device with no sync types: it gets the roster but no data keys.
107    pub fn roster_only(&self) -> bool {
108        self.class == DeviceClass::Service && self.types.is_empty()
109    }
110}
111
112/// The user's devices and the current sealing epoch.
113#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
114pub struct Roster {
115    pub epoch: u32,
116    pub certs: Vec<NodeCert>,
117    /// Device keys, rotations and admissions (public; sealed epoch keys inside).
118    #[serde(default, skip_serializing_if = "KeyChain::is_empty_and_rootless")]
119    pub chain: KeyChain,
120    /// Device grants (roles, class). Kept only when they verify under the user key
121    /// (checked on [`Roster::add_grant`] and [`Roster::merge`]).
122    #[serde(default, skip_serializing_if = "Vec::is_empty")]
123    pub grants: Vec<DeviceGrant>,
124}
125
126impl Roster {
127    pub fn new() -> Self {
128        Self::default()
129    }
130
131    /// The first device to hold an identity self-certifies and is the initial roster of one.
132    pub fn self_certify(profile: &Profile, user: &Keypair, peer_id: &str, label: &str, at_ms: i64) -> Result<NodeCert> {
133        let uid = user::user_id(&user.public());
134        Ok(profile.certify(user, &uid, peer_id, label, at_ms)?)
135    }
136
137    /// Insert or replace the cert for this peer id. Does not change the epoch.
138    pub fn upsert(&mut self, cert: NodeCert) {
139        if let Some(existing) = self.certs.iter_mut().find(|c| c.peer_id == cert.peer_id) {
140            *existing = cert;
141        } else {
142            self.certs.push(cert);
143        }
144    }
145
146    pub fn get(&self, peer_id: &str) -> Option<&NodeCert> {
147        self.certs.iter().find(|c| c.peer_id == peer_id)
148    }
149
150    pub fn active(&self) -> impl Iterator<Item = &NodeCert> {
151        self.certs.iter().filter(|c| c.active())
152    }
153
154    /// Sign a revocation, attach it to the cert, and bump the key epoch. This alone does
155    /// not shut out a device that holds the seed: use [`crate::SyncState::revoke`], which
156    /// also rotates to a random epoch key.
157    pub fn revoke(&mut self, profile: &Profile, user: &Keypair, peer_id: &str, at_ms: i64) -> Result<NodeCert> {
158        let uid = user::user_id(&user.public());
159        let sig = profile.revoke(user, &uid, peer_id, at_ms)?;
160        let cert = self.certs.iter_mut().find(|c| c.peer_id == peer_id).ok_or_else(|| SyncError::Protocol(format!("no cert for {peer_id}")))?;
161        if cert.user_id != uid {
162            return Err(SyncError::Protocol("revocation user does not match the cert".into()));
163        }
164        cert.revoked_at = Some(at_ms);
165        cert.revocation = Some(sig);
166        self.epoch = self.epoch.saturating_add(1);
167        Ok(cert.clone())
168    }
169
170    /// Add a grant if it verifies under `key` and is newer than the one held for that
171    /// device. Returns whether it was taken.
172    pub fn add_grant(&mut self, grant: DeviceGrant, key: &PublicKey) -> bool {
173        if !grant.verify(key) {
174            return false;
175        }
176        match self.grants.iter_mut().find(|g| g.peer_id == grant.peer_id) {
177            Some(g) if (g.issued_at, &g.sig) >= (grant.issued_at, &grant.sig) => false,
178            Some(g) => {
179                *g = grant;
180                true
181            }
182            None => {
183                self.grants.push(grant);
184                true
185            }
186        }
187    }
188
189    /// The grant in force for `peer_id`: the newest held, and only while its cert is
190    /// active. Grants are verified when they are added, so this does not check again.
191    pub fn grant_of(&self, peer_id: &str) -> Option<&DeviceGrant> {
192        self.get(peer_id).filter(|c| c.active())?;
193        self.grants.iter().find(|g| g.peer_id == peer_id)
194    }
195
196    /// The roles granted to `peer_id`, `None` when it has no grant (a device linked
197    /// before grants, or one never given any).
198    pub fn roles_of(&self, peer_id: &str) -> Option<&[String]> {
199        self.grant_of(peer_id).map(|g| g.roles.as_slice())
200    }
201
202    /// Whether `peer_id` holds a grant with `role`.
203    pub fn has_role(&self, peer_id: &str, role: &str) -> bool {
204        self.grant_of(peer_id).is_some_and(|g| g.has_role(role))
205    }
206
207    /// Whether `peer_id` was linked as a service device (no seed).
208    pub fn is_service(&self, peer_id: &str) -> bool {
209        self.grant_of(peer_id).is_some_and(|g| g.class == DeviceClass::Service)
210    }
211
212    /// Whether `peer_id` may hold data keys: every device except a roster-only service
213    /// device.
214    pub fn holds_keys(&self, peer_id: &str) -> bool {
215        !self.grant_of(peer_id).is_some_and(DeviceGrant::roster_only)
216    }
217
218    /// When `peer_id`'s grant made it a service device (one grant is held per device), for
219    /// ignoring the rotations and admissions it signs from then on.
220    pub(crate) fn service_since(&self, peer_id: &str) -> Option<i64> {
221        self.grants.iter().find(|g| g.peer_id == peer_id && g.class == DeviceClass::Service).map(|g| g.issued_at)
222    }
223
224    /// Merge another replica's certs, key chain and grants. A signed revocation wins over
225    /// a still-active copy of the same cert. The epoch is the max of the two.
226    pub fn merge(&mut self, other: &Roster, key: &PublicKey, profile: &Profile) {
227        self.epoch = self.epoch.max(other.epoch);
228        self.chain.merge(&other.chain);
229        for g in &other.grants {
230            self.add_grant(g.clone(), key);
231        }
232        for c in &other.certs {
233            if !profile.verify_cert(key, c) {
234                continue;
235            }
236            match self.certs.iter_mut().find(|x| x.peer_id == c.peer_id) {
237                Some(existing) => {
238                    if !existing.active() {
239                        continue;
240                    }
241                    if !c.active() {
242                        *existing = c.clone();
243                    }
244                }
245                None => self.certs.push(c.clone()),
246            }
247        }
248    }
249}
250
251/// Why a hello is refused, as sent on the wire.
252#[derive(Debug, Clone, Copy, PartialEq, Eq)]
253pub enum SessionCheck {
254    Ok,
255    WrongUser,
256    Revoked,
257    EpochBehind,
258    TypeOff,
259}
260
261impl SessionCheck {
262    pub fn reason(self) -> Option<&'static str> {
263        match self {
264            SessionCheck::Ok => None,
265            SessionCheck::WrongUser => Some("wrong-user"),
266            SessionCheck::Revoked => Some("revoked"),
267            SessionCheck::EpochBehind => Some("epoch-behind"),
268            SessionCheck::TypeOff => Some("type-off"),
269        }
270    }
271}
272
273/// What a peer presents in Hello, for [`Roster::check_session`].
274pub struct SessionOffer<'a> {
275    pub cert: &'a NodeCert,
276    pub epoch: u32,
277    pub types: &'a [String],
278}
279
280impl Roster {
281    /// Accept a session only if the cert is for `user_id`, verifies, is not revoked, and
282    /// the peer's epoch is not behind ours. `offered_types` must intersect `our_types`.
283    pub fn check_session(
284        &self,
285        profile: &Profile,
286        user_key: &PublicKey,
287        user_id: &str,
288        offer: &SessionOffer<'_>,
289        our_types: &[String],
290    ) -> SessionCheck {
291        let cert = offer.cert;
292        if cert.user_id != user_id || user::user_id(user_key) != user_id || !profile.verify_cert(user_key, cert) {
293            return SessionCheck::WrongUser;
294        }
295        let revoked_here = self.get(&cert.peer_id).is_some_and(|c| !c.active()) || !cert.active();
296        if revoked_here || !profile.verify_cert(user_key, cert) {
297            return SessionCheck::Revoked;
298        }
299        if offer.epoch < self.epoch {
300            return SessionCheck::EpochBehind;
301        }
302        if !offer.types.iter().any(|t| our_types.iter().any(|o| o == t)) {
303            return SessionCheck::TypeOff;
304        }
305        SessionCheck::Ok
306    }
307}
308
309/// What [`Roster::check_caller`] decided about a caller.
310#[derive(Debug, Clone, Copy, PartialEq, Eq)]
311pub enum CallerCheck {
312    /// An active, verified device of this user, in the key chain's head once there is one.
313    Linked,
314    /// No cert for this peer in the roster. A cert the caller presents is not enough: anyone
315    /// holding the seed (a revoked device too) can mint one.
316    Unknown,
317    /// Revoked here, or the caller presented a revoked cert.
318    Revoked,
319    /// The cert is for another user or another peer, or does not verify.
320    WrongUser,
321    /// In the roster but not a member of the current key chain's head (not yet admitted).
322    NotAdmitted,
323}
324
325impl CallerCheck {
326    /// The refusal reason to send back, `None` for [`CallerCheck::Linked`].
327    pub fn reason(self) -> Option<&'static str> {
328        match self {
329            CallerCheck::Linked => None,
330            CallerCheck::Unknown => Some("unknown-device"),
331            CallerCheck::Revoked => Some("revoked"),
332            CallerCheck::WrongUser => Some("wrong-user"),
333            CallerCheck::NotAdmitted => Some("needs-admission"),
334        }
335    }
336}
337
338impl Roster {
339    /// Whether the caller of an app call or stream served by this device is one of the
340    /// user's linked devices. `peer` must be the transport-authenticated peer id (Noise),
341    /// never one the caller sent. `presented` is the cert the caller sent with the call, if
342    /// any; it must match `peer` and the user, and a revoked one is refused, but only this
343    /// roster's own cert admits a caller.
344    pub fn check_caller(&self, profile: &Profile, user_key: &PublicKey, peer: &str, presented: Option<&NodeCert>) -> CallerCheck {
345        let uid = user::user_id(user_key);
346        if let Some(p) = presented {
347            if p.peer_id != peer || p.user_id != uid || !profile.verify_cert(user_key, p) {
348                return CallerCheck::WrongUser;
349            }
350            if !p.active() {
351                return CallerCheck::Revoked;
352            }
353        }
354        let Some(cert) = self.get(peer) else { return CallerCheck::Unknown };
355        if !cert.active() {
356            return CallerCheck::Revoked;
357        }
358        if cert.user_id != uid || !profile.verify_cert(user_key, cert) {
359            return CallerCheck::WrongUser;
360        }
361        // A service device is never a member of a rotation it did not need (a roster-only
362        // one holds no keys at all); its grant admits it.
363        if self.chain_view().head().is_some_and(|h| !h.members.contains(peer)) && !self.is_service(peer) {
364            return CallerCheck::NotAdmitted;
365        }
366        CallerCheck::Linked
367    }
368}
369
370/// Default profile used for certs unless the application passes another.
371pub fn default_profile() -> &'static Profile {
372    &WEIRDNET
373}
374
375#[cfg(test)]
376mod tests {
377    use super::*;
378    use weirdnet_net::Keypair;
379
380    fn user() -> Keypair {
381        Keypair::generate_ed25519()
382    }
383
384    #[test]
385    fn first_device_self_certifies_and_is_the_roster_of_one() {
386        let u = user();
387        let cert = Roster::self_certify(&WEIRDNET, &u, "peer-a", "desktop", 1_000).unwrap();
388        assert_eq!(cert.peer_id, "peer-a");
389        assert!(cert.active());
390        assert!(WEIRDNET.verify_cert(&u.public(), &cert));
391        let mut r = Roster::new();
392        r.upsert(cert);
393        assert_eq!(r.active().count(), 1);
394        assert_eq!(r.epoch, 0);
395    }
396
397    #[test]
398    fn revoke_bumps_the_epoch_and_rejects_that_peer() {
399        let u = user();
400        let uid = user::user_id(&u.public());
401        let mut r = Roster::new();
402        r.upsert(Roster::self_certify(&WEIRDNET, &u, "peer-a", "phone", 1).unwrap());
403        r.upsert(Roster::self_certify(&WEIRDNET, &u, "peer-b", "desktop", 2).unwrap());
404        let revoked = r.revoke(&WEIRDNET, &u, "peer-a", 3).unwrap();
405        assert_eq!(r.epoch, 1);
406        assert!(!revoked.active());
407        assert!(WEIRDNET.verify_cert(&u.public(), &revoked));
408        let check = r.check_session(
409            &WEIRDNET,
410            &u.public(),
411            &uid,
412            &SessionOffer { cert: &revoked, epoch: 1, types: &["bookmarks".into()] },
413            &["bookmarks".into()],
414        );
415        assert_eq!(check, SessionCheck::Revoked);
416        let b = r.get("peer-b").unwrap().clone();
417        assert_eq!(
418            r.check_session(&WEIRDNET, &u.public(), &uid, &SessionOffer { cert: &b, epoch: 1, types: &["bookmarks".into()] }, &["bookmarks".into()]),
419            SessionCheck::Ok
420        );
421        assert_eq!(
422            r.check_session(&WEIRDNET, &u.public(), &uid, &SessionOffer { cert: &b, epoch: 0, types: &["bookmarks".into()] }, &["bookmarks".into()]),
423            SessionCheck::EpochBehind
424        );
425        assert_eq!(
426            r.check_session(&WEIRDNET, &u.public(), &uid, &SessionOffer { cert: &b, epoch: 1, types: &["settings".into()] }, &["bookmarks".into()]),
427            SessionCheck::TypeOff
428        );
429    }
430
431    #[test]
432    fn a_foreign_user_cert_is_wrong_user() {
433        let a = user();
434        let b = user();
435        let cert = Roster::self_certify(&WEIRDNET, &b, "peer-x", "x", 1).unwrap();
436        let r = Roster::new();
437        let uid = user::user_id(&a.public());
438        assert_eq!(
439            r.check_session(
440                &WEIRDNET,
441                &a.public(),
442                &uid,
443                &SessionOffer { cert: &cert, epoch: 0, types: &["bookmarks".into()] },
444                &["bookmarks".into()]
445            ),
446            SessionCheck::WrongUser
447        );
448    }
449
450    #[test]
451    fn callers_are_checked_against_the_roster() {
452        let u = user();
453        let mut r = Roster::new();
454        r.upsert(Roster::self_certify(&WEIRDNET, &u, "peer-a", "desktop", 1).unwrap());
455        r.upsert(Roster::self_certify(&WEIRDNET, &u, "peer-b", "phone", 2).unwrap());
456        let a = r.get("peer-a").unwrap().clone();
457        let check = |r: &Roster, peer: &str, presented: Option<&NodeCert>| r.check_caller(&WEIRDNET, &u.public(), peer, presented);
458        assert_eq!(check(&r, "peer-a", None), CallerCheck::Linked);
459        assert_eq!(check(&r, "peer-a", Some(&a)), CallerCheck::Linked);
460        assert_eq!(check(&r, "peer-b", Some(&a)), CallerCheck::WrongUser, "a cert for another peer");
461        // A cert minted with the user key for a peer this roster never had.
462        let minted = Roster::self_certify(&WEIRDNET, &u, "peer-m", "minted", 3).unwrap();
463        assert_eq!(check(&r, "peer-m", Some(&minted)), CallerCheck::Unknown);
464        assert_eq!(check(&r, "peer-x", None), CallerCheck::Unknown);
465        // Another user's device.
466        let other = user();
467        let foreign = Roster::self_certify(&WEIRDNET, &other, "peer-a", "x", 1).unwrap();
468        assert_eq!(check(&r, "peer-a", Some(&foreign)), CallerCheck::WrongUser);
469        let mut theirs = Roster::new();
470        theirs.upsert(foreign);
471        assert_eq!(check(&theirs, "peer-a", None), CallerCheck::WrongUser);
472        // Revoked here, and a revoked cert presented to a roster that has not heard.
473        let stale = r.clone();
474        let revoked = r.revoke(&WEIRDNET, &u, "peer-b", 4).unwrap();
475        assert_eq!(check(&r, "peer-b", None), CallerCheck::Revoked);
476        assert_eq!(check(&stale, "peer-b", Some(&revoked)), CallerCheck::Revoked);
477        assert_eq!(CallerCheck::Revoked.reason(), Some("revoked"));
478        assert_eq!(CallerCheck::Linked.reason(), None);
479    }
480
481    #[test]
482    fn merge_takes_a_signed_revocation_and_the_higher_epoch() {
483        let u = user();
484        let mut a = Roster::new();
485        let mut b = Roster::new();
486        let ca = Roster::self_certify(&WEIRDNET, &u, "peer-a", "a", 1).unwrap();
487        let cb = Roster::self_certify(&WEIRDNET, &u, "peer-b", "b", 2).unwrap();
488        a.upsert(ca.clone());
489        a.upsert(cb.clone());
490        b.upsert(ca);
491        b.upsert(cb);
492        b.revoke(&WEIRDNET, &u, "peer-a", 9).unwrap();
493        a.merge(&b, &u.public(), &WEIRDNET);
494        assert_eq!(a.epoch, 1);
495        assert!(!a.get("peer-a").unwrap().active());
496        assert!(a.get("peer-b").unwrap().active());
497    }
498}