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 device link delivers;
8//! - `node.key`: this node's key (libp2p protobuf encoding);
9//! - `keys`: the epoch keys ([`EpochKeys::export`]);
10//! - `roster.json`: the public roster, in the format Morph links with.
11//!
12//! The files are plain, not sealed. Apps that keep secrets in the OS keystore should hold
13//! [`SyncState`] themselves until this store grows a keystore backend.
14//!
15//! Each identity announces one sync type (`ymir.pool`, `bragi.app`, …). [`Identity::tick`] runs
16//! a pass of that type against every other active device with [`pull_from_shared`], so devices
17//! linked or revoked elsewhere reach this one even when the type carries no records yet: the
18//! roster and the key chain ride along with every pass.
19//!
20//! ```no_run
21//! # fn main() -> weirdnet_sync::Result<()> {
22//! use weirdnet_sync::identity::Identity;
23//! let dir = std::path::Path::new("/tmp/example-identity");
24//! let me = match Identity::open(dir, "example.app")? {
25//!     Some(me) => me,
26//!     None => Identity::create(dir, "my laptop", "example.app")?,
27//! };
28//! println!("{} on {}", me.user_id(), me.peer_id());
29//! # Ok(()) }
30//! ```
31
32use std::io::Write;
33use std::path::{Path, PathBuf};
34use std::str::FromStr;
35use std::sync::{Arc, Mutex, MutexGuard};
36
37use serde::{Deserialize, Serialize};
38use weirdnet_net::user::NodeCert;
39use weirdnet_net::{Keypair, Multiaddr, Node, PeerId, PublicKey, WEIRDNET};
40
41use crate::net::{SyncState, pull_from_shared};
42use crate::roster::Roster;
43use crate::rotation::{Device, EpochKeys};
44use crate::{NodeId, OpLog, Result, SyncError};
45
46/// What a link transfer carries besides the identity: the roster, in Morph's format, so any two
47/// Weirdnet apps can link each other.
48#[derive(Debug, Clone, Default, Serialize, Deserialize)]
49#[non_exhaustive]
50pub struct LinkSettings {
51    #[serde(default)]
52    pub roster: Roster,
53}
54
55/// The node type sync passes run on.
56pub type SyncNode = Node<Vec<u8>, Vec<u8>>;
57
58/// What one [`Identity::tick`] did.
59#[derive(Debug, Default)]
60#[non_exhaustive]
61pub struct Tick {
62    /// Devices a pass finished against.
63    pub reached: usize,
64    /// New log entries stored, over all devices.
65    pub applied: usize,
66    /// Devices a pass did not finish against (peer id) and why.
67    pub failed: Vec<(String, SyncError)>,
68}
69
70/// The user identity, this node's key and certificate, and the roster, stored in a directory.
71pub struct Identity {
72    dir: PathBuf,
73    node_key: Keypair,
74    sync_type: String,
75    state: Arc<Mutex<SyncState>>,
76}
77
78impl std::fmt::Debug for Identity {
79    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
80        // Never the seed or keys.
81        f.debug_struct("Identity").field("dir", &self.dir).field("peer_id", &self.peer_id()).field("sync_type", &self.sync_type).finish()
82    }
83}
84
85fn now_ms() -> i64 {
86    std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as i64).unwrap_or(0)
87}
88
89fn err(msg: impl Into<String>) -> SyncError {
90    SyncError::Identity(msg.into())
91}
92
93fn io(what: &str, path: &Path, e: std::io::Error) -> SyncError {
94    SyncError::Io(format!("{what} {}: {e}", path.display()))
95}
96
97/// The user key from its 32-byte seed.
98fn user_from_seed(seed: &[u8]) -> Result<Keypair> {
99    let mut bytes: [u8; 32] = seed.try_into().map_err(|_| err("the identity seed is not 32 bytes"))?;
100    Keypair::ed25519_from_bytes(&mut bytes).map_err(|e| err(format!("identity seed: {e}")))
101}
102
103fn write_private(path: &Path, bytes: &[u8]) -> Result<()> {
104    let tmp = path.with_extension("tmp");
105    {
106        let mut o = std::fs::OpenOptions::new();
107        o.write(true).create(true).truncate(true);
108        #[cfg(unix)]
109        {
110            use std::os::unix::fs::OpenOptionsExt;
111            o.mode(0o600);
112        }
113        let mut f = o.open(&tmp).map_err(|e| io("writing", &tmp, e))?;
114        f.write_all(bytes).and_then(|()| f.sync_all()).map_err(|e| io("writing", &tmp, e))?;
115    }
116    std::fs::rename(&tmp, path).map_err(|e| io("writing", path, e))
117}
118
119fn ensure_dir(dir: &Path) -> Result<()> {
120    std::fs::create_dir_all(dir).map_err(|e| io("creating", dir, e))?;
121    #[cfg(unix)]
122    {
123        use std::os::unix::fs::PermissionsExt;
124        std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700)).map_err(|e| io("securing", dir, e))?;
125    }
126    Ok(())
127}
128
129impl Identity {
130    /// Whether `dir` holds an identity.
131    pub fn exists(dir: &Path) -> bool {
132        dir.join("seed").is_file() && dir.join("node.key").is_file()
133    }
134
135    /// A new Weirdnet user identity with this device as its first node, announcing `sync_type`.
136    /// To join the user's existing devices, link from one of them and [`Identity::adopt`].
137    /// Never overwrites an identity.
138    pub fn create(dir: &Path, label: &str, sync_type: impl Into<String>) -> Result<Self> {
139        if Self::exists(dir) {
140            return Err(err(format!("{} already holds an identity", dir.display())));
141        }
142        let mut seed = [0u8; 32];
143        getrandom::fill(&mut seed).map_err(|e| err(format!("random seed: {e}")))?;
144        let user = user_from_seed(&seed)?;
145        let node_key = Keypair::generate_ed25519();
146        let cert = Roster::self_certify(&WEIRDNET, &user, &node_key.public().to_peer_id().to_string(), label, now_ms())
147            .map_err(|e| err(format!("certifying this node: {e}")))?;
148        let mut roster = Roster::new();
149        roster.upsert(cert.clone());
150        let me = Self::build(dir, seed.to_vec(), node_key, cert, roster, EpochKeys::default(), sync_type.into())?;
151        me.save()?;
152        Ok(me)
153    }
154
155    /// The identity a device link delivered: `seed`, the node certificate the existing device
156    /// made for `node_key`, and its [`LinkSettings`] (JSON; empty or unreadable means none).
157    pub fn adopt(dir: &Path, node_key: Keypair, seed: &[u8], cert: NodeCert, settings: &str, sync_type: impl Into<String>) -> Result<Self> {
158        if Self::exists(dir) {
159            return Err(err(format!("{} already holds an identity", dir.display())));
160        }
161        let user = user_from_seed(seed)?;
162        let peer = node_key.public().to_peer_id().to_string();
163        if cert.peer_id != peer || cert.user_id != weirdnet_net::user::user_id(&user.public()) || !WEIRDNET.verify_cert(&user.public(), &cert) {
164            return Err(err("the link's certificate is not for this node and identity"));
165        }
166        let given: LinkSettings = serde_json::from_str(settings).unwrap_or_default();
167        let mut roster = Roster::new();
168        roster.merge(&given.roster, &user.public(), &WEIRDNET);
169        roster.upsert(cert.clone());
170        let me = Self::build(dir, seed.to_vec(), node_key, cert, roster, EpochKeys::default(), sync_type.into())?;
171        me.save()?;
172        Ok(me)
173    }
174
175    /// The identity stored in `dir`, if any, announcing `sync_type`.
176    pub fn open(dir: &Path, sync_type: impl Into<String>) -> Result<Option<Self>> {
177        if !Self::exists(dir) {
178            return Ok(None);
179        }
180        let seed_path = dir.join("seed");
181        let seed = std::fs::read(&seed_path).map_err(|e| io("reading", &seed_path, e))?;
182        let key_path = dir.join("node.key");
183        let node_key = Keypair::from_protobuf_encoding(&std::fs::read(&key_path).map_err(|e| io("reading", &key_path, e))?)
184            .map_err(|e| err(format!("node key: {e}")))?;
185        let roster: Roster = match std::fs::read(dir.join("roster.json")) {
186            Ok(b) => serde_json::from_slice(&b).map_err(|e| err(format!("roster.json: {e}")))?,
187            Err(_) => Roster::new(),
188        };
189        let keys = std::fs::read(dir.join("keys")).ok().and_then(|b| EpochKeys::import(&b).ok()).unwrap_or_default();
190        let peer = node_key.public().to_peer_id().to_string();
191        let cert = roster.get(&peer).cloned().ok_or_else(|| err("the roster has no certificate for this node"))?;
192        Self::build(dir, seed, node_key, cert, roster, keys, sync_type.into()).map(Some)
193    }
194
195    fn build(dir: &Path, seed: Vec<u8>, node_key: Keypair, our_cert: NodeCert, roster: Roster, keys: EpochKeys, sync_type: String) -> Result<Self> {
196        ensure_dir(dir)?;
197        let user = user_from_seed(&seed)?;
198        let mut st = SyncState {
199            user_id: our_cert.user_id.clone(),
200            user_key: user.public(),
201            our_node: NodeId::new(our_cert.peer_id.clone()),
202            our_cert,
203            seed,
204            types: vec![sync_type.clone()],
205            roster,
206            log: OpLog::new(),
207            clock: None,
208            device: Device::from_node_key(&node_key).ok(),
209            keys,
210            auto_first_rotation: true,
211            records: Default::default(),
212        };
213        st.publish_device_key(now_ms())?;
214        st.refresh_keys();
215        Ok(Self { dir: dir.to_path_buf(), node_key, sync_type, state: Arc::new(Mutex::new(st)) })
216    }
217
218    fn lock(&self) -> MutexGuard<'_, SyncState> {
219        self.state.lock().unwrap_or_else(|e| e.into_inner())
220    }
221
222    /// Writes the roster and keys (and, the first time, the seed and node key).
223    pub fn save(&self) -> Result<()> {
224        ensure_dir(&self.dir)?;
225        let (seed, roster, keys) = {
226            let st = self.lock();
227            let roster = serde_json::to_vec_pretty(&st.roster).map_err(|e| err(format!("roster.json: {e}")))?;
228            (st.seed.clone(), roster, st.keys.export())
229        };
230        if !self.dir.join("seed").is_file() {
231            write_private(&self.dir.join("seed"), &seed)?;
232        }
233        if !self.dir.join("node.key").is_file() {
234            let key = self.node_key.to_protobuf_encoding().map_err(|e| err(format!("node key: {e}")))?;
235            write_private(&self.dir.join("node.key"), &key)?;
236        }
237        write_private(&self.dir.join("roster.json"), &roster)?;
238        write_private(&self.dir.join("keys"), &keys)
239    }
240
241    /// The directory it is stored in.
242    pub fn dir(&self) -> &Path {
243        &self.dir
244    }
245
246    /// The sync type it announces.
247    pub fn sync_type(&self) -> &str {
248        &self.sync_type
249    }
250
251    pub fn node_key(&self) -> &Keypair {
252        &self.node_key
253    }
254
255    pub fn peer_id(&self) -> PeerId {
256        self.node_key.public().to_peer_id()
257    }
258
259    /// The shared sync state, for a [`crate::SyncHandler`] answering peers that pull from here.
260    pub fn state(&self) -> Arc<Mutex<SyncState>> {
261        self.state.clone()
262    }
263
264    pub fn user_key(&self) -> PublicKey {
265        self.lock().user_key.clone()
266    }
267
268    pub fn user_id(&self) -> String {
269        self.lock().user_id.clone()
270    }
271
272    pub fn our_cert(&self) -> NodeCert {
273        self.lock().our_cert.clone()
274    }
275
276    pub fn roster(&self) -> Roster {
277        self.lock().roster.clone()
278    }
279
280    /// The roster as it is now, for callers that check peers later (an inference server's
281    /// roster check, the pool's linked nodes).
282    pub fn roster_view(&self) -> Arc<dyn Fn() -> Roster + Send + Sync> {
283        let st = self.state.clone();
284        Arc::new(move || st.lock().unwrap_or_else(|e| e.into_inner()).roster.clone())
285    }
286
287    /// The [`LinkSettings`] payload (JSON) for a device linked from here.
288    pub fn link_settings(&self) -> String {
289        serde_json::to_string(&LinkSettings { roster: self.roster() }).unwrap_or_else(|_| "{}".into())
290    }
291
292    /// The seed, for a device link sent from here.
293    pub fn seed(&self) -> Result<weirdnet_net::Key32> {
294        weirdnet_net::Key32::from_slice(&self.lock().seed).map_err(|e| err(format!("identity seed: {e}")))
295    }
296
297    /// The user linked `cert`'s device from here: it joins the roster (and the key chain once
298    /// its device key is known), and the roster is saved.
299    pub fn approve(&self, cert: NodeCert) -> Result<()> {
300        self.lock().approve(cert, now_ms())?;
301        self.save()
302    }
303
304    /// Revokes a device everywhere this roster reaches (and rotates the keys), then saves.
305    /// This node's own certificate can't be revoked here.
306    pub fn revoke(&self, peer: &str) -> Result<NodeCert> {
307        let cert = {
308            let mut st = self.lock();
309            if peer == st.our_cert.peer_id {
310                return Err(err("this is this node's own certificate"));
311            }
312            let user = user_from_seed(&st.seed)?;
313            st.revoke(&user, peer, now_ms())?
314        };
315        self.save()?;
316        Ok(cert)
317    }
318
319    /// One sync pass of [`Identity::sync_type`] against every other active device in the roster,
320    /// then a save. Blocking; call it from a blocking task. `addrs` gives the addresses to dial a
321    /// device at. Each pull goes into a snapshot that is merged back
322    /// ([`pull_from_shared`]), so a handler on the same state can answer a peer pulling from
323    /// here at the same moment. Errors only if saving fails.
324    pub fn tick(&self, node: &SyncNode, addrs: &dyn Fn(&NodeCert) -> Vec<Multiaddr>) -> Result<Tick> {
325        let me = node.peer_id().to_string();
326        let peers: Vec<NodeCert> = self.lock().roster.active().filter(|c| c.peer_id != me).cloned().collect();
327        let mut tick = Tick::default();
328        for cert in peers {
329            let Ok(peer) = PeerId::from_str(&cert.peer_id) else { continue };
330            let out = pull_from_shared(&self.state, node, peer, &addrs(&cert), &self.sync_type);
331            tick.applied += out.applied;
332            match out.error {
333                None => tick.reached += 1,
334                Some(e) => tick.failed.push((cert.peer_id.clone(), e)),
335            }
336        }
337        self.save()?;
338        Ok(tick)
339    }
340}
341
342#[cfg(test)]
343mod tests {
344    use super::*;
345    use crate::CallerCheck;
346
347    const TYPE: &str = "test.app";
348
349    #[test]
350    fn create_open_link_and_revoke() {
351        let tmp = tempfile::tempdir().unwrap();
352        let a_dir = tmp.path().join("a");
353        let a = Identity::create(&a_dir, "box-a", TYPE).unwrap();
354        assert!(Identity::create(&a_dir, "again", TYPE).is_err(), "never overwrites an identity");
355        assert_eq!(a.sync_type(), TYPE);
356        assert_eq!(a.state().lock().unwrap().types, [TYPE]);
357        #[cfg(unix)]
358        {
359            use std::os::unix::fs::PermissionsExt;
360            for f in ["seed", "node.key", "keys", "roster.json"] {
361                assert_eq!(std::fs::metadata(a_dir.join(f)).unwrap().permissions().mode() & 0o777, 0o600, "{f}");
362            }
363            assert_eq!(std::fs::metadata(&a_dir).unwrap().permissions().mode() & 0o777, 0o700);
364        }
365        assert!(!format!("{a:?}").contains("seed:"), "Debug shows no secrets");
366
367        // Link a second device the way a device link does: a cert from the seed holder.
368        let b_key = Keypair::generate_ed25519();
369        let user = user_from_seed(&a.seed().unwrap().0).unwrap();
370        let b_cert = Roster::self_certify(&WEIRDNET, &user, &b_key.public().to_peer_id().to_string(), "box-b", now_ms()).unwrap();
371        a.approve(b_cert.clone()).unwrap();
372        let (seed, settings) = (a.seed().unwrap(), a.link_settings());
373        let wrong_key = Keypair::generate_ed25519();
374        assert!(Identity::adopt(&tmp.path().join("x"), wrong_key, &seed.0, b_cert.clone(), &settings, TYPE).is_err(), "cert for another node");
375        let b = Identity::adopt(&tmp.path().join("b"), b_key, &seed.0, b_cert.clone(), &settings, "other.app").unwrap();
376        assert_eq!(b.user_id(), a.user_id());
377        let a_peer = a.peer_id().to_string();
378        let b_peer = b.peer_id().to_string();
379        assert_eq!(b.roster().check_caller(&WEIRDNET, &b.user_key(), &a_peer, None), CallerCheck::Linked);
380        assert_eq!(a.roster().check_caller(&WEIRDNET, &a.user_key(), &b_peer, Some(&b_cert)), CallerCheck::Linked);
381
382        // A stranger with another identity is not admitted.
383        let c = Identity::create(&tmp.path().join("c"), "stranger", TYPE).unwrap();
384        assert_eq!(a.roster().check_caller(&WEIRDNET, &a.user_key(), &c.peer_id().to_string(), Some(&c.our_cert())), CallerCheck::WrongUser);
385
386        // Reopening keeps the roster; revoking sticks.
387        assert!(Identity::open(&tmp.path().join("none"), TYPE).unwrap().is_none());
388        let again = Identity::open(&a_dir, TYPE).unwrap().unwrap();
389        assert_eq!(again.peer_id(), a.peer_id());
390        again.revoke(&b_peer).unwrap();
391        let reopened = Identity::open(&a_dir, TYPE).unwrap().unwrap();
392        assert_eq!(reopened.roster().check_caller(&WEIRDNET, &reopened.user_key(), &b_peer, None), CallerCheck::Revoked);
393        assert!(reopened.revoke(&a_peer).is_err());
394        assert!((reopened.roster_view())().get(&b_peer).is_some_and(|c| !c.active()));
395    }
396
397    /// A links B; B links C. One tick on A (against B, over memory nodes) teaches A about C.
398    #[test]
399    fn tick_brings_devices_linked_elsewhere() {
400        use crate::net::{node_config, start_node};
401        let tmp = tempfile::tempdir().unwrap();
402        let a = Identity::create(&tmp.path().join("a"), "a", TYPE).unwrap();
403        let user = user_from_seed(&a.seed().unwrap().0).unwrap();
404        let link = |from: &Identity, name: &str| {
405            let key = Keypair::generate_ed25519();
406            let cert = Roster::self_certify(&WEIRDNET, &user, &key.public().to_peer_id().to_string(), name, now_ms()).unwrap();
407            from.approve(cert.clone()).unwrap();
408            Identity::adopt(&tmp.path().join(name), key, &from.seed().unwrap().0, cert, &from.link_settings(), TYPE).unwrap()
409        };
410        let b = link(&a, "b");
411        let c = link(&b, "c");
412        let c_peer = c.peer_id().to_string();
413        assert!(a.roster().get(&c_peer).is_none());
414
415        let node_a = start_node(a.node_key().clone(), node_config(true), a.state()).unwrap();
416        let node_b = start_node(b.node_key().clone(), node_config(true), b.state()).unwrap();
417        let b_addrs: Vec<Multiaddr> = node_b.reachable_addrs().into_iter().map(|s| s.parse().unwrap()).collect();
418        let b_peer = b.peer_id().to_string();
419        let tick = a.tick(&node_a, &|cert| if cert.peer_id == b_peer { b_addrs.clone() } else { Vec::new() }).unwrap();
420        assert_eq!((tick.reached, tick.failed.len()), (1, 0), "{:?}", tick.failed);
421        assert!(a.roster().get(&c_peer).is_some_and(|c| c.active()), "A learned C");
422        let saved = Identity::open(a.dir(), TYPE).unwrap().unwrap();
423        assert!(saved.roster().get(&c_peer).is_some(), "the tick saved the roster");
424    }
425}