1use crate::error::{Result, SyncError};
33use crate::net::SyncState;
34use crate::protocol::{decode, encode};
35use crate::roster::Roster;
36use crate::seal::{SyncKey, rotated_sync_key};
37use serde::{Deserialize, Serialize};
38use std::collections::{BTreeMap, BTreeSet};
39use weirdnet_keys::exchange::{self, ExchangeSecret};
40use weirdnet_keys::mac::HmacSha256;
41use weirdnet_keys::{Key32, Sealed, kdf, open, seal};
42use weirdnet_net::profile::WEIRDNET;
43use weirdnet_net::user::NodeCert;
44use weirdnet_net::{Keypair, PeerId, PublicKey};
45use zeroize::{Zeroize, Zeroizing};
46
47const DEVICE_KEY: &str = "weirdnet-sync/v1/device-key";
48const ROTATION: &str = "weirdnet-sync/v1/rotation";
49const ADMISSION: &str = "weirdnet-sync/v1/admission";
50const SEAL_KEY: &[u8] = b"weirdnet-sync/v1/seal-key";
51const SEAL_SAS: &[u8] = b"weirdnet-sync/v1/seal-sas";
52
53pub fn peer_public(peer: &str) -> Option<PublicKey> {
55 let pid: PeerId = peer.parse().ok()?;
56 let bytes = pid.to_bytes();
57 if bytes.len() < 2 || bytes[0] != 0 || bytes.len() != 2 + bytes[1] as usize {
58 return None;
59 }
60 let key = PublicKey::try_decode_protobuf(&bytes[2..]).ok()?;
61 (key.to_peer_id() == pid).then_some(key)
62}
63
64fn hash_hex(domain: &[u8], data: &[u8], n: usize) -> String {
65 let mut h = HmacSha256::new(domain);
66 h.update(data);
67 hex::encode(&h.finalize()[..n])
68}
69
70fn key_check(key: &Key32) -> String {
71 let mut h = HmacSha256::new(&key.0);
72 h.update(b"weirdnet-sync/v1/key-check");
73 hex::encode(&h.finalize()[..16])
74}
75
76fn crypto(msg: impl Into<String>) -> SyncError {
77 SyncError::Crypto(msg.into())
78}
79
80#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
82pub struct DeviceKey {
83 pub peer_id: String,
84 pub exchange: String,
86 pub at_ms: i64,
87 pub sig: Vec<u8>,
88}
89
90impl DeviceKey {
91 fn signing_bytes(peer: &str, exchange: &str, at: i64) -> Vec<u8> {
92 format!("{DEVICE_KEY}\n{peer}\n{exchange}\n{at}").into_bytes()
93 }
94
95 pub fn verify(&self) -> bool {
97 self.public().is_some()
98 && peer_public(&self.peer_id).is_some_and(|k| k.verify(&Self::signing_bytes(&self.peer_id, &self.exchange, self.at_ms), &self.sig))
99 }
100
101 pub fn public(&self) -> Option<[u8; 32]> {
102 hex::decode(&self.exchange).ok()?.try_into().ok()
103 }
104
105 pub fn fingerprint(&self) -> String {
107 let h = hash_hex(b"weirdnet-sync/v1/fingerprint", format!("{}|{}", self.peer_id, self.exchange).as_bytes(), 6);
108 format!("{}-{}-{}", &h[..4], &h[4..8], &h[8..])
109 }
110}
111
112pub struct Device {
115 node: Keypair,
116 exchange: ExchangeSecret,
117}
118
119impl Clone for Device {
120 fn clone(&self) -> Self {
121 Self { node: self.node.clone(), exchange: ExchangeSecret::from_bytes(*self.exchange.to_bytes()) }
122 }
123}
124
125impl std::fmt::Debug for Device {
126 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
127 write!(f, "Device({})", self.peer_id())
128 }
129}
130
131impl Device {
132 pub fn from_node_key(node: &Keypair) -> Result<Self> {
133 let bytes = Zeroizing::new(node.to_protobuf_encoding().map_err(|e| crypto(format!("node key: {e}")))?);
134 let k = kdf::hkdf(&bytes, Some(b"weirdnet-sync/v1"), b"weirdnet-sync/v1/exchange")?;
135 Ok(Self { node: node.clone(), exchange: ExchangeSecret::from_bytes(k.0) })
136 }
137
138 pub fn peer_id(&self) -> String {
139 self.node.public().to_peer_id().to_string()
140 }
141
142 pub fn device_key(&self, at_ms: i64) -> Result<DeviceKey> {
143 let peer = self.peer_id();
144 let exchange = hex::encode(self.exchange.public());
145 let sig = self.sign(&DeviceKey::signing_bytes(&peer, &exchange, at_ms))?;
146 Ok(DeviceKey { peer_id: peer, exchange, at_ms, sig })
147 }
148
149 pub(crate) fn sign(&self, bytes: &[u8]) -> Result<Vec<u8>> {
150 self.node.sign(bytes).map_err(|e| crypto(format!("sign: {e}")))
151 }
152}
153
154#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
156pub struct SealedKey {
157 pub peer_id: String,
158 pub sealed: Sealed,
159}
160
161#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
163pub struct Rotation {
164 pub epoch: u32,
165 pub parent: Option<String>,
167 pub by: String,
168 pub at_ms: i64,
169 pub eph: String,
171 pub check: String,
173 pub keys: Vec<SealedKey>,
174 pub sig: Vec<u8>,
175}
176
177impl Rotation {
178 fn body(&self) -> Vec<u8> {
179 encode(&(ROTATION, self.epoch, &self.parent, &self.by, self.at_ms, &self.eph, &self.check, &self.keys)).unwrap_or_default()
180 }
181
182 pub fn id(&self) -> String {
183 hash_hex(ROTATION.as_bytes(), &self.body(), 16)
184 }
185
186 fn signed(&self) -> bool {
187 peer_public(&self.by).is_some_and(|k| k.verify(&self.body(), &self.sig))
188 }
189
190 pub fn recipients(&self) -> impl Iterator<Item = &str> {
191 self.keys.iter().map(|k| k.peer_id.as_str())
192 }
193
194 fn transcript(&self, recipient: &str, recipient_pub: &[u8; 32]) -> Vec<u8> {
195 let parent = self.parent.as_deref().unwrap_or("-");
196 format!("{ROTATION}|e{}|{parent}|{}|{recipient}|{}|{}", self.epoch, self.by, self.eph, hex::encode(recipient_pub)).into_bytes()
197 }
198}
199
200#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
203pub struct Admission {
204 pub rotation: String,
205 pub peer_id: String,
206 pub by: String,
207 pub at_ms: i64,
208 pub eph: String,
209 pub sealed: Sealed,
210 pub sig: Vec<u8>,
211}
212
213impl Admission {
214 fn body(&self) -> Vec<u8> {
215 encode(&(ADMISSION, &self.rotation, &self.peer_id, &self.by, self.at_ms, &self.eph, &self.sealed)).unwrap_or_default()
216 }
217
218 pub fn id(&self) -> String {
219 hash_hex(ADMISSION.as_bytes(), &self.body(), 16)
220 }
221
222 fn signed(&self) -> bool {
223 peer_public(&self.by).is_some_and(|k| k.verify(&self.body(), &self.sig))
224 }
225
226 fn transcript(&self, recipient_pub: &[u8; 32]) -> Vec<u8> {
227 format!("{ADMISSION}|{}|{}|{}|{}|{}", self.rotation, self.peer_id, self.by, self.eph, hex::encode(recipient_pub)).into_bytes()
228 }
229}
230
231#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
234pub struct KeyChain {
235 #[serde(default)]
236 pub devices: Vec<DeviceKey>,
237 #[serde(default)]
238 pub rotations: Vec<Rotation>,
239 #[serde(default)]
240 pub admissions: Vec<Admission>,
241 #[serde(default, skip_serializing_if = "Option::is_none")]
243 pub root: Option<String>,
244 #[serde(default, skip_serializing_if = "Vec::is_empty")]
247 pub approved: Vec<String>,
248}
249
250impl KeyChain {
251 pub fn is_empty(&self) -> bool {
252 self.devices.is_empty() && self.rotations.is_empty() && self.admissions.is_empty()
253 }
254
255 pub fn is_empty_and_rootless(&self) -> bool {
256 self.is_empty() && self.root.is_none() && self.approved.is_empty()
257 }
258
259 pub fn device(&self, peer_id: &str) -> Option<&DeviceKey> {
260 self.devices.iter().find(|d| d.peer_id == peer_id)
261 }
262
263 pub fn add_device(&mut self, dk: DeviceKey) -> bool {
265 if !dk.verify() {
266 return false;
267 }
268 match self.devices.iter_mut().find(|d| d.peer_id == dk.peer_id) {
269 Some(d) if d.at_ms < dk.at_ms => *d = dk,
270 Some(_) => {}
271 None => self.devices.push(dk),
272 }
273 true
274 }
275
276 pub fn merge(&mut self, other: &KeyChain) {
279 for d in &other.devices {
280 self.add_device(d.clone());
281 }
282 let have: BTreeSet<String> = self.rotations.iter().map(Rotation::id).collect();
283 for r in &other.rotations {
284 if !have.contains(&r.id()) && r.signed() {
285 self.rotations.push(r.clone());
286 }
287 }
288 let have: BTreeSet<String> = self.admissions.iter().map(Admission::id).collect();
289 for a in &other.admissions {
290 if !have.contains(&a.id()) && a.signed() {
291 self.admissions.push(a.clone());
292 }
293 }
294 }
295
296 pub fn shared(&self) -> KeyChain {
298 KeyChain { root: None, approved: Vec::new(), ..self.clone() }
299 }
300}
301
302#[derive(Debug, Clone)]
304pub struct ValidRotation {
305 pub id: String,
306 pub epoch: u32,
307 pub members: BTreeSet<String>,
308 pub clean: bool,
309}
310
311type Ided<'a, T> = (String, &'a T);
313
314#[derive(Debug, Clone, Default)]
316pub struct ChainView {
317 pub root: Option<String>,
318 pub valid: BTreeMap<String, ValidRotation>,
319 pub admissions: Vec<String>,
320 pub head: Option<String>,
321}
322
323impl ChainView {
324 pub fn head(&self) -> Option<&ValidRotation> {
325 self.head.as_ref().and_then(|h| self.valid.get(h))
326 }
327
328 pub fn dirty(&self) -> bool {
330 self.head().is_some_and(|h| !h.clean)
331 }
332}
333
334impl Roster {
335 fn revoked_set(&self) -> BTreeSet<&str> {
336 self.certs.iter().filter(|c| !c.active()).map(|c| c.peer_id.as_str()).collect()
337 }
338
339 fn active_set(&self) -> BTreeSet<&str> {
340 self.active().map(|c| c.peer_id.as_str()).collect()
341 }
342
343 fn signed_parts(&self) -> (Vec<Ided<'_, Rotation>>, Vec<Ided<'_, Admission>>) {
344 let active = self.active_set();
345 let known: BTreeSet<&str> = self.certs.iter().map(|c| c.peer_id.as_str()).collect();
346 let by_service = |by: &str, at: i64| self.service_since(by).is_some_and(|t| at >= t);
348 let rots = self
349 .chain
350 .rotations
351 .iter()
352 .filter(|r| known.contains(r.by.as_str()) && !by_service(&r.by, r.at_ms) && r.signed())
353 .map(|r| (r.id(), r))
354 .collect();
355 let adms = self
356 .chain
357 .admissions
358 .iter()
359 .filter(|a| active.contains(a.by.as_str()) && !by_service(&a.by, a.at_ms) && a.signed())
360 .map(|a| (a.id(), a))
361 .collect();
362 (rots, adms)
363 }
364
365 pub fn all_views(&self) -> Vec<ChainView> {
369 let revoked = self.revoked_set();
370 let (rots, adms) = self.signed_parts();
371 rots.iter()
372 .filter(|(_, r)| r.parent.is_none() && r.recipients().any(|p| p == r.by))
373 .map(|root| self.view_from(root, &rots, &adms, &revoked))
374 .collect()
375 }
376
377 pub fn chain_view(&self) -> ChainView {
379 let revoked = self.revoked_set();
380 let (rots, adms) = self.signed_parts();
381
382 let roots: Vec<&(String, &Rotation)> = rots.iter().filter(|(_, r)| r.parent.is_none() && r.recipients().any(|p| p == r.by)).collect();
383 fn order(r: &(String, &Rotation)) -> (u32, String) {
384 (r.1.epoch, r.0.clone())
385 }
386 let mut root = match &self.chain.root {
387 Some(id) => roots.iter().find(|(rid, _)| rid == id).copied(),
388 None => roots.iter().copied().min_by_key(|r| order(r)),
389 };
390 let mut seen = BTreeSet::new();
395 while let Some(cur) = root {
396 if !seen.insert(cur.0.clone()) {
397 break;
398 }
399 let view = self.view_from(cur, &rots, &adms, &revoked);
400 let trusted = |r: &&&(String, &Rotation)| view.valid.values().any(|v| v.members.contains(&r.1.by));
401 match roots.iter().filter(trusted).min_by_key(|r| order(r)) {
402 Some(best) if order(best) < order(cur) => root = Some(best),
403 _ => return view,
404 }
405 }
406 root.map(|r| self.view_from(r, &rots, &adms, &revoked)).unwrap_or_default()
407 }
408
409 fn view_from(
410 &self,
411 (root_id, root_rot): &(String, &Rotation),
412 rots: &[(String, &Rotation)],
413 adms: &[(String, &Admission)],
414 revoked: &BTreeSet<&str>,
415 ) -> ChainView {
416 let mut view = ChainView { root: Some(root_id.clone()), ..ChainView::default() };
417
418 let members_of = |id: &str, r: &Rotation, admitted: &mut Vec<String>| -> BTreeSet<String> {
419 let mut m: BTreeSet<String> = r.recipients().map(str::to_string).collect();
420 loop {
421 let mut grew = false;
422 for (aid, a) in adms.iter().filter(|(_, a)| a.rotation == id) {
423 if m.contains(&a.by) && !revoked.contains(a.by.as_str()) && !m.contains(&a.peer_id) {
424 m.insert(a.peer_id.clone());
425 admitted.push(aid.clone());
426 grew = true;
427 }
428 }
429 if !grew {
430 return m;
431 }
432 }
433 };
434 let mut admitted = Vec::new();
435 let add = |view: &mut ChainView, id: &str, r: &Rotation, admitted: &mut Vec<String>| {
436 let members = members_of(id, r, admitted);
437 let clean = !members.iter().any(|m| revoked.contains(m.as_str()));
438 view.valid.insert(id.to_string(), ValidRotation { id: id.to_string(), epoch: r.epoch, members, clean });
439 };
440 add(&mut view, root_id, root_rot, &mut admitted);
441 loop {
442 let mut grew = false;
443 for (id, r) in rots {
444 if view.valid.contains_key(id) {
445 continue;
446 }
447 let Some(p) = r.parent.as_ref().and_then(|p| view.valid.get(p)) else { continue };
448 if r.epoch == p.epoch.saturating_add(1) && p.members.contains(&r.by) && r.recipients().any(|x| x == r.by) {
449 add(&mut view, id, r, &mut admitted);
450 grew = true;
451 }
452 }
453 if !grew {
454 break;
455 }
456 }
457 let parent: BTreeMap<&str, Option<&str>> = rots.iter().map(|(id, r)| (id.as_str(), r.parent.as_deref())).collect();
461 let mut keep: BTreeSet<String> = BTreeSet::new();
462 for (id, r) in rots {
463 if !view.valid.contains_key(id) || revoked.contains(r.by.as_str()) {
464 continue;
465 }
466 let mut cur = Some(id.as_str());
467 while let Some(c) = cur {
468 if !keep.insert(c.to_string()) {
469 break;
470 }
471 cur = parent.get(c).copied().flatten();
472 }
473 }
474 view.valid.retain(|id, _| keep.contains(id));
475 if view.valid.is_empty() {
476 return ChainView::default();
477 }
478 let kept_adm: BTreeSet<String> = adms.iter().filter(|(_, a)| view.valid.contains_key(&a.rotation)).map(|(id, _)| id.clone()).collect();
479 admitted.retain(|id| kept_adm.contains(id));
480 view.admissions = admitted;
481 view.head = view
482 .valid
483 .values()
484 .max_by(|a, b| (a.epoch, a.clean, std::cmp::Reverse(&a.id)).cmp(&(b.epoch, b.clean, std::cmp::Reverse(&b.id))))
485 .map(|v| v.id.clone());
486 view
487 }
488
489 pub fn head_id(&self) -> Option<String> {
491 self.chain_view().head
492 }
493}
494
495#[derive(Clone, Default, PartialEq)]
503pub struct EpochKeys {
504 keys: BTreeMap<String, (u32, Key32)>,
505 scoped: BTreeMap<(String, String), (u32, SyncKey)>,
506}
507
508impl std::fmt::Debug for EpochKeys {
509 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
510 if self.scoped.is_empty() {
511 write!(f, "EpochKeys({} keys)", self.keys.len())
512 } else {
513 write!(f, "EpochKeys({} keys, {} scoped)", self.keys.len(), self.scoped.len())
514 }
515 }
516}
517
518#[derive(Serialize, Deserialize)]
521struct KeyEntry {
522 id: String,
523 epoch: u32,
524 key: [u8; 32],
525 #[serde(default, skip_serializing_if = "Option::is_none")]
526 typ: Option<String>,
527}
528
529impl EpochKeys {
530 pub fn new() -> Self {
531 Self::default()
532 }
533 pub fn get(&self, id: &str) -> Option<&Key32> {
535 self.keys.get(id).map(|(_, k)| k)
536 }
537 pub fn has(&self, id: &str) -> bool {
539 self.keys.contains_key(id) || self.scoped_types(id).next().is_some()
540 }
541 pub fn has_epoch_key(&self, id: &str) -> bool {
543 self.keys.contains_key(id)
544 }
545 pub fn insert(&mut self, id: String, epoch: u32, key: Key32) {
546 self.keys.insert(id, (epoch, key));
547 }
548 pub fn get_scoped(&self, id: &str, typ: &str) -> Option<&SyncKey> {
550 self.scoped.get(&(id.to_string(), typ.to_string())).map(|(_, k)| k)
551 }
552 pub fn insert_scoped(&mut self, id: String, typ: String, epoch: u32, key: SyncKey) {
554 self.scoped.insert((id, typ), (epoch, key));
555 }
556 pub fn scoped_types<'a>(&'a self, id: &'a str) -> impl Iterator<Item = &'a str> + 'a {
558 self.scoped.range((id.to_string(), String::new())..).take_while(move |((i, _), _)| i == id).map(|((_, t), _)| t.as_str())
559 }
560 pub fn len(&self) -> usize {
562 self.keys.len() + self.scoped.len()
563 }
564 pub fn epoch_key_count(&self) -> usize {
566 self.keys.len()
567 }
568 pub fn scoped_len(&self) -> usize {
570 self.scoped.len()
571 }
572 pub fn is_empty(&self) -> bool {
573 self.keys.is_empty() && self.scoped.is_empty()
574 }
575 pub fn ids(&self) -> impl Iterator<Item = (&str, u32)> {
577 let mut all: BTreeMap<&str, u32> = self.keys.iter().map(|(id, (e, _))| (id.as_str(), *e)).collect();
578 for ((id, _), (e, _)) in &self.scoped {
579 all.entry(id.as_str()).or_insert(*e);
580 }
581 all.into_iter()
582 }
583 pub fn sync_key(&self, user_id: &str, typ: &str, epoch: u32, id: &str) -> Result<SyncKey> {
586 if let Some((_, k)) = self.keys.get(id) {
587 return rotated_sync_key(k, user_id, typ, epoch, id);
588 }
589 match self.scoped.get(&(id.to_string(), typ.to_string())) {
590 Some((e, k)) if *e == epoch => Ok(k.clone()),
591 Some(_) => Err(crypto("the scoped key is for another epoch")),
592 None if self.has(id) => Err(crypto("no key for this type under this rotation")),
593 None => Err(crypto("unknown epoch key")),
594 }
595 }
596 pub fn scope(&self, user_id: &str, types: &[String]) -> Result<EpochKeys> {
600 self.scope_where(user_id, types, |_| true)
601 }
602
603 fn scope_where(&self, user_id: &str, types: &[String], only: impl Fn(&str) -> bool) -> Result<EpochKeys> {
604 let mut out = EpochKeys::new();
605 for (id, (epoch, key)) in self.keys.iter().filter(|(id, _)| only(id)) {
606 for t in types {
607 out.scoped.insert((id.clone(), t.clone()), (*epoch, rotated_sync_key(key, user_id, t, *epoch, id)?));
608 }
609 }
610 for ((id, t), v) in &self.scoped {
611 if only(id) && types.contains(t) {
612 out.scoped.entry((id.clone(), t.clone())).or_insert_with(|| v.clone());
613 }
614 }
615 Ok(out)
616 }
617
618 pub fn narrow_to(&mut self, user_id: &str, types: &[String]) -> Result<()> {
621 *self = self.scope(user_id, types)?;
622 Ok(())
623 }
624
625 pub fn merge(&mut self, other: &EpochKeys) {
627 for (id, v) in &other.keys {
628 self.keys.entry(id.clone()).or_insert_with(|| v.clone());
629 }
630 for (k, v) in &other.scoped {
631 self.scoped.entry(k.clone()).or_insert_with(|| v.clone());
632 }
633 }
634
635 fn entries(&self, only: impl Fn(&str) -> bool) -> Zeroizing<Vec<u8>> {
636 let mut list: Vec<KeyEntry> =
637 self.keys.iter().filter(|(id, _)| only(id)).map(|(id, (e, k))| KeyEntry { id: id.clone(), epoch: *e, key: k.0, typ: None }).collect();
638 list.extend(self.scoped.iter().filter(|((id, _), _)| only(id)).map(|((id, t), (e, k))| KeyEntry {
639 id: id.clone(),
640 epoch: *e,
641 key: k.0,
642 typ: Some(t.clone()),
643 }));
644 let out = Zeroizing::new(encode(&list).unwrap_or_default());
645 for e in &mut list {
646 e.key.zeroize();
647 }
648 out
649 }
650
651 fn absorb(&mut self, bytes: &[u8], accept: impl Fn(&str, u32, Option<&str>, &Key32) -> bool) -> Result<usize> {
654 let mut list: Vec<KeyEntry> = decode(bytes)?;
655 let mut n = 0;
656 for e in &mut list {
657 let key = Key32(e.key);
658 e.key.zeroize();
659 match e.typ.take() {
660 None if !self.keys.contains_key(&e.id) && accept(&e.id, e.epoch, None, &key) => {
661 self.keys.insert(e.id.clone(), (e.epoch, key));
662 n += 1;
663 }
664 Some(t) if !self.scoped.contains_key(&(e.id.clone(), t.clone())) && accept(&e.id, e.epoch, Some(&t), &key) => {
665 self.scoped.insert((e.id.clone(), t), (e.epoch, key));
666 n += 1;
667 }
668 _ => {}
669 }
670 }
671 Ok(n)
672 }
673
674 pub fn export(&self) -> Zeroizing<Vec<u8>> {
676 self.entries(|_| true)
677 }
678
679 pub fn import(bytes: &[u8]) -> Result<Self> {
680 let mut k = Self::new();
681 k.absorb(bytes, |_, _, _, _| true)?;
682 Ok(k)
683 }
684}
685
686fn seal_to(eph: &ExchangeSecret, to: &[u8; 32], transcript: &[u8], plain: &[u8]) -> Result<Sealed> {
687 let shared = eph.agree(to).ok_or_else(|| crypto("low-order device key"))?;
688 let (k, _) = exchange::derive(&shared, transcript, SEAL_KEY, SEAL_SAS)?;
689 Ok(seal(&k, plain, transcript)?)
690}
691
692fn open_from(me: &ExchangeSecret, eph_hex: &str, transcript: &[u8], sealed: &Sealed) -> Result<Zeroizing<Vec<u8>>> {
693 let eph: [u8; 32] = hex::decode(eph_hex).ok().and_then(|b| b.try_into().ok()).ok_or_else(|| crypto("bad ephemeral key"))?;
694 let shared = me.agree(&eph).ok_or_else(|| crypto("low-order ephemeral key"))?;
695 let (k, _) = exchange::derive(&shared, transcript, SEAL_KEY, SEAL_SAS)?;
696 Ok(open(&k, sealed, transcript)?)
697}
698
699#[derive(Debug, Clone, PartialEq, Eq)]
701pub enum KeyStatus {
702 Seed,
704 Current { epoch: u32 },
706 NeedsAdmission,
709 Revoked,
711 RosterOnly,
714}
715
716impl SyncState {
717 pub fn publish_device_key(&mut self, at_ms: i64) -> Result<()> {
719 let device = self.device.as_ref().ok_or_else(|| SyncError::Protocol("no device key".into()))?;
720 if self.roster.chain.device(&device.peer_id()).is_none() {
721 let dk = device.device_key(at_ms)?;
722 self.roster.chain.add_device(dk);
723 }
724 Ok(())
725 }
726
727 pub fn key_status(&self) -> KeyStatus {
728 if self.roster.get(&self.our_cert.peer_id).is_some_and(|c| !c.active()) || !self.our_cert.active() {
729 return KeyStatus::Revoked;
730 }
731 if !self.roster.holds_keys(&self.our_cert.peer_id) {
732 return KeyStatus::RosterOnly;
733 }
734 let view = self.roster.chain_view();
735 match view.head() {
736 None => KeyStatus::Seed,
737 Some(h) if self.keys.has(&h.id) => KeyStatus::Current { epoch: h.epoch },
738 Some(_) => KeyStatus::NeedsAdmission,
739 }
740 }
741
742 pub fn needs_admission(&self) -> bool {
743 self.key_status() == KeyStatus::NeedsAdmission
744 }
745
746 pub fn devices_without_key(&self) -> Vec<NodeCert> {
751 self.roster
752 .active()
753 .filter(|c| self.roster.holds_keys(&c.peer_id) && self.roster.chain.device(&c.peer_id).is_none_or(|d| !d.verify()))
754 .cloned()
755 .collect()
756 }
757
758 pub fn first_rotation_due(&self) -> bool {
766 let Some(device) = &self.device else { return false };
767 if self.is_service() || self.key_status() != KeyStatus::Seed {
768 return false;
769 }
770 let active: Vec<&NodeCert> = self.roster.active().filter(|c| !self.roster.is_service(&c.peer_id)).collect();
772 let me = device.peer_id();
773 active.len() >= 2 && active.iter().any(|c| c.peer_id == me) && self.devices_without_key().is_empty() && active.iter().all(|c| c.peer_id >= me)
774 }
775
776 pub fn rotate_if_first_due(&mut self, at_ms: i64) -> Result<Option<String>> {
778 if self.first_rotation_due() { self.rotate(at_ms).map(Some) } else { Ok(None) }
779 }
780
781 pub fn needs_rotation(&self) -> bool {
783 let view = self.roster.chain_view();
784 self.device.is_some()
785 && !self.is_service()
786 && view.dirty()
787 && view.head().is_some_and(|h| self.keys.has(&h.id))
788 && self.key_status() != KeyStatus::Revoked
789 }
790
791 pub fn refresh_keys(&mut self) -> usize {
794 let Some(device) = self.device.clone() else { return 0 };
795 let me = device.peer_id();
796 let Some(my_pub) = self.roster.chain.device(&me).and_then(DeviceKey::public) else { return 0 };
797 let view = self.roster.chain_view();
798 let views = self.roster.all_views();
799 let valid = |id: &str| views.iter().any(|v| v.valid.contains_key(id));
800 let mut n = 0;
801 let checks: BTreeMap<String, (u32, String)> = self.roster.chain.rotations.iter().map(|r| (r.id(), (r.epoch, r.check.clone()))).collect();
802 for r in &self.roster.chain.rotations {
803 let id = r.id();
804 if !valid(&id) || self.keys.has(&id) {
805 continue;
806 }
807 let Some(sk) = r.keys.iter().find(|k| k.peer_id == me) else { continue };
808 if let Ok(plain) = open_from(&device.exchange, &r.eph, &r.transcript(&me, &my_pub), &sk.sealed)
809 && let Ok(key) = Key32::from_slice(&plain)
810 && key_check(&key) == r.check
811 {
812 self.keys.insert(id, r.epoch, key);
813 n += 1;
814 }
815 }
816 for a in &self.roster.chain.admissions {
817 if a.peer_id != me || !views.iter().any(|v| v.admissions.contains(&a.id())) {
818 continue;
819 }
820 if let Ok(plain) = open_from(&device.exchange, &a.eph, &a.transcript(&my_pub), &a.sealed) {
821 let accept = |id: &str, epoch: u32, typ: Option<&str>, key: &Key32| {
825 valid(id)
826 && checks.get(id).is_some_and(|(e, c)| match typ {
827 None => *c == key_check(key),
828 Some(_) => *e == epoch,
829 })
830 };
831 n += self.keys.absorb(&plain, accept).unwrap_or(0);
832 }
833 }
834 self.narrow_keys();
835 if self.roster.chain.root.is_none()
836 && let Some(root) = &view.root
837 && view.valid.keys().any(|id| self.keys.has(id))
838 {
839 self.roster.chain.root = Some(root.clone());
840 }
841 if let Some(h) = view.head() {
842 self.roster.epoch = self.roster.epoch.max(h.epoch);
843 }
844 n
845 }
846
847 pub fn rotate(&mut self, at_ms: i64) -> Result<String> {
850 let view = self.roster.chain_view();
851 self.rotate_on(&view, at_ms)
852 }
853
854 fn rotate_on(&mut self, view: &ChainView, at_ms: i64) -> Result<String> {
857 if self.is_service() {
858 return Err(SyncError::NotPermitted("rotate".into()));
859 }
860 let device = self.device.clone().ok_or_else(|| SyncError::Protocol("no device key".into()))?;
861 let me = device.peer_id();
862 self.publish_device_key(at_ms)?;
863 if self.key_status() == KeyStatus::Revoked {
864 return Err(SyncError::Refused("revoked".into()));
865 }
866 let active: BTreeSet<String> = self.roster.active().map(|c| c.peer_id.clone()).collect();
867 let (parent, epoch, mut candidates): (Option<String>, u32, BTreeSet<String>) = match view.head() {
868 Some(h) if !self.keys.has(&h.id) => return Err(SyncError::Refused("needs-admission".into())),
869 Some(h) => (Some(h.id.clone()), h.epoch.saturating_add(1), h.members.clone()),
870 None => (None, self.roster.epoch.saturating_add(1), active.clone()),
871 };
872 candidates.extend(self.roster.chain.approved.iter().cloned());
873 candidates.extend(self.roster.active().filter(|c| self.roster.is_service(&c.peer_id)).map(|c| c.peer_id.clone()));
876 candidates.retain(|p| self.roster.holds_keys(p));
877 let key = Key32::random()?;
878 let eph = ExchangeSecret::generate();
879 let mut r = Rotation {
880 epoch,
881 parent,
882 by: me.clone(),
883 at_ms,
884 eph: hex::encode(eph.public()),
885 check: key_check(&key),
886 keys: Vec::new(),
887 sig: Vec::new(),
888 };
889 let mut recipients: Vec<String> = candidates.into_iter().filter(|p| active.contains(p)).collect();
890 if !recipients.contains(&me) {
891 recipients.push(me.clone());
892 }
893 let mut scoped = Vec::new();
897 for peer in recipients {
898 let Some(public) = self.roster.chain.device(&peer).and_then(DeviceKey::public) else { continue };
899 if peer != me
900 && let Some(types) = self.roster.scoped_types(&peer)
901 {
902 scoped.push((peer, public, types));
903 continue;
904 }
905 let sealed = seal_to(&eph, &public, &r.transcript(&peer, &public), &key.0)?;
906 r.keys.push(SealedKey { peer_id: peer, sealed });
907 }
908 r.sig = device.sign(&r.body())?;
909 let id = r.id();
910 if r.parent.is_none() {
911 self.roster.chain.root = Some(id.clone());
912 }
913 self.roster.chain.rotations.push(r);
914 self.keys.insert(id.clone(), epoch, key);
915 self.roster.epoch = self.roster.epoch.max(epoch);
916 for (peer, public, types) in scoped {
917 let plain = self.keys.scope_where(&self.user_id, &types, |k| k == id)?.entries(|_| true);
918 self.push_admission(&device, &id, &peer, &public, &plain, at_ms)?;
919 }
920 Ok(id)
921 }
922
923 pub fn revoke(&mut self, user: &Keypair, peer_id: &str, at_ms: i64) -> Result<NodeCert> {
926 if self.is_service() {
927 return Err(SyncError::NotPermitted("revoke".into()));
928 }
929 let before = self.roster.chain_view();
930 let cert = self.roster.revoke(&WEIRDNET, user, peer_id, at_ms)?;
931 if self.device.is_some() {
932 self.rotate_on(&before, at_ms)?;
933 }
934 Ok(cert)
935 }
936
937 pub fn approve(&mut self, cert: NodeCert, at_ms: i64) -> Result<bool> {
941 if self.is_service() {
942 return Err(SyncError::NotPermitted("approve".into()));
943 }
944 if !WEIRDNET.verify_cert(&self.user_key, &cert) || !cert.active() || cert.user_id != self.user_id {
945 return Err(SyncError::Refused("wrong-user".into()));
946 }
947 if self.roster.get(&cert.peer_id).is_some_and(|c| !c.active()) {
948 return Err(SyncError::Refused("revoked".into()));
949 }
950 let peer = cert.peer_id.clone();
951 self.roster.upsert(cert);
952 if !self.roster.holds_keys(&peer) {
953 return Ok(false);
955 }
956 if !self.roster.chain.approved.contains(&peer) {
957 self.roster.chain.approved.push(peer.clone());
958 }
959 Ok(self.admit_approved(at_ms).contains(&peer))
960 }
961
962 pub fn admit_approved(&mut self, at_ms: i64) -> Vec<String> {
967 let mut admitted = Vec::new();
968 if self.roster.chain.approved.is_empty() || self.device.is_none() || self.is_service() {
969 return admitted;
970 }
971 let roster = &self.roster;
972 let drop: Vec<String> = roster.chain.approved.iter().filter(|p| !roster.holds_keys(p)).cloned().collect();
973 self.roster.chain.approved.retain(|p| !drop.contains(p));
974 for peer in self.roster.chain.approved.clone() {
975 let active = self.roster.get(&peer).is_some_and(|c| c.active());
976 let mut done = active;
977 let mut any = false;
978 for view in self.roster.all_views() {
979 let Some(head) = view.head() else { continue };
980 if !self.keys.has(&head.id) {
981 if view.root == self.roster.chain_view().root {
982 done = false;
983 }
984 continue;
985 }
986 any = true;
987 if !active || head.members.contains(&peer) {
988 continue;
989 }
990 let admitted_now = self.roster.chain.device(&peer).is_some()
991 && self.roster.get(&peer).cloned().is_some_and(|cert| self.admit_to(cert, &view, at_ms).unwrap_or(false));
992 if admitted_now {
993 if !admitted.contains(&peer) {
994 admitted.push(peer.clone());
995 }
996 } else {
997 done = false;
998 }
999 }
1000 if !active || (any && done) {
1001 self.roster.chain.approved.retain(|p| p != &peer);
1002 }
1003 }
1004 admitted
1005 }
1006
1007 pub fn admit(&mut self, cert: NodeCert, at_ms: i64) -> Result<bool> {
1012 if !WEIRDNET.verify_cert(&self.user_key, &cert) || !cert.active() || cert.user_id != self.user_id {
1013 return Err(SyncError::Refused("wrong-user".into()));
1014 }
1015 if self.roster.get(&cert.peer_id).is_some_and(|c| !c.active()) {
1016 return Err(SyncError::Refused("revoked".into()));
1017 }
1018 self.roster.upsert(cert.clone());
1019 let view = self.roster.chain_view();
1020 self.admit_to(cert, &view, at_ms)
1021 }
1022
1023 fn admit_to(&mut self, cert: NodeCert, view: &ChainView, at_ms: i64) -> Result<bool> {
1024 if self.is_service() {
1025 return Err(SyncError::NotPermitted("admit".into()));
1026 }
1027 if !self.roster.holds_keys(&cert.peer_id) {
1028 return Ok(false);
1029 }
1030 let device = self.device.clone().ok_or_else(|| SyncError::Protocol("no device key".into()))?;
1031 let peer = cert.peer_id.clone();
1032 let Some(head) = view.head() else { return Ok(false) };
1033 if !self.keys.has(&head.id) {
1034 return Err(SyncError::Refused("needs-admission".into()));
1035 }
1036 let public = self
1037 .roster
1038 .chain
1039 .device(&peer)
1040 .and_then(DeviceKey::public)
1041 .ok_or_else(|| SyncError::Protocol(format!("no device key for {peer} yet")))?;
1042 let plain = match self.roster.scoped_types(&peer) {
1045 Some(types) => self.keys.scope_where(&self.user_id, &types, |id| view.valid.contains_key(id))?.entries(|_| true),
1046 None => self.keys.entries(|id| view.valid.contains_key(id)),
1047 };
1048 self.push_admission(&device, &head.id, &peer, &public, &plain, at_ms)?;
1049 Ok(true)
1050 }
1051
1052 fn push_admission(&mut self, device: &Device, rotation: &str, peer: &str, public: &[u8; 32], plain: &[u8], at_ms: i64) -> Result<()> {
1054 let eph = ExchangeSecret::generate();
1055 let mut a = Admission {
1056 rotation: rotation.to_string(),
1057 peer_id: peer.to_string(),
1058 by: device.peer_id(),
1059 at_ms,
1060 eph: hex::encode(eph.public()),
1061 sealed: Sealed { nonce: String::new(), ct: String::new() },
1062 sig: Vec::new(),
1063 };
1064 a.sealed = seal_to(&eph, public, &a.transcript(public), plain)?;
1065 a.sig = device.sign(&a.body())?;
1066 self.roster.chain.admissions.push(a);
1067 Ok(())
1068 }
1069
1070 pub(crate) fn narrow_keys(&mut self) {
1074 if !self.is_service() {
1075 return;
1076 }
1077 let Some(types) = self.roster.scoped_types(&self.our_cert.peer_id) else {
1078 if self.roster.grant_of(&self.our_cert.peer_id).is_some_and(crate::roster::DeviceGrant::roster_only) {
1079 self.keys = EpochKeys::new();
1080 }
1081 return;
1082 };
1083 if self.keys.epoch_key_count() == 0 && self.keys.ids().all(|(id, _)| self.keys.scoped_types(id).all(|t| types.iter().any(|x| x == t))) {
1084 return;
1085 }
1086 let user_id = self.user_id.clone();
1087 if self.keys.narrow_to(&user_id, &types).is_err() {
1088 self.keys = EpochKeys::new();
1089 }
1090 }
1091}
1092
1093#[cfg(test)]
1094mod tests {
1095 use super::*;
1096
1097 #[test]
1098 fn a_device_key_verifies_only_for_its_own_node() {
1099 let node = Keypair::generate_ed25519();
1100 let d = Device::from_node_key(&node).unwrap();
1101 let dk = d.device_key(5).unwrap();
1102 assert!(dk.verify());
1103 assert_eq!(dk.peer_id, node.public().to_peer_id().to_string());
1104 assert_eq!(Device::from_node_key(&node).unwrap().device_key(5).unwrap().exchange, dk.exchange);
1106 let other = Device::from_node_key(&Keypair::generate_ed25519()).unwrap().device_key(5).unwrap();
1107 assert!(!DeviceKey { exchange: other.exchange.clone(), ..dk.clone() }.verify(), "a swapped exchange key fails");
1108 assert!(!DeviceKey { peer_id: other.peer_id.clone(), ..dk.clone() }.verify());
1109 assert_eq!(dk.fingerprint().len(), 14);
1110 assert!(format!("{d:?}").starts_with("Device(12D3"));
1111 }
1112
1113 #[test]
1114 fn epoch_keys_export_and_import() {
1115 let mut k = EpochKeys::new();
1116 k.insert("a".into(), 1, Key32::random().unwrap());
1117 k.insert("b".into(), 2, Key32::random().unwrap());
1118 let back = EpochKeys::import(&k.export()).unwrap();
1119 assert_eq!(back, k);
1120 assert_eq!(format!("{k:?}"), "EpochKeys(2 keys)");
1121 }
1122
1123 #[test]
1124 fn a_sealed_copy_opens_only_for_its_recipient() {
1125 let a = Device::from_node_key(&Keypair::generate_ed25519()).unwrap();
1126 let b = Device::from_node_key(&Keypair::generate_ed25519()).unwrap();
1127 let eph = ExchangeSecret::generate();
1128 let to = a.exchange.public();
1129 let s = seal_to(&eph, &to, b"t", b"key").unwrap();
1130 let eph_hex = hex::encode(eph.public());
1131 assert_eq!(&open_from(&a.exchange, &eph_hex, b"t", &s).unwrap()[..], b"key");
1132 assert!(open_from(&b.exchange, &eph_hex, b"t", &s).is_err());
1133 assert!(open_from(&a.exchange, &eph_hex, b"other", &s).is_err());
1134 }
1135
1136 #[test]
1137 fn peer_public_round_trips() {
1138 let k = Keypair::generate_ed25519();
1139 let pid = k.public().to_peer_id().to_string();
1140 assert_eq!(peer_public(&pid).unwrap(), k.public());
1141 assert!(peer_public("not-a-peer").is_none());
1142 }
1143}