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    /// The sync types a service device with this grant holds type-scoped keys for instead
107    /// of the epoch keys (since 0.8.3): its granted types, their chunk types
108    /// ([`crate::chunk_type`]) and [`LEASE_TYPE`](crate::lease::LEASE_TYPE), which every
109    /// service device with sync types gets so it can vote and stand for leases (grant only
110    /// `weirdnet.lease` for a lease-only device). `None` for a full device (it holds the
111    /// epoch keys) and for a roster-only one (no keys).
112    pub fn scoped_types(&self) -> Option<Vec<String>> {
113        if self.class != DeviceClass::Service || self.roster_only() {
114            return None;
115        }
116        let mut out: Vec<String> = Vec::with_capacity(self.types.len() * 2 + 1);
117        for t in &self.types {
118            out.push(t.clone());
119            if t != crate::lease::LEASE_TYPE {
120                out.push(crate::record::chunk_type(t));
121            }
122        }
123        out.push(crate::lease::LEASE_TYPE.to_string());
124        out.sort();
125        out.dedup();
126        Some(out)
127    }
128
129    /// A service device with no sync types: it gets the roster but no data keys.
130    pub fn roster_only(&self) -> bool {
131        self.class == DeviceClass::Service && self.types.is_empty()
132    }
133}
134
135/// The user's devices and the current sealing epoch.
136#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
137pub struct Roster {
138    pub epoch: u32,
139    pub certs: Vec<NodeCert>,
140    /// Device keys, rotations and admissions (public; sealed epoch keys inside).
141    #[serde(default, skip_serializing_if = "KeyChain::is_empty_and_rootless")]
142    pub chain: KeyChain,
143    /// Device grants (roles, class). Kept only when they verify under the user key
144    /// (checked on [`Roster::add_grant`] and [`Roster::merge`]).
145    #[serde(default, skip_serializing_if = "Vec::is_empty")]
146    pub grants: Vec<DeviceGrant>,
147}
148
149impl Roster {
150    pub fn new() -> Self {
151        Self::default()
152    }
153
154    /// The first device to hold an identity self-certifies and is the initial roster of one.
155    pub fn self_certify(profile: &Profile, user: &Keypair, peer_id: &str, label: &str, at_ms: i64) -> Result<NodeCert> {
156        let uid = user::user_id(&user.public());
157        Ok(profile.certify(user, &uid, peer_id, label, at_ms)?)
158    }
159
160    /// Insert or replace the cert for this peer id. Does not change the epoch.
161    pub fn upsert(&mut self, cert: NodeCert) {
162        if let Some(existing) = self.certs.iter_mut().find(|c| c.peer_id == cert.peer_id) {
163            *existing = cert;
164        } else {
165            self.certs.push(cert);
166        }
167    }
168
169    pub fn get(&self, peer_id: &str) -> Option<&NodeCert> {
170        self.certs.iter().find(|c| c.peer_id == peer_id)
171    }
172
173    pub fn active(&self) -> impl Iterator<Item = &NodeCert> {
174        self.certs.iter().filter(|c| c.active())
175    }
176
177    /// Sign a revocation, attach it to the cert, and bump the key epoch. This alone does
178    /// not shut out a device that holds the seed: use [`crate::SyncState::revoke`], which
179    /// also rotates to a random epoch key.
180    pub fn revoke(&mut self, profile: &Profile, user: &Keypair, peer_id: &str, at_ms: i64) -> Result<NodeCert> {
181        let uid = user::user_id(&user.public());
182        let sig = profile.revoke(user, &uid, peer_id, at_ms)?;
183        let cert = self.certs.iter_mut().find(|c| c.peer_id == peer_id).ok_or_else(|| SyncError::Protocol(format!("no cert for {peer_id}")))?;
184        if cert.user_id != uid {
185            return Err(SyncError::Protocol("revocation user does not match the cert".into()));
186        }
187        cert.revoked_at = Some(at_ms);
188        cert.revocation = Some(sig);
189        self.epoch = self.epoch.saturating_add(1);
190        Ok(cert.clone())
191    }
192
193    /// Add a grant if it verifies under `key` and is newer than the one held for that
194    /// device. Returns whether it was taken.
195    pub fn add_grant(&mut self, grant: DeviceGrant, key: &PublicKey) -> bool {
196        if !grant.verify(key) {
197            return false;
198        }
199        match self.grants.iter_mut().find(|g| g.peer_id == grant.peer_id) {
200            Some(g) if (g.issued_at, &g.sig) >= (grant.issued_at, &grant.sig) => false,
201            Some(g) => {
202                *g = grant;
203                true
204            }
205            None => {
206                self.grants.push(grant);
207                true
208            }
209        }
210    }
211
212    /// The grant in force for `peer_id`: the newest held, and only while its cert is
213    /// active. Grants are verified when they are added, so this does not check again.
214    pub fn grant_of(&self, peer_id: &str) -> Option<&DeviceGrant> {
215        self.get(peer_id).filter(|c| c.active())?;
216        self.grants.iter().find(|g| g.peer_id == peer_id)
217    }
218
219    /// The roles granted to `peer_id`, `None` when it has no grant (a device linked
220    /// before grants, or one never given any).
221    pub fn roles_of(&self, peer_id: &str) -> Option<&[String]> {
222        self.grant_of(peer_id).map(|g| g.roles.as_slice())
223    }
224
225    /// Whether `peer_id` holds a grant with `role`.
226    pub fn has_role(&self, peer_id: &str, role: &str) -> bool {
227        self.grant_of(peer_id).is_some_and(|g| g.has_role(role))
228    }
229
230    /// Whether `peer_id` was linked as a service device (no seed).
231    pub fn is_service(&self, peer_id: &str) -> bool {
232        self.grant_of(peer_id).is_some_and(|g| g.class == DeviceClass::Service)
233    }
234
235    /// Whether `peer_id` may hold data keys: every device except a roster-only service
236    /// device.
237    pub fn holds_keys(&self, peer_id: &str) -> bool {
238        !self.grant_of(peer_id).is_some_and(DeviceGrant::roster_only)
239    }
240
241    /// The sync types `peer_id` holds type-scoped keys for instead of the epoch keys
242    /// (since 0.8.3; see [`DeviceGrant::scoped_types`]), while its cert is active. `None`
243    /// for every other device: a full device holds the epoch keys, a roster-only one none.
244    pub fn scoped_types(&self, peer_id: &str) -> Option<Vec<String>> {
245        self.grant_of(peer_id)?.scoped_types()
246    }
247
248    /// Whether `peer_id` may sync `typ` with this device (since 0.8.3): every device may,
249    /// except a service device, which may sync only the types in its grant (and their
250    /// chunk types) plus [`LEASE_TYPE`](crate::lease::LEASE_TYPE), and nothing when its
251    /// grant is roster-only. Checked on every hello, pull, ack and lease request.
252    pub fn may_sync(&self, peer_id: &str, typ: &str) -> bool {
253        let Some(g) = self.grants.iter().find(|g| g.peer_id == peer_id) else { return true };
254        if g.class != DeviceClass::Service {
255            return true;
256        }
257        if g.roster_only() {
258            return false;
259        }
260        let base = crate::record::base_type(typ).unwrap_or(typ);
261        typ == crate::lease::LEASE_TYPE || g.types.iter().any(|t| t == typ || t == base)
262    }
263
264    /// When `peer_id`'s grant made it a service device (one grant is held per device), for
265    /// ignoring the rotations and admissions it signs from then on.
266    pub(crate) fn service_since(&self, peer_id: &str) -> Option<i64> {
267        self.grants.iter().find(|g| g.peer_id == peer_id && g.class == DeviceClass::Service).map(|g| g.issued_at)
268    }
269
270    /// Merge another replica's certs, key chain and grants. A signed revocation wins over
271    /// a still-active copy of the same cert. The epoch is the max of the two.
272    pub fn merge(&mut self, other: &Roster, key: &PublicKey, profile: &Profile) {
273        self.epoch = self.epoch.max(other.epoch);
274        self.chain.merge(&other.chain);
275        for g in &other.grants {
276            self.add_grant(g.clone(), key);
277        }
278        for c in &other.certs {
279            if !profile.verify_cert(key, c) {
280                continue;
281            }
282            match self.certs.iter_mut().find(|x| x.peer_id == c.peer_id) {
283                Some(existing) => {
284                    if !existing.active() {
285                        continue;
286                    }
287                    if !c.active() {
288                        *existing = c.clone();
289                    }
290                }
291                None => self.certs.push(c.clone()),
292            }
293        }
294    }
295}
296
297/// Why a hello is refused, as sent on the wire.
298#[derive(Debug, Clone, Copy, PartialEq, Eq)]
299pub enum SessionCheck {
300    Ok,
301    WrongUser,
302    Revoked,
303    EpochBehind,
304    TypeOff,
305}
306
307impl SessionCheck {
308    pub fn reason(self) -> Option<&'static str> {
309        match self {
310            SessionCheck::Ok => None,
311            SessionCheck::WrongUser => Some("wrong-user"),
312            SessionCheck::Revoked => Some("revoked"),
313            SessionCheck::EpochBehind => Some("epoch-behind"),
314            SessionCheck::TypeOff => Some("type-off"),
315        }
316    }
317}
318
319/// What a peer presents in Hello, for [`Roster::check_session`].
320pub struct SessionOffer<'a> {
321    pub cert: &'a NodeCert,
322    pub epoch: u32,
323    pub types: &'a [String],
324}
325
326impl Roster {
327    /// Accept a session only if the cert is for `user_id`, verifies, is not revoked, and
328    /// the peer's epoch is not behind ours. `offered_types` must intersect `our_types`.
329    pub fn check_session(
330        &self,
331        profile: &Profile,
332        user_key: &PublicKey,
333        user_id: &str,
334        offer: &SessionOffer<'_>,
335        our_types: &[String],
336    ) -> SessionCheck {
337        let cert = offer.cert;
338        if cert.user_id != user_id || user::user_id(user_key) != user_id || !profile.verify_cert(user_key, cert) {
339            return SessionCheck::WrongUser;
340        }
341        let revoked_here = self.get(&cert.peer_id).is_some_and(|c| !c.active()) || !cert.active();
342        if revoked_here || !profile.verify_cert(user_key, cert) {
343            return SessionCheck::Revoked;
344        }
345        if offer.epoch < self.epoch {
346            return SessionCheck::EpochBehind;
347        }
348        if !offer.types.iter().any(|t| our_types.iter().any(|o| o == t)) {
349            return SessionCheck::TypeOff;
350        }
351        SessionCheck::Ok
352    }
353}
354
355/// What [`Roster::check_caller`] decided about a caller.
356#[derive(Debug, Clone, Copy, PartialEq, Eq)]
357pub enum CallerCheck {
358    /// An active, verified device of this user, in the key chain's head once there is one.
359    Linked,
360    /// No cert for this peer in the roster. A cert the caller presents is not enough: anyone
361    /// holding the seed (a revoked device too) can mint one.
362    Unknown,
363    /// Revoked here, or the caller presented a revoked cert.
364    Revoked,
365    /// The cert is for another user or another peer, or does not verify.
366    WrongUser,
367    /// In the roster but not a member of the current key chain's head (not yet admitted).
368    NotAdmitted,
369}
370
371impl CallerCheck {
372    /// The refusal reason to send back, `None` for [`CallerCheck::Linked`].
373    pub fn reason(self) -> Option<&'static str> {
374        match self {
375            CallerCheck::Linked => None,
376            CallerCheck::Unknown => Some("unknown-device"),
377            CallerCheck::Revoked => Some("revoked"),
378            CallerCheck::WrongUser => Some("wrong-user"),
379            CallerCheck::NotAdmitted => Some("needs-admission"),
380        }
381    }
382}
383
384impl Roster {
385    /// Whether the caller of an app call or stream served by this device is one of the
386    /// user's linked devices. `peer` must be the transport-authenticated peer id (Noise),
387    /// never one the caller sent. `presented` is the cert the caller sent with the call, if
388    /// any; it must match `peer` and the user, and a revoked one is refused, but only this
389    /// roster's own cert admits a caller.
390    pub fn check_caller(&self, profile: &Profile, user_key: &PublicKey, peer: &str, presented: Option<&NodeCert>) -> CallerCheck {
391        let uid = user::user_id(user_key);
392        if let Some(p) = presented {
393            if p.peer_id != peer || p.user_id != uid || !profile.verify_cert(user_key, p) {
394                return CallerCheck::WrongUser;
395            }
396            if !p.active() {
397                return CallerCheck::Revoked;
398            }
399        }
400        let Some(cert) = self.get(peer) else { return CallerCheck::Unknown };
401        if !cert.active() {
402            return CallerCheck::Revoked;
403        }
404        if cert.user_id != uid || !profile.verify_cert(user_key, cert) {
405            return CallerCheck::WrongUser;
406        }
407        // A service device is never a member of a rotation it did not need (a roster-only
408        // one holds no keys at all); its grant admits it.
409        if self.chain_view().head().is_some_and(|h| !h.members.contains(peer)) && !self.is_service(peer) {
410            return CallerCheck::NotAdmitted;
411        }
412        CallerCheck::Linked
413    }
414}
415
416/// Default profile used for certs unless the application passes another.
417pub fn default_profile() -> &'static Profile {
418    &WEIRDNET
419}
420
421#[cfg(test)]
422mod tests {
423    use super::*;
424    use weirdnet_net::Keypair;
425
426    fn user() -> Keypair {
427        Keypair::generate_ed25519()
428    }
429
430    #[test]
431    fn first_device_self_certifies_and_is_the_roster_of_one() {
432        let u = user();
433        let cert = Roster::self_certify(&WEIRDNET, &u, "peer-a", "desktop", 1_000).unwrap();
434        assert_eq!(cert.peer_id, "peer-a");
435        assert!(cert.active());
436        assert!(WEIRDNET.verify_cert(&u.public(), &cert));
437        let mut r = Roster::new();
438        r.upsert(cert);
439        assert_eq!(r.active().count(), 1);
440        assert_eq!(r.epoch, 0);
441    }
442
443    #[test]
444    fn revoke_bumps_the_epoch_and_rejects_that_peer() {
445        let u = user();
446        let uid = user::user_id(&u.public());
447        let mut r = Roster::new();
448        r.upsert(Roster::self_certify(&WEIRDNET, &u, "peer-a", "phone", 1).unwrap());
449        r.upsert(Roster::self_certify(&WEIRDNET, &u, "peer-b", "desktop", 2).unwrap());
450        let revoked = r.revoke(&WEIRDNET, &u, "peer-a", 3).unwrap();
451        assert_eq!(r.epoch, 1);
452        assert!(!revoked.active());
453        assert!(WEIRDNET.verify_cert(&u.public(), &revoked));
454        let check = r.check_session(
455            &WEIRDNET,
456            &u.public(),
457            &uid,
458            &SessionOffer { cert: &revoked, epoch: 1, types: &["bookmarks".into()] },
459            &["bookmarks".into()],
460        );
461        assert_eq!(check, SessionCheck::Revoked);
462        let b = r.get("peer-b").unwrap().clone();
463        assert_eq!(
464            r.check_session(&WEIRDNET, &u.public(), &uid, &SessionOffer { cert: &b, epoch: 1, types: &["bookmarks".into()] }, &["bookmarks".into()]),
465            SessionCheck::Ok
466        );
467        assert_eq!(
468            r.check_session(&WEIRDNET, &u.public(), &uid, &SessionOffer { cert: &b, epoch: 0, types: &["bookmarks".into()] }, &["bookmarks".into()]),
469            SessionCheck::EpochBehind
470        );
471        assert_eq!(
472            r.check_session(&WEIRDNET, &u.public(), &uid, &SessionOffer { cert: &b, epoch: 1, types: &["settings".into()] }, &["bookmarks".into()]),
473            SessionCheck::TypeOff
474        );
475    }
476
477    #[test]
478    fn a_foreign_user_cert_is_wrong_user() {
479        let a = user();
480        let b = user();
481        let cert = Roster::self_certify(&WEIRDNET, &b, "peer-x", "x", 1).unwrap();
482        let r = Roster::new();
483        let uid = user::user_id(&a.public());
484        assert_eq!(
485            r.check_session(
486                &WEIRDNET,
487                &a.public(),
488                &uid,
489                &SessionOffer { cert: &cert, epoch: 0, types: &["bookmarks".into()] },
490                &["bookmarks".into()]
491            ),
492            SessionCheck::WrongUser
493        );
494    }
495
496    #[test]
497    fn callers_are_checked_against_the_roster() {
498        let u = user();
499        let mut r = Roster::new();
500        r.upsert(Roster::self_certify(&WEIRDNET, &u, "peer-a", "desktop", 1).unwrap());
501        r.upsert(Roster::self_certify(&WEIRDNET, &u, "peer-b", "phone", 2).unwrap());
502        let a = r.get("peer-a").unwrap().clone();
503        let check = |r: &Roster, peer: &str, presented: Option<&NodeCert>| r.check_caller(&WEIRDNET, &u.public(), peer, presented);
504        assert_eq!(check(&r, "peer-a", None), CallerCheck::Linked);
505        assert_eq!(check(&r, "peer-a", Some(&a)), CallerCheck::Linked);
506        assert_eq!(check(&r, "peer-b", Some(&a)), CallerCheck::WrongUser, "a cert for another peer");
507        // A cert minted with the user key for a peer this roster never had.
508        let minted = Roster::self_certify(&WEIRDNET, &u, "peer-m", "minted", 3).unwrap();
509        assert_eq!(check(&r, "peer-m", Some(&minted)), CallerCheck::Unknown);
510        assert_eq!(check(&r, "peer-x", None), CallerCheck::Unknown);
511        // Another user's device.
512        let other = user();
513        let foreign = Roster::self_certify(&WEIRDNET, &other, "peer-a", "x", 1).unwrap();
514        assert_eq!(check(&r, "peer-a", Some(&foreign)), CallerCheck::WrongUser);
515        let mut theirs = Roster::new();
516        theirs.upsert(foreign);
517        assert_eq!(check(&theirs, "peer-a", None), CallerCheck::WrongUser);
518        // Revoked here, and a revoked cert presented to a roster that has not heard.
519        let stale = r.clone();
520        let revoked = r.revoke(&WEIRDNET, &u, "peer-b", 4).unwrap();
521        assert_eq!(check(&r, "peer-b", None), CallerCheck::Revoked);
522        assert_eq!(check(&stale, "peer-b", Some(&revoked)), CallerCheck::Revoked);
523        assert_eq!(CallerCheck::Revoked.reason(), Some("revoked"));
524        assert_eq!(CallerCheck::Linked.reason(), None);
525    }
526
527    #[test]
528    fn merge_takes_a_signed_revocation_and_the_higher_epoch() {
529        let u = user();
530        let mut a = Roster::new();
531        let mut b = Roster::new();
532        let ca = Roster::self_certify(&WEIRDNET, &u, "peer-a", "a", 1).unwrap();
533        let cb = Roster::self_certify(&WEIRDNET, &u, "peer-b", "b", 2).unwrap();
534        a.upsert(ca.clone());
535        a.upsert(cb.clone());
536        b.upsert(ca);
537        b.upsert(cb);
538        b.revoke(&WEIRDNET, &u, "peer-a", 9).unwrap();
539        a.merge(&b, &u.public(), &WEIRDNET);
540        assert_eq!(a.epoch, 1);
541        assert!(!a.get("peer-a").unwrap().active());
542        assert!(a.get("peer-b").unwrap().active());
543    }
544}