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";
130
131/// The user identity, this node's key and certificate, and the roster, stored in a directory.
132pub struct Identity {
133    dir: PathBuf,
134    node_key: Keypair,
135    sync_type: String,
136    secrets: Arc<dyn SecretStore>,
137    state: Arc<Mutex<SyncState>>,
138}
139
140impl std::fmt::Debug for Identity {
141    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
142        // Never the seed or keys.
143        f.debug_struct("Identity").field("dir", &self.dir).field("peer_id", &self.peer_id()).field("sync_type", &self.sync_type).finish()
144    }
145}
146
147fn now_ms() -> i64 {
148    std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as i64).unwrap_or(0)
149}
150
151fn err(msg: impl Into<String>) -> SyncError {
152    SyncError::Identity(msg.into())
153}
154
155fn io(what: &str, path: &Path, e: std::io::Error) -> SyncError {
156    SyncError::Io(format!("{what} {}: {e}", path.display()))
157}
158
159/// The user key from its 32-byte seed.
160fn user_from_seed(seed: &[u8]) -> Result<Keypair> {
161    let mut bytes: [u8; 32] = seed.try_into().map_err(|_| err("the identity seed is not 32 bytes"))?;
162    Keypair::ed25519_from_bytes(&mut bytes).map_err(|e| err(format!("identity seed: {e}")))
163}
164
165fn write_private(path: &Path, bytes: &[u8]) -> Result<()> {
166    let tmp = path.with_extension("tmp");
167    {
168        let mut o = std::fs::OpenOptions::new();
169        o.write(true).create(true).truncate(true);
170        #[cfg(unix)]
171        {
172            use std::os::unix::fs::OpenOptionsExt;
173            o.mode(0o600);
174        }
175        let mut f = o.open(&tmp).map_err(|e| io("writing", &tmp, e))?;
176        f.write_all(bytes).and_then(|()| f.sync_all()).map_err(|e| io("writing", &tmp, e))?;
177    }
178    std::fs::rename(&tmp, path).map_err(|e| io("writing", path, e))
179}
180
181fn ensure_dir(dir: &Path) -> Result<()> {
182    std::fs::create_dir_all(dir).map_err(|e| io("creating", dir, e))?;
183    #[cfg(unix)]
184    {
185        use std::os::unix::fs::PermissionsExt;
186        std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700)).map_err(|e| io("securing", dir, e))?;
187    }
188    Ok(())
189}
190
191impl Identity {
192    /// Whether `dir` holds an identity (with its secrets in files).
193    pub fn exists(dir: &Path) -> bool {
194        Self::exists_with(dir, &FileSecrets::new(dir))
195    }
196
197    /// Whether `dir` holds an identity whose secrets are in `secrets`.
198    pub fn exists_with(dir: &Path, secrets: &dyn SecretStore) -> bool {
199        let has = |n: &str| secrets.read(n).ok().flatten().is_some();
200        (has("seed") || dir.join(CREDENTIAL).is_file()) && has("node.key")
201    }
202
203    /// A new Weirdnet user identity with this device as its first node, announcing `sync_type`.
204    /// To join the user's existing devices, link from one of them and [`Identity::adopt`].
205    /// Never overwrites an identity.
206    pub fn create(dir: &Path, label: &str, sync_type: impl Into<String>) -> Result<Self> {
207        Self::create_with(dir, Arc::new(FileSecrets::new(dir)), label, sync_type)
208    }
209
210    /// [`Identity::create`] with the secrets in `secrets`.
211    pub fn create_with(dir: &Path, secrets: Arc<dyn SecretStore>, label: &str, sync_type: impl Into<String>) -> Result<Self> {
212        if Self::exists_with(dir, secrets.as_ref()) {
213            return Err(err(format!("{} already holds an identity", dir.display())));
214        }
215        let mut seed = zeroize::Zeroizing::new([0u8; 32]);
216        getrandom::fill(seed.as_mut()).map_err(|e| err(format!("random seed: {e}")))?;
217        let user = user_from_seed(seed.as_ref())?;
218        let node_key = Keypair::generate_ed25519();
219        let cert = Roster::self_certify(&WEIRDNET, &user, &node_key.public().to_peer_id().to_string(), label, now_ms())
220            .map_err(|e| err(format!("certifying this node: {e}")))?;
221        let mut roster = Roster::new();
222        roster.upsert(cert.clone());
223        let me = Self::build(dir, secrets, Some(seed.to_vec()), user.public(), node_key, cert, roster, EpochKeys::default(), sync_type.into())?;
224        me.save()?;
225        Ok(me)
226    }
227
228    /// The identity a device link delivered: `seed`, the node certificate the existing device
229    /// made for `node_key`, and its [`LinkSettings`] (JSON; empty or unreadable means none).
230    pub fn adopt(dir: &Path, node_key: Keypair, seed: &[u8], cert: NodeCert, settings: &str, sync_type: impl Into<String>) -> Result<Self> {
231        Self::adopt_with(dir, Arc::new(FileSecrets::new(dir)), node_key, seed, cert, settings, sync_type)
232    }
233
234    /// [`Identity::adopt`] with the secrets in `secrets`.
235    pub fn adopt_with(
236        dir: &Path,
237        secrets: Arc<dyn SecretStore>,
238        node_key: Keypair,
239        seed: &[u8],
240        cert: NodeCert,
241        settings: &str,
242        sync_type: impl Into<String>,
243    ) -> Result<Self> {
244        if Self::exists_with(dir, secrets.as_ref()) {
245            return Err(err(format!("{} already holds an identity", dir.display())));
246        }
247        let user = user_from_seed(seed)?;
248        let peer = node_key.public().to_peer_id().to_string();
249        if cert.peer_id != peer || cert.user_id != weirdnet_net::user::user_id(&user.public()) || !WEIRDNET.verify_cert(&user.public(), &cert) {
250            return Err(err("the link's certificate is not for this node and identity"));
251        }
252        let given: LinkSettings = serde_json::from_str(settings).unwrap_or_default();
253        let mut roster = Roster::new();
254        roster.merge(&given.roster, &user.public(), &WEIRDNET);
255        roster.upsert(cert.clone());
256        let me = Self::build(dir, secrets, Some(seed.to_vec()), user.public(), node_key, cert, roster, EpochKeys::default(), sync_type.into())?;
257        me.save()?;
258        Ok(me)
259    }
260
261    /// The identity a **service** link delivered (`weirdnet-device-link`'s credential): the
262    /// user's public key, the node certificate the linking device made for `node_key`, and
263    /// the [`LinkBundle`] (its bytes). No seed: this node verifies, serves and syncs, but
264    /// cannot admit, revoke, grant or rotate, and with a roster-only grant holds no data keys.
265    pub fn adopt_service(
266        dir: &Path,
267        node_key: Keypair,
268        user_key: &[u8],
269        cert: NodeCert,
270        bundle: &[u8],
271        sync_type: impl Into<String>,
272    ) -> Result<Self> {
273        Self::adopt_service_with(dir, Arc::new(FileSecrets::new(dir)), node_key, user_key, cert, bundle, sync_type)
274    }
275
276    /// [`Identity::adopt_service`] with the secrets in `secrets`.
277    pub fn adopt_service_with(
278        dir: &Path,
279        secrets: Arc<dyn SecretStore>,
280        node_key: Keypair,
281        user_key: &[u8],
282        cert: NodeCert,
283        bundle: &[u8],
284        sync_type: impl Into<String>,
285    ) -> Result<Self> {
286        if Self::exists_with(dir, secrets.as_ref()) {
287            return Err(err(format!("{} already holds an identity", dir.display())));
288        }
289        let user_key = PublicKey::try_decode_protobuf(user_key).map_err(|e| err(format!("user key: {e}")))?;
290        if cert.user_id != weirdnet_net::user::user_id(&user_key) {
291            return Err(err("the link's certificate is not for this identity"));
292        }
293        let bundle = LinkBundle::from_bytes(bundle)?;
294        let sync_type = sync_type.into();
295        let st = SyncState::new_service(user_key, cert, &node_key, vec![sync_type.clone()], &bundle)
296            .map_err(|e| err(format!("the service link did not check out: {e}")))?;
297        ensure_dir(dir)?;
298        let me = Self { dir: dir.to_path_buf(), node_key, sync_type, secrets, state: Arc::new(Mutex::new(st)) };
299        me.save()?;
300        Ok(me)
301    }
302
303    /// The identity stored in `dir`, if any, announcing `sync_type`.
304    pub fn open(dir: &Path, sync_type: impl Into<String>) -> Result<Option<Self>> {
305        Self::open_with(dir, Arc::new(FileSecrets::new(dir)), sync_type)
306    }
307
308    /// [`Identity::open`] with the secrets in `secrets`.
309    pub fn open_with(dir: &Path, secrets: Arc<dyn SecretStore>, sync_type: impl Into<String>) -> Result<Option<Self>> {
310        if !Self::exists_with(dir, secrets.as_ref()) {
311            return Ok(None);
312        }
313        let seed = secrets.read("seed")?.map(|s| s.to_vec());
314        let user_key = match &seed {
315            Some(s) => user_from_seed(s)?.public(),
316            None => {
317                let path = dir.join(CREDENTIAL);
318                let c: Credential = serde_json::from_slice(&std::fs::read(&path).map_err(|e| io("reading", &path, e))?)
319                    .map_err(|e| err(format!("{CREDENTIAL}: {e}")))?;
320                let bytes = hex::decode(&c.user_key).map_err(|e| err(format!("{CREDENTIAL}: {e}")))?;
321                PublicKey::try_decode_protobuf(&bytes).map_err(|e| err(format!("{CREDENTIAL}: {e}")))?
322            }
323        };
324        let key_bytes = secrets.read("node.key")?.ok_or_else(|| err("no node key"))?;
325        let node_key = Keypair::from_protobuf_encoding(&key_bytes).map_err(|e| err(format!("node key: {e}")))?;
326        let roster: Roster = match std::fs::read(dir.join("roster.json")) {
327            Ok(b) => serde_json::from_slice(&b).map_err(|e| err(format!("roster.json: {e}")))?,
328            Err(_) => Roster::new(),
329        };
330        let keys = secrets.read("keys")?.and_then(|b| EpochKeys::import(&b).ok()).unwrap_or_default();
331        let peer = node_key.public().to_peer_id().to_string();
332        let cert = roster.get(&peer).cloned().ok_or_else(|| err("the roster has no certificate for this node"))?;
333        Self::build(dir, secrets, seed, user_key, node_key, cert, roster, keys, sync_type.into()).map(Some)
334    }
335
336    #[allow(clippy::too_many_arguments)]
337    fn build(
338        dir: &Path,
339        secrets: Arc<dyn SecretStore>,
340        seed: Option<Vec<u8>>,
341        user_key: PublicKey,
342        node_key: Keypair,
343        our_cert: NodeCert,
344        roster: Roster,
345        keys: EpochKeys,
346        sync_type: String,
347    ) -> Result<Self> {
348        ensure_dir(dir)?;
349        let service = seed.is_none();
350        let mut st = SyncState {
351            user_id: our_cert.user_id.clone(),
352            user_key,
353            our_node: NodeId::new(our_cert.peer_id.clone()),
354            our_cert,
355            seed,
356            types: vec![sync_type.clone()],
357            roster,
358            log: OpLog::new(),
359            clock: None,
360            device: Device::from_node_key(&node_key).ok(),
361            keys,
362            auto_first_rotation: !service,
363            records: Default::default(),
364        };
365        st.publish_device_key(now_ms())?;
366        st.refresh_keys();
367        Ok(Self { dir: dir.to_path_buf(), node_key, sync_type, secrets, state: Arc::new(Mutex::new(st)) })
368    }
369
370    fn lock(&self) -> MutexGuard<'_, SyncState> {
371        self.state.lock().unwrap_or_else(|e| e.into_inner())
372    }
373
374    /// Writes the roster and keys (and, the first time, the seed or credential and the node key).
375    pub fn save(&self) -> Result<()> {
376        ensure_dir(&self.dir)?;
377        let (seed, user_key, roster, keys) = {
378            let st = self.lock();
379            let roster = serde_json::to_vec_pretty(&st.roster).map_err(|e| err(format!("roster.json: {e}")))?;
380            (st.seed.clone().map(zeroize::Zeroizing::new), st.user_key.encode_protobuf(), roster, st.keys.export())
381        };
382        match &seed {
383            Some(seed) if self.secrets.read("seed")?.is_none() => self.secrets.write("seed", seed)?,
384            Some(_) => {}
385            None if !self.dir.join(CREDENTIAL).is_file() => {
386                let c = serde_json::to_vec_pretty(&Credential { user_key: hex::encode(user_key) }).map_err(|e| err(format!("{CREDENTIAL}: {e}")))?;
387                write_private(&self.dir.join(CREDENTIAL), &c)?;
388            }
389            None => {}
390        }
391        if self.secrets.read("node.key")?.is_none() {
392            let key = zeroize::Zeroizing::new(self.node_key.to_protobuf_encoding().map_err(|e| err(format!("node key: {e}")))?);
393            self.secrets.write("node.key", &key)?;
394        }
395        write_private(&self.dir.join("roster.json"), &roster)?;
396        self.secrets.write("keys", &keys)
397    }
398
399    /// Whether this is a service device (linked without the seed).
400    pub fn is_service(&self) -> bool {
401        self.lock().is_service()
402    }
403
404    /// The directory it is stored in.
405    pub fn dir(&self) -> &Path {
406        &self.dir
407    }
408
409    /// The sync type it announces.
410    pub fn sync_type(&self) -> &str {
411        &self.sync_type
412    }
413
414    pub fn node_key(&self) -> &Keypair {
415        &self.node_key
416    }
417
418    pub fn peer_id(&self) -> PeerId {
419        self.node_key.public().to_peer_id()
420    }
421
422    /// The shared sync state, for a [`crate::SyncHandler`] answering peers that pull from here.
423    pub fn state(&self) -> Arc<Mutex<SyncState>> {
424        self.state.clone()
425    }
426
427    pub fn user_key(&self) -> PublicKey {
428        self.lock().user_key.clone()
429    }
430
431    pub fn user_id(&self) -> String {
432        self.lock().user_id.clone()
433    }
434
435    pub fn our_cert(&self) -> NodeCert {
436        self.lock().our_cert.clone()
437    }
438
439    pub fn roster(&self) -> Roster {
440        self.lock().roster.clone()
441    }
442
443    /// The roster as it is now, for callers that check peers later (an inference server's
444    /// roster check, the pool's linked nodes).
445    pub fn roster_view(&self) -> Arc<dyn Fn() -> Roster + Send + Sync> {
446        let st = self.state.clone();
447        Arc::new(move || st.lock().unwrap_or_else(|e| e.into_inner()).roster.clone())
448    }
449
450    /// The [`LinkSettings`] payload (JSON) for a device linked from here.
451    pub fn link_settings(&self) -> String {
452        serde_json::to_string(&LinkSettings { roster: self.roster() }).unwrap_or_else(|_| "{}".into())
453    }
454
455    /// The seed, for a full device link sent from here. A service device has none.
456    pub fn seed(&self) -> Result<weirdnet_net::Key32> {
457        let st = self.lock();
458        let seed = st.seed.as_ref().ok_or_else(|| SyncError::NotPermitted("the seed".into()))?;
459        weirdnet_net::Key32::from_slice(seed).map_err(|e| err(format!("identity seed: {e}")))
460    }
461
462    /// The user keypair (secret), for minting the certificate of a device linked from here
463    /// (a service link). A service device has none.
464    pub fn user_keypair(&self) -> Result<Keypair> {
465        let st = self.lock();
466        let seed = st.seed.as_ref().ok_or_else(|| SyncError::NotPermitted("the user key".into()))?;
467        user_from_seed(seed)
468    }
469
470    /// Grant `peer` a class and roles (and, for a service device, sync types), then save.
471    /// Needs the seed.
472    pub fn grant(&self, peer: &str, class: DeviceClass, roles: &[String], types: &[String]) -> Result<DeviceGrant> {
473        let g = self.lock().grant(peer, class, roles, types, now_ms())?;
474        self.save()?;
475        Ok(g)
476    }
477
478    /// The [`LinkBundle`] bytes for a service link to `peer` (see
479    /// [`SyncState::service_bundle`]), then save (the grant, and a first rotation if one was
480    /// needed). After the link, [`Identity::approve`] the certificate it returns.
481    pub fn service_bundle(&self, peer: &str, roles: &[String], types: &[String]) -> Result<zeroize::Zeroizing<Vec<u8>>> {
482        let bytes = self.lock().service_bundle(peer, roles, types, now_ms())?.to_bytes()?;
483        self.save()?;
484        Ok(bytes)
485    }
486
487    /// The user linked `cert`'s device from here: it joins the roster (and the key chain once
488    /// its device key is known), and the roster is saved.
489    pub fn approve(&self, cert: NodeCert) -> Result<()> {
490        self.lock().approve(cert, now_ms())?;
491        self.save()
492    }
493
494    /// Revokes a device everywhere this roster reaches (and rotates the keys), then saves.
495    /// This node's own certificate can't be revoked here.
496    pub fn revoke(&self, peer: &str) -> Result<NodeCert> {
497        let cert = {
498            let mut st = self.lock();
499            if peer == st.our_cert.peer_id {
500                return Err(err("this is this node's own certificate"));
501            }
502            let seed = st.seed.as_ref().ok_or_else(|| SyncError::NotPermitted("revoke".into()))?;
503            let user = user_from_seed(seed)?;
504            st.revoke(&user, peer, now_ms())?
505        };
506        self.save()?;
507        Ok(cert)
508    }
509
510    /// One sync pass of [`Identity::sync_type`] against every other active device in the roster,
511    /// then a save. Blocking; call it from a blocking task. `addrs` gives the addresses to dial a
512    /// device at. Each pull goes into a snapshot that is merged back
513    /// ([`pull_from_shared`]), so a handler on the same state can answer a peer pulling from
514    /// here at the same moment. Errors only if saving fails.
515    pub fn tick(&self, node: &SyncNode, addrs: &dyn Fn(&NodeCert) -> Vec<Multiaddr>) -> Result<Tick> {
516        let me = node.peer_id().to_string();
517        let peers: Vec<NodeCert> = self.lock().roster.active().filter(|c| c.peer_id != me).cloned().collect();
518        let mut tick = Tick::default();
519        for cert in peers {
520            let Ok(peer) = PeerId::from_str(&cert.peer_id) else { continue };
521            let out = pull_from_shared(&self.state, node, peer, &addrs(&cert), &self.sync_type);
522            tick.applied += out.applied;
523            match out.error {
524                None => tick.reached += 1,
525                Some(e) => tick.failed.push((cert.peer_id.clone(), e)),
526            }
527        }
528        self.save()?;
529        Ok(tick)
530    }
531}
532
533#[cfg(test)]
534mod tests {
535    use super::*;
536    use crate::CallerCheck;
537
538    const TYPE: &str = "test.app";
539
540    #[test]
541    fn create_open_link_and_revoke() {
542        let tmp = tempfile::tempdir().unwrap();
543        let a_dir = tmp.path().join("a");
544        let a = Identity::create(&a_dir, "box-a", TYPE).unwrap();
545        assert!(Identity::create(&a_dir, "again", TYPE).is_err(), "never overwrites an identity");
546        assert_eq!(a.sync_type(), TYPE);
547        assert_eq!(a.state().lock().unwrap().types, [TYPE]);
548        #[cfg(unix)]
549        {
550            use std::os::unix::fs::PermissionsExt;
551            for f in ["seed", "node.key", "keys", "roster.json"] {
552                assert_eq!(std::fs::metadata(a_dir.join(f)).unwrap().permissions().mode() & 0o777, 0o600, "{f}");
553            }
554            assert_eq!(std::fs::metadata(&a_dir).unwrap().permissions().mode() & 0o777, 0o700);
555        }
556        assert!(!format!("{a:?}").contains("seed:"), "Debug shows no secrets");
557
558        // Link a second device the way a device link does: a cert from the seed holder.
559        let b_key = Keypair::generate_ed25519();
560        let user = user_from_seed(&a.seed().unwrap().0).unwrap();
561        let b_cert = Roster::self_certify(&WEIRDNET, &user, &b_key.public().to_peer_id().to_string(), "box-b", now_ms()).unwrap();
562        a.approve(b_cert.clone()).unwrap();
563        let (seed, settings) = (a.seed().unwrap(), a.link_settings());
564        let wrong_key = Keypair::generate_ed25519();
565        assert!(Identity::adopt(&tmp.path().join("x"), wrong_key, &seed.0, b_cert.clone(), &settings, TYPE).is_err(), "cert for another node");
566        let b = Identity::adopt(&tmp.path().join("b"), b_key, &seed.0, b_cert.clone(), &settings, "other.app").unwrap();
567        assert_eq!(b.user_id(), a.user_id());
568        let a_peer = a.peer_id().to_string();
569        let b_peer = b.peer_id().to_string();
570        assert_eq!(b.roster().check_caller(&WEIRDNET, &b.user_key(), &a_peer, None), CallerCheck::Linked);
571        assert_eq!(a.roster().check_caller(&WEIRDNET, &a.user_key(), &b_peer, Some(&b_cert)), CallerCheck::Linked);
572
573        // A stranger with another identity is not admitted.
574        let c = Identity::create(&tmp.path().join("c"), "stranger", TYPE).unwrap();
575        assert_eq!(a.roster().check_caller(&WEIRDNET, &a.user_key(), &c.peer_id().to_string(), Some(&c.our_cert())), CallerCheck::WrongUser);
576
577        // Reopening keeps the roster; revoking sticks.
578        assert!(Identity::open(&tmp.path().join("none"), TYPE).unwrap().is_none());
579        let again = Identity::open(&a_dir, TYPE).unwrap().unwrap();
580        assert_eq!(again.peer_id(), a.peer_id());
581        again.revoke(&b_peer).unwrap();
582        let reopened = Identity::open(&a_dir, TYPE).unwrap().unwrap();
583        assert_eq!(reopened.roster().check_caller(&WEIRDNET, &reopened.user_key(), &b_peer, None), CallerCheck::Revoked);
584        assert!(reopened.revoke(&a_peer).is_err());
585        assert!((reopened.roster_view())().get(&b_peer).is_some_and(|c| !c.active()));
586    }
587
588    /// A links B; B links C. One tick on A (against B, over memory nodes) teaches A about C.
589    #[test]
590    fn tick_brings_devices_linked_elsewhere() {
591        use crate::net::{node_config, start_node};
592        let tmp = tempfile::tempdir().unwrap();
593        let a = Identity::create(&tmp.path().join("a"), "a", TYPE).unwrap();
594        let user = user_from_seed(&a.seed().unwrap().0).unwrap();
595        let link = |from: &Identity, name: &str| {
596            let key = Keypair::generate_ed25519();
597            let cert = Roster::self_certify(&WEIRDNET, &user, &key.public().to_peer_id().to_string(), name, now_ms()).unwrap();
598            from.approve(cert.clone()).unwrap();
599            Identity::adopt(&tmp.path().join(name), key, &from.seed().unwrap().0, cert, &from.link_settings(), TYPE).unwrap()
600        };
601        let b = link(&a, "b");
602        let c = link(&b, "c");
603        let c_peer = c.peer_id().to_string();
604        assert!(a.roster().get(&c_peer).is_none());
605
606        let node_a = start_node(a.node_key().clone(), node_config(true), a.state()).unwrap();
607        let node_b = start_node(b.node_key().clone(), node_config(true), b.state()).unwrap();
608        let b_addrs: Vec<Multiaddr> = node_b.reachable_addrs().into_iter().map(|s| s.parse().unwrap()).collect();
609        let b_peer = b.peer_id().to_string();
610        let tick = a.tick(&node_a, &|cert| if cert.peer_id == b_peer { b_addrs.clone() } else { Vec::new() }).unwrap();
611        assert_eq!((tick.reached, tick.failed.len()), (1, 0), "{:?}", tick.failed);
612        assert!(a.roster().get(&c_peer).is_some_and(|c| c.active()), "A learned C");
613        let saved = Identity::open(a.dir(), TYPE).unwrap().unwrap();
614        assert!(saved.roster().get(&c_peer).is_some(), "the tick saved the roster");
615    }
616}