Skip to main content

vela_protocol/objects/
identity.rs

1//! Producer identity binding (`vib_`): a self-signed proof that a key controls
2//! an actor id, plus authoritative revocation.
3//!
4//! ## What this adds over `ActorRecord`
5//!
6//! `sign::ActorRecord` is a *registry entry*: it maps `actor.id -> public_key`,
7//! but the binding is asserted by whoever writes the registry, not proven by the
8//! key-holder. An [`IdentityBinding`] closes that gap. It is signed **by the very
9//! key it binds**, so the signature is a proof of possession: only the holder of
10//! `public_key_hex` could have produced it. It also records `actor_class`
11//! (human / agent / org), which the substrate previously only inferred from the
12//! id prefix.
13//!
14//! ## Revocation is authoritative because it is self-signed
15//!
16//! An [`IdentityRevocation`] (`vir_`) is signed by the same key it revokes. A
17//! holder who loses trust in their own key, or who is done with an id, signs a
18//! revocation; the reducer then derives the binding as inactive on read. No
19//! third party can revoke your binding, and you cannot deny revoking your own.
20//!
21//! ## The honest limit
22//!
23//! This proves key possession and binds a class. It does NOT prove the actor is
24//! a distinct human (one person can self-sign a hundred bindings), so it is the
25//! foundation for, not the solution to, the sybil-resistance named open in
26//! `docs/SIGNIFICANCE_SLOT.md`. Distinct-personhood is a layer above this one.
27
28use ed25519_dalek::SigningKey;
29use serde::{Deserialize, Serialize};
30use sha2::{Digest, Sha256};
31
32pub const IDENTITY_BINDING_SCHEMA: &str = "vela.identity_binding.v0.1";
33pub const IDENTITY_REVOCATION_SCHEMA: &str = "vela.identity_revocation.v0.1";
34
35/// What kind of actor controls the id. Inferred-by-prefix before; bound here.
36#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
37#[serde(rename_all = "snake_case")]
38pub enum ActorClass {
39    Human,
40    Agent,
41    Org,
42}
43
44/// A self-signed proof that `public_key_hex` controls `actor_id`.
45#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
46pub struct IdentityBinding {
47    pub schema: String,
48    /// `vib_<16hex>`, content-addressed over the body with id/signature zeroed.
49    pub binding_id: String,
50    /// Stable namespaced id, e.g. "reviewer:human-reviewer".
51    pub actor_id: String,
52    pub actor_class: ActorClass,
53    /// The Ed25519 public key being bound. MUST equal the signer (proof of
54    /// possession): the binding is signed by the key it binds.
55    pub public_key_hex: String,
56    pub created_at: String,
57    pub signature: String,
58}
59
60/// Draft for [`IdentityBinding::build`].
61pub struct IdentityBindingDraft {
62    pub actor_id: String,
63    pub actor_class: ActorClass,
64    pub created_at: String,
65}
66
67impl IdentityBinding {
68    /// Self-sign a binding: the key proves it controls `actor_id`.
69    pub fn build(draft: IdentityBindingDraft, key: &SigningKey) -> Result<Self, String> {
70        if draft.actor_id.trim().is_empty() {
71            return Err("identity_binding.actor_id cannot be empty".to_string());
72        }
73        let mut b = IdentityBinding {
74            schema: IDENTITY_BINDING_SCHEMA.to_string(),
75            binding_id: String::new(),
76            actor_id: draft.actor_id,
77            actor_class: draft.actor_class,
78            public_key_hex: hex::encode(key.verifying_key().to_bytes()),
79            created_at: draft.created_at,
80            signature: String::new(),
81        };
82        let preimage = b.id_preimage_bytes()?;
83        b.signature = hex::encode(crate::sign::sign_bytes(key, &preimage));
84        b.binding_id = b.derive_id()?;
85        Ok(b)
86    }
87
88    fn id_preimage_bytes(&self) -> Result<Vec<u8>, String> {
89        let mut p = self.clone();
90        p.binding_id = String::new();
91        p.signature = String::new();
92        crate::canonical::to_canonical_bytes(&p)
93            .map_err(|e| format!("canonicalize identity_binding preimage: {e}"))
94    }
95
96    pub fn derive_id(&self) -> Result<String, String> {
97        let bytes = self.id_preimage_bytes()?;
98        Ok(format!(
99            "vib_{}",
100            &hex::encode(Sha256::digest(&bytes))[..16]
101        ))
102    }
103
104    /// Full typed credential identity over the same canonical preimage used by
105    /// the readable `vib_` handle. The short handle is routing only; authority
106    /// comparisons use this complete root.
107    pub fn credential_root(&self) -> Result<String, String> {
108        let bytes = self.id_preimage_bytes()?;
109        Ok(format!("sha256:{}", hex::encode(Sha256::digest(&bytes))))
110    }
111
112    /// Verify: id re-derives, and the signature is valid under
113    /// `public_key_hex` — i.e. the key being bound actually signed this. That
114    /// equality (signer == bound key) is the proof of possession.
115    pub fn verify(&self) -> Result<(), String> {
116        if self.schema != IDENTITY_BINDING_SCHEMA {
117            return Err(format!(
118                "identity_binding.schema must be `{IDENTITY_BINDING_SCHEMA}`"
119            ));
120        }
121        if !self.binding_id.starts_with("vib_") {
122            return Err(format!(
123                "binding id must start with `vib_`, got `{}`",
124                self.binding_id
125            ));
126        }
127        let preimage = self.id_preimage_bytes()?;
128        if !crate::sign::verify_action_signature(&preimage, &self.signature, &self.public_key_hex)?
129        {
130            return Err(
131                "identity_binding signature does not verify under the bound key \
132                        (no proof of possession)"
133                    .to_string(),
134            );
135        }
136        let rederived = self.derive_id()?;
137        if rederived != self.binding_id {
138            return Err(format!(
139                "binding_id mismatch: declared {}, rebuilt {}",
140                self.binding_id, rederived
141            ));
142        }
143        Ok(())
144    }
145}
146
147/// A self-signed revocation of an [`IdentityBinding`]. Signed by the same key it
148/// revokes, so revocation is authoritative and non-repudiable.
149#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
150pub struct IdentityRevocation {
151    pub schema: String,
152    pub revocation_id: String,
153    /// The `vib_` being revoked.
154    pub binding_id: String,
155    /// The key that signs (must equal the revoked binding's `public_key_hex`).
156    pub public_key_hex: String,
157    pub reason: String,
158    pub revoked_at: String,
159    pub signature: String,
160}
161
162/// Draft for [`IdentityRevocation::build`].
163pub struct IdentityRevocationDraft {
164    pub binding_id: String,
165    pub reason: String,
166    pub revoked_at: String,
167}
168
169impl IdentityRevocation {
170    pub fn build(draft: IdentityRevocationDraft, key: &SigningKey) -> Result<Self, String> {
171        if !draft.binding_id.starts_with("vib_") {
172            return Err("identity_revocation.binding_id must be a `vib_` id".to_string());
173        }
174        let mut r = IdentityRevocation {
175            schema: IDENTITY_REVOCATION_SCHEMA.to_string(),
176            revocation_id: String::new(),
177            binding_id: draft.binding_id,
178            public_key_hex: hex::encode(key.verifying_key().to_bytes()),
179            reason: draft.reason,
180            revoked_at: draft.revoked_at,
181            signature: String::new(),
182        };
183        let preimage = r.id_preimage_bytes()?;
184        r.signature = hex::encode(crate::sign::sign_bytes(key, &preimage));
185        r.revocation_id = format!("vir_{}", &hex::encode(Sha256::digest(&preimage))[..16]);
186        Ok(r)
187    }
188
189    fn id_preimage_bytes(&self) -> Result<Vec<u8>, String> {
190        let mut p = self.clone();
191        p.revocation_id = String::new();
192        p.signature = String::new();
193        crate::canonical::to_canonical_bytes(&p)
194            .map_err(|e| format!("canonicalize identity_revocation preimage: {e}"))
195    }
196
197    pub fn verify(&self) -> Result<(), String> {
198        let preimage = self.id_preimage_bytes()?;
199        if !crate::sign::verify_action_signature(&preimage, &self.signature, &self.public_key_hex)?
200        {
201            return Err(
202                "identity_revocation signature does not verify under the declared key".to_string(),
203            );
204        }
205        Ok(())
206    }
207
208    /// Authoritative check: this revocation legitimately revokes `binding` iff it
209    /// is signed by the SAME key the binding bound. A revocation signed by any
210    /// other key is not authoritative and is ignored.
211    #[must_use]
212    pub fn authoritatively_revokes(&self, binding: &IdentityBinding) -> bool {
213        self.binding_id == binding.binding_id
214            && self.public_key_hex == binding.public_key_hex
215            && self.verify().is_ok()
216    }
217}
218
219#[cfg(test)]
220mod tests {
221    use super::*;
222    use rand::rngs::OsRng;
223
224    fn key() -> SigningKey {
225        SigningKey::generate(&mut OsRng)
226    }
227
228    fn draft() -> IdentityBindingDraft {
229        IdentityBindingDraft {
230            actor_id: "reviewer:will-blair".into(),
231            actor_class: ActorClass::Human,
232            created_at: "2026-06-09T00:00:00Z".into(),
233        }
234    }
235
236    #[test]
237    fn self_signed_binding_verifies() {
238        let b = IdentityBinding::build(draft(), &key()).unwrap();
239        assert!(b.binding_id.starts_with("vib_"));
240        let full = b.credential_root().unwrap();
241        assert!(full.starts_with("sha256:"));
242        assert_eq!(
243            &full["sha256:".len()..][..16],
244            &b.binding_id["vib_".len()..]
245        );
246        b.verify().unwrap();
247    }
248
249    #[test]
250    fn binding_signed_by_other_key_fails_possession() {
251        let mut b = IdentityBinding::build(draft(), &key()).unwrap();
252        // Swap in a different key's pubkey: the signature no longer matches the
253        // bound key, so proof-of-possession fails.
254        b.public_key_hex = hex::encode(key().verifying_key().to_bytes());
255        assert!(b.verify().is_err());
256    }
257
258    #[test]
259    fn self_revocation_is_authoritative_and_foreign_is_not() {
260        let k = key();
261        let b = IdentityBinding::build(draft(), &k).unwrap();
262        let rev = IdentityRevocation::build(
263            IdentityRevocationDraft {
264                binding_id: b.binding_id.clone(),
265                reason: "key rotated".into(),
266                revoked_at: "2026-06-10T00:00:00Z".into(),
267            },
268            &k,
269        )
270        .unwrap();
271        assert!(rev.authoritatively_revokes(&b), "same key must revoke");
272
273        // A revocation by a different key targeting the same binding is NOT authoritative.
274        let foreign = IdentityRevocation::build(
275            IdentityRevocationDraft {
276                binding_id: b.binding_id.clone(),
277                reason: "malicious".into(),
278                revoked_at: "2026-06-10T00:00:00Z".into(),
279            },
280            &key(),
281        )
282        .unwrap();
283        assert!(
284            !foreign.authoritatively_revokes(&b),
285            "foreign key cannot revoke"
286        );
287    }
288}