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