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 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 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 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#[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
319pub struct SessionOffer<'a> {
321 pub cert: &'a NodeCert,
322 pub epoch: u32,
323 pub types: &'a [String],
324}
325
326impl Roster {
327 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
357pub enum CallerCheck {
358 Linked,
360 Unknown,
363 Revoked,
365 WrongUser,
367 NotAdmitted,
369}
370
371impl CallerCheck {
372 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 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 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
416pub 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 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 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 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}