Skip to main content

qualia_core_db/identity/credentials/
mod.rs

1//! W3C Verifiable Credentials — issue / hold / present / verify, signed with real
2//! ML-DSA-65 (FIPS-204) via [`crate::crypto::fiduciary_crypto`].
3//!
4//! Consolidated from two stranded worktree branches (`0.0.19-g2-vc` = the runtime,
5//! `0.0.19-g3-cbor-ld` = the [`codecs`]) into one module with a **single** `Credential`
6//! type — the duplicate `Credential` each branch had defined is unified here.
7//!
8//! Verification is **fail-closed**: a missing proof, a tampered credential, or a failed
9//! signature check all return an error, never a silent `false`/`true`.
10
11use std::collections::HashMap;
12
13use serde::{Deserialize, Serialize};
14
15use crate::crypto::fiduciary_crypto::{FiduciaryCrypto, MlDsaSignature};
16
17pub mod codecs;
18
19/// Error types for Verifiable Credentials.
20#[derive(Debug, Clone, PartialEq)]
21pub enum VcError {
22    CryptoError(String),
23    SerializationError(String),
24    MissingProof,
25    VerificationFailed,
26    NotImplemented,
27}
28
29/// W3C Verifiable Credential Data Model.
30#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
31pub struct Credential {
32    #[serde(rename = "@context")]
33    pub context: Vec<String>,
34    pub id: String,
35    #[serde(rename = "type")]
36    pub types: Vec<String>,
37    pub issuer: String,
38    #[serde(rename = "issuanceDate")]
39    pub issuance_date: String,
40    #[serde(rename = "credentialSubject")]
41    pub credential_subject: HashMap<String, String>,
42    #[serde(skip_serializing_if = "Option::is_none")]
43    pub proof: Option<Proof>,
44}
45
46/// W3C Verifiable Presentation Data Model.
47#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
48pub struct Presentation {
49    #[serde(rename = "@context")]
50    pub context: Vec<String>,
51    #[serde(rename = "type")]
52    pub types: Vec<String>,
53    #[serde(rename = "verifiableCredential")]
54    pub verifiable_credential: Vec<Credential>,
55    #[serde(skip_serializing_if = "Option::is_none")]
56    pub proof: Option<Proof>,
57}
58
59/// Proof object (Data Integrity Proof) carrying the ML-DSA signature.
60#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
61pub struct Proof {
62    #[serde(rename = "type")]
63    pub proof_type: String,
64    pub created: String,
65    #[serde(rename = "verificationMethod")]
66    pub verification_method: String,
67    #[serde(rename = "proofPurpose")]
68    pub proof_purpose: String,
69    #[serde(rename = "proofValue")]
70    pub proof_value: MlDsaSignature,
71}
72
73/// Selective-disclosure interface (BBS-style); not yet implemented.
74pub trait SelectiveDisclosure {
75    /// Generates a selective presentation.
76    fn generate_selective_presentation(
77        &self,
78        credential: &Credential,
79        disclosed_fields: &[String],
80    ) -> Result<Presentation, VcError>;
81    /// Verifies a selective presentation.
82    fn verify_selective_presentation(&self, presentation: &Presentation) -> Result<bool, VcError>;
83}
84
85/// Zero-knowledge predicate-disclosure interface; not yet implemented.
86pub trait ZkDisclosure {
87    /// Generates a ZK proof.
88    fn generate_zk_proof(
89        &self,
90        credential: &Credential,
91        predicates: &[String],
92    ) -> Result<Presentation, VcError>;
93    /// Verifies a ZK proof.
94    fn verify_zk_proof(&self, presentation: &Presentation) -> Result<bool, VcError>;
95}
96
97/// Credential status (revocation/suspension) interface.
98pub trait CredentialStatus {
99    /// Checks credential status.
100    fn check_status(&self, credential_id: &str) -> Result<StatusResult, VcError>;
101}
102
103#[derive(Debug, Clone, PartialEq)]
104pub enum StatusResult {
105    Valid,
106    Revoked,
107    Suspended,
108}
109
110/// Issues, holds, presents, and verifies Verifiable Credentials with ML-DSA-65 proofs.
111pub struct VcRuntime {
112    crypto: FiduciaryCrypto,
113    revocation_registry: std::sync::RwLock<HashMap<String, StatusResult>>,
114}
115
116impl VcRuntime {
117    /// Creates a default `VcRuntime`.
118    pub fn new(crypto: FiduciaryCrypto) -> Self {
119        Self {
120            crypto,
121            revocation_registry: std::sync::RwLock::new(HashMap::new()),
122        }
123    }
124
125    /// Revoke a credential by ID in the status registry.
126    pub fn revoke_credential(&self, credential_id: &str) {
127        if let Ok(mut reg) = self.revocation_registry.write() {
128            reg.insert(credential_id.to_string(), StatusResult::Revoked);
129        }
130    }
131
132    /// Suspend a credential by ID in the status registry.
133    pub fn suspend_credential(&self, credential_id: &str) {
134        if let Ok(mut reg) = self.revocation_registry.write() {
135            reg.insert(credential_id.to_string(), StatusResult::Suspended);
136        }
137    }
138
139    /// Issue a Verifiable Credential: sign the proof-less credential and attach the proof.
140    pub fn issue(
141        &self,
142        mut credential: Credential,
143        key_id: Option<&str>,
144    ) -> Result<Credential, VcError> {
145        credential.proof = None;
146
147        let serialized = serde_json::to_vec(&credential)
148            .map_err(|e| VcError::SerializationError(e.to_string()))?;
149
150        let signature = self
151            .crypto
152            .sign(
153                &serialized,
154                key_id,
155                "vc-dm".to_string(),
156                "assertionMethod".to_string(),
157            )
158            .map_err(|e| VcError::CryptoError(format!("{:?}", e)))?;
159
160        credential.proof = Some(Proof {
161            proof_type: "MlDsaSignature2024".to_string(),
162            created: "2026-06-24T00:00:00Z".to_string(),
163            verification_method: key_id.unwrap_or("default").to_string(),
164            proof_purpose: "assertionMethod".to_string(),
165            proof_value: signature,
166        });
167        Ok(credential)
168    }
169
170    /// Hold a credential (secure storage is the caller's responsibility for now).
171    pub fn hold(&self, _credential: &Credential) -> Result<(), VcError> {
172        Ok(())
173    }
174
175    /// Present one or more credentials inside a signed Verifiable Presentation.
176    pub fn present(
177        &self,
178        credentials: Vec<Credential>,
179        key_id: Option<&str>,
180    ) -> Result<Presentation, VcError> {
181        let mut presentation = Presentation {
182            context: vec!["https://www.w3.org/2018/credentials/v1".to_string()],
183            types: vec!["VerifiablePresentation".to_string()],
184            verifiable_credential: credentials,
185            proof: None,
186        };
187
188        let serialized = serde_json::to_vec(&presentation)
189            .map_err(|e| VcError::SerializationError(e.to_string()))?;
190
191        let signature = self
192            .crypto
193            .sign(
194                &serialized,
195                key_id,
196                "vc-dm".to_string(),
197                "authentication".to_string(),
198            )
199            .map_err(|e| VcError::CryptoError(format!("{:?}", e)))?;
200
201        presentation.proof = Some(Proof {
202            proof_type: "MlDsaSignature2024".to_string(),
203            created: "2026-06-24T00:00:00Z".to_string(),
204            verification_method: key_id.unwrap_or("default").to_string(),
205            proof_purpose: "authentication".to_string(),
206            proof_value: signature,
207        });
208        Ok(presentation)
209    }
210
211    /// Verify a credential's proof. **Fail-closed**: missing proof or a failed check errors.
212    pub fn verify_credential(&self, credential: &Credential) -> Result<bool, VcError> {
213        let proof = credential.proof.as_ref().ok_or(VcError::MissingProof)?;
214
215        let mut bare = credential.clone();
216        bare.proof = None;
217        let serialized =
218            serde_json::to_vec(&bare).map_err(|e| VcError::SerializationError(e.to_string()))?;
219
220        let ok = self
221            .crypto
222            .verify(
223                &serialized,
224                &proof.proof_value,
225                Some(&proof.verification_method),
226                "vc-dm".to_string(),
227                proof.proof_purpose.clone(),
228            )
229            .map_err(|e| VcError::CryptoError(format!("{:?}", e)))?;
230
231        if !ok {
232            return Err(VcError::VerificationFailed);
233        }
234        Ok(true)
235    }
236
237    /// Verify a presentation's proof and every credential it carries (all fail-closed).
238    pub fn verify_presentation(&self, presentation: &Presentation) -> Result<bool, VcError> {
239        let proof = presentation.proof.as_ref().ok_or(VcError::MissingProof)?;
240
241        let mut bare = presentation.clone();
242        bare.proof = None;
243        let serialized =
244            serde_json::to_vec(&bare).map_err(|e| VcError::SerializationError(e.to_string()))?;
245
246        let ok = self
247            .crypto
248            .verify(
249                &serialized,
250                &proof.proof_value,
251                Some(&proof.verification_method),
252                "vc-dm".to_string(),
253                proof.proof_purpose.clone(),
254            )
255            .map_err(|e| VcError::CryptoError(format!("{:?}", e)))?;
256
257        if !ok {
258            return Err(VcError::VerificationFailed);
259        }
260
261        for cred in &presentation.verifiable_credential {
262            if !self.verify_credential(cred)? {
263                return Err(VcError::VerificationFailed);
264            }
265        }
266        Ok(true)
267    }
268}
269
270impl CredentialStatus for VcRuntime {
271    /// Checks credential status.
272    fn check_status(&self, credential_id: &str) -> Result<StatusResult, VcError> {
273        let reg = self
274            .revocation_registry
275            .read()
276            .map_err(|e| VcError::CryptoError(format!("Lock error: {:?}", e)))?;
277        Ok(reg.get(credential_id).cloned().unwrap_or(StatusResult::Valid))
278    }
279}
280
281impl SelectiveDisclosure for VcRuntime {
282    /// Generates a selective presentation.
283    fn generate_selective_presentation(
284        &self,
285        credential: &Credential,
286        disclosed_fields: &[String],
287    ) -> Result<Presentation, VcError> {
288        self.verify_credential(credential)?;
289
290        for field in disclosed_fields {
291            if !credential.credential_subject.contains_key(field) {
292                return Err(VcError::VerificationFailed);
293            }
294        }
295
296        let mut filtered_subject = HashMap::new();
297        if let Some(id) = credential.credential_subject.get("id") {
298            filtered_subject.insert("id".to_string(), id.clone());
299        }
300        for field in disclosed_fields {
301            if let Some(val) = credential.credential_subject.get(field) {
302                filtered_subject.insert(field.clone(), val.clone());
303            }
304        }
305
306        use sha2::{Digest, Sha256};
307        let mut hidden_hasher = Sha256::new();
308        for (k, v) in &credential.credential_subject {
309            if !disclosed_fields.contains(k) && k != "id" {
310                hidden_hasher.update(k.as_bytes());
311                hidden_hasher.update(b":");
312                hidden_hasher.update(v.as_bytes());
313                hidden_hasher.update(b";");
314            }
315        }
316        let hidden_hash = hex::encode(hidden_hasher.finalize());
317        filtered_subject.insert("_hiddenFieldsDigest".to_string(), hidden_hash);
318
319        let derived_cred = Credential {
320            context: credential.context.clone(),
321            id: format!("{}-selective", credential.id),
322            types: {
323                let mut t = credential.types.clone();
324                if !t.contains(&"SelectiveDisclosureCredential".to_string()) {
325                    t.push("SelectiveDisclosureCredential".to_string());
326                }
327                t
328            },
329            issuer: credential.issuer.clone(),
330            issuance_date: credential.issuance_date.clone(),
331            credential_subject: filtered_subject,
332            proof: None,
333        };
334
335        let key_id = credential
336            .proof
337            .as_ref()
338            .map(|p| p.verification_method.as_str());
339        let signed_cred = self.issue(derived_cred, key_id)?;
340        self.present(vec![signed_cred], key_id)
341    }
342
343    /// Verifies a selective presentation.
344    fn verify_selective_presentation(&self, presentation: &Presentation) -> Result<bool, VcError> {
345        self.verify_presentation(presentation)
346    }
347}
348
349impl ZkDisclosure for VcRuntime {
350    /// Generates a ZK proof.
351    fn generate_zk_proof(
352        &self,
353        credential: &Credential,
354        predicates: &[String],
355    ) -> Result<Presentation, VcError> {
356        self.verify_credential(credential)?;
357
358        use sha2::{Digest, Sha256};
359        let mut zk_subject = HashMap::new();
360        if let Some(id) = credential.credential_subject.get("id") {
361            zk_subject.insert("id".to_string(), id.clone());
362        }
363
364        for (idx, pred) in predicates.iter().enumerate() {
365            let satisfied = evaluate_credential_predicate(&credential.credential_subject, pred)?;
366            if !satisfied {
367                return Err(VcError::VerificationFailed);
368            }
369
370            let mut hasher = Sha256::new();
371            hasher.update(credential.id.as_bytes());
372            hasher.update(b"||");
373            hasher.update(pred.as_bytes());
374            hasher.update(b"||satisfied");
375            let commitment = hex::encode(hasher.finalize());
376
377            zk_subject.insert(format!("predicate_{}", idx), pred.clone());
378            zk_subject.insert(format!("predicate_{}_satisfied", idx), "true".to_string());
379            zk_subject.insert(format!("zk_commitment_{}", idx), commitment);
380        }
381
382        let zk_cred = Credential {
383            context: credential.context.clone(),
384            id: format!("{}-zk", credential.id),
385            types: {
386                let mut t = credential.types.clone();
387                if !t.contains(&"ZkPredicateCredential".to_string()) {
388                    t.push("ZkPredicateCredential".to_string());
389                }
390                t
391            },
392            issuer: credential.issuer.clone(),
393            issuance_date: credential.issuance_date.clone(),
394            credential_subject: zk_subject,
395            proof: None,
396        };
397
398        let key_id = credential
399            .proof
400            .as_ref()
401            .map(|p| p.verification_method.as_str());
402        let signed_cred = self.issue(zk_cred, key_id)?;
403        self.present(vec![signed_cred], key_id)
404    }
405
406    /// Verifies a ZK proof.
407    fn verify_zk_proof(&self, presentation: &Presentation) -> Result<bool, VcError> {
408        self.verify_presentation(presentation)?;
409        use sha2::{Digest, Sha256};
410
411        for cred in &presentation.verifiable_credential {
412            let mut idx = 0;
413            while let Some(pred) = cred.credential_subject.get(&format!("predicate_{}", idx)) {
414                let satisfied_str = cred
415                    .credential_subject
416                    .get(&format!("predicate_{}_satisfied", idx))
417                    .ok_or(VcError::VerificationFailed)?;
418                if satisfied_str != "true" {
419                    return Err(VcError::VerificationFailed);
420                }
421
422                let commitment = cred
423                    .credential_subject
424                    .get(&format!("zk_commitment_{}", idx))
425                    .ok_or(VcError::VerificationFailed)?;
426
427                let mut hasher = Sha256::new();
428                let orig_cred_id = cred.id.trim_end_matches("-zk");
429                hasher.update(orig_cred_id.as_bytes());
430                hasher.update(b"||");
431                hasher.update(pred.as_bytes());
432                hasher.update(b"||satisfied");
433                let expected = hex::encode(hasher.finalize());
434
435                if commitment != &expected {
436                    return Err(VcError::VerificationFailed);
437                }
438                idx += 1;
439            }
440        }
441        Ok(true)
442    }
443}
444
445fn evaluate_credential_predicate(
446    subject: &HashMap<String, String>,
447    pred: &str,
448) -> Result<bool, VcError> {
449    let pred = pred.trim();
450    if let Some((k, v)) = pred.split_once(">=") {
451        let (k, v) = (k.trim(), v.trim());
452        let val_str = subject.get(k).ok_or(VcError::VerificationFailed)?;
453        if let (Ok(lhs), Ok(rhs)) = (val_str.parse::<f64>(), v.parse::<f64>()) {
454            return Ok(lhs >= rhs);
455        }
456        return Ok(val_str.as_str() >= v);
457    }
458    if let Some((k, v)) = pred.split_once("<=") {
459        let (k, v) = (k.trim(), v.trim());
460        let val_str = subject.get(k).ok_or(VcError::VerificationFailed)?;
461        if let (Ok(lhs), Ok(rhs)) = (val_str.parse::<f64>(), v.parse::<f64>()) {
462            return Ok(lhs <= rhs);
463        }
464        return Ok(val_str.as_str() <= v);
465    }
466    if let Some((k, v)) = pred.split_once("==") {
467        let (k, v) = (k.trim(), v.trim());
468        let val_str = subject.get(k).ok_or(VcError::VerificationFailed)?;
469        return Ok(val_str == v);
470    }
471    if let Some((k, v)) = pred.split_once("!=") {
472        let (k, v) = (k.trim(), v.trim());
473        let val_str = subject.get(k).ok_or(VcError::VerificationFailed)?;
474        return Ok(val_str != v);
475    }
476    if let Some((k, v)) = pred.split_once('>') {
477        let (k, v) = (k.trim(), v.trim());
478        let val_str = subject.get(k).ok_or(VcError::VerificationFailed)?;
479        if let (Ok(lhs), Ok(rhs)) = (val_str.parse::<f64>(), v.parse::<f64>()) {
480            return Ok(lhs > rhs);
481        }
482        return Ok(val_str.as_str() > v);
483    }
484    if let Some((k, v)) = pred.split_once('<') {
485        let (k, v) = (k.trim(), v.trim());
486        let val_str = subject.get(k).ok_or(VcError::VerificationFailed)?;
487        if let (Ok(lhs), Ok(rhs)) = (val_str.parse::<f64>(), v.parse::<f64>()) {
488            return Ok(lhs < rhs);
489        }
490        return Ok(val_str.as_str() < v);
491    }
492    Ok(subject.contains_key(pred))
493}
494
495#[cfg(test)]
496mod tests {
497    use super::*;
498
499    fn test_credential() -> Credential {
500        let mut subject = HashMap::new();
501        subject.insert(
502            "id".to_string(),
503            "did:example:ebfeb1f712ebc6f1c276e12ec21".to_string(),
504        );
505        subject.insert(
506            "degree".to_string(),
507            "Bachelor of Science and Arts".to_string(),
508        );
509        subject.insert("gpa".to_string(), "3.85".to_string());
510        subject.insert("age".to_string(), "24".to_string());
511        Credential {
512            context: vec!["https://www.w3.org/2018/credentials/v1".to_string()],
513            id: "http://example.edu/credentials/3732".to_string(),
514            types: vec![
515                "VerifiableCredential".to_string(),
516                "UniversityDegreeCredential".to_string(),
517            ],
518            issuer: "https://example.edu/issuers/565049".to_string(),
519            issuance_date: "2010-01-01T19:23:24Z".to_string(),
520            credential_subject: subject,
521            proof: None,
522        }
523    }
524
525    #[test]
526    fn issue_verify_roundtrip() {
527        let mut crypto = FiduciaryCrypto::new();
528        crypto.generate_key("default".to_string()).unwrap();
529        let runtime = VcRuntime::new(crypto);
530
531        let issued = runtime
532            .issue(test_credential(), Some("default"))
533            .expect("issue");
534        assert!(issued.proof.is_some());
535        assert_eq!(runtime.verify_credential(&issued), Ok(true));
536    }
537
538    #[test]
539    fn tampered_credential_fails_closed() {
540        let mut crypto = FiduciaryCrypto::new();
541        crypto.generate_key("default".to_string()).unwrap();
542        let runtime = VcRuntime::new(crypto);
543
544        let mut issued = runtime.issue(test_credential(), Some("default")).unwrap();
545        issued.issuer = "https://hacker.com".to_string();
546        assert!(matches!(
547            runtime.verify_credential(&issued),
548            Err(VcError::VerificationFailed) | Err(VcError::CryptoError(_))
549        ));
550    }
551
552    #[test]
553    fn unsigned_credential_fails_closed() {
554        let runtime = VcRuntime::new(FiduciaryCrypto::new());
555        assert_eq!(
556            runtime.verify_credential(&test_credential()),
557            Err(VcError::MissingProof)
558        );
559    }
560
561    #[test]
562    fn present_verify_roundtrip() {
563        let mut crypto = FiduciaryCrypto::new();
564        crypto.generate_key("default".to_string()).unwrap();
565        let runtime = VcRuntime::new(crypto);
566
567        let issued = runtime.issue(test_credential(), Some("default")).unwrap();
568        let presentation = runtime.present(vec![issued], Some("default")).unwrap();
569        assert_eq!(runtime.verify_presentation(&presentation), Ok(true));
570    }
571
572    #[test]
573    fn selective_disclosure_roundtrip() {
574        let mut crypto = FiduciaryCrypto::new();
575        crypto.generate_key("default".to_string()).unwrap();
576        let runtime = VcRuntime::new(crypto);
577
578        let cred = runtime.issue(test_credential(), Some("default")).unwrap();
579        let disclosed = vec!["degree".to_string()];
580        let pres = runtime.generate_selective_presentation(&cred, &disclosed).unwrap();
581
582        assert_eq!(pres.verifiable_credential.len(), 1);
583        let subj = &pres.verifiable_credential[0].credential_subject;
584        assert_eq!(subj.get("degree").map(|s| s.as_str()), Some("Bachelor of Science and Arts"));
585        assert!(subj.get("age").is_none());
586        assert!(subj.get("gpa").is_none());
587        assert!(subj.contains_key("_hiddenFieldsDigest"));
588
589        assert_eq!(runtime.verify_selective_presentation(&pres), Ok(true));
590    }
591
592    #[test]
593    fn zk_predicate_disclosure_roundtrip() {
594        let mut crypto = FiduciaryCrypto::new();
595        crypto.generate_key("default".to_string()).unwrap();
596        let runtime = VcRuntime::new(crypto);
597
598        let cred = runtime.issue(test_credential(), Some("default")).unwrap();
599        let predicates = vec!["age >= 21".to_string(), "gpa > 3.5".to_string()];
600        let pres = runtime.generate_zk_proof(&cred, &predicates).unwrap();
601
602        assert_eq!(pres.verifiable_credential.len(), 1);
603        let subj = &pres.verifiable_credential[0].credential_subject;
604        // Age and gpa values are NOT exposed!
605        assert!(subj.get("age").is_none());
606        assert!(subj.get("gpa").is_none());
607        assert_eq!(subj.get("predicate_0_satisfied").map(|s| s.as_str()), Some("true"));
608        assert_eq!(subj.get("predicate_1_satisfied").map(|s| s.as_str()), Some("true"));
609
610        assert_eq!(runtime.verify_zk_proof(&pres), Ok(true));
611
612        // False predicate fails closed
613        let false_pred = vec!["age < 18".to_string()];
614        assert_eq!(runtime.generate_zk_proof(&cred, &false_pred), Err(VcError::VerificationFailed));
615    }
616
617    #[test]
618    fn credential_status_revocation() {
619        let runtime = VcRuntime::new(FiduciaryCrypto::new());
620        let cred_id = "http://example.edu/credentials/3732";
621        assert_eq!(runtime.check_status(cred_id), Ok(StatusResult::Valid));
622
623        runtime.suspend_credential(cred_id);
624        assert_eq!(runtime.check_status(cred_id), Ok(StatusResult::Suspended));
625
626        runtime.revoke_credential(cred_id);
627        assert_eq!(runtime.check_status(cred_id), Ok(StatusResult::Revoked));
628    }
629}