Skip to main content

weirdnet_sync/
identity.rs

1//! This device's place in the user's Weirdnet: the user identity, its own node key and
2//! certificate, and the linked-devices roster it shares with the user's other devices (Morph,
3//! Ymir, Bragi, …), kept current by sync passes.
4//!
5//! An [`Identity`] lives in one directory (0700 on Unix), secrets in 0600 files:
6//!
7//! - `seed`: the user key seed, which a full device link delivers (a service device, linked
8//!   with a certificate only, has none and keeps `credential.json`, the user's public key,
9//!   instead; see [`Identity::adopt_service`]);
10//! - `node.key`: this node's key (libp2p protobuf encoding);
11//! - `keys`: the epoch keys ([`EpochKeys::export`]);
12//! - `roster.json`: the public roster, in the format Morph links with.
13//!
14//! The secrets (`seed`, `node.key`, `keys`) go through a [`SecretStore`]: 0600 files in the
15//! directory by default ([`FileSecrets`]); apps that keep secrets in the OS keystore pass
16//! their own store to the `*_with` constructors. `roster.json` and `credential.json` are
17//! public and stay files.
18//!
19//! Each identity announces one sync type (`ymir.pool`, `bragi.app`, …). [`Identity::tick`] runs
20//! a pass of that type against every other active device with [`pull_from_shared`], so devices
21//! linked or revoked elsewhere reach this one even when the type carries no records yet: the
22//! roster and the key chain ride along with every pass.
23//!
24//! ```no_run
25//! # fn main() -> weirdnet_sync::Result<()> {
26//! use weirdnet_sync::identity::Identity;
27//! let dir = std::path::Path::new("/tmp/example-identity");
28//! let me = match Identity::open(dir, "example.app")? {
29//!     Some(me) => me,
30//!     None => Identity::create(dir, "my laptop", "example.app")?,
31//! };
32//! println!("{} on {}", me.user_id(), me.peer_id());
33//! # Ok(()) }
34//! ```
35
36use std::io::Write;
37use std::path::{Path, PathBuf};
38use std::str::FromStr;
39use std::sync::{Arc, Mutex, MutexGuard};
40
41use serde::{Deserialize, Serialize};
42use weirdnet_net::user::NodeCert;
43use weirdnet_net::{Keypair, Multiaddr, Node, PeerId, PublicKey, WEIRDNET};
44
45use crate::net::{LinkBundle, SyncState, pull_from_shared};
46use crate::roster::{DeviceClass, DeviceGrant, Roster};
47use crate::rotation::{Device, EpochKeys};
48use crate::{NodeId, OpLog, Result, SyncError};
49
50/// What a link transfer carries besides the identity: the roster, in Morph's format, so any two
51/// Weirdnet apps can link each other.
52#[derive(Debug, Clone, Default, Serialize, Deserialize)]
53#[non_exhaustive]
54pub struct LinkSettings {
55    #[serde(default)]
56    pub roster: Roster,
57}
58
59/// The node type sync passes run on.
60pub type SyncNode = Node<Vec<u8>, Vec<u8>>;
61
62/// What one [`Identity::tick`] did.
63#[derive(Debug, Default)]
64#[non_exhaustive]
65pub struct Tick {
66    /// Devices a pass finished against.
67    pub reached: usize,
68    /// New log entries stored, over all devices.
69    pub applied: usize,
70    /// Devices a pass did not finish against (peer id) and why.
71    pub failed: Vec<(String, SyncError)>,
72}
73
74/// Where an [`Identity`] keeps its secrets (`seed`, `node.key`, `keys`): bytes by name.
75/// Implement it over the OS keystore to keep them out of files.
76pub trait SecretStore: Send + Sync {
77    /// The secret, or `None` when it is not stored.
78    fn read(&self, name: &str) -> Result<Option<zeroize::Zeroizing<Vec<u8>>>>;
79    /// Store (replace) the secret.
80    fn write(&self, name: &str, bytes: &[u8]) -> Result<()>;
81    /// Forget the secret (no error when it is not stored).
82    fn remove(&self, name: &str) -> Result<()>;
83}
84
85/// The default [`SecretStore`]: one 0600 file per secret in the identity's directory.
86#[derive(Debug, Clone)]
87pub struct FileSecrets {
88    dir: PathBuf,
89}
90
91impl FileSecrets {
92    pub fn new(dir: &Path) -> Self {
93        Self { dir: dir.to_path_buf() }
94    }
95}
96
97impl SecretStore for FileSecrets {
98    fn read(&self, name: &str) -> Result<Option<zeroize::Zeroizing<Vec<u8>>>> {
99        let path = self.dir.join(name);
100        match std::fs::read(&path) {
101            Ok(b) => Ok(Some(zeroize::Zeroizing::new(b))),
102            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
103            Err(e) => Err(io("reading", &path, e)),
104        }
105    }
106
107    fn write(&self, name: &str, bytes: &[u8]) -> Result<()> {
108        ensure_dir(&self.dir)?;
109        write_private(&self.dir.join(name), bytes)
110    }
111
112    fn remove(&self, name: &str) -> Result<()> {
113        let path = self.dir.join(name);
114        match std::fs::remove_file(&path) {
115            Ok(()) => Ok(()),
116            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
117            Err(e) => Err(io("removing", &path, e)),
118        }
119    }
120}
121
122/// `credential.json` on a service device: the user's public key (protobuf, hex), which a
123/// full device derives from its seed.
124#[derive(Serialize, Deserialize)]
125struct Credential {
126    user_key: String,
127}
128
129const CREDENTIAL: &str = "credential.json";
130const VOTER: &str = "voter.cbor";
131
132/// The user identity, this node's key and certificate, and the roster, stored in a directory.
133pub struct Identity {
134    dir: PathBuf,
135    node_key: Keypair,
136    sync_type: String,
137    secrets: Arc<dyn SecretStore>,
138    state: Arc<Mutex<SyncState>>,
139}
140
141impl std::fmt::Debug for Identity {
142    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
143        // Never the seed or keys.
144        f.debug_struct("Identity").field("dir", &self.dir).field("peer_id", &self.peer_id()).field("sync_type", &self.sync_type).finish()
145    }
146}
147
148fn now_ms() -> i64 {
149    std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as i64).unwrap_or(0)
150}
151
152fn err(msg: impl Into<String>) -> SyncError {
153    SyncError::Identity(msg.into())
154}
155
156fn io(what: &str, path: &Path, e: std::io::Error) -> SyncError {
157    SyncError::Io(format!("{what} {}: {e}", path.display()))
158}
159
160/// The user key from its 32-byte seed.
161fn user_from_seed(seed: &[u8]) -> Result<Keypair> {
162    let mut bytes: [u8; 32] = seed.try_into().map_err(|_| err("the identity seed is not 32 bytes"))?;
163    Keypair::ed25519_from_bytes(&mut bytes).map_err(|e| err(format!("identity seed: {e}")))
164}
165
166fn write_private(path: &Path, bytes: &[u8]) -> Result<()> {
167    let tmp = path.with_extension("tmp");
168    {
169        let mut o = std::fs::OpenOptions::new();
170        o.write(true).create(true).truncate(true);
171        #[cfg(unix)]
172        {
173            use std::os::unix::fs::OpenOptionsExt;
174            o.mode(0o600);
175        }
176        let mut f = o.open(&tmp).map_err(|e| io("writing", &tmp, e))?;
177        f.write_all(bytes).and_then(|()| f.sync_all()).map_err(|e| io("writing", &tmp, e))?;
178    }
179    std::fs::rename(&tmp, path).map_err(|e| io("writing", path, e))
180}
181
182fn ensure_dir(dir: &Path) -> Result<()> {
183    std::fs::create_dir_all(dir).map_err(|e| io("creating", dir, e))?;
184    #[cfg(unix)]
185    {
186        use std::os::unix::fs::PermissionsExt;
187        std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700)).map_err(|e| io("securing", dir, e))?;
188    }
189    Ok(())
190}
191
192impl Identity {
193    /// Whether `dir` holds an identity (with its secrets in files).
194    pub fn exists(dir: &Path) -> bool {
195        Self::exists_with(dir, &FileSecrets::new(dir))
196    }
197
198    /// Whether `dir` holds an identity whose secrets are in `secrets`.
199    pub fn exists_with(dir: &Path, secrets: &dyn SecretStore) -> bool {
200        let has = |n: &str| secrets.read(n).ok().flatten().is_some();
201        (has("seed") || dir.join(CREDENTIAL).is_file()) && has("node.key")
202    }
203
204    /// A new Weirdnet user identity with this device as its first node, announcing `sync_type`.
205    /// To join the user's existing devices, link from one of them and [`Identity::adopt`].
206    /// Never overwrites an identity.
207    pub fn create(dir: &Path, label: &str, sync_type: impl Into<String>) -> Result<Self> {
208        Self::create_with(dir, Arc::new(FileSecrets::new(dir)), label, sync_type)
209    }
210
211    /// [`Identity::create`] with the secrets in `secrets`.
212    pub fn create_with(dir: &Path, secrets: Arc<dyn SecretStore>, label: &str, sync_type: impl Into<String>) -> Result<Self> {
213        if Self::exists_with(dir, secrets.as_ref()) {
214            return Err(err(format!("{} already holds an identity", dir.display())));
215        }
216        let mut seed = zeroize::Zeroizing::new([0u8; 32]);
217        getrandom::fill(seed.as_mut()).map_err(|e| err(format!("random seed: {e}")))?;
218        let user = user_from_seed(seed.as_ref())?;
219        let node_key = Keypair::generate_ed25519();
220        let cert = Roster::self_certify(&WEIRDNET, &user, &node_key.public().to_peer_id().to_string(), label, now_ms())
221            .map_err(|e| err(format!("certifying this node: {e}")))?;
222        let mut roster = Roster::new();
223        roster.upsert(cert.clone());
224        let me = Self::build(dir, secrets, Some(seed.to_vec()), user.public(), node_key, cert, roster, EpochKeys::default(), sync_type.into())?;
225        me.save()?;
226        Ok(me)
227    }
228
229    /// The identity a device link delivered: `seed`, the node certificate the existing device
230    /// made for `node_key`, and its [`LinkSettings`] (JSON; empty or unreadable means none).
231    pub fn adopt(dir: &Path, node_key: Keypair, seed: &[u8], cert: NodeCert, settings: &str, sync_type: impl Into<String>) -> Result<Self> {
232        Self::adopt_with(dir, Arc::new(FileSecrets::new(dir)), node_key, seed, cert, settings, sync_type)
233    }
234
235    /// [`Identity::adopt`] with the secrets in `secrets`.
236    pub fn adopt_with(
237        dir: &Path,
238        secrets: Arc<dyn SecretStore>,
239        node_key: Keypair,
240        seed: &[u8],
241        cert: NodeCert,
242        settings: &str,
243        sync_type: impl Into<String>,
244    ) -> Result<Self> {
245        if Self::exists_with(dir, secrets.as_ref()) {
246            return Err(err(format!("{} already holds an identity", dir.display())));
247        }
248        let user = user_from_seed(seed)?;
249        let peer = node_key.public().to_peer_id().to_string();
250        if cert.peer_id != peer || cert.user_id != weirdnet_net::user::user_id(&user.public()) || !WEIRDNET.verify_cert(&user.public(), &cert) {
251            return Err(err("the link's certificate is not for this node and identity"));
252        }
253        let given: LinkSettings = serde_json::from_str(settings).unwrap_or_default();
254        let mut roster = Roster::new();
255        roster.merge(&given.roster, &user.public(), &WEIRDNET);
256        roster.upsert(cert.clone());
257        let me = Self::build(dir, secrets, Some(seed.to_vec()), user.public(), node_key, cert, roster, EpochKeys::default(), sync_type.into())?;
258        me.save()?;
259        Ok(me)
260    }
261
262    /// The identity a **service** link delivered (`weirdnet-device-link`'s credential): the
263    /// user's public key, the node certificate the linking device made for `node_key`, and
264    /// the [`LinkBundle`] (its bytes). No seed: this node verifies, serves and syncs, but
265    /// cannot admit, revoke, grant or rotate, and with a roster-only grant holds no data keys.
266    pub fn adopt_service(
267        dir: &Path,
268        node_key: Keypair,
269        user_key: &[u8],
270        cert: NodeCert,
271        bundle: &[u8],
272        sync_type: impl Into<String>,
273    ) -> Result<Self> {
274        Self::adopt_service_with(dir, Arc::new(FileSecrets::new(dir)), node_key, user_key, cert, bundle, sync_type)
275    }
276
277    /// [`Identity::adopt_service`] with the secrets in `secrets`.
278    pub fn adopt_service_with(
279        dir: &Path,
280        secrets: Arc<dyn SecretStore>,
281        node_key: Keypair,
282        user_key: &[u8],
283        cert: NodeCert,
284        bundle: &[u8],
285        sync_type: impl Into<String>,
286    ) -> Result<Self> {
287        if Self::exists_with(dir, secrets.as_ref()) {
288            return Err(err(format!("{} already holds an identity", dir.display())));
289        }
290        let user_key = PublicKey::try_decode_protobuf(user_key).map_err(|e| err(format!("user key: {e}")))?;
291        if cert.user_id != weirdnet_net::user::user_id(&user_key) {
292            return Err(err("the link's certificate is not for this identity"));
293        }
294        let bundle = LinkBundle::from_bytes(bundle)?;
295        let sync_type = sync_type.into();
296        let st = SyncState::new_service(user_key, cert, &node_key, vec![sync_type.clone()], &bundle)
297            .map_err(|e| err(format!("the service link did not check out: {e}")))?;
298        ensure_dir(dir)?;
299        let me = Self { dir: dir.to_path_buf(), node_key, sync_type, secrets, state: Arc::new(Mutex::new(st)) };
300        me.save()?;
301        Ok(me)
302    }
303
304    /// The identity stored in `dir`, if any, announcing `sync_type`.
305    pub fn open(dir: &Path, sync_type: impl Into<String>) -> Result<Option<Self>> {
306        Self::open_with(dir, Arc::new(FileSecrets::new(dir)), sync_type)
307    }
308
309    /// [`Identity::open`] with the secrets in `secrets`.
310    pub fn open_with(dir: &Path, secrets: Arc<dyn SecretStore>, sync_type: impl Into<String>) -> Result<Option<Self>> {
311        if !Self::exists_with(dir, secrets.as_ref()) {
312            return Ok(None);
313        }
314        let seed = secrets.read("seed")?.map(|s| s.to_vec());
315        let user_key = match &seed {
316            Some(s) => user_from_seed(s)?.public(),
317            None => {
318                let path = dir.join(CREDENTIAL);
319                let c: Credential = serde_json::from_slice(&std::fs::read(&path).map_err(|e| io("reading", &path, e))?)
320                    .map_err(|e| err(format!("{CREDENTIAL}: {e}")))?;
321                let bytes = hex::decode(&c.user_key).map_err(|e| err(format!("{CREDENTIAL}: {e}")))?;
322                PublicKey::try_decode_protobuf(&bytes).map_err(|e| err(format!("{CREDENTIAL}: {e}")))?
323            }
324        };
325        let key_bytes = secrets.read("node.key")?.ok_or_else(|| err("no node key"))?;
326        let node_key = Keypair::from_protobuf_encoding(&key_bytes).map_err(|e| err(format!("node key: {e}")))?;
327        let roster: Roster = match std::fs::read(dir.join("roster.json")) {
328            Ok(b) => serde_json::from_slice(&b).map_err(|e| err(format!("roster.json: {e}")))?,
329            Err(_) => Roster::new(),
330        };
331        let keys = secrets.read("keys")?.and_then(|b| EpochKeys::import(&b).ok()).unwrap_or_default();
332        let peer = node_key.public().to_peer_id().to_string();
333        let cert = roster.get(&peer).cloned().ok_or_else(|| err("the roster has no certificate for this node"))?;
334        Self::build(dir, secrets, seed, user_key, node_key, cert, roster, keys, sync_type.into()).map(Some)
335    }
336
337    #[allow(clippy::too_many_arguments)]
338    fn build(
339        dir: &Path,
340        secrets: Arc<dyn SecretStore>,
341        seed: Option<Vec<u8>>,
342        user_key: PublicKey,
343        node_key: Keypair,
344        our_cert: NodeCert,
345        roster: Roster,
346        keys: EpochKeys,
347        sync_type: String,
348    ) -> Result<Self> {
349        ensure_dir(dir)?;
350        let service = seed.is_none();
351        let mut st = SyncState {
352            user_id: our_cert.user_id.clone(),
353            user_key,
354            our_node: NodeId::new(our_cert.peer_id.clone()),
355            our_cert,
356            seed,
357            types: vec![sync_type.clone()],
358            roster,
359            log: OpLog::new(),
360            clock: None,
361            device: Device::from_node_key(&node_key).ok(),
362            keys,
363            auto_first_rotation: !service,
364            records: Default::default(),
365            voter: None,
366        };
367        st.publish_device_key(now_ms())?;
368        st.refresh_keys();
369        Ok(Self { dir: dir.to_path_buf(), node_key, sync_type, secrets, state: Arc::new(Mutex::new(st)) })
370    }
371
372    fn lock(&self) -> MutexGuard<'_, SyncState> {
373        self.state.lock().unwrap_or_else(|e| e.into_inner())
374    }
375
376    /// Writes the roster and keys (and, the first time, the seed or credential and the node key).
377    pub fn save(&self) -> Result<()> {
378        ensure_dir(&self.dir)?;
379        let (seed, user_key, roster, keys) = {
380            let st = self.lock();
381            let roster = serde_json::to_vec_pretty(&st.roster).map_err(|e| err(format!("roster.json: {e}")))?;
382            (st.seed.clone().map(zeroize::Zeroizing::new), st.user_key.encode_protobuf(), roster, st.keys.export())
383        };
384        match &seed {
385            Some(seed) if self.secrets.read("seed")?.is_none() => self.secrets.write("seed", seed)?,
386            Some(_) => {}
387            None if !self.dir.join(CREDENTIAL).is_file() => {
388                let c = serde_json::to_vec_pretty(&Credential { user_key: hex::encode(user_key) }).map_err(|e| err(format!("{CREDENTIAL}: {e}")))?;
389                write_private(&self.dir.join(CREDENTIAL), &c)?;
390            }
391            None => {}
392        }
393        if self.secrets.read("node.key")?.is_none() {
394            let key = zeroize::Zeroizing::new(self.node_key.to_protobuf_encoding().map_err(|e| err(format!("node key: {e}")))?);
395            self.secrets.write("node.key", &key)?;
396        }
397        write_private(&self.dir.join("roster.json"), &roster)?;
398        self.secrets.write("keys", &keys)
399    }
400
401    /// Make this device a lease voter for `candidates` (see [`crate::lease`]). Its terms are
402    /// kept in `voter.cbor` (public), read back here after a restart and written before each
403    /// new term is granted, so a crash can never hand out a term twice.
404    pub fn enable_voter(&self, candidates: crate::lease::Voters) -> Result<()> {
405        self.enable_voter_with(crate::lease::Voter::new(candidates.clone()), candidates)
406    }
407
408    /// [`enable_voter`](Self::enable_voter) with a configured fresh voter (for example a
409    /// shorter [`Voter::with_max_duration`](crate::lease::Voter::with_max_duration)), used when
410    /// no `voter.cbor` exists yet; a stored one keeps its terms and gets the same maximum.
411    pub fn enable_voter_with(&self, fresh: crate::lease::Voter, candidates: crate::lease::Voters) -> Result<()> {
412        ensure_dir(&self.dir)?;
413        let path = self.dir.join(VOTER);
414        let voter = match std::fs::read(&path) {
415            Ok(bytes) => crate::lease::Voter::import(&bytes, candidates)?.with_max_duration(fresh.max_duration()),
416            Err(e) if e.kind() == std::io::ErrorKind::NotFound => fresh,
417            Err(e) => return Err(io("reading", &path, e)),
418        };
419        let store = path.clone();
420        let voter = voter.with_persist(move |bytes| write_private(&store, bytes).map_err(|e| std::io::Error::other(e.to_string())));
421        self.lock().set_voter(Some(voter));
422        Ok(())
423    }
424
425    /// Stop voting (the stored terms stay on disk).
426    pub fn disable_voter(&self) {
427        self.lock().set_voter(None);
428    }
429
430    /// Whether this is a service device (linked without the seed).
431    pub fn is_service(&self) -> bool {
432        self.lock().is_service()
433    }
434
435    /// The directory it is stored in.
436    pub fn dir(&self) -> &Path {
437        &self.dir
438    }
439
440    /// The sync type it announces.
441    pub fn sync_type(&self) -> &str {
442        &self.sync_type
443    }
444
445    pub fn node_key(&self) -> &Keypair {
446        &self.node_key
447    }
448
449    pub fn peer_id(&self) -> PeerId {
450        self.node_key.public().to_peer_id()
451    }
452
453    /// The shared sync state, for a [`crate::SyncHandler`] answering peers that pull from here.
454    pub fn state(&self) -> Arc<Mutex<SyncState>> {
455        self.state.clone()
456    }
457
458    pub fn user_key(&self) -> PublicKey {
459        self.lock().user_key.clone()
460    }
461
462    pub fn user_id(&self) -> String {
463        self.lock().user_id.clone()
464    }
465
466    pub fn our_cert(&self) -> NodeCert {
467        self.lock().our_cert.clone()
468    }
469
470    pub fn roster(&self) -> Roster {
471        self.lock().roster.clone()
472    }
473
474    /// The roster as it is now, for callers that check peers later (an inference server's
475    /// roster check, the pool's linked nodes).
476    pub fn roster_view(&self) -> Arc<dyn Fn() -> Roster + Send + Sync> {
477        let st = self.state.clone();
478        Arc::new(move || st.lock().unwrap_or_else(|e| e.into_inner()).roster.clone())
479    }
480
481    /// The [`LinkSettings`] payload (JSON) for a device linked from here.
482    pub fn link_settings(&self) -> String {
483        serde_json::to_string(&LinkSettings { roster: self.roster() }).unwrap_or_else(|_| "{}".into())
484    }
485
486    /// The seed, for a full device link sent from here. A service device has none.
487    pub fn seed(&self) -> Result<weirdnet_net::Key32> {
488        let st = self.lock();
489        let seed = st.seed.as_ref().ok_or_else(|| SyncError::NotPermitted("the seed".into()))?;
490        weirdnet_net::Key32::from_slice(seed).map_err(|e| err(format!("identity seed: {e}")))
491    }
492
493    /// The user keypair (secret), for minting the certificate of a device linked from here
494    /// (a service link). A service device has none.
495    pub fn user_keypair(&self) -> Result<Keypair> {
496        let st = self.lock();
497        let seed = st.seed.as_ref().ok_or_else(|| SyncError::NotPermitted("the user key".into()))?;
498        user_from_seed(seed)
499    }
500
501    /// Grant `peer` a class and roles (and, for a service device, sync types), then save.
502    /// Needs the seed.
503    pub fn grant(&self, peer: &str, class: DeviceClass, roles: &[String], types: &[String]) -> Result<DeviceGrant> {
504        let g = self.lock().grant(peer, class, roles, types, now_ms())?;
505        self.save()?;
506        Ok(g)
507    }
508
509    /// The [`LinkBundle`] bytes for a service link to `peer` (see
510    /// [`SyncState::service_bundle`]), then save (the grant, and a first rotation if one was
511    /// needed). After the link, [`Identity::approve`] the certificate it returns.
512    pub fn service_bundle(&self, peer: &str, roles: &[String], types: &[String]) -> Result<zeroize::Zeroizing<Vec<u8>>> {
513        let bytes = self.lock().service_bundle(peer, roles, types, now_ms())?.to_bytes()?;
514        self.save()?;
515        Ok(bytes)
516    }
517
518    /// The user linked `cert`'s device from here: it joins the roster (and the key chain once
519    /// its device key is known), and the roster is saved.
520    pub fn approve(&self, cert: NodeCert) -> Result<()> {
521        self.lock().approve(cert, now_ms())?;
522        self.save()
523    }
524
525    /// Revokes a device everywhere this roster reaches (and rotates the keys), then saves.
526    /// This node's own certificate can't be revoked here.
527    pub fn revoke(&self, peer: &str) -> Result<NodeCert> {
528        let cert = {
529            let mut st = self.lock();
530            if peer == st.our_cert.peer_id {
531                return Err(err("this is this node's own certificate"));
532            }
533            let seed = st.seed.as_ref().ok_or_else(|| SyncError::NotPermitted("revoke".into()))?;
534            let user = user_from_seed(seed)?;
535            st.revoke(&user, peer, now_ms())?
536        };
537        self.save()?;
538        Ok(cert)
539    }
540
541    /// One sync pass of [`Identity::sync_type`] against every other active device in the roster,
542    /// then a save. Blocking; call it from a blocking task. `addrs` gives the addresses to dial a
543    /// device at. Each pull goes into a snapshot that is merged back
544    /// ([`pull_from_shared`]), so a handler on the same state can answer a peer pulling from
545    /// here at the same moment. Errors only if saving fails.
546    pub fn tick(&self, node: &SyncNode, addrs: &dyn Fn(&NodeCert) -> Vec<Multiaddr>) -> Result<Tick> {
547        let me = node.peer_id().to_string();
548        let peers: Vec<NodeCert> = self.lock().roster.active().filter(|c| c.peer_id != me).cloned().collect();
549        let mut tick = Tick::default();
550        for cert in peers {
551            let Ok(peer) = PeerId::from_str(&cert.peer_id) else { continue };
552            let out = pull_from_shared(&self.state, node, peer, &addrs(&cert), &self.sync_type);
553            tick.applied += out.applied;
554            match out.error {
555                None => tick.reached += 1,
556                Some(e) => tick.failed.push((cert.peer_id.clone(), e)),
557            }
558        }
559        self.save()?;
560        Ok(tick)
561    }
562}
563
564#[cfg(test)]
565mod tests {
566    use super::*;
567    use crate::CallerCheck;
568
569    const TYPE: &str = "test.app";
570
571    #[test]
572    fn create_open_link_and_revoke() {
573        let tmp = tempfile::tempdir().unwrap();
574        let a_dir = tmp.path().join("a");
575        let a = Identity::create(&a_dir, "box-a", TYPE).unwrap();
576        assert!(Identity::create(&a_dir, "again", TYPE).is_err(), "never overwrites an identity");
577        assert_eq!(a.sync_type(), TYPE);
578        assert_eq!(a.state().lock().unwrap().types, [TYPE]);
579        #[cfg(unix)]
580        {
581            use std::os::unix::fs::PermissionsExt;
582            for f in ["seed", "node.key", "keys", "roster.json"] {
583                assert_eq!(std::fs::metadata(a_dir.join(f)).unwrap().permissions().mode() & 0o777, 0o600, "{f}");
584            }
585            assert_eq!(std::fs::metadata(&a_dir).unwrap().permissions().mode() & 0o777, 0o700);
586        }
587        assert!(!format!("{a:?}").contains("seed:"), "Debug shows no secrets");
588
589        // Link a second device the way a device link does: a cert from the seed holder.
590        let b_key = Keypair::generate_ed25519();
591        let user = user_from_seed(&a.seed().unwrap().0).unwrap();
592        let b_cert = Roster::self_certify(&WEIRDNET, &user, &b_key.public().to_peer_id().to_string(), "box-b", now_ms()).unwrap();
593        a.approve(b_cert.clone()).unwrap();
594        let (seed, settings) = (a.seed().unwrap(), a.link_settings());
595        let wrong_key = Keypair::generate_ed25519();
596        assert!(Identity::adopt(&tmp.path().join("x"), wrong_key, &seed.0, b_cert.clone(), &settings, TYPE).is_err(), "cert for another node");
597        let b = Identity::adopt(&tmp.path().join("b"), b_key, &seed.0, b_cert.clone(), &settings, "other.app").unwrap();
598        assert_eq!(b.user_id(), a.user_id());
599        let a_peer = a.peer_id().to_string();
600        let b_peer = b.peer_id().to_string();
601        assert_eq!(b.roster().check_caller(&WEIRDNET, &b.user_key(), &a_peer, None), CallerCheck::Linked);
602        assert_eq!(a.roster().check_caller(&WEIRDNET, &a.user_key(), &b_peer, Some(&b_cert)), CallerCheck::Linked);
603
604        // A stranger with another identity is not admitted.
605        let c = Identity::create(&tmp.path().join("c"), "stranger", TYPE).unwrap();
606        assert_eq!(a.roster().check_caller(&WEIRDNET, &a.user_key(), &c.peer_id().to_string(), Some(&c.our_cert())), CallerCheck::WrongUser);
607
608        // Reopening keeps the roster; revoking sticks.
609        assert!(Identity::open(&tmp.path().join("none"), TYPE).unwrap().is_none());
610        let again = Identity::open(&a_dir, TYPE).unwrap().unwrap();
611        assert_eq!(again.peer_id(), a.peer_id());
612        again.revoke(&b_peer).unwrap();
613        let reopened = Identity::open(&a_dir, TYPE).unwrap().unwrap();
614        assert_eq!(reopened.roster().check_caller(&WEIRDNET, &reopened.user_key(), &b_peer, None), CallerCheck::Revoked);
615        assert!(reopened.revoke(&a_peer).is_err());
616        assert!((reopened.roster_view())().get(&b_peer).is_some_and(|c| !c.active()));
617    }
618
619    /// A links B; B links C. One tick on A (against B, over memory nodes) teaches A about C.
620    #[test]
621    fn tick_brings_devices_linked_elsewhere() {
622        use crate::net::{node_config, start_node};
623        let tmp = tempfile::tempdir().unwrap();
624        let a = Identity::create(&tmp.path().join("a"), "a", TYPE).unwrap();
625        let user = user_from_seed(&a.seed().unwrap().0).unwrap();
626        let link = |from: &Identity, name: &str| {
627            let key = Keypair::generate_ed25519();
628            let cert = Roster::self_certify(&WEIRDNET, &user, &key.public().to_peer_id().to_string(), name, now_ms()).unwrap();
629            from.approve(cert.clone()).unwrap();
630            Identity::adopt(&tmp.path().join(name), key, &from.seed().unwrap().0, cert, &from.link_settings(), TYPE).unwrap()
631        };
632        let b = link(&a, "b");
633        let c = link(&b, "c");
634        let c_peer = c.peer_id().to_string();
635        assert!(a.roster().get(&c_peer).is_none());
636
637        let node_a = start_node(a.node_key().clone(), node_config(true), a.state()).unwrap();
638        let node_b = start_node(b.node_key().clone(), node_config(true), b.state()).unwrap();
639        let b_addrs: Vec<Multiaddr> = node_b.reachable_addrs().into_iter().map(|s| s.parse().unwrap()).collect();
640        let b_peer = b.peer_id().to_string();
641        let tick = a.tick(&node_a, &|cert| if cert.peer_id == b_peer { b_addrs.clone() } else { Vec::new() }).unwrap();
642        assert_eq!((tick.reached, tick.failed.len()), (1, 0), "{:?}", tick.failed);
643        assert!(a.roster().get(&c_peer).is_some_and(|c| c.active()), "A learned C");
644        let saved = Identity::open(a.dir(), TYPE).unwrap().unwrap();
645        assert!(saved.roster().get(&c_peer).is_some(), "the tick saved the roster");
646    }
647}