1use crate::error::{NetError, Result};
9use crate::profile::Profile;
10use libp2p::identity::{Keypair, PublicKey};
11use serde::{Deserialize, Serialize};
12use sha2::Digest;
13
14#[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 pub fn active(&self) -> bool {
30 self.revoked_at.is_none()
31 }
32}
33
34#[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 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
59pub fn user_id(key: &PublicKey) -> String {
61 hex::encode(&sha2::Sha256::digest(key.encode_protobuf())[..16])
62}
63
64pub fn decode_keypair(bytes: &[u8]) -> Result<Keypair> {
66 Keypair::from_protobuf_encoding(bytes).map_err(|e| NetError::Crypto(format!("user identity: {e}")))
67}
68
69pub 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 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 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 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 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 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}