1use 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";
15pub const MAX_GRANT_ROLES: usize = 16;
17pub const MAX_GRANT_TYPES: usize = 64;
19const MAX_NAME: usize = 128;
20
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
23#[serde(rename_all = "kebab-case")]
24pub enum DeviceClass {
25 Full,
27 Service,
31}
32
33#[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 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 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 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 pub fn roster_only(&self) -> bool {
131 self.class == DeviceClass::Service && self.types.is_empty()
132 }
133}
134
135#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
137pub struct Roster {
138 pub epoch: u32,
139 pub certs: Vec<NodeCert>,
140 #[serde(default, skip_serializing_if = "KeyChain::is_empty_and_rootless")]
142 pub chain: KeyChain,
143 #[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 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 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 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 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 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 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 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 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 pub fn holds_keys(&self, peer_id: &str) -> bool {
238 !self.grant_of(peer_id).is_some_and(DeviceGrant::roster_only)
239 }
240
241 pub fn scoped_types(&self, peer_id: &str) -> Option<Vec<String>> {
245 self.grant_of(peer_id)?.scoped_types()
246 }
247
248 pub fn service_granted(&self, typ: &str) -> bool {
252 self.active().any(|c| self.grant_of(&c.peer_id).is_some_and(|g| g.class == DeviceClass::Service && g.types.iter().any(|t| t == typ)))
253 }
254
255 pub fn may_sync(&self, peer_id: &str, typ: &str) -> bool {
260 let Some(g) = self.grants.iter().find(|g| g.peer_id == peer_id) else { return true };
261 if g.class != DeviceClass::Service {
262 return true;
263 }
264 if g.roster_only() {
265 return false;
266 }
267 let base = crate::record::base_type(typ).unwrap_or(typ);
268 typ == crate::lease::LEASE_TYPE || g.types.iter().any(|t| t == typ || t == base)
269 }
270
271 pub(crate) fn service_since(&self, peer_id: &str) -> Option<i64> {
274 self.grants.iter().find(|g| g.peer_id == peer_id && g.class == DeviceClass::Service).map(|g| g.issued_at)
275 }
276
277 pub fn merge(&mut self, other: &Roster, key: &PublicKey, profile: &Profile) {
280 self.epoch = self.epoch.max(other.epoch);
281 self.chain.merge(&other.chain);
282 for g in &other.grants {
283 self.add_grant(g.clone(), key);
284 }
285 for c in &other.certs {
286 if !profile.verify_cert(key, c) {
287 continue;
288 }
289 match self.certs.iter_mut().find(|x| x.peer_id == c.peer_id) {
290 Some(existing) => {
291 if !existing.active() {
292 continue;
293 }
294 if !c.active() {
295 *existing = c.clone();
296 }
297 }
298 None => self.certs.push(c.clone()),
299 }
300 }
301 }
302}
303
304#[derive(Debug, Clone, Copy, PartialEq, Eq)]
306pub enum SessionCheck {
307 Ok,
308 WrongUser,
309 Revoked,
310 EpochBehind,
311 TypeOff,
312}
313
314impl SessionCheck {
315 pub fn reason(self) -> Option<&'static str> {
316 match self {
317 SessionCheck::Ok => None,
318 SessionCheck::WrongUser => Some("wrong-user"),
319 SessionCheck::Revoked => Some("revoked"),
320 SessionCheck::EpochBehind => Some("epoch-behind"),
321 SessionCheck::TypeOff => Some("type-off"),
322 }
323 }
324}
325
326pub struct SessionOffer<'a> {
328 pub cert: &'a NodeCert,
329 pub epoch: u32,
330 pub types: &'a [String],
331}
332
333impl Roster {
334 pub fn check_session(
337 &self,
338 profile: &Profile,
339 user_key: &PublicKey,
340 user_id: &str,
341 offer: &SessionOffer<'_>,
342 our_types: &[String],
343 ) -> SessionCheck {
344 let cert = offer.cert;
345 if cert.user_id != user_id || user::user_id(user_key) != user_id || !profile.verify_cert(user_key, cert) {
346 return SessionCheck::WrongUser;
347 }
348 let revoked_here = self.get(&cert.peer_id).is_some_and(|c| !c.active()) || !cert.active();
349 if revoked_here || !profile.verify_cert(user_key, cert) {
350 return SessionCheck::Revoked;
351 }
352 if offer.epoch < self.epoch {
353 return SessionCheck::EpochBehind;
354 }
355 if !offer.types.iter().any(|t| our_types.iter().any(|o| o == t)) {
356 return SessionCheck::TypeOff;
357 }
358 SessionCheck::Ok
359 }
360}
361
362#[derive(Debug, Clone, Copy, PartialEq, Eq)]
364pub enum CallerCheck {
365 Linked,
367 Unknown,
370 Revoked,
372 WrongUser,
374 NotAdmitted,
376}
377
378impl CallerCheck {
379 pub fn reason(self) -> Option<&'static str> {
381 match self {
382 CallerCheck::Linked => None,
383 CallerCheck::Unknown => Some("unknown-device"),
384 CallerCheck::Revoked => Some("revoked"),
385 CallerCheck::WrongUser => Some("wrong-user"),
386 CallerCheck::NotAdmitted => Some("needs-admission"),
387 }
388 }
389}
390
391impl Roster {
392 pub fn check_caller(&self, profile: &Profile, user_key: &PublicKey, peer: &str, presented: Option<&NodeCert>) -> CallerCheck {
398 let uid = user::user_id(user_key);
399 if let Some(p) = presented {
400 if p.peer_id != peer || p.user_id != uid || !profile.verify_cert(user_key, p) {
401 return CallerCheck::WrongUser;
402 }
403 if !p.active() {
404 return CallerCheck::Revoked;
405 }
406 }
407 let Some(cert) = self.get(peer) else { return CallerCheck::Unknown };
408 if !cert.active() {
409 return CallerCheck::Revoked;
410 }
411 if cert.user_id != uid || !profile.verify_cert(user_key, cert) {
412 return CallerCheck::WrongUser;
413 }
414 if self.chain_view().head().is_some_and(|h| !h.members.contains(peer)) && !self.is_service(peer) {
417 return CallerCheck::NotAdmitted;
418 }
419 CallerCheck::Linked
420 }
421}
422
423pub fn default_profile() -> &'static Profile {
425 &WEIRDNET
426}
427
428#[cfg(test)]
429mod tests {
430 use super::*;
431 use weirdnet_net::Keypair;
432
433 fn user() -> Keypair {
434 Keypair::generate_ed25519()
435 }
436
437 #[test]
438 fn first_device_self_certifies_and_is_the_roster_of_one() {
439 let u = user();
440 let cert = Roster::self_certify(&WEIRDNET, &u, "peer-a", "desktop", 1_000).unwrap();
441 assert_eq!(cert.peer_id, "peer-a");
442 assert!(cert.active());
443 assert!(WEIRDNET.verify_cert(&u.public(), &cert));
444 let mut r = Roster::new();
445 r.upsert(cert);
446 assert_eq!(r.active().count(), 1);
447 assert_eq!(r.epoch, 0);
448 }
449
450 #[test]
451 fn revoke_bumps_the_epoch_and_rejects_that_peer() {
452 let u = user();
453 let uid = user::user_id(&u.public());
454 let mut r = Roster::new();
455 r.upsert(Roster::self_certify(&WEIRDNET, &u, "peer-a", "phone", 1).unwrap());
456 r.upsert(Roster::self_certify(&WEIRDNET, &u, "peer-b", "desktop", 2).unwrap());
457 let revoked = r.revoke(&WEIRDNET, &u, "peer-a", 3).unwrap();
458 assert_eq!(r.epoch, 1);
459 assert!(!revoked.active());
460 assert!(WEIRDNET.verify_cert(&u.public(), &revoked));
461 let check = r.check_session(
462 &WEIRDNET,
463 &u.public(),
464 &uid,
465 &SessionOffer { cert: &revoked, epoch: 1, types: &["bookmarks".into()] },
466 &["bookmarks".into()],
467 );
468 assert_eq!(check, SessionCheck::Revoked);
469 let b = r.get("peer-b").unwrap().clone();
470 assert_eq!(
471 r.check_session(&WEIRDNET, &u.public(), &uid, &SessionOffer { cert: &b, epoch: 1, types: &["bookmarks".into()] }, &["bookmarks".into()]),
472 SessionCheck::Ok
473 );
474 assert_eq!(
475 r.check_session(&WEIRDNET, &u.public(), &uid, &SessionOffer { cert: &b, epoch: 0, types: &["bookmarks".into()] }, &["bookmarks".into()]),
476 SessionCheck::EpochBehind
477 );
478 assert_eq!(
479 r.check_session(&WEIRDNET, &u.public(), &uid, &SessionOffer { cert: &b, epoch: 1, types: &["settings".into()] }, &["bookmarks".into()]),
480 SessionCheck::TypeOff
481 );
482 }
483
484 #[test]
485 fn a_foreign_user_cert_is_wrong_user() {
486 let a = user();
487 let b = user();
488 let cert = Roster::self_certify(&WEIRDNET, &b, "peer-x", "x", 1).unwrap();
489 let r = Roster::new();
490 let uid = user::user_id(&a.public());
491 assert_eq!(
492 r.check_session(
493 &WEIRDNET,
494 &a.public(),
495 &uid,
496 &SessionOffer { cert: &cert, epoch: 0, types: &["bookmarks".into()] },
497 &["bookmarks".into()]
498 ),
499 SessionCheck::WrongUser
500 );
501 }
502
503 #[test]
504 fn callers_are_checked_against_the_roster() {
505 let u = user();
506 let mut r = Roster::new();
507 r.upsert(Roster::self_certify(&WEIRDNET, &u, "peer-a", "desktop", 1).unwrap());
508 r.upsert(Roster::self_certify(&WEIRDNET, &u, "peer-b", "phone", 2).unwrap());
509 let a = r.get("peer-a").unwrap().clone();
510 let check = |r: &Roster, peer: &str, presented: Option<&NodeCert>| r.check_caller(&WEIRDNET, &u.public(), peer, presented);
511 assert_eq!(check(&r, "peer-a", None), CallerCheck::Linked);
512 assert_eq!(check(&r, "peer-a", Some(&a)), CallerCheck::Linked);
513 assert_eq!(check(&r, "peer-b", Some(&a)), CallerCheck::WrongUser, "a cert for another peer");
514 let minted = Roster::self_certify(&WEIRDNET, &u, "peer-m", "minted", 3).unwrap();
516 assert_eq!(check(&r, "peer-m", Some(&minted)), CallerCheck::Unknown);
517 assert_eq!(check(&r, "peer-x", None), CallerCheck::Unknown);
518 let other = user();
520 let foreign = Roster::self_certify(&WEIRDNET, &other, "peer-a", "x", 1).unwrap();
521 assert_eq!(check(&r, "peer-a", Some(&foreign)), CallerCheck::WrongUser);
522 let mut theirs = Roster::new();
523 theirs.upsert(foreign);
524 assert_eq!(check(&theirs, "peer-a", None), CallerCheck::WrongUser);
525 let stale = r.clone();
527 let revoked = r.revoke(&WEIRDNET, &u, "peer-b", 4).unwrap();
528 assert_eq!(check(&r, "peer-b", None), CallerCheck::Revoked);
529 assert_eq!(check(&stale, "peer-b", Some(&revoked)), CallerCheck::Revoked);
530 assert_eq!(CallerCheck::Revoked.reason(), Some("revoked"));
531 assert_eq!(CallerCheck::Linked.reason(), None);
532 }
533
534 #[test]
535 fn merge_takes_a_signed_revocation_and_the_higher_epoch() {
536 let u = user();
537 let mut a = Roster::new();
538 let mut b = Roster::new();
539 let ca = Roster::self_certify(&WEIRDNET, &u, "peer-a", "a", 1).unwrap();
540 let cb = Roster::self_certify(&WEIRDNET, &u, "peer-b", "b", 2).unwrap();
541 a.upsert(ca.clone());
542 a.upsert(cb.clone());
543 b.upsert(ca);
544 b.upsert(cb);
545 b.revoke(&WEIRDNET, &u, "peer-a", 9).unwrap();
546 a.merge(&b, &u.public(), &WEIRDNET);
547 assert_eq!(a.epoch, 1);
548 assert!(!a.get("peer-a").unwrap().active());
549 assert!(a.get("peer-b").unwrap().active());
550 }
551}