Skip to main content

qualia_core_db/crypto/
verifiable_credential.rs

1//! Verifiable Credentials — native issue / verify core (#19).
2//!
3//! A credential = an ISSUER (an agent), a SUBJECT (an agent), a set of claim quins, and
4//! a validity window, sealed with an Ed25519 signature over a canonical SHA-256 digest of
5//! those fields. This is the NATIVE proof (fast, fits the engine); a W3C JSON-LD Data
6//! Integrity export is future work, and the lineage is the W3C Verifiable Claims WG.
7//!
8//! Two principles are enforced here:
9//! * **Verification authenticates ORIGIN, not TRUTH** (principle-identifiers-not-identity):
10//!   a valid signature proves *who said it*, not that the claim is true. A verified VC
11//!   still enters the frame-relative machinery; it is never auto-promoted to fact.
12//! * **Grounded issuers** (agency.n3 G1', via `agent.rs`): a credential whose issuer is
13//!   an `ArtificialAgent` with no Principal is rejected by [`verify_grounded`] — an AI
14//!   agent cannot issue free-floating credentials with no human accountable behind it.
15
16use crate::NQuin;
17use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey};
18use sha2::{Digest, Sha256};
19
20/// A credential: who attests, about whom, what, and for how long.
21#[derive(Debug, Clone, PartialEq, Eq)]
22pub struct Credential {
23    /// The issuing agent's identifier.
24    pub issuer: u64,
25    /// The subject the claims are about.
26    pub subject: u64,
27    /// Transaction time (when issued), unix seconds.
28    pub issued_at: u32,
29    /// Valid-until, unix seconds; `0` = no expiry.
30    pub valid_until: u32,
31    /// The claim quins (the subject's attested attributes). Order is part of the credential.
32    pub claims: Vec<NQuin>,
33}
34
35#[derive(Debug, PartialEq, Eq)]
36pub enum VcError {
37    /// The signature does not verify against the issuer key over the credential bytes.
38    InvalidSignature,
39    /// `now` is past `valid_until`.
40    Expired,
41    /// The issuer is an ungrounded artificial agent (no Principal) — agency.n3 G1'.
42    UngroundedIssuer,
43    /// The binary payload is too short to parse a Credential header.
44    DecodeTooShort,
45    /// The binary payload is too short for the declared claim count.
46    DecodeBadClaimCount,
47}
48
49impl std::fmt::Display for VcError {
50    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
51        match self {
52            Self::InvalidSignature => write!(f, "VC invalid signature"),
53            Self::Expired => write!(f, "VC expired"),
54            Self::UngroundedIssuer => write!(f, "VC ungrounded issuer"),
55            Self::DecodeTooShort => write!(f, "VC decode: too short"),
56            Self::DecodeBadClaimCount => write!(f, "VC decode: bad claim count"),
57        }
58    }
59}
60impl std::error::Error for VcError {}
61
62/// Canonical SHA-256 digest over the binding fields + claim quins (claim count is
63/// length-prefixed to prevent extension ambiguity). Streams — no allocation.
64fn digest(c: &Credential) -> [u8; 32] {
65    let mut h = Sha256::new();
66    h.update(b"q42-vc-v1");
67    h.update(c.issuer.to_le_bytes());
68    h.update(c.subject.to_le_bytes());
69    h.update(c.issued_at.to_le_bytes());
70    h.update(c.valid_until.to_le_bytes());
71    h.update((c.claims.len() as u64).to_le_bytes());
72    for q in &c.claims {
73        let b: &[u8; 48] = bytemuck::cast_ref(q);
74        h.update(b);
75    }
76    h.finalize().into()
77}
78
79/// Issue: seal the credential with the issuer's Ed25519 signing key.
80pub fn issue(signing_key: &SigningKey, credential: &Credential) -> Signature {
81    signing_key.sign(&digest(credential))
82}
83
84/// Verify the signature + expiry. Authenticates the claim's ORIGIN (who issued it) and
85/// that it has not lapsed — NOT that the claim is true.
86pub fn verify(
87    credential: &Credential,
88    issuer_key: &VerifyingKey,
89    signature: &Signature,
90    now: u32,
91) -> Result<(), VcError> {
92    if credential.valid_until != 0 && now > credential.valid_until {
93        return Err(VcError::Expired);
94    }
95    issuer_key
96        .verify(&digest(credential), signature)
97        .map_err(|_| VcError::InvalidSignature)
98}
99
100/// Verify as [`verify`], and additionally reject the credential if its issuer is an
101/// ungrounded artificial agent in `index` (agency.n3 G1' — no human Principal behind it).
102pub fn verify_grounded(
103    credential: &Credential,
104    issuer_key: &VerifyingKey,
105    signature: &Signature,
106    now: u32,
107    index: &crate::indexing::QuinIndex,
108) -> Result<(), VcError> {
109    if crate::agent::is_ungrounded_agency(index, credential.issuer) {
110        return Err(VcError::UngroundedIssuer);
111    }
112    verify(credential, issuer_key, signature, now)
113}
114
115/// Issue: seal the credential with the issuer's post-quantum ML-DSA-65 secret key.
116pub fn issue_pq(
117    signing_key: &[u8; crate::crypto::network::types::ML_DSA_65_SK_LEN],
118    credential: &Credential,
119    out_sig: &mut [u8; crate::crypto::network::types::ML_DSA_65_SIG_LEN],
120) -> Result<(), VcError> {
121    use fips204::ml_dsa_65::PrivateKey;
122    use fips204::traits::{SerDes, Signer};
123
124    let Ok(sk) = PrivateKey::try_from_bytes(*signing_key) else {
125        return Err(VcError::InvalidSignature);
126    };
127    let d = digest(credential);
128    let Ok(sig) = sk.try_sign(&d, b"qualia:vc:pq:v1") else {
129        return Err(VcError::InvalidSignature);
130    };
131    out_sig.copy_from_slice(&sig);
132    Ok(())
133}
134
135/// Verify a post-quantum ML-DSA-65 credential signature + expiry.
136pub fn verify_pq(
137    credential: &Credential,
138    issuer_pk: &[u8; crate::crypto::network::types::ML_DSA_65_PK_LEN],
139    signature: &[u8; crate::crypto::network::types::ML_DSA_65_SIG_LEN],
140    now: u32,
141) -> Result<(), VcError> {
142    use fips204::ml_dsa_65::PublicKey;
143    use fips204::traits::{SerDes, Verifier};
144
145    if credential.valid_until != 0 && now > credential.valid_until {
146        return Err(VcError::Expired);
147    }
148    let Ok(pk) = PublicKey::try_from_bytes(*issuer_pk) else {
149        return Err(VcError::InvalidSignature);
150    };
151    let d = digest(credential);
152    if pk.verify(&d, signature, b"qualia:vc:pq:v1") {
153        Ok(())
154    } else {
155        Err(VcError::InvalidSignature)
156    }
157}
158
159/// Issue: seal the credential with a hybrid DualProof (ML-DSA-65 + Ed25519).
160pub fn issue_dual(
161    mldsa_sk: &[u8; crate::crypto::network::types::ML_DSA_65_SK_LEN],
162    ed25519_seed: &[u8; 32],
163    credential: &Credential,
164    out: &mut crate::crypto::network::dual_sign::DualProof,
165) -> Result<(), VcError> {
166    let d = digest(credential);
167    crate::crypto::network::dual_sign::sign_dual(
168        mldsa_sk,
169        ed25519_seed,
170        &d,
171        b"qualia:vc:dual:v1",
172        out,
173    )
174    .map_err(|_| VcError::InvalidSignature)
175}
176
177/// Verify a hybrid DualProof (ML-DSA-65 + Ed25519) credential signature + expiry.
178pub fn verify_dual(
179    credential: &Credential,
180    ed25519_pk: &[u8; crate::crypto::network::types::ED25519_PK_LEN],
181    mldsa_pk: &[u8; crate::crypto::network::types::ML_DSA_65_PK_LEN],
182    proof: &crate::crypto::network::dual_sign::DualProof,
183    now: u32,
184) -> Result<(), VcError> {
185    if credential.valid_until != 0 && now > credential.valid_until {
186        return Err(VcError::Expired);
187    }
188    let d = digest(credential);
189    crate::crypto::network::dual_sign::verify_dual(
190        mldsa_pk,
191        ed25519_pk,
192        &d,
193        b"qualia:vc:dual:v1",
194        proof,
195    )
196    .map_err(|_| VcError::InvalidSignature)
197}
198
199/// Serialize a `Credential` to binary format.
200pub fn encode_credential(c: &Credential) -> Vec<u8> {
201    let mut out = Vec::with_capacity(28 + c.claims.len() * 48);
202    out.extend_from_slice(&c.issuer.to_le_bytes());
203    out.extend_from_slice(&c.subject.to_le_bytes());
204    out.extend_from_slice(&c.issued_at.to_le_bytes());
205    out.extend_from_slice(&c.valid_until.to_le_bytes());
206    out.extend_from_slice(&(c.claims.len() as u32).to_le_bytes());
207    for q in &c.claims {
208        let b: &[u8; 48] = bytemuck::cast_ref(q);
209        out.extend_from_slice(b);
210    }
211    out
212}
213
214/// Deserialize a `Credential` from binary format.
215pub fn decode_credential(bytes: &[u8]) -> Result<Credential, VcError> {
216    if bytes.len() < 28 {
217        return Err(VcError::DecodeTooShort);
218    }
219    let issuer = u64::from_le_bytes(bytes[0..8].try_into().unwrap());
220    let subject = u64::from_le_bytes(bytes[8..16].try_into().unwrap());
221    let issued_at = u32::from_le_bytes(bytes[16..20].try_into().unwrap());
222    let valid_until = u32::from_le_bytes(bytes[20..24].try_into().unwrap());
223    let claims_len = u32::from_le_bytes(bytes[24..28].try_into().unwrap()) as usize;
224    if bytes.len() < 28 + claims_len * 48 {
225        return Err(VcError::DecodeBadClaimCount);
226    }
227    let mut claims = Vec::with_capacity(claims_len);
228    for i in 0..claims_len {
229        let start = 28 + i * 48;
230        let b = &bytes[start..start + 48];
231        // Claims sit at offset 28 + i*48 in the byte stream, so `b` is only
232        // 4-aligned while NQuin (6×u64) needs 8-alignment — `from_bytes` would
233        // panic (TargetAlignmentGreaterAndInputNotAligned) on any real decode.
234        // `pod_read_unaligned` copies the 48 bytes with no alignment requirement.
235        let q: NQuin = bytemuck::pod_read_unaligned(b);
236        claims.push(q);
237    }
238    Ok(Credential {
239        issuer,
240        subject,
241        issued_at,
242        valid_until,
243        claims,
244    })
245}
246
247#[cfg(test)]
248mod tests {
249    use super::*;
250    use crate::agent::{A_ARTIFICIAL_AGENT, P_OPERATED_BY, P_RDF_TYPE};
251    use crate::indexing::QuinIndex;
252    use crate::q_hash;
253
254    fn key() -> SigningKey {
255        // Static secret so the test needs no RNG (mirrors agency.rs).
256        SigningKey::from_bytes(&[7u8; 32])
257    }
258    fn quin(s: u64, p: u64, o: u64) -> NQuin {
259        NQuin {
260            subject: s,
261            predicate: p,
262            object: o,
263            context: 0,
264            metadata: 0,
265            parity: 0,
266        }
267    }
268    fn sample() -> Credential {
269        Credential {
270            issuer: q_hash("did:example:issuer"),
271            subject: q_hash("did:example:alice"),
272            issued_at: 1_000,
273            valid_until: 2_000,
274            claims: vec![quin(
275                q_hash("did:example:alice"),
276                q_hash("https://ns.webcivics.net/capability/heldBy"),
277                q_hash("cap:FluidDynamics"),
278            )],
279        }
280    }
281
282    #[test]
283    fn issue_and_verify_roundtrip() {
284        let sk = key();
285        let c = sample();
286        let sig = issue(&sk, &c);
287        assert_eq!(verify(&c, &sk.verifying_key(), &sig, 1_500), Ok(()));
288    }
289
290    #[test]
291    fn tampered_claim_fails_verification() {
292        let sk = key();
293        let mut c = sample();
294        let sig = issue(&sk, &c);
295        c.claims[0].object = q_hash("cap:ForgedCredential"); // tamper after signing
296        assert_eq!(
297            verify(&c, &sk.verifying_key(), &sig, 1_500),
298            Err(VcError::InvalidSignature)
299        );
300    }
301
302    #[test]
303    fn wrong_issuer_key_fails() {
304        let sk = key();
305        let impostor = SigningKey::from_bytes(&[9u8; 32]);
306        let c = sample();
307        let sig = issue(&sk, &c);
308        assert_eq!(
309            verify(&c, &impostor.verifying_key(), &sig, 1_500),
310            Err(VcError::InvalidSignature)
311        );
312    }
313
314    #[test]
315    fn expired_credential_fails() {
316        let sk = key();
317        let c = sample();
318        let sig = issue(&sk, &c);
319        assert_eq!(
320            verify(&c, &sk.verifying_key(), &sig, 2_001),
321            Err(VcError::Expired)
322        );
323    }
324
325    #[test]
326    fn ungrounded_ai_issuer_is_rejected_but_grounded_one_is_accepted() {
327        let sk = key();
328        let c = sample();
329        let sig = issue(&sk, &c);
330
331        // Issuer is an ArtificialAgent with NO Principal -> ungrounded -> rejected.
332        let ungrounded = QuinIndex::from_slice(&[quin(c.issuer, P_RDF_TYPE, A_ARTIFICIAL_AGENT)]);
333        assert_eq!(
334            verify_grounded(&c, &sk.verifying_key(), &sig, 1_500, &ungrounded),
335            Err(VcError::UngroundedIssuer)
336        );
337
338        // Same issuer, now with a human Principal behind it -> grounded -> signature governs.
339        let human = q_hash("did:example:tim");
340        let grounded = QuinIndex::from_slice(&[
341            quin(c.issuer, P_RDF_TYPE, A_ARTIFICIAL_AGENT),
342            quin(c.issuer, P_OPERATED_BY, human),
343        ]);
344        assert_eq!(
345            verify_grounded(&c, &sk.verifying_key(), &sig, 1_500, &grounded),
346            Ok(())
347        );
348    }
349
350    #[test]
351    fn encode_decode_roundtrips() {
352        let c = sample();
353        let bytes = encode_credential(&c);
354        let back = decode_credential(&bytes).unwrap();
355        assert_eq!(c.issuer, back.issuer);
356        assert_eq!(c.subject, back.subject);
357        assert_eq!(c.issued_at, back.issued_at);
358        assert_eq!(c.valid_until, back.valid_until);
359        assert_eq!(c.claims.len(), back.claims.len());
360        assert_eq!(c.claims[0].subject, back.claims[0].subject);
361    }
362
363    #[test]
364    fn decode_rejects_truncated() {
365        assert_eq!(decode_credential(&[0u8; 10]), Err(VcError::DecodeTooShort));
366
367        let c = sample();
368        let mut bytes = encode_credential(&c);
369        bytes.truncate(bytes.len() - 10);
370        assert_eq!(decode_credential(&bytes), Err(VcError::DecodeBadClaimCount));
371    }
372
373    #[test]
374    fn test_pq_and_dual_credential_issue_and_verify() {
375        use crate::crypto::network::dual_sign::DualProof;
376        use crate::crypto::network::mldsa::generate_keypair;
377        use crate::crypto::network::types::{ED25519_PK_LEN, ED25519_SIG_LEN, ML_DSA_65_SIG_LEN};
378
379        let c = sample();
380        let (mldsa_sk, mldsa_pk) = generate_keypair().unwrap();
381        let ed_seed = [55u8; 32];
382        let ed_signing = SigningKey::from_bytes(&ed_seed);
383        let ed_pk_bytes: [u8; ED25519_PK_LEN] = ed_signing.verifying_key().to_bytes();
384
385        // 1. Post-Quantum ML-DSA-65 test
386        let mut pq_sig = [0u8; ML_DSA_65_SIG_LEN];
387        issue_pq(&mldsa_sk, &c, &mut pq_sig).unwrap();
388        assert_eq!(verify_pq(&c, &mldsa_pk, &pq_sig, 1_500), Ok(()));
389
390        // Expired fails
391        assert_eq!(
392            verify_pq(&c, &mldsa_pk, &pq_sig, 2_500),
393            Err(VcError::Expired)
394        );
395
396        // 2. Hybrid DualProof test
397        let mut dual_proof = DualProof {
398            mldsa_sig: [0u8; ML_DSA_65_SIG_LEN],
399            ed25519_sig: [0u8; ED25519_SIG_LEN],
400        };
401        issue_dual(&mldsa_sk, &ed_seed, &c, &mut dual_proof).unwrap();
402        assert_eq!(
403            verify_dual(&c, &ed_pk_bytes, &mldsa_pk, &dual_proof, 1_500),
404            Ok(())
405        );
406
407        // Tampering fails
408        let mut tampered = c.clone();
409        tampered.claims[0].object = 999_999;
410        assert_eq!(
411            verify_pq(&tampered, &mldsa_pk, &pq_sig, 1_500),
412            Err(VcError::InvalidSignature)
413        );
414        assert_eq!(
415            verify_dual(&tampered, &ed_pk_bytes, &mldsa_pk, &dual_proof, 1_500),
416            Err(VcError::InvalidSignature)
417        );
418    }
419}