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