1use 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#[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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
46pub struct IdentityBinding {
47 pub schema: String,
48 pub binding_id: String,
50 pub actor_id: String,
52 pub actor_class: ActorClass,
53 pub public_key_hex: String,
56 pub created_at: String,
57 pub signature: String,
58}
59
60pub struct IdentityBindingDraft {
62 pub actor_id: String,
63 pub actor_class: ActorClass,
64 pub created_at: String,
65}
66
67impl IdentityBinding {
68 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 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 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
150pub struct IdentityRevocation {
151 pub schema: String,
152 pub revocation_id: String,
153 pub binding_id: String,
155 pub public_key_hex: String,
157 pub reason: String,
158 pub revoked_at: String,
159 pub signature: String,
160}
161
162pub 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 #[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 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 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}