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        let sig = ml.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    if let Some(slh) = slhdsa {
302        let mut proof = unsigned_proof(SLHDSA128_CRYPTOSUITE_ID, slh.verification_method, created);
303        let sig = slh.key.sign(&data_integrity::hash_data(&base, &proof)?)?;
304        proof.insert(
305            "proofValue".into(),
306            Value::String(format!("u{}", URL_SAFE_NO_PAD.encode(sig))),
307        );
308        proofs.push(Value::Object(proof));
309    }
310    Ok(Value::Array(proofs))
311}
312
313/// Build a proof set ([`build_proof_set`]) and attach it to the credential
314/// under `proof`, replacing any existing proof.
315pub fn sign_set(
316    credential: &Value,
317    ed25519_seed: &[u8],
318    ed25519_verification_method: &str,
319    mldsa: Option<PqSigner<'_, MlDsa44KeyPair>>,
320    slhdsa: Option<PqSigner<'_, SlhDsa128KeyPair>>,
321    created: &str,
322) -> Result<Value> {
323    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
324    let proof = build_proof_set(
325        credential,
326        ed25519_seed,
327        ed25519_verification_method,
328        mldsa,
329        slhdsa,
330        created,
331    )?;
332    let mut signed = strip_proof(credential)?;
333    signed
334        .as_object_mut()
335        .unwrap()
336        .insert("proof".into(), proof);
337    Ok(signed)
338}
339
340/// Build a dual proof (an array of two proofs, Ed25519 and ML-DSA-44) for
341/// `credential`.
342pub fn build_dual_proof(
343    credential: &Value,
344    ed25519_seed: &[u8],
345    mldsa: &MlDsa44KeyPair,
346    ed25519_verification_method: &str,
347    mldsa_verification_method: &str,
348    created: &str,
349) -> Result<Value> {
350    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
351    build_proof_set(
352        credential,
353        ed25519_seed,
354        ed25519_verification_method,
355        Some(PqSigner {
356            key: mldsa,
357            verification_method: mldsa_verification_method,
358        }),
359        None,
360        created,
361    )
362}
363
364/// Build a dual proof and attach it to the credential under `proof`.
365pub fn sign_dual(
366    credential: &Value,
367    ed25519_seed: &[u8],
368    mldsa: &MlDsa44KeyPair,
369    ed25519_verification_method: &str,
370    mldsa_verification_method: &str,
371    created: &str,
372) -> Result<Value> {
373    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
374    sign_set(
375        credential,
376        ed25519_seed,
377        ed25519_verification_method,
378        Some(PqSigner {
379            key: mldsa,
380            verification_method: mldsa_verification_method,
381        }),
382        None,
383        created,
384    )
385}
386
387/// Decode a multibase base64url ("u") proofValue strictly: no padding,
388/// canonical trailing bits, exactly `expected` bytes.
389fn decode_b64u_proof_value(proof_value: &str, expected: usize, name: &str) -> Result<Vec<u8>> {
390    let body = proof_value.strip_prefix('u').ok_or_else(|| {
391        CoreError::Json(format!("{name} proofValue must be multibase base64url (u)"))
392    })?;
393    // The longest value read is one that could hold the signature: nothing
394    // longer is decoded.
395    if body.len() > expected.div_ceil(3) * 4 {
396        return Err(CoreError::InvalidSignatureLength {
397            expected,
398            got: body.len() / 4 * 3,
399        });
400    }
401    // URL_SAFE_NO_PAD refuses padding and non-canonical trailing bits.
402    let sig = URL_SAFE_NO_PAD
403        .decode(body)
404        .map_err(|e| CoreError::Json(format!("bad base64url proofValue: {e}")))?;
405    if sig.len() != expected {
406        return Err(CoreError::InvalidSignatureLength {
407            expected,
408            got: sig.len(),
409        });
410    }
411    Ok(sig)
412}
413
414/// Decode an ML-DSA-44 proofValue strictly: multibase base64url without
415/// padding ('u'), canonical trailing bits, exactly 2420 bytes.
416pub fn decode_mldsa44_proof_value(proof_value: &str) -> Result<Vec<u8>> {
417    decode_b64u_proof_value(proof_value, MLDSA44_SIG_LEN, "ML-DSA-44")
418}
419
420/// Decode an SLH-DSA-SHA2-128s proofValue strictly: multibase base64url
421/// without padding ('u'), canonical trailing bits, exactly 7856 bytes.
422pub fn decode_slhdsa128_proof_value(proof_value: &str) -> Result<Vec<u8>> {
423    decode_b64u_proof_value(proof_value, SLHDSA128_SIG_LEN, "SLH-DSA")
424}
425
426/// Check one post-quantum member of a set against `base` (the document
427/// without its proof): type "DataIntegrityProof", a strict proofValue, the
428/// document's @context, and the signature over the 64-byte hashData. An
429/// ML-DSA-44 member also verifies over the pre-alignment signing input.
430fn verify_pq_member(base: &Value, proof: &Value, suite: Suite, public: &[u8]) -> Result<bool> {
431    let name = if suite == Suite::Mldsa44 {
432        "ml-dsa"
433    } else {
434        "slh-dsa"
435    };
436    let proof_obj = proof
437        .as_object()
438        .ok_or_else(|| CoreError::Json(format!("{name} proof must be an object")))?;
439    if proof_obj.get("type").and_then(|v| v.as_str()) != Some(PROOF_TYPE) {
440        return Ok(false);
441    }
442    let pv = proof_obj
443        .get("proofValue")
444        .and_then(|v| v.as_str())
445        .ok_or_else(|| CoreError::Json(format!("{name} proof missing proofValue")))?;
446    let sig = match suite {
447        Suite::Mldsa44 => decode_mldsa44_proof_value(pv)?,
448        _ => decode_slhdsa128_proof_value(pv)?,
449    };
450    if !data_integrity::proof_context_matches(base, proof_obj) {
451        return Ok(false);
452    }
453    let mut unsigned = proof_obj.clone();
454    unsigned.remove("proofValue");
455    let signing_input = data_integrity::hash_data(base, &unsigned)?;
456    if suite == Suite::Slhdsa128 {
457        return slh::verify(public, &signing_input, &sig);
458    }
459    if pq::verify(public, &signing_input, &sig)? {
460        return Ok(true);
461    }
462    let legacy = data_integrity::legacy_proof_digest(base, &unsigned)?;
463    pq::verify(public, &legacy, &sig)
464}
465
466/// Which members of a set verified, or None when one did not.
467struct Seen {
468    eddsa: bool,
469    mldsa44: bool,
470    slhdsa128: bool,
471}
472
473fn verify_members(
474    credential: &Value,
475    ed25519_public: &[u8],
476    mldsa_public: Option<&[u8]>,
477    slhdsa_public: Option<&[u8]>,
478    skip_unkeyed: bool,
479) -> Result<Option<Seen>> {
480    let proofs = credential
481        .as_object()
482        .and_then(|o| o.get("proof"))
483        .and_then(|p| p.as_array())
484        .ok_or_else(|| CoreError::Json("dual proof requires a proof array".into()))?;
485    // The array must be a proof set and nothing else: exactly one
486    // `eddsa-jcs-2022` proof, at least one post-quantum proof, at most one of
487    // each post-quantum suite, and no member of any other suite (the v1.6.x
488    // composite included). Anything else is refused before a signature is
489    // checked, so no member is ever left out of the answer.
490    if set_members(proofs).is_none() {
491        return Ok(None);
492    }
493    let base = strip_proof(credential)?;
494    let Some(issuer) = crate::credentials::issuer_did(credential) else {
495        return Ok(None);
496    };
497
498    // Every proof present in the set must verify. A proof that fails fails the
499    // whole set immediately, so a later proof of the same cryptosuite can never
500    // overwrite an earlier failure.
501    let mut seen = Seen {
502        eddsa: false,
503        mldsa44: false,
504        slhdsa128: false,
505    };
506    for p in proofs {
507        if !crate::credentials::proof_bound_to_issuer(p, issuer) {
508            return Ok(None);
509        }
510        match Suite::of_proof(p) {
511            Some(Suite::Eddsa) => {
512                let mut c = base.clone();
513                c.as_object_mut().unwrap().insert("proof".into(), p.clone());
514                if !data_integrity::verify_proof(&c, ed25519_public)? {
515                    return Ok(None);
516                }
517                seen.eddsa = true;
518            }
519            Some(suite) => {
520                // A post-quantum member with no key to check it with fails
521                // the set: a proof this verifier knows is never skipped.
522                let key = if suite == Suite::Mldsa44 {
523                    mldsa_public
524                } else {
525                    slhdsa_public
526                };
527                let Some(key) = key else {
528                    if skip_unkeyed {
529                        continue;
530                    }
531                    return Ok(None);
532                };
533                if !verify_pq_member(&base, p, suite, key)? {
534                    return Ok(None);
535                }
536                if suite == Suite::Mldsa44 {
537                    seen.mldsa44 = true;
538                } else {
539                    seen.slhdsa128 = true;
540                }
541            }
542            // set_members let no other suite through.
543            None => return Ok(None),
544        }
545    }
546    Ok(Some(seen))
547}
548
549/// Verify a proof set with the issuer's keys: the Ed25519 proof and every
550/// post-quantum proof in the array MUST validate. Returns Ok(true) only when
551/// the array is a proof set ([`set_members`]) and every proof in it verified.
552/// A post-quantum proof whose key is not given fails the set. So does an
553/// array that is not a proof set: a member of another cryptosuite (the
554/// v1.6.x composite included), no `eddsa-jcs-2022` proof or more than one,
555/// or two proofs of one post-quantum suite.
556///
557/// Every member of the set must be bound to the credential's issuer
558/// (proofPurpose "assertionMethod" and a verificationMethod of the issuer's
559/// DID). A
560/// post-quantum member must have type "DataIntegrityProof", its cryptosuite
561/// identifier exactly (`mldsa44-jcs-2024`, the pre-alignment
562/// `mldsa44-jcs-2026`, or `slhdsa128-jcs-2024`), and a strict proofValue
563/// ([`decode_mldsa44_proof_value`], [`decode_slhdsa128_proof_value`]).
564pub fn verify_set(
565    credential: &Value,
566    ed25519_public: &[u8],
567    mldsa_public: Option<&[u8]>,
568    slhdsa_public: Option<&[u8]>,
569) -> Result<bool> {
570    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
571    Ok(verify_members(
572        credential,
573        ed25519_public,
574        mldsa_public,
575        slhdsa_public,
576        false,
577    )?
578    .is_some_and(|seen| seen.eddsa && (seen.mldsa44 || seen.slhdsa128)))
579}
580
581/// Verify the members of a proof set a verifier holds keys for: the Ed25519
582/// proof must verify, and so must every post-quantum proof whose key is
583/// given. A post-quantum proof whose key is not given is left unchecked. For
584/// a grant in a delegation chain when post-quantum is not required; a
585/// verifier that requires post-quantum uses [`verify_set`].
586pub fn verify_set_known_keys(
587    credential: &Value,
588    ed25519_public: &[u8],
589    mldsa_public: Option<&[u8]>,
590    slhdsa_public: Option<&[u8]>,
591) -> Result<bool> {
592    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
593    Ok(verify_members(
594        credential,
595        ed25519_public,
596        mldsa_public,
597        slhdsa_public,
598        true,
599    )?
600    .is_some_and(|seen| seen.eddsa))
601}
602
603/// Verify a dual proof: both the Ed25519 and the ML-DSA-44 proofs in the array
604/// MUST validate. Returns Ok(true) only if both are present and valid. A set
605/// that also carries an SLH-DSA proof fails here, because this call has no
606/// key to check it with; use [`verify_set`] for such a set.
607pub fn verify_dual(credential: &Value, ed25519_public: &[u8], mldsa_public: &[u8]) -> Result<bool> {
608    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
609    // Both members of the set must be present, so a credential cannot drop the
610    // post-quantum proof and still be accepted as a proof set.
611    Ok(
612        verify_members(credential, ed25519_public, Some(mldsa_public), None, false)?
613            .is_some_and(|seen| seen.eddsa && seen.mldsa44),
614    )
615}
616
617/// Convenience: derive the Ed25519 public key for a dual self-check.
618pub fn ed25519_public_from_seed(seed: &[u8]) -> Result<[u8; 32]> {
619    Ok(Ed25519KeyPair::from_seed_slice(seed)?.public_key())
620}
621
622/// The v1.6.x composite proof (one proof whose proofValue is
623/// base58btc(ed25519_sig || mldsa44_sig) over the pre-alignment digest), for
624/// tests that check every verifier refuses it. Built only in test builds:
625/// the core has no way to emit this proof.
626#[cfg(test)]
627pub(crate) fn composite_for_tests(
628    credential: &Value,
629    ed25519_seed: &[u8],
630    mldsa: &MlDsa44KeyPair,
631    verification_method: &str,
632    created: &str,
633) -> Value {
634    let base = strip_proof(credential).unwrap();
635    let mut proof = unsigned_proof(
636        "hybrid-eddsa-mldsa44-jcs-2026",
637        verification_method,
638        created,
639    );
640    let digest = data_integrity::legacy_proof_digest(&base, &proof).unwrap();
641    let mut combined = Ed25519KeyPair::from_seed_slice(ed25519_seed)
642        .unwrap()
643        .sign(&digest)
644        .to_vec();
645    combined.extend_from_slice(&mldsa.sign(&digest).unwrap());
646    proof.insert(
647        "proofValue".into(),
648        Value::String(format!("z{}", bs58::encode(combined).into_string())),
649    );
650    let mut signed = base;
651    signed["proof"] = Value::Object(proof);
652    signed
653}
654
655// What the no_std depth guard checks in the JSON these types carry.
656crate::nesting::nested_fields!(SetMembers<'_>; eddsa, mldsa44, slhdsa128);
657
658#[cfg(test)]
659mod tests {
660    use super::*;
661    use serde_json::json;
662
663    fn cred() -> Value {
664        json!({
665            "@context": ["https://www.w3.org/ns/credentials/v2"],
666            "type": ["VerifiableCredential", "VouchCredential"],
667            "issuer": "did:web:agent.example.com",
668            "validFrom": "2026-04-26T10:00:00Z",
669            "validUntil": "2026-04-26T10:05:00Z",
670            "credentialSubject": { "id": "did:web:agent.example.com", "vouchVersion": "1.0",
671                "intent": { "action": "read", "target": "t", "resource": "https://api/x" } }
672        })
673    }
674
675    #[test]
676    #[cfg_attr(not(feature = "std"), ignore = "needs a random source (std)")]
677    fn dual_proof_roundtrip() {
678        let seed = [4u8; 32];
679        let ml = MlDsa44KeyPair::generate().unwrap();
680        let signed = sign_dual(
681            &cred(),
682            &seed,
683            &ml,
684            "did:web:agent.example.com#key-1",
685            "did:web:agent.example.com#key-2",
686            "2026-04-26T10:00:00Z",
687        )
688        .unwrap();
689        assert!(signed["proof"].is_array());
690        let ed_pub = ed25519_public_from_seed(&seed).unwrap();
691        assert!(verify_dual(&signed, &ed_pub, &ml.public_key()).unwrap());
692    }
693
694    #[test]
695    #[cfg_attr(not(feature = "std"), ignore = "needs a random source (std)")]
696    fn dual_proof_tamper_fails() {
697        let seed = [4u8; 32];
698        let ml = MlDsa44KeyPair::generate().unwrap();
699        let mut 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        signed["credentialSubject"]["intent"]["action"] = json!("delete");
709        let ed_pub = ed25519_public_from_seed(&seed).unwrap();
710        assert!(!verify_dual(&signed, &ed_pub, &ml.public_key()).unwrap());
711    }
712
713    /// A failing proof cannot be masked by appending a second, valid proof of
714    /// the same cryptosuite after it.
715    #[test]
716    #[cfg_attr(not(feature = "std"), ignore = "needs a random source (std)")]
717    fn appended_valid_proof_cannot_mask_a_failing_one() {
718        let seed = [4u8; 32];
719        let ml = MlDsa44KeyPair::generate().unwrap();
720        let signed = sign_dual(
721            &cred(),
722            &seed,
723            &ml,
724            "did:web:agent.example.com#key-1",
725            "did:web:agent.example.com#key-2",
726            "2026-04-26T10:00:00Z",
727        )
728        .unwrap();
729        let ed_pub = ed25519_public_from_seed(&seed).unwrap();
730        let proofs = signed["proof"].as_array().unwrap().clone();
731
732        // Corrupt the classical proof, then append the untouched valid one.
733        let mut broken = proofs[0].clone();
734        broken["proofValue"] = json!("z2SkKQBFXKcxxHbEnDaZjXPRWzHnbe1ZgArebQmqQ1Rf6H3nJa4vp3rzYaC5nnrFVFTL6wPMuJUAQGf7oEENy4vX");
735
736        let mut attacked = signed.clone();
737        attacked["proof"] = json!([broken, proofs[0].clone(), proofs[1].clone()]);
738        assert!(
739            !verify_dual(&attacked, &ed_pub, &ml.public_key()).unwrap(),
740            "a failing proof must fail the set even when a valid proof follows it"
741        );
742    }
743
744    /// The set primitives refuse an array that is not a proof set, whatever
745    /// its good members say: a member of another cryptosuite, the v1.6.x
746    /// composite, no `eddsa-jcs-2022` proof or two of them, or two proofs of
747    /// one post-quantum suite.
748    #[test]
749    #[cfg_attr(not(feature = "std"), ignore = "needs a random source (std)")]
750    fn an_array_that_is_not_a_proof_set_is_refused() {
751        let seed = [4u8; 32];
752        let ml = MlDsa44KeyPair::generate().unwrap();
753        let vm = "did:web:agent.example.com#key-1";
754        let created = "2026-04-26T10:00:00Z";
755        let signed = sign_dual(
756            &cred(),
757            &seed,
758            &ml,
759            vm,
760            "did:web:agent.example.com#key-2",
761            created,
762        )
763        .unwrap();
764        let ed_pub = ed25519_public_from_seed(&seed).unwrap();
765        let ml_pub = ml.public_key();
766        let proofs = signed["proof"].as_array().unwrap().clone();
767        let (ed_proof, ml_proof) = (proofs[0].clone(), proofs[1].clone());
768        assert!(verify_dual(&signed, &ed_pub, &ml_pub).unwrap());
769
770        let mut future = ed_proof.clone();
771        future["cryptosuite"] = json!("some-unregistered-suite-2030");
772        // A composite proof with two valid signatures inside.
773        let composite = composite_for_tests(&cred(), &seed, &ml, vm, created)["proof"].clone();
774        // The pre-alignment identifier is ML-DSA-44 too, so it is a second
775        // proof of that suite.
776        let mut legacy_ml = ml_proof.clone();
777        legacy_ml["cryptosuite"] = json!(MLDSA44_LEGACY_CRYPTOSUITE_ID);
778
779        let cases: Vec<(&str, Value)> = vec![
780            (
781                "a member of an unknown suite",
782                json!([ed_proof, ml_proof, future]),
783            ),
784            (
785                "an unknown suite in place of the post-quantum proof",
786                json!([ed_proof, future]),
787            ),
788            ("a composite member", json!([ed_proof, ml_proof, composite])),
789            (
790                "a composite member first",
791                json!([composite, ed_proof, ml_proof]),
792            ),
793            ("no eddsa-jcs-2022 proof", json!([ml_proof])),
794            (
795                "two eddsa-jcs-2022 proofs",
796                json!([ed_proof, ed_proof, ml_proof]),
797            ),
798            (
799                "two ML-DSA-44 proofs",
800                json!([ed_proof, ml_proof, ml_proof]),
801            ),
802            (
803                "two ML-DSA-44 proofs under both identifiers",
804                json!([ed_proof, ml_proof, legacy_ml]),
805            ),
806            (
807                "a member that is not an object",
808                json!([ed_proof, ml_proof, "x"]),
809            ),
810            ("an empty array", json!([])),
811        ];
812        for (name, proof) in cases {
813            let mut c = signed.clone();
814            c["proof"] = proof;
815            assert!(!verify_dual(&c, &ed_pub, &ml_pub).unwrap(), "{name}");
816            assert!(
817                !verify_set(&c, &ed_pub, Some(&ml_pub), None).unwrap(),
818                "{name}"
819            );
820            assert!(
821                !verify_set_known_keys(&c, &ed_pub, Some(&ml_pub), None).unwrap(),
822                "{name}"
823            );
824            // With no post-quantum key the lenient form checks the Ed25519
825            // proof alone, and still refuses the array.
826            assert!(
827                !verify_set_known_keys(&c, &ed_pub, None, None).unwrap(),
828                "{name}"
829            );
830        }
831    }
832
833    #[test]
834    #[cfg_attr(not(feature = "std"), ignore = "needs a random source (std)")]
835    fn proof_set_without_the_post_quantum_member_fails() {
836        let seed = [4u8; 32];
837        let ml = MlDsa44KeyPair::generate().unwrap();
838        let signed = sign_dual(
839            &cred(),
840            &seed,
841            &ml,
842            "did:web:agent.example.com#key-1",
843            "did:web:agent.example.com#key-2",
844            "2026-04-26T10:00:00Z",
845        )
846        .unwrap();
847        let ed_pub = ed25519_public_from_seed(&seed).unwrap();
848        let classical_only = signed["proof"].as_array().unwrap()[0].clone();
849
850        let mut stripped = signed.clone();
851        stripped["proof"] = json!([classical_only]);
852        assert!(!verify_dual(&stripped, &ed_pub, &ml.public_key()).unwrap());
853    }
854
855    fn signed(vm_ed: &str, vm_ml: &str) -> (Value, [u8; 32], MlDsa44KeyPair) {
856        let seed = [4u8; 32];
857        let ml = MlDsa44KeyPair::generate().unwrap();
858        let signed = sign_dual(&cred(), &seed, &ml, vm_ed, vm_ml, "2026-04-26T10:00:00Z").unwrap();
859        (signed, ed25519_public_from_seed(&seed).unwrap(), ml)
860    }
861
862    #[test]
863    #[cfg_attr(not(feature = "std"), ignore = "needs a random source (std)")]
864    fn every_member_must_be_bound_to_the_issuer() {
865        let (s, ed, ml) = signed(
866            "did:web:agent.example.com#key-1",
867            "did:web:other.example.com#key-2",
868        );
869        assert!(!verify_dual(&s, &ed, &ml.public_key()).unwrap());
870        // An unknown extra member that names another DID also fails the set.
871        let (s, ed, ml) = signed(
872            "did:web:agent.example.com#key-1",
873            "did:web:agent.example.com#key-2",
874        );
875        let mut extra = s["proof"][0].clone();
876        extra["cryptosuite"] = json!("some-unregistered-suite-2030");
877        extra["verificationMethod"] = json!("did:web:someone-else.example#key-1");
878        let mut set = s.clone();
879        set["proof"].as_array_mut().unwrap().push(extra);
880        assert!(!verify_dual(&set, &ed, &ml.public_key()).unwrap());
881    }
882
883    #[test]
884    #[cfg_attr(not(feature = "std"), ignore = "needs a random source (std)")]
885    fn mldsa_member_type_and_proof_value_are_strict() {
886        let (s, ed, ml) = signed(
887            "did:web:agent.example.com#key-1",
888            "did:web:agent.example.com#key-2",
889        );
890        let pk = ml.public_key();
891        assert!(verify_dual(&s, &ed, &pk).unwrap());
892        let mut t = s.clone();
893        t["proof"][1]["type"] = json!("Ed25519Signature2020");
894        assert!(!verify_dual(&t, &ed, &pk).unwrap());
895        let mut t = s.clone();
896        t["proof"][1]["cryptosuite"] = json!("MLDSA44-JCS-2024");
897        assert!(
898            !verify_dual(&t, &ed, &pk).unwrap(),
899            "case-changed suite is not ML-DSA"
900        );
901        let pv = s["proof"][1]["proofValue"].as_str().unwrap().to_string();
902        let raw = URL_SAFE_NO_PAD.decode(&pv[1..]).unwrap();
903        // base58btc instead of base64url, padding, a short signature.
904        for bad in [
905            format!("z{}", bs58::encode(&raw).into_string()),
906            format!("{pv}=="),
907            format!("u{}", URL_SAFE_NO_PAD.encode(&raw[..2419])),
908        ] {
909            let mut t = s.clone();
910            t["proof"][1]["proofValue"] = json!(bad);
911            assert!(verify_dual(&t, &ed, &pk).is_err());
912        }
913        assert!(decode_mldsa44_proof_value(&pv).is_ok());
914    }
915
916    fn three(vm: &str) -> (Value, [u8; 32], MlDsa44KeyPair, SlhDsa128KeyPair) {
917        let seed = [4u8; 32];
918        let ml = MlDsa44KeyPair::generate().unwrap();
919        let slh_key = SlhDsa128KeyPair::generate().unwrap();
920        let signed = sign_set(
921            &cred(),
922            &seed,
923            &format!("{vm}#key-1"),
924            Some(PqSigner {
925                key: &ml,
926                verification_method: &format!("{vm}#key-2"),
927            }),
928            Some(PqSigner {
929                key: &slh_key,
930                verification_method: &format!("{vm}#key-3"),
931            }),
932            "2026-04-26T10:00:00Z",
933        )
934        .unwrap();
935        (
936            signed,
937            ed25519_public_from_seed(&seed).unwrap(),
938            ml,
939            slh_key,
940        )
941    }
942
943    #[test]
944    #[cfg_attr(not(feature = "std"), ignore = "needs a random source (std)")]
945    fn a_set_of_three_needs_every_key_and_every_proof() {
946        let (s, ed, ml, slh_key) = three("did:web:agent.example.com");
947        let (mlp, slhp) = (ml.public_key(), slh_key.public_key());
948        assert_eq!(
949            proof_suites(&s),
950            [Suite::Eddsa, Suite::Mldsa44, Suite::Slhdsa128]
951        );
952        assert!(verify_set(&s, &ed, Some(&mlp), Some(&slhp)).unwrap());
953        // A post-quantum proof with no key to check it fails the set.
954        assert!(!verify_set(&s, &ed, Some(&mlp), None).unwrap());
955        assert!(!verify_set(&s, &ed, None, Some(&slhp)).unwrap());
956        assert!(!verify_dual(&s, &ed, &mlp).unwrap());
957        // Another key pair's SLH-DSA key, and a changed document.
958        let other = SlhDsa128KeyPair::generate().unwrap().public_key();
959        assert!(!verify_set(&s, &ed, Some(&mlp), Some(&other)).unwrap());
960        let mut t = s.clone();
961        t["credentialSubject"]["intent"]["action"] = json!("delete");
962        assert!(!verify_set(&t, &ed, Some(&mlp), Some(&slhp)).unwrap());
963        // The SLH-DSA member's type, suite spelling and proofValue are strict.
964        let mut t = s.clone();
965        t["proof"][2]["type"] = json!("Ed25519Signature2020");
966        assert!(!verify_set(&t, &ed, Some(&mlp), Some(&slhp)).unwrap());
967        let pv = s["proof"][2]["proofValue"].as_str().unwrap().to_string();
968        let raw = URL_SAFE_NO_PAD.decode(&pv[1..]).unwrap();
969        for bad in [
970            format!("{pv}="),
971            format!("u{}", URL_SAFE_NO_PAD.encode(&raw[..raw.len() - 1])),
972            format!("z{}", bs58::encode(&raw[..64]).into_string()),
973            format!("u{}", "A".repeat(20_000)),
974        ] {
975            let mut t = s.clone();
976            t["proof"][2]["proofValue"] = json!(bad);
977            assert!(verify_set(&t, &ed, Some(&mlp), Some(&slhp)).is_err());
978        }
979    }
980
981    #[test]
982    #[cfg_attr(not(feature = "std"), ignore = "needs a random source (std)")]
983    fn set_shape_and_required_suites() {
984        let (s, _, _, _) = three("did:web:agent.example.com");
985        let p = s["proof"].as_array().unwrap().clone();
986        let shape = |items: Vec<Value>| set_members(&items).map(|m| m.suites());
987        assert_eq!(
988            shape(vec![p[0].clone(), p[2].clone()]),
989            Some(vec![Suite::Eddsa, Suite::Slhdsa128])
990        );
991        assert_eq!(
992            shape(vec![p[2].clone(), p[1].clone(), p[0].clone()]).map(|v| v.len()),
993            Some(3)
994        );
995        // No Ed25519 proof, no post-quantum proof, two of one suite, and an
996        // unknown suite are not proof sets.
997        assert!(shape(vec![p[1].clone(), p[2].clone()]).is_none());
998        assert!(shape(vec![p[0].clone()]).is_none());
999        assert!(shape(vec![p[0].clone(), p[2].clone(), p[2].clone()]).is_none());
1000        let mut composite = p[0].clone();
1001        composite["cryptosuite"] = json!("hybrid-eddsa-mldsa44-jcs-2026");
1002        assert!(shape(vec![p[0].clone(), p[1].clone(), composite.clone()]).is_none());
1003        assert_eq!(Suite::of("hybrid-eddsa-mldsa44-jcs-2026"), None);
1004        assert!(proof_suites(&json!({ "proof": composite })).is_empty());
1005
1006        let need = |post_quantum, mldsa44, slhdsa128| Required {
1007            post_quantum,
1008            mldsa44,
1009            slhdsa128,
1010        };
1011        let (e, m, sl) = (Suite::Eddsa, Suite::Mldsa44, Suite::Slhdsa128);
1012        assert!(need(false, false, false).met_by(&[e]));
1013        assert!(!need(true, false, false).met_by(&[e]));
1014        assert!(need(true, false, false).met_by(&[e, sl]));
1015        assert!(!need(false, true, false).met_by(&[e, sl]));
1016        assert!(!need(false, false, true).met_by(&[e, m]));
1017        assert!(need(true, true, true).met_by(&[e, m, sl]));
1018        // The Ed25519 proof is always required.
1019        assert!(!need(false, false, false).met_by(&[m, sl]));
1020        assert_eq!(
1021            Required::default().with(sl).with(e),
1022            need(false, false, true)
1023        );
1024
1025        assert_eq!(
1026            required_suites_from_json(&json!(["slhdsa128-jcs-2024", "eddsa-jcs-2022"])).unwrap(),
1027            vec![sl, e]
1028        );
1029        for bad in [
1030            json!("mldsa44-jcs-2024"),
1031            json!(["mldsa44-jcs-2026"]),
1032            json!(["hybrid-eddsa-mldsa44-jcs-2026"]),
1033            json!(["mldsa44-jcs-2024", "mldsa44-jcs-2024"]),
1034            json!([7]),
1035        ] {
1036            assert!(required_suites_from_json(&bad).is_err(), "{bad}");
1037        }
1038    }
1039
1040    #[test]
1041    #[cfg_attr(not(feature = "std"), ignore = "needs a random source (std)")]
1042    fn a_valid_composite_credential_is_refused() {
1043        // Both signatures in the composite proof are valid; no verifier here
1044        // reads it.
1045        let seed = [4u8; 32];
1046        let ml = MlDsa44KeyPair::generate().unwrap();
1047        let ed = ed25519_public_from_seed(&seed).unwrap();
1048        let composite = composite_for_tests(
1049            &cred(),
1050            &seed,
1051            &ml,
1052            "did:web:agent.example.com#key-1",
1053            "2026-04-26T10:00:00Z",
1054        );
1055        assert!(verify_dual(&composite, &ed, &ml.public_key()).is_err());
1056        assert!(verify_set(&composite, &ed, Some(&ml.public_key()), None).is_err());
1057        assert!(data_integrity::verify_proof(&composite, &ed).is_err());
1058        let opts = crate::delegation::ChainOptions::default();
1059        for key in [Some(&ml.public_key()[..]), None] {
1060            let (r, _) = crate::credentials::verify_with_keys(
1061                &composite,
1062                &ed,
1063                key,
1064                "2026-04-26T10:01:00Z",
1065                30,
1066                &opts,
1067            )
1068            .unwrap();
1069            assert!(!r.proof_valid && r.time_valid);
1070        }
1071        assert_eq!(
1072            crate::decision::read_proofs(&composite, "did:web:agent.example.com", 0, 0).err(),
1073            Some(REASON_UNSUPPORTED_CRYPTOSUITE)
1074        );
1075    }
1076}