1use ed25519_dalek::{Signer, SigningKey, Verifier, VerifyingKey};
14use shamir_algorithm::ShamirSS;
15use std::collections::BTreeMap;
16use zeroize::Zeroize;
17use zeroize::Zeroizing;
18
19#[derive(Debug, Clone, PartialEq)]
21pub struct Share {
22 pub index: u8,
23 pub m: u8,
25 pub data: Vec<u8>,
26}
27
28#[derive(Debug, Clone)]
30pub struct ThresholdConfig {
31 pub m: u8,
32 pub n: u8,
33 pub guardian_dids: Vec<String>,
34}
35
36impl ThresholdConfig {
37 pub fn validate(&self) -> Result<(), String> {
38 if self.m == 0 {
39 return Err("threshold M cannot be zero".to_string());
40 }
41 if self.n == 0 {
42 return Err("share count N cannot be zero".to_string());
43 }
44 if self.m > self.n {
45 return Err(format!(
46 "threshold M ({}) cannot exceed share count N ({})",
47 self.m, self.n
48 ));
49 }
50 if self.guardian_dids.len() != self.n as usize {
51 return Err(format!(
52 "expected {} guardian DIDs, got {}",
53 self.n,
54 self.guardian_dids.len()
55 ));
56 }
57 Ok(())
58 }
59}
60
61pub fn split_key(secret: &[u8], m: u8, n: u8) -> Result<Vec<Share>, String> {
64 if m == 0 {
65 return Err("threshold M cannot be zero".to_string());
66 }
67 if n == 0 || m > n {
68 return Err("invalid M-of-N configuration".to_string());
69 }
70 if secret.len() != 32 {
71 return Err(format!(
72 "Ed25519 seed must be 32 bytes, got {}",
73 secret.len()
74 ));
75 }
76
77 let shares = ShamirSS::split(n as i32, m as i32, secret.to_vec())
78 .map_err(|e| format!("shamir split failed: {}", e))?;
79
80 Ok(shares
81 .into_iter()
82 .map(|(index, data)| Share {
83 index: index as u8,
84 m,
85 data,
86 })
87 .collect())
88}
89
90pub fn reconstruct_secret(shares: &[Share]) -> Result<Vec<u8>, String> {
92 if shares.len() < 2 {
93 return Err("need at least 2 shares to reconstruct".to_string());
94 }
95 let mut parts: BTreeMap<i32, Vec<u8>> = BTreeMap::new();
96 for share in shares {
97 parts.insert(share.index as i32, share.data.clone());
98 }
99 ShamirSS::join(parts).map_err(|e| format!("shamir join failed: {}", e))
100}
101
102pub fn threshold_sign(shares: &[Share], message: &[u8]) -> Result<ed25519_dalek::Signature, String> {
105 if shares.is_empty() {
106 return Err("no shares provided".to_string());
107 }
108 let m = shares[0].m;
109 if (shares.len() as u8) < m {
110 return Err(format!(
111 "insufficient shares: need {}, got {}",
112 m,
113 shares.len()
114 ));
115 }
116 let secret = reconstruct_secret(shares)?;
117 let seed: [u8; 32] = secret
118 .try_into()
119 .map_err(|_| "reconstructed secret is not 32 bytes".to_string())?;
120 let signing_key = SigningKey::from_bytes(&seed);
121 Ok(signing_key.sign(message))
122}
123
124pub fn threshold_verify(
126 public_key: &VerifyingKey,
127 signature: &ed25519_dalek::Signature,
128 message: &[u8],
129) -> bool {
130 public_key.verify(message, signature).is_ok()
131}
132
133pub fn generate_threshold_keypair(
135 m: u8,
136 n: u8,
137) -> Result<(VerifyingKey, Vec<Share>), String> {
138 use rand::rngs::OsRng;
139 let signing_key = SigningKey::generate(&mut OsRng);
140 let verifying_key = signing_key.verifying_key();
141 let shares = split_key(signing_key.as_bytes(), m, n)?;
142 Ok((verifying_key, shares))
143}
144
145pub struct EphemeralCA {
153 pub did: String,
154 seed: Zeroizing<[u8; 32]>,
155 pub verifying_key: VerifyingKey,
156 pub capabilities: Vec<String>,
157 pub delegation_vcard: Option<String>,
158 shredded: bool,
159}
160
161impl EphemeralCA {
162 pub fn new(capabilities: Vec<String>) -> Self {
164 use rand::rngs::OsRng;
165 let signing_key = SigningKey::generate(&mut OsRng);
166 let verifying_key = signing_key.verifying_key();
167 let did = format!(
168 "did:key:{}",
169 base64_url_encode(&verifying_key.to_bytes())
170 );
171 EphemeralCA {
172 did,
173 seed: Zeroizing::new(signing_key.to_bytes()),
174 verifying_key,
175 capabilities,
176 delegation_vcard: None,
177 shredded: false,
178 }
179 }
180
181 fn signing_key(&self) -> Result<SigningKey, String> {
183 if self.shredded {
184 return Err("EphemeralCA has been shredded".to_string());
185 }
186 Ok(SigningKey::from_bytes(&self.seed))
187 }
188
189 pub fn issue_delegation(&mut self) -> Result<String, String> {
191 if self.shredded {
192 return Err("EphemeralCA has been shredded".to_string());
193 }
194 let signing_key = self.signing_key()?;
195 let timestamp = chrono::Utc::now().to_rfc3339();
196 let vcard_without_sig = format!(
197 "vcard_token:\n agent_did: {}\n capabilities: {:?}\n timestamp: {}\n verifying_key: {}",
198 self.did,
199 self.capabilities,
200 timestamp,
201 hex::encode(self.verifying_key.to_bytes())
202 );
203 let signature = signing_key.sign(vcard_without_sig.as_bytes());
204 let vcard = format!(
205 "{}\n signature: {}",
206 vcard_without_sig,
207 hex::encode(signature.to_bytes())
208 );
209 self.delegation_vcard = Some(vcard.clone());
210 Ok(vcard)
211 }
212
213 pub fn sign(&self, message: &[u8]) -> Result<ed25519_dalek::Signature, String> {
215 let signing_key = self.signing_key()?;
216 Ok(signing_key.sign(message))
217 }
218
219 pub fn verify(
221 &self,
222 signature: &ed25519_dalek::Signature,
223 message: &[u8],
224 ) -> bool {
225 self.verifying_key.verify(message, signature).is_ok()
226 }
227
228 pub fn shred(&mut self) {
230 if self.shredded {
231 return;
232 }
233 self.seed.zeroize();
234 self.capabilities.clear();
235 self.delegation_vcard = None;
236 self.shredded = true;
237 }
238
239 pub fn is_shredded(&self) -> bool {
241 self.shredded
242 }
243}
244
245impl Drop for EphemeralCA {
246 fn drop(&mut self) {
247 self.shred();
248 }
249}
250
251pub fn verify_delegation(
253 vcard_yaml: &str,
254 ca_verifying_key: &VerifyingKey,
255) -> bool {
256 let mut payload_lines = Vec::new();
258 let mut signature_hex = String::new();
259 for line in vcard_yaml.lines() {
260 let trimmed = line.trim();
261 if let Some(rest) = trimmed.strip_prefix("signature:") {
262 signature_hex = rest.trim().to_string();
263 } else {
264 payload_lines.push(line);
265 }
266 }
267 if signature_hex.is_empty() {
268 return false;
269 }
270 let sig_bytes = match hex::decode(&signature_hex) {
271 Ok(b) => b,
272 Err(_) => return false,
273 };
274 let sig = match ed25519_dalek::Signature::from_slice(&sig_bytes) {
275 Ok(s) => s,
276 Err(_) => return false,
277 };
278 let payload = payload_lines.join("\n");
279 ca_verifying_key.verify(payload.as_bytes(), &sig).is_ok()
280}
281
282fn base64_url_encode(bytes: &[u8]) -> String {
283 const ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
285 let mut result = String::new();
286 let mut i = 0;
287 while i + 3 <= bytes.len() {
288 let n = ((bytes[i] as u32) << 16) | ((bytes[i + 1] as u32) << 8) | (bytes[i + 2] as u32);
289 result.push(ALPHABET[((n >> 18) & 63) as usize] as char);
290 result.push(ALPHABET[((n >> 12) & 63) as usize] as char);
291 result.push(ALPHABET[((n >> 6) & 63) as usize] as char);
292 result.push(ALPHABET[(n & 63) as usize] as char);
293 i += 3;
294 }
295 let rem = bytes.len() - i;
296 if rem == 1 {
297 let n = (bytes[i] as u32) << 16;
298 result.push(ALPHABET[((n >> 18) & 63) as usize] as char);
299 result.push(ALPHABET[((n >> 12) & 63) as usize] as char);
300 } else if rem == 2 {
301 let n = ((bytes[i] as u32) << 16) | ((bytes[i + 1] as u32) << 8);
302 result.push(ALPHABET[((n >> 18) & 63) as usize] as char);
303 result.push(ALPHABET[((n >> 12) & 63) as usize] as char);
304 result.push(ALPHABET[((n >> 6) & 63) as usize] as char);
305 }
306 result
307}
308
309#[cfg(test)]
310mod tests {
311 use super::*;
312
313 #[test]
314 fn test_3_of_5_threshold_signing_and_verification() {
315 let (vk, shares) = generate_threshold_keypair(3, 5).unwrap();
316 let message = b"threshold test message";
317 let sig = threshold_sign(&shares[..3], message).unwrap();
318 assert!(threshold_verify(&vk, &sig, message));
319 }
320
321 #[test]
322 fn test_below_threshold_fails() {
323 let (_vk, shares) = generate_threshold_keypair(3, 5).unwrap();
324 let message = b"threshold test message";
325 assert!(threshold_sign(&shares[..2], message).is_err());
326 }
327
328 #[test]
329 fn test_corrupted_share_produces_invalid_signature() {
330 let (vk, mut shares) = generate_threshold_keypair(3, 5).unwrap();
331 shares[0].data[0] ^= 0xFF;
332 let message = b"threshold test message";
333 let sig = threshold_sign(&shares[..3], message).unwrap();
334 assert!(!threshold_verify(&vk, &sig, message));
335 }
336
337 #[test]
338 fn test_threshold_config_validation() {
339 assert!(ThresholdConfig {
340 m: 3,
341 n: 5,
342 guardian_dids: vec!["a".to_string(), "b".to_string(), "c".to_string(), "d".to_string(), "e".to_string()],
343 }
344 .validate()
345 .is_ok());
346 assert!(ThresholdConfig {
347 m: 0,
348 n: 5,
349 guardian_dids: vec!["a".to_string(); 5],
350 }
351 .validate()
352 .is_err());
353 assert!(ThresholdConfig {
354 m: 6,
355 n: 5,
356 guardian_dids: vec!["a".to_string(); 5],
357 }
358 .validate()
359 .is_err());
360 }
361
362 #[test]
363 fn test_ephemeral_ca_sign_and_verify() {
364 let ca = EphemeralCA::new(vec!["execute".to_string()]);
365 let message = b"test message from CA";
366 let sig = ca.sign(message).unwrap();
367 assert!(ca.verify(&sig, message));
368 assert!(!ca.is_shredded());
369 }
370
371 #[test]
372 fn test_ephemeral_ca_delegation() {
373 let mut ca = EphemeralCA::new(vec!["execute".to_string(), "delegate".to_string()]);
374 let vcard = ca.issue_delegation().unwrap();
375 assert!(vcard.contains("vcard_token:"));
376 assert!(vcard.contains(&ca.did));
377 assert!(vcard.contains("signature:"));
378 assert!(verify_delegation(&vcard, &ca.verifying_key));
379 }
380
381 #[test]
382 fn test_ephemeral_ca_shred_blocks_signing() {
383 let mut ca = EphemeralCA::new(vec!["execute".to_string()]);
384 ca.shred();
385 assert!(ca.is_shredded());
386 assert!(ca.sign(b"msg").is_err());
387 assert!(ca.issue_delegation().is_err());
388 }
389
390 #[test]
391 fn test_ephemeral_ca_drop_calls_shred() {
392 let mut ca = EphemeralCA::new(vec!["execute".to_string()]);
393 let did = ca.did.clone();
394 {
395 let _ca2 = EphemeralCA::new(vec!["temp".to_string()]);
396 }
398 assert!(!ca.is_shredded());
400 ca.shred();
401 assert!(ca.is_shredded());
402 assert!(!did.is_empty());
404 }
405
406 #[test]
407 fn test_ephemeral_ca_did_format() {
408 let ca = EphemeralCA::new(vec!["execute".to_string()]);
409 assert!(ca.did.starts_with("did:key:"));
410 assert!(ca.did.len() > "did:key:".len() + 10);
411 }
412
413 #[test]
414 fn test_verify_delegation_rejects_tampered() {
415 let mut ca = EphemeralCA::new(vec!["execute".to_string()]);
416 let mut vcard = ca.issue_delegation().unwrap();
417 vcard = vcard.replace(&ca.did, "did:key:fake");
419 assert!(!verify_delegation(&vcard, &ca.verifying_key));
420 }
421}