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