1use 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#[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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
41pub struct IdentityBinding {
42 pub schema: String,
43 pub binding_id: String,
45 pub actor_id: String,
47 pub actor_class: ActorClass,
48 pub public_key_hex: String,
51 pub created_at: String,
52 pub signature: String,
53}
54
55pub struct IdentityBindingDraft {
57 pub actor_id: String,
58 pub actor_class: ActorClass,
59 pub created_at: String,
60}
61
62impl IdentityBinding {
63 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 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 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
145pub struct IdentityRevocation {
146 pub schema: String,
147 pub revocation_id: String,
148 pub binding_id: String,
150 pub public_key_hex: String,
152 pub reason: String,
153 pub revoked_at: String,
154 pub signature: String,
155}
156
157pub 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 #[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 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 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}