Skip to main content

weirdnet_net/
user.rs

1//! User identities: a person's Ed25519 signing key, separate from node keys. The user
2//! certifies each node it links (a signature over the node's peer id) and can revoke it
3//! later; peers check these before treating a node as acting for a user. A [`Card`] is what
4//! a node says about its user: the public key and the certificates, never a secret.
5//!
6//! Which users are trusted, what a connection may do and where certificates are kept are
7//! the application's decisions; this module only makes and checks the signatures.
8use crate::error::{NetError, Result};
9use crate::profile::Profile;
10use libp2p::identity::{Keypair, PublicKey};
11use serde::{Deserialize, Serialize};
12use sha2::Digest;
13
14/// A user's certificate for one node, with its revocation when there is one.
15#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
16pub struct NodeCert {
17    pub user_id: String,
18    pub peer_id: String,
19    pub label: String,
20    pub cert: Vec<u8>,
21    pub issued_at: i64,
22    pub revoked_at: Option<i64>,
23    #[serde(default, skip_serializing_if = "Option::is_none")]
24    pub revocation: Option<Vec<u8>>,
25}
26
27impl NodeCert {
28    /// Not revoked.
29    pub fn active(&self) -> bool {
30        self.revoked_at.is_none()
31    }
32}
33
34/// What a node says about its user over an exchange: the user's public key (protobuf) and
35/// the certificates (and revocations) of the user's nodes.
36#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
37pub struct Card {
38    pub id: String,
39    pub label: String,
40    pub key: Vec<u8>,
41    pub nodes: Vec<NodeCert>,
42}
43
44impl Card {
45    /// A short fingerprint of what the card says (to re-introduce only after a change).
46    pub fn digest(&self) -> String {
47        let mut h = sha2::Sha256::new();
48        h.update(self.id.as_bytes());
49        h.update(self.label.as_bytes());
50        for n in &self.nodes {
51            h.update(n.peer_id.as_bytes());
52            h.update(n.issued_at.to_le_bytes());
53            h.update(n.revoked_at.unwrap_or(0).to_le_bytes());
54        }
55        hex::encode(&h.finalize()[..8])
56    }
57}
58
59/// The user id of a public key: 32 hex characters of its SHA-256.
60pub fn user_id(key: &PublicKey) -> String {
61    hex::encode(&sha2::Sha256::digest(key.encode_protobuf())[..16])
62}
63
64/// A user keypair from its protobuf encoding.
65pub fn decode_keypair(bytes: &[u8]) -> Result<Keypair> {
66    Keypair::from_protobuf_encoding(bytes).map_err(|e| NetError::Crypto(format!("user identity: {e}")))
67}
68
69/// A user public key from its protobuf encoding.
70pub fn decode_public(bytes: &[u8]) -> Result<PublicKey> {
71    PublicKey::try_decode_protobuf(bytes).map_err(|e| NetError::Crypto(format!("user key: {e}")))
72}
73
74impl Profile {
75    pub fn cert_bytes(&self, user: &str, peer: &str, at: i64) -> Vec<u8> {
76        format!("{}\n{user}\n{peer}\n{at}", self.cert).into_bytes()
77    }
78
79    pub fn revoke_bytes(&self, user: &str, peer: &str, at: i64) -> Vec<u8> {
80        format!("{}\n{user}\n{peer}\n{at}", self.revoke).into_bytes()
81    }
82
83    /// The user's certificate for a node, issued at `at` (ms).
84    pub fn certify(&self, kp: &Keypair, user: &str, peer: &str, label: &str, at: i64) -> Result<NodeCert> {
85        let cert = kp.sign(&self.cert_bytes(user, peer, at)).map_err(|e| NetError::Crypto(format!("certify: {e}")))?;
86        Ok(NodeCert { user_id: user.into(), peer_id: peer.into(), label: label.into(), cert, issued_at: at, revoked_at: None, revocation: None })
87    }
88
89    /// The user's signed revocation of a node at `at` (ms).
90    pub fn revoke(&self, kp: &Keypair, user: &str, peer: &str, at: i64) -> Result<Vec<u8>> {
91        kp.sign(&self.revoke_bytes(user, peer, at)).map_err(|e| NetError::Crypto(format!("revoke: {e}")))
92    }
93
94    /// Check a certificate (and its revocation, if any) against the user's key. A
95    /// revocation time without its signature (or the other way round) fails.
96    pub fn verify_cert(&self, key: &PublicKey, n: &NodeCert) -> bool {
97        if user_id(key) != n.user_id || !key.verify(&self.cert_bytes(&n.user_id, &n.peer_id, n.issued_at), &n.cert) {
98            return false;
99        }
100        match (n.revoked_at, &n.revocation) {
101            (None, None) => true,
102            (Some(at), Some(sig)) => key.verify(&self.revoke_bytes(&n.user_id, &n.peer_id, at), sig),
103            _ => false,
104        }
105    }
106
107    /// Check a card a peer sent: the id must be its key's, and it must carry a valid,
108    /// unrevoked certificate for that very peer. Returns the user's key; which of the
109    /// card's certificates to keep (those that verify) is up to the caller.
110    pub fn check_card(&self, from_peer: &str, card: &Card) -> Result<PublicKey> {
111        let key = decode_public(&card.key)?;
112        if user_id(&key) != card.id {
113            return Err(NetError::Crypto("user card: the id does not match the key".into()));
114        }
115        if !card.nodes.iter().any(|n| n.peer_id == from_peer && n.user_id == card.id && n.active() && self.verify_cert(&key, n)) {
116            return Err(NetError::Crypto("user card: no valid certificate for the sending node".into()));
117        }
118        Ok(key)
119    }
120
121    /// On a node being linked: check a grant (the user's card and signing key) from the
122    /// approving node. The key must be the card's, the card must certify this node (`me`)
123    /// and the approving node, neither revoked. Returns the user keypair.
124    pub fn check_grant(&self, me: &str, from_peer: &str, card: &Card, keypair: &[u8]) -> Result<Keypair> {
125        let kp = decode_keypair(keypair)?;
126        if user_id(&kp.public()) != card.id || kp.public().encode_protobuf() != card.key {
127            return Err(NetError::Crypto("link: the key does not match the user".into()));
128        }
129        let key = kp.public();
130        if !card.nodes.iter().any(|n| n.peer_id == me && n.active() && self.verify_cert(&key, n)) {
131            return Err(NetError::Crypto("link: no certificate for this node".into()));
132        }
133        if !card.nodes.iter().any(|n| n.peer_id == from_peer && n.active() && self.verify_cert(&key, n)) {
134            return Err(NetError::Crypto("link: the approving node is not the user's".into()));
135        }
136        Ok(kp)
137    }
138}