Skip to main content

vouch_core/
hybrid.rs

1//! Post-quantum credentials as a Data Integrity proof set.
2//!
3//! The credential carries a `proof` ARRAY of independent proofs: exactly one
4//! `eddsa-jcs-2022` proof, and one proof for each post-quantum suite the
5//! issuer signs with, `mldsa44-jcs-2024` (ML-DSA-44, FIPS 204) and/or
6//! `slhdsa128-jcs-2024` (SLH-DSA-SHA2-128s, FIPS 205). Each proof is computed
7//! over the same unsecured document with only its own proof configuration,
8//! and each verifies on its own, so a verifier that understands only some of
9//! the cryptosuites can still check those proofs. Every member a verifier
10//! knows must verify for the set to verify ([`verify_set`]); the Ed25519
11//! member is always required.
12//!
13//! One pre-alignment identifier is accepted on verification and never
14//! emitted: `mldsa44-jcs-2026`. The v1.6.x composite proof
15//! (`hybrid-eddsa-mldsa44-jcs-2026`, one proofValue holding both signatures)
16//! is refused by every verifier as of 4.0; such credentials are issued again
17//! as a proof set.
18
19use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
20use serde_json::{Map, Value};
21
22use crate::data_integrity::{self, BuildProofOptions, PROOF_TYPE};
23use crate::error::{CoreError, Result};
24use crate::keys::Ed25519KeyPair;
25use crate::pq::{self, MlDsa44KeyPair, MLDSA44_SIG_LEN};
26use crate::slh::{self, SlhDsa128KeyPair, SLHDSA128_SIG_LEN};
27
28pub const EDDSA_CRYPTOSUITE_ID: &str = "eddsa-jcs-2022";
29/// The W3C Quantum-Resistant Cryptosuites identifier for ML-DSA-44 over JCS.
30pub const MLDSA44_CRYPTOSUITE_ID: &str = "mldsa44-jcs-2024";
31/// Pre-alignment identifier, accepted on verification only.
32pub const MLDSA44_LEGACY_CRYPTOSUITE_ID: &str = "mldsa44-jcs-2026";
33/// The W3C Quantum-Resistant Cryptosuites identifier for SLH-DSA-SHA2-128s
34/// over JCS.
35pub const SLHDSA128_CRYPTOSUITE_ID: &str = "slhdsa128-jcs-2024";
36
37/// Why a proof whose cryptosuite no verifier accepts is refused. The v1.6.x
38/// composite `hybrid-eddsa-mldsa44-jcs-2026` proof gets this answer.
39pub const REASON_UNSUPPORTED_CRYPTOSUITE: &str = "a proof uses an unsupported cryptosuite";
40
41/// The signature a cryptosuite identifier names.
42#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
43pub enum Suite {
44    Eddsa,
45    Mldsa44,
46    Slhdsa128,
47}
48
49impl Suite {
50    /// The identifier a new proof of this suite carries.
51    pub fn id(self) -> &'static str {
52        match self {
53            Suite::Eddsa => EDDSA_CRYPTOSUITE_ID,
54            Suite::Mldsa44 => MLDSA44_CRYPTOSUITE_ID,
55            Suite::Slhdsa128 => SLHDSA128_CRYPTOSUITE_ID,
56        }
57    }
58
59    /// The suite a cryptosuite identifier names, matched exactly (the
60    /// pre-alignment `mldsa44-jcs-2026` is ML-DSA-44). None for every other
61    /// identifier, the v1.6.x composite included.
62    pub fn of(id: &str) -> Option<Suite> {
63        match id {
64            EDDSA_CRYPTOSUITE_ID => Some(Suite::Eddsa),
65            MLDSA44_CRYPTOSUITE_ID | MLDSA44_LEGACY_CRYPTOSUITE_ID => Some(Suite::Mldsa44),
66            SLHDSA128_CRYPTOSUITE_ID => Some(Suite::Slhdsa128),
67            _ => None,
68        }
69    }
70
71    /// The suite of one proof, from its `cryptosuite` member.
72    pub fn of_proof(proof: &Value) -> Option<Suite> {
73        proof
74            .get("cryptosuite")
75            .and_then(Value::as_str)
76            .and_then(Suite::of)
77    }
78}
79
80/// The members of a well-formed proof set, by suite.
81#[derive(Debug, Clone, Copy)]
82pub struct SetMembers<'a> {
83    pub eddsa: &'a Value,
84    pub mldsa44: Option<&'a Value>,
85    pub slhdsa128: Option<&'a Value>,
86}
87
88impl SetMembers<'_> {
89    /// The suites of the set, in a fixed order.
90    pub fn suites(&self) -> Vec<Suite> {
91        let mut out = vec![Suite::Eddsa];
92        if self.mldsa44.is_some() {
93            out.push(Suite::Mldsa44);
94        }
95        if self.slhdsa128.is_some() {
96            out.push(Suite::Slhdsa128);
97        }
98        out
99    }
100}
101
102/// Sort the members of a `proof` array by suite. A proof set is exactly one
103/// `eddsa-jcs-2022` proof and at least one post-quantum proof, with at most
104/// one proof of each post-quantum suite and no proof of any other suite.
105/// None for every other array.
106pub fn set_members(items: &[Value]) -> Option<SetMembers<'_>> {
107    let (mut eddsa, mut mldsa44, mut slhdsa128) = (None, None, None);
108    for p in items {
109        let slot = match Suite::of_proof(p)? {
110            Suite::Eddsa => &mut eddsa,
111            Suite::Mldsa44 => &mut mldsa44,
112            Suite::Slhdsa128 => &mut slhdsa128,
113        };
114        if slot.replace(p).is_some() {
115            return None; // two proofs of one suite
116        }
117    }
118    if mldsa44.is_none() && slhdsa128.is_none() {
119        return None; // no post-quantum member
120    }
121    Some(SetMembers {
122        eddsa: eddsa?,
123        mldsa44,
124        slhdsa128,
125    })
126}
127
128/// The suites of a credential's (or a grant's) proof as a verifier counts
129/// them: one `eddsa-jcs-2022` proof object is that one suite, a well-formed
130/// proof set is its members' suites, anything else is none.
131pub fn proof_suites(credential: &Value) -> Vec<Suite> {
132    match credential.get("proof") {
133        Some(p @ Value::Object(_)) if Suite::of_proof(p) == Some(Suite::Eddsa) => {
134            vec![Suite::Eddsa]
135        }
136        Some(Value::Array(items)) => set_members(items).map(|m| m.suites()).unwrap_or_default(),
137        _ => Vec::new(),
138    }
139}
140
141/// Why a credential whose proofs lack a cryptosuite the verifier requires is
142/// refused: a suite named by the verifier's `requireSuites` setting, or a
143/// post-quantum suite whose key the caller handed over or the issuer's DID
144/// document publishes for assertions.
145pub const REASON_REQUIRED_SUITE_MISSING: &str =
146    "the credential's proofs do not include a required cryptosuite";
147
148/// What a verifier requires of a credential's proofs beyond the Ed25519
149/// proof, which is always required.
150#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
151pub struct Required {
152    /// Some post-quantum proof: a single classical proof is refused.
153    pub post_quantum: bool,
154    /// The ML-DSA-44 proof.
155    pub mldsa44: bool,
156    /// The SLH-DSA-SHA2-128s proof.
157    pub slhdsa128: bool,
158}
159
160impl Required {
161    /// True when anything post-quantum is required, so a single classical
162    /// proof cannot meet it.
163    pub fn any(&self) -> bool {
164        self.post_quantum || self.mldsa44 || self.slhdsa128
165    }
166
167    /// Require a suite by name (`eddsa-jcs-2022` adds nothing: it is always
168    /// required).
169    pub fn with(mut self, suite: Suite) -> Self {
170        match suite {
171            Suite::Eddsa => {}
172            Suite::Mldsa44 => self.mldsa44 = true,
173            Suite::Slhdsa128 => self.slhdsa128 = true,
174        }
175        self
176    }
177
178    /// True when a proof with these suites meets the requirement.
179    pub fn met_by(&self, suites: &[Suite]) -> bool {
180        let has = |s: Suite| suites.contains(&s);
181        has(Suite::Eddsa)
182            && (!self.post_quantum || has(Suite::Mldsa44) || has(Suite::Slhdsa128))
183            && (!self.mldsa44 || has(Suite::Mldsa44))
184            && (!self.slhdsa128 || has(Suite::Slhdsa128))
185    }
186}
187
188/// Read a verifier's `requireSuites` setting: a list of cryptosuite
189/// identifiers (`eddsa-jcs-2022`, `mldsa44-jcs-2024`, `slhdsa128-jcs-2024`),
190/// each at most once. Anything else is an error.
191pub fn required_suites_from_json(v: &Value) -> Result<Vec<Suite>> {
192    let bad = || {
193        CoreError::Json(
194            "requireSuites must be a list of eddsa-jcs-2022, mldsa44-jcs-2024 or slhdsa128-jcs-2024, each at most once"
195                .into(),
196        )
197    };
198    let items = v.as_array().ok_or_else(bad)?;
199    let mut out = Vec::new();
200    for item in items {
201        let suite = match item.as_str() {
202            Some(EDDSA_CRYPTOSUITE_ID) => Suite::Eddsa,
203            Some(MLDSA44_CRYPTOSUITE_ID) => Suite::Mldsa44,
204            Some(SLHDSA128_CRYPTOSUITE_ID) => Suite::Slhdsa128,
205            _ => return Err(bad()),
206        };
207        if out.contains(&suite) {
208            return Err(bad());
209        }
210        out.push(suite);
211    }
212    Ok(out)
213}
214
215fn strip_proof(credential: &Value) -> Result<Value> {
216    let mut base = credential.clone();
217    base.as_object_mut()
218        .ok_or_else(|| CoreError::Json("credential must be an object".into()))?
219        .remove("proof");
220    Ok(base)
221}
222
223fn unsigned_proof(
224    cryptosuite: &str,
225    verification_method: &str,
226    created: &str,
227) -> Map<String, Value> {
228    let mut p = Map::new();
229    p.insert("type".into(), Value::String(PROOF_TYPE.into()));
230    p.insert("cryptosuite".into(), Value::String(cryptosuite.into()));
231    p.insert("created".into(), Value::String(created.into()));
232    p.insert(
233        "verificationMethod".into(),
234        Value::String(verification_method.into()),
235    );
236    p.insert(
237        "proofPurpose".into(),
238        Value::String("assertionMethod".into()),
239    );
240    p
241}
242
243/// A post-quantum key and the verificationMethod its proof names.
244pub struct PqSigner<'a, K> {
245    pub key: &'a K,
246    pub verification_method: &'a str,
247}
248
249// Two references: copied whatever the key type is.
250impl<K> Clone for PqSigner<'_, K> {
251    fn clone(&self) -> Self {
252        *self
253    }
254}
255impl<K> Copy for PqSigner<'_, K> {}
256
257/// Build a proof set for `credential`: the `eddsa-jcs-2022` proof first, then
258/// an `mldsa44-jcs-2024` proof and an `slhdsa128-jcs-2024` proof for each
259/// post-quantum key given, all over the same unsecured document with the same
260/// `created`. At least one post-quantum key is required.
261pub fn build_proof_set(
262    credential: &Value,
263    ed25519_seed: &[u8],
264    ed25519_verification_method: &str,
265    mldsa: Option<PqSigner<'_, MlDsa44KeyPair>>,
266    slhdsa: Option<PqSigner<'_, SlhDsa128KeyPair>>,
267    created: &str,
268) -> Result<Value> {
269    if mldsa.is_none() && slhdsa.is_none() {
270        return Err(CoreError::Crypto(
271            "a proof set needs at least one post-quantum key".into(),
272        ));
273    }
274    let base = strip_proof(credential)?;
275    let mut proofs = vec![data_integrity::build_proof(
276        &base,
277        ed25519_seed,
278        &BuildProofOptions::new(ed25519_verification_method, created),
279    )?];
280    // The Quantum-Resistant Cryptosuites specification encodes proofValue as a
281    // base64url-nopad Multibase value ("u"). The classical eddsa-jcs-2022 suite
282    // is specified separately and keeps base58btc ("z").
283    if let Some(ml) = mldsa {
284        let mut proof = unsigned_proof(MLDSA44_CRYPTOSUITE_ID, ml.verification_method, created);
285        let sig = ml.key.sign(&data_integrity::hash_data(&base, &proof)?)?;
286        proof.insert(
287            "proofValue".into(),
288            Value::String(format!("u{}", URL_SAFE_NO_PAD.encode(sig))),
289        );
290        proofs.push(Value::Object(proof));
291    }
292    if let Some(slh) = slhdsa {
293        let mut proof = unsigned_proof(SLHDSA128_CRYPTOSUITE_ID, slh.verification_method, created);
294        let sig = slh.key.sign(&data_integrity::hash_data(&base, &proof)?)?;
295        proof.insert(
296            "proofValue".into(),
297            Value::String(format!("u{}", URL_SAFE_NO_PAD.encode(sig))),
298        );
299        proofs.push(Value::Object(proof));
300    }
301    Ok(Value::Array(proofs))
302}
303
304/// Build a proof set ([`build_proof_set`]) and attach it to the credential
305/// under `proof`, replacing any existing proof.
306pub fn sign_set(
307    credential: &Value,
308    ed25519_seed: &[u8],
309    ed25519_verification_method: &str,
310    mldsa: Option<PqSigner<'_, MlDsa44KeyPair>>,
311    slhdsa: Option<PqSigner<'_, SlhDsa128KeyPair>>,
312    created: &str,
313) -> Result<Value> {
314    let proof = build_proof_set(
315        credential,
316        ed25519_seed,
317        ed25519_verification_method,
318        mldsa,
319        slhdsa,
320        created,
321    )?;
322    let mut signed = strip_proof(credential)?;
323    signed
324        .as_object_mut()
325        .unwrap()
326        .insert("proof".into(), proof);
327    Ok(signed)
328}
329
330/// Build a dual proof (an array of two proofs, Ed25519 and ML-DSA-44) for
331/// `credential`.
332pub fn build_dual_proof(
333    credential: &Value,
334    ed25519_seed: &[u8],
335    mldsa: &MlDsa44KeyPair,
336    ed25519_verification_method: &str,
337    mldsa_verification_method: &str,
338    created: &str,
339) -> Result<Value> {
340    build_proof_set(
341        credential,
342        ed25519_seed,
343        ed25519_verification_method,
344        Some(PqSigner {
345            key: mldsa,
346            verification_method: mldsa_verification_method,
347        }),
348        None,
349        created,
350    )
351}
352
353/// Build a dual proof and attach it to the credential under `proof`.
354pub fn sign_dual(
355    credential: &Value,
356    ed25519_seed: &[u8],
357    mldsa: &MlDsa44KeyPair,
358    ed25519_verification_method: &str,
359    mldsa_verification_method: &str,
360    created: &str,
361) -> Result<Value> {
362    sign_set(
363        credential,
364        ed25519_seed,
365        ed25519_verification_method,
366        Some(PqSigner {
367            key: mldsa,
368            verification_method: mldsa_verification_method,
369        }),
370        None,
371        created,
372    )
373}
374
375/// Decode a multibase base64url ("u") proofValue strictly: no padding,
376/// canonical trailing bits, exactly `expected` bytes.
377fn decode_b64u_proof_value(proof_value: &str, expected: usize, name: &str) -> Result<Vec<u8>> {
378    let body = proof_value.strip_prefix('u').ok_or_else(|| {
379        CoreError::Json(format!("{name} proofValue must be multibase base64url (u)"))
380    })?;
381    // The longest value read is one that could hold the signature: nothing
382    // longer is decoded.
383    if body.len() > expected.div_ceil(3) * 4 {
384        return Err(CoreError::InvalidSignatureLength {
385            expected,
386            got: body.len() / 4 * 3,
387        });
388    }
389    // URL_SAFE_NO_PAD refuses padding and non-canonical trailing bits.
390    let sig = URL_SAFE_NO_PAD
391        .decode(body)
392        .map_err(|e| CoreError::Json(format!("bad base64url proofValue: {e}")))?;
393    if sig.len() != expected {
394        return Err(CoreError::InvalidSignatureLength {
395            expected,
396            got: sig.len(),
397        });
398    }
399    Ok(sig)
400}
401
402/// Decode an ML-DSA-44 proofValue strictly: multibase base64url without
403/// padding ('u'), canonical trailing bits, exactly 2420 bytes.
404pub fn decode_mldsa44_proof_value(proof_value: &str) -> Result<Vec<u8>> {
405    decode_b64u_proof_value(proof_value, MLDSA44_SIG_LEN, "ML-DSA-44")
406}
407
408/// Decode an SLH-DSA-SHA2-128s proofValue strictly: multibase base64url
409/// without padding ('u'), canonical trailing bits, exactly 7856 bytes.
410pub fn decode_slhdsa128_proof_value(proof_value: &str) -> Result<Vec<u8>> {
411    decode_b64u_proof_value(proof_value, SLHDSA128_SIG_LEN, "SLH-DSA")
412}
413
414/// Check one post-quantum member of a set against `base` (the document
415/// without its proof): type "DataIntegrityProof", a strict proofValue, the
416/// document's @context, and the signature over the 64-byte hashData. An
417/// ML-DSA-44 member also verifies over the pre-alignment signing input.
418fn verify_pq_member(base: &Value, proof: &Value, suite: Suite, public: &[u8]) -> Result<bool> {
419    let name = if suite == Suite::Mldsa44 {
420        "ml-dsa"
421    } else {
422        "slh-dsa"
423    };
424    let proof_obj = proof
425        .as_object()
426        .ok_or_else(|| CoreError::Json(format!("{name} proof must be an object")))?;
427    if proof_obj.get("type").and_then(|v| v.as_str()) != Some(PROOF_TYPE) {
428        return Ok(false);
429    }
430    let pv = proof_obj
431        .get("proofValue")
432        .and_then(|v| v.as_str())
433        .ok_or_else(|| CoreError::Json(format!("{name} proof missing proofValue")))?;
434    let sig = match suite {
435        Suite::Mldsa44 => decode_mldsa44_proof_value(pv)?,
436        _ => decode_slhdsa128_proof_value(pv)?,
437    };
438    if !data_integrity::proof_context_matches(base, proof_obj) {
439        return Ok(false);
440    }
441    let mut unsigned = proof_obj.clone();
442    unsigned.remove("proofValue");
443    let signing_input = data_integrity::hash_data(base, &unsigned)?;
444    if suite == Suite::Slhdsa128 {
445        return slh::verify(public, &signing_input, &sig);
446    }
447    if pq::verify(public, &signing_input, &sig)? {
448        return Ok(true);
449    }
450    let legacy = data_integrity::legacy_proof_digest(base, &unsigned)?;
451    pq::verify(public, &legacy, &sig)
452}
453
454/// Which members of a set verified, or None when one did not.
455struct Seen {
456    eddsa: bool,
457    mldsa44: bool,
458    slhdsa128: bool,
459}
460
461fn verify_members(
462    credential: &Value,
463    ed25519_public: &[u8],
464    mldsa_public: Option<&[u8]>,
465    slhdsa_public: Option<&[u8]>,
466    skip_unkeyed: bool,
467) -> Result<Option<Seen>> {
468    let proofs = credential
469        .as_object()
470        .and_then(|o| o.get("proof"))
471        .and_then(|p| p.as_array())
472        .ok_or_else(|| CoreError::Json("dual proof requires a proof array".into()))?;
473    // The array must be a proof set and nothing else: exactly one
474    // `eddsa-jcs-2022` proof, at least one post-quantum proof, at most one of
475    // each post-quantum suite, and no member of any other suite (the v1.6.x
476    // composite included). Anything else is refused before a signature is
477    // checked, so no member is ever left out of the answer.
478    if set_members(proofs).is_none() {
479        return Ok(None);
480    }
481    let base = strip_proof(credential)?;
482    let Some(issuer) = crate::credentials::issuer_did(credential) else {
483        return Ok(None);
484    };
485
486    // Every proof present in the set must verify. A proof that fails fails the
487    // whole set immediately, so a later proof of the same cryptosuite can never
488    // overwrite an earlier failure.
489    let mut seen = Seen {
490        eddsa: false,
491        mldsa44: false,
492        slhdsa128: false,
493    };
494    for p in proofs {
495        if !crate::credentials::proof_bound_to_issuer(p, issuer) {
496            return Ok(None);
497        }
498        match Suite::of_proof(p) {
499            Some(Suite::Eddsa) => {
500                let mut c = base.clone();
501                c.as_object_mut().unwrap().insert("proof".into(), p.clone());
502                if !data_integrity::verify_proof(&c, ed25519_public)? {
503                    return Ok(None);
504                }
505                seen.eddsa = true;
506            }
507            Some(suite) => {
508                // A post-quantum member with no key to check it with fails
509                // the set: a proof this verifier knows is never skipped.
510                let key = if suite == Suite::Mldsa44 {
511                    mldsa_public
512                } else {
513                    slhdsa_public
514                };
515                let Some(key) = key else {
516                    if skip_unkeyed {
517                        continue;
518                    }
519                    return Ok(None);
520                };
521                if !verify_pq_member(&base, p, suite, key)? {
522                    return Ok(None);
523                }
524                if suite == Suite::Mldsa44 {
525                    seen.mldsa44 = true;
526                } else {
527                    seen.slhdsa128 = true;
528                }
529            }
530            // set_members let no other suite through.
531            None => return Ok(None),
532        }
533    }
534    Ok(Some(seen))
535}
536
537/// Verify a proof set with the issuer's keys: the Ed25519 proof and every
538/// post-quantum proof in the array MUST validate. Returns Ok(true) only when
539/// the array is a proof set ([`set_members`]) and every proof in it verified.
540/// A post-quantum proof whose key is not given fails the set. So does an
541/// array that is not a proof set: a member of another cryptosuite (the
542/// v1.6.x composite included), no `eddsa-jcs-2022` proof or more than one,
543/// or two proofs of one post-quantum suite.
544///
545/// Every member of the set must be bound to the credential's issuer
546/// (proofPurpose "assertionMethod" and a verificationMethod of the issuer's
547/// DID). A
548/// post-quantum member must have type "DataIntegrityProof", its cryptosuite
549/// identifier exactly (`mldsa44-jcs-2024`, the pre-alignment
550/// `mldsa44-jcs-2026`, or `slhdsa128-jcs-2024`), and a strict proofValue
551/// ([`decode_mldsa44_proof_value`], [`decode_slhdsa128_proof_value`]).
552pub fn verify_set(
553    credential: &Value,
554    ed25519_public: &[u8],
555    mldsa_public: Option<&[u8]>,
556    slhdsa_public: Option<&[u8]>,
557) -> Result<bool> {
558    Ok(verify_members(
559        credential,
560        ed25519_public,
561        mldsa_public,
562        slhdsa_public,
563        false,
564    )?
565    .is_some_and(|seen| seen.eddsa && (seen.mldsa44 || seen.slhdsa128)))
566}
567
568/// Verify the members of a proof set a verifier holds keys for: the Ed25519
569/// proof must verify, and so must every post-quantum proof whose key is
570/// given. A post-quantum proof whose key is not given is left unchecked. For
571/// a grant in a delegation chain when post-quantum is not required; a
572/// verifier that requires post-quantum uses [`verify_set`].
573pub fn verify_set_known_keys(
574    credential: &Value,
575    ed25519_public: &[u8],
576    mldsa_public: Option<&[u8]>,
577    slhdsa_public: Option<&[u8]>,
578) -> Result<bool> {
579    Ok(verify_members(
580        credential,
581        ed25519_public,
582        mldsa_public,
583        slhdsa_public,
584        true,
585    )?
586    .is_some_and(|seen| seen.eddsa))
587}
588
589/// Verify a dual proof: both the Ed25519 and the ML-DSA-44 proofs in the array
590/// MUST validate. Returns Ok(true) only if both are present and valid. A set
591/// that also carries an SLH-DSA proof fails here, because this call has no
592/// key to check it with; use [`verify_set`] for such a set.
593pub fn verify_dual(credential: &Value, ed25519_public: &[u8], mldsa_public: &[u8]) -> Result<bool> {
594    // Both members of the set must be present, so a credential cannot drop the
595    // post-quantum proof and still be accepted as a proof set.
596    Ok(
597        verify_members(credential, ed25519_public, Some(mldsa_public), None, false)?
598            .is_some_and(|seen| seen.eddsa && seen.mldsa44),
599    )
600}
601
602/// Convenience: derive the Ed25519 public key for a dual self-check.
603pub fn ed25519_public_from_seed(seed: &[u8]) -> Result<[u8; 32]> {
604    Ok(Ed25519KeyPair::from_seed_slice(seed)?.public_key())
605}
606
607/// The v1.6.x composite proof (one proof whose proofValue is
608/// base58btc(ed25519_sig || mldsa44_sig) over the pre-alignment digest), for
609/// tests that check every verifier refuses it. Built only in test builds:
610/// the core has no way to emit this proof.
611#[cfg(test)]
612pub(crate) fn composite_for_tests(
613    credential: &Value,
614    ed25519_seed: &[u8],
615    mldsa: &MlDsa44KeyPair,
616    verification_method: &str,
617    created: &str,
618) -> Value {
619    let base = strip_proof(credential).unwrap();
620    let mut proof = unsigned_proof(
621        "hybrid-eddsa-mldsa44-jcs-2026",
622        verification_method,
623        created,
624    );
625    let digest = data_integrity::legacy_proof_digest(&base, &proof).unwrap();
626    let mut combined = Ed25519KeyPair::from_seed_slice(ed25519_seed)
627        .unwrap()
628        .sign(&digest)
629        .to_vec();
630    combined.extend_from_slice(&mldsa.sign(&digest).unwrap());
631    proof.insert(
632        "proofValue".into(),
633        Value::String(format!("z{}", bs58::encode(combined).into_string())),
634    );
635    let mut signed = base;
636    signed["proof"] = Value::Object(proof);
637    signed
638}
639
640#[cfg(test)]
641mod tests {
642    use super::*;
643    use serde_json::json;
644
645    fn cred() -> Value {
646        json!({
647            "@context": ["https://www.w3.org/ns/credentials/v2"],
648            "type": ["VerifiableCredential", "VouchCredential"],
649            "issuer": "did:web:agent.example.com",
650            "validFrom": "2026-04-26T10:00:00Z",
651            "validUntil": "2026-04-26T10:05:00Z",
652            "credentialSubject": { "id": "did:web:agent.example.com", "vouchVersion": "1.0",
653                "intent": { "action": "read", "target": "t", "resource": "https://api/x" } }
654        })
655    }
656
657    #[test]
658    fn dual_proof_roundtrip() {
659        let seed = [4u8; 32];
660        let ml = MlDsa44KeyPair::generate().unwrap();
661        let signed = sign_dual(
662            &cred(),
663            &seed,
664            &ml,
665            "did:web:agent.example.com#key-1",
666            "did:web:agent.example.com#key-2",
667            "2026-04-26T10:00:00Z",
668        )
669        .unwrap();
670        assert!(signed["proof"].is_array());
671        let ed_pub = ed25519_public_from_seed(&seed).unwrap();
672        assert!(verify_dual(&signed, &ed_pub, &ml.public_key()).unwrap());
673    }
674
675    #[test]
676    fn dual_proof_tamper_fails() {
677        let seed = [4u8; 32];
678        let ml = MlDsa44KeyPair::generate().unwrap();
679        let mut signed = sign_dual(
680            &cred(),
681            &seed,
682            &ml,
683            "did:web:agent.example.com#key-1",
684            "did:web:agent.example.com#key-2",
685            "2026-04-26T10:00:00Z",
686        )
687        .unwrap();
688        signed["credentialSubject"]["intent"]["action"] = json!("delete");
689        let ed_pub = ed25519_public_from_seed(&seed).unwrap();
690        assert!(!verify_dual(&signed, &ed_pub, &ml.public_key()).unwrap());
691    }
692
693    /// A failing proof cannot be masked by appending a second, valid proof of
694    /// the same cryptosuite after it.
695    #[test]
696    fn appended_valid_proof_cannot_mask_a_failing_one() {
697        let seed = [4u8; 32];
698        let ml = MlDsa44KeyPair::generate().unwrap();
699        let signed = sign_dual(
700            &cred(),
701            &seed,
702            &ml,
703            "did:web:agent.example.com#key-1",
704            "did:web:agent.example.com#key-2",
705            "2026-04-26T10:00:00Z",
706        )
707        .unwrap();
708        let ed_pub = ed25519_public_from_seed(&seed).unwrap();
709        let proofs = signed["proof"].as_array().unwrap().clone();
710
711        // Corrupt the classical proof, then append the untouched valid one.
712        let mut broken = proofs[0].clone();
713        broken["proofValue"] = json!("z2SkKQBFXKcxxHbEnDaZjXPRWzHnbe1ZgArebQmqQ1Rf6H3nJa4vp3rzYaC5nnrFVFTL6wPMuJUAQGf7oEENy4vX");
714
715        let mut attacked = signed.clone();
716        attacked["proof"] = json!([broken, proofs[0].clone(), proofs[1].clone()]);
717        assert!(
718            !verify_dual(&attacked, &ed_pub, &ml.public_key()).unwrap(),
719            "a failing proof must fail the set even when a valid proof follows it"
720        );
721    }
722
723    /// The set primitives refuse an array that is not a proof set, whatever
724    /// its good members say: a member of another cryptosuite, the v1.6.x
725    /// composite, no `eddsa-jcs-2022` proof or two of them, or two proofs of
726    /// one post-quantum suite.
727    #[test]
728    fn an_array_that_is_not_a_proof_set_is_refused() {
729        let seed = [4u8; 32];
730        let ml = MlDsa44KeyPair::generate().unwrap();
731        let vm = "did:web:agent.example.com#key-1";
732        let created = "2026-04-26T10:00:00Z";
733        let signed = sign_dual(
734            &cred(),
735            &seed,
736            &ml,
737            vm,
738            "did:web:agent.example.com#key-2",
739            created,
740        )
741        .unwrap();
742        let ed_pub = ed25519_public_from_seed(&seed).unwrap();
743        let ml_pub = ml.public_key();
744        let proofs = signed["proof"].as_array().unwrap().clone();
745        let (ed_proof, ml_proof) = (proofs[0].clone(), proofs[1].clone());
746        assert!(verify_dual(&signed, &ed_pub, &ml_pub).unwrap());
747
748        let mut future = ed_proof.clone();
749        future["cryptosuite"] = json!("some-unregistered-suite-2030");
750        // A composite proof with two valid signatures inside.
751        let composite = composite_for_tests(&cred(), &seed, &ml, vm, created)["proof"].clone();
752        // The pre-alignment identifier is ML-DSA-44 too, so it is a second
753        // proof of that suite.
754        let mut legacy_ml = ml_proof.clone();
755        legacy_ml["cryptosuite"] = json!(MLDSA44_LEGACY_CRYPTOSUITE_ID);
756
757        let cases: Vec<(&str, Value)> = vec![
758            (
759                "a member of an unknown suite",
760                json!([ed_proof, ml_proof, future]),
761            ),
762            (
763                "an unknown suite in place of the post-quantum proof",
764                json!([ed_proof, future]),
765            ),
766            ("a composite member", json!([ed_proof, ml_proof, composite])),
767            (
768                "a composite member first",
769                json!([composite, ed_proof, ml_proof]),
770            ),
771            ("no eddsa-jcs-2022 proof", json!([ml_proof])),
772            (
773                "two eddsa-jcs-2022 proofs",
774                json!([ed_proof, ed_proof, ml_proof]),
775            ),
776            (
777                "two ML-DSA-44 proofs",
778                json!([ed_proof, ml_proof, ml_proof]),
779            ),
780            (
781                "two ML-DSA-44 proofs under both identifiers",
782                json!([ed_proof, ml_proof, legacy_ml]),
783            ),
784            (
785                "a member that is not an object",
786                json!([ed_proof, ml_proof, "x"]),
787            ),
788            ("an empty array", json!([])),
789        ];
790        for (name, proof) in cases {
791            let mut c = signed.clone();
792            c["proof"] = proof;
793            assert!(!verify_dual(&c, &ed_pub, &ml_pub).unwrap(), "{name}");
794            assert!(
795                !verify_set(&c, &ed_pub, Some(&ml_pub), None).unwrap(),
796                "{name}"
797            );
798            assert!(
799                !verify_set_known_keys(&c, &ed_pub, Some(&ml_pub), None).unwrap(),
800                "{name}"
801            );
802            // With no post-quantum key the lenient form checks the Ed25519
803            // proof alone, and still refuses the array.
804            assert!(
805                !verify_set_known_keys(&c, &ed_pub, None, None).unwrap(),
806                "{name}"
807            );
808        }
809    }
810
811    #[test]
812    fn proof_set_without_the_post_quantum_member_fails() {
813        let seed = [4u8; 32];
814        let ml = MlDsa44KeyPair::generate().unwrap();
815        let signed = sign_dual(
816            &cred(),
817            &seed,
818            &ml,
819            "did:web:agent.example.com#key-1",
820            "did:web:agent.example.com#key-2",
821            "2026-04-26T10:00:00Z",
822        )
823        .unwrap();
824        let ed_pub = ed25519_public_from_seed(&seed).unwrap();
825        let classical_only = signed["proof"].as_array().unwrap()[0].clone();
826
827        let mut stripped = signed.clone();
828        stripped["proof"] = json!([classical_only]);
829        assert!(!verify_dual(&stripped, &ed_pub, &ml.public_key()).unwrap());
830    }
831
832    fn signed(vm_ed: &str, vm_ml: &str) -> (Value, [u8; 32], MlDsa44KeyPair) {
833        let seed = [4u8; 32];
834        let ml = MlDsa44KeyPair::generate().unwrap();
835        let signed = sign_dual(&cred(), &seed, &ml, vm_ed, vm_ml, "2026-04-26T10:00:00Z").unwrap();
836        (signed, ed25519_public_from_seed(&seed).unwrap(), ml)
837    }
838
839    #[test]
840    fn every_member_must_be_bound_to_the_issuer() {
841        let (s, ed, ml) = signed(
842            "did:web:agent.example.com#key-1",
843            "did:web:other.example.com#key-2",
844        );
845        assert!(!verify_dual(&s, &ed, &ml.public_key()).unwrap());
846        // An unknown extra member that names another DID also fails the set.
847        let (s, ed, ml) = signed(
848            "did:web:agent.example.com#key-1",
849            "did:web:agent.example.com#key-2",
850        );
851        let mut extra = s["proof"][0].clone();
852        extra["cryptosuite"] = json!("some-unregistered-suite-2030");
853        extra["verificationMethod"] = json!("did:web:someone-else.example#key-1");
854        let mut set = s.clone();
855        set["proof"].as_array_mut().unwrap().push(extra);
856        assert!(!verify_dual(&set, &ed, &ml.public_key()).unwrap());
857    }
858
859    #[test]
860    fn mldsa_member_type_and_proof_value_are_strict() {
861        let (s, ed, ml) = signed(
862            "did:web:agent.example.com#key-1",
863            "did:web:agent.example.com#key-2",
864        );
865        let pk = ml.public_key();
866        assert!(verify_dual(&s, &ed, &pk).unwrap());
867        let mut t = s.clone();
868        t["proof"][1]["type"] = json!("Ed25519Signature2020");
869        assert!(!verify_dual(&t, &ed, &pk).unwrap());
870        let mut t = s.clone();
871        t["proof"][1]["cryptosuite"] = json!("MLDSA44-JCS-2024");
872        assert!(
873            !verify_dual(&t, &ed, &pk).unwrap(),
874            "case-changed suite is not ML-DSA"
875        );
876        let pv = s["proof"][1]["proofValue"].as_str().unwrap().to_string();
877        let raw = URL_SAFE_NO_PAD.decode(&pv[1..]).unwrap();
878        // base58btc instead of base64url, padding, a short signature.
879        for bad in [
880            format!("z{}", bs58::encode(&raw).into_string()),
881            format!("{pv}=="),
882            format!("u{}", URL_SAFE_NO_PAD.encode(&raw[..2419])),
883        ] {
884            let mut t = s.clone();
885            t["proof"][1]["proofValue"] = json!(bad);
886            assert!(verify_dual(&t, &ed, &pk).is_err());
887        }
888        assert!(decode_mldsa44_proof_value(&pv).is_ok());
889    }
890
891    fn three(vm: &str) -> (Value, [u8; 32], MlDsa44KeyPair, SlhDsa128KeyPair) {
892        let seed = [4u8; 32];
893        let ml = MlDsa44KeyPair::generate().unwrap();
894        let slh_key = SlhDsa128KeyPair::generate().unwrap();
895        let signed = sign_set(
896            &cred(),
897            &seed,
898            &format!("{vm}#key-1"),
899            Some(PqSigner {
900                key: &ml,
901                verification_method: &format!("{vm}#key-2"),
902            }),
903            Some(PqSigner {
904                key: &slh_key,
905                verification_method: &format!("{vm}#key-3"),
906            }),
907            "2026-04-26T10:00:00Z",
908        )
909        .unwrap();
910        (
911            signed,
912            ed25519_public_from_seed(&seed).unwrap(),
913            ml,
914            slh_key,
915        )
916    }
917
918    #[test]
919    fn a_set_of_three_needs_every_key_and_every_proof() {
920        let (s, ed, ml, slh_key) = three("did:web:agent.example.com");
921        let (mlp, slhp) = (ml.public_key(), slh_key.public_key());
922        assert_eq!(
923            proof_suites(&s),
924            [Suite::Eddsa, Suite::Mldsa44, Suite::Slhdsa128]
925        );
926        assert!(verify_set(&s, &ed, Some(&mlp), Some(&slhp)).unwrap());
927        // A post-quantum proof with no key to check it fails the set.
928        assert!(!verify_set(&s, &ed, Some(&mlp), None).unwrap());
929        assert!(!verify_set(&s, &ed, None, Some(&slhp)).unwrap());
930        assert!(!verify_dual(&s, &ed, &mlp).unwrap());
931        // Another key pair's SLH-DSA key, and a changed document.
932        let other = SlhDsa128KeyPair::generate().unwrap().public_key();
933        assert!(!verify_set(&s, &ed, Some(&mlp), Some(&other)).unwrap());
934        let mut t = s.clone();
935        t["credentialSubject"]["intent"]["action"] = json!("delete");
936        assert!(!verify_set(&t, &ed, Some(&mlp), Some(&slhp)).unwrap());
937        // The SLH-DSA member's type, suite spelling and proofValue are strict.
938        let mut t = s.clone();
939        t["proof"][2]["type"] = json!("Ed25519Signature2020");
940        assert!(!verify_set(&t, &ed, Some(&mlp), Some(&slhp)).unwrap());
941        let pv = s["proof"][2]["proofValue"].as_str().unwrap().to_string();
942        let raw = URL_SAFE_NO_PAD.decode(&pv[1..]).unwrap();
943        for bad in [
944            format!("{pv}="),
945            format!("u{}", URL_SAFE_NO_PAD.encode(&raw[..raw.len() - 1])),
946            format!("z{}", bs58::encode(&raw[..64]).into_string()),
947            format!("u{}", "A".repeat(20_000)),
948        ] {
949            let mut t = s.clone();
950            t["proof"][2]["proofValue"] = json!(bad);
951            assert!(verify_set(&t, &ed, Some(&mlp), Some(&slhp)).is_err());
952        }
953    }
954
955    #[test]
956    fn set_shape_and_required_suites() {
957        let (s, _, _, _) = three("did:web:agent.example.com");
958        let p = s["proof"].as_array().unwrap().clone();
959        let shape = |items: Vec<Value>| set_members(&items).map(|m| m.suites());
960        assert_eq!(
961            shape(vec![p[0].clone(), p[2].clone()]),
962            Some(vec![Suite::Eddsa, Suite::Slhdsa128])
963        );
964        assert_eq!(
965            shape(vec![p[2].clone(), p[1].clone(), p[0].clone()]).map(|v| v.len()),
966            Some(3)
967        );
968        // No Ed25519 proof, no post-quantum proof, two of one suite, and an
969        // unknown suite are not proof sets.
970        assert!(shape(vec![p[1].clone(), p[2].clone()]).is_none());
971        assert!(shape(vec![p[0].clone()]).is_none());
972        assert!(shape(vec![p[0].clone(), p[2].clone(), p[2].clone()]).is_none());
973        let mut composite = p[0].clone();
974        composite["cryptosuite"] = json!("hybrid-eddsa-mldsa44-jcs-2026");
975        assert!(shape(vec![p[0].clone(), p[1].clone(), composite.clone()]).is_none());
976        assert_eq!(Suite::of("hybrid-eddsa-mldsa44-jcs-2026"), None);
977        assert!(proof_suites(&json!({ "proof": composite })).is_empty());
978
979        let need = |post_quantum, mldsa44, slhdsa128| Required {
980            post_quantum,
981            mldsa44,
982            slhdsa128,
983        };
984        let (e, m, sl) = (Suite::Eddsa, Suite::Mldsa44, Suite::Slhdsa128);
985        assert!(need(false, false, false).met_by(&[e]));
986        assert!(!need(true, false, false).met_by(&[e]));
987        assert!(need(true, false, false).met_by(&[e, sl]));
988        assert!(!need(false, true, false).met_by(&[e, sl]));
989        assert!(!need(false, false, true).met_by(&[e, m]));
990        assert!(need(true, true, true).met_by(&[e, m, sl]));
991        // The Ed25519 proof is always required.
992        assert!(!need(false, false, false).met_by(&[m, sl]));
993        assert_eq!(
994            Required::default().with(sl).with(e),
995            need(false, false, true)
996        );
997
998        assert_eq!(
999            required_suites_from_json(&json!(["slhdsa128-jcs-2024", "eddsa-jcs-2022"])).unwrap(),
1000            vec![sl, e]
1001        );
1002        for bad in [
1003            json!("mldsa44-jcs-2024"),
1004            json!(["mldsa44-jcs-2026"]),
1005            json!(["hybrid-eddsa-mldsa44-jcs-2026"]),
1006            json!(["mldsa44-jcs-2024", "mldsa44-jcs-2024"]),
1007            json!([7]),
1008        ] {
1009            assert!(required_suites_from_json(&bad).is_err(), "{bad}");
1010        }
1011    }
1012
1013    #[test]
1014    fn a_valid_composite_credential_is_refused() {
1015        // Both signatures in the composite proof are valid; no verifier here
1016        // reads it.
1017        let seed = [4u8; 32];
1018        let ml = MlDsa44KeyPair::generate().unwrap();
1019        let ed = ed25519_public_from_seed(&seed).unwrap();
1020        let composite = composite_for_tests(
1021            &cred(),
1022            &seed,
1023            &ml,
1024            "did:web:agent.example.com#key-1",
1025            "2026-04-26T10:00:00Z",
1026        );
1027        assert!(verify_dual(&composite, &ed, &ml.public_key()).is_err());
1028        assert!(verify_set(&composite, &ed, Some(&ml.public_key()), None).is_err());
1029        assert!(data_integrity::verify_proof(&composite, &ed).is_err());
1030        let opts = crate::delegation::ChainOptions::default();
1031        for key in [Some(&ml.public_key()[..]), None] {
1032            let (r, _) = crate::credentials::verify_with_keys(
1033                &composite,
1034                &ed,
1035                key,
1036                "2026-04-26T10:01:00Z",
1037                30,
1038                &opts,
1039            )
1040            .unwrap();
1041            assert!(!r.proof_valid && r.time_valid);
1042        }
1043        assert_eq!(
1044            crate::decision::read_proofs(&composite, "did:web:agent.example.com", 0, 0).err(),
1045            Some(REASON_UNSUPPORTED_CRYPTOSUITE)
1046        );
1047    }
1048}