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 roster_only(&self) -> bool {
108 self.class == DeviceClass::Service && self.types.is_empty()
109 }
110}
111
112#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
114pub struct Roster {
115 pub epoch: u32,
116 pub certs: Vec<NodeCert>,
117 #[serde(default, skip_serializing_if = "KeyChain::is_empty_and_rootless")]
119 pub chain: KeyChain,
120 #[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 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 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 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 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 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 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 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 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 pub fn holds_keys(&self, peer_id: &str) -> bool {
215 !self.grant_of(peer_id).is_some_and(DeviceGrant::roster_only)
216 }
217
218 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 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#[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
273pub struct SessionOffer<'a> {
275 pub cert: &'a NodeCert,
276 pub epoch: u32,
277 pub types: &'a [String],
278}
279
280impl Roster {
281 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
311pub enum CallerCheck {
312 Linked,
314 Unknown,
317 Revoked,
319 WrongUser,
321 NotAdmitted,
323}
324
325impl CallerCheck {
326 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 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 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
370pub 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 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 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 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}