Skip to main content

vouch_core/
proof_json.rs

1//! Data Integrity proofs and key formats for the language SDKs, as JSON.
2//!
3//! The Python reference's `vouch.crypto` primitives (`data_integrity`,
4//! `data_integrity_hybrid`, `multikey`, `ed25519_check`, `mldsa_check`),
5//! once, with the reference's behavior: the same checks in the same order,
6//! the same answer (a verdict, or a refusal with the reference's text). The
7//! language SDKs keep only key objects and the Ed25519 / ML-DSA / SLH-DSA
8//! signing calls; the signing input, the proof shape, the proofValue
9//! encodings, the strict key and signature rules and every verification run
10//! here.
11//!
12//! These are the primitives: a proof is checked against the key the caller
13//! names, with no issuer binding. The verifier's decision
14//! ([`crate::decision`]) adds the binding.
15//!
16//! One entry, [`rules_json`], `{"op": ...}` in, JSON out; bytes are standard
17//! base64. A refusal is an `Err`: [`CoreError::Crypto`] for a key or
18//! signature the strict Ed25519 rules refuse (the reference's
19//! `WeakKeyError`), [`CoreError::Json`] for anything else (`ValueError`).
20
21#[allow(unused_imports)]
22use crate::prelude::*;
23
24use base64::{
25    engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD},
26    Engine,
27};
28use serde_json::{json, Map, Value};
29use sha2::{Digest, Sha256};
30
31use crate::data_integrity::{self, CRYPTOSUITE_ID as EDDSA, PROOF_TYPE};
32use crate::error::{CoreError, Result};
33use crate::hybrid::MLDSA44_LEGACY_CRYPTOSUITE_ID as MLDSA44_LEGACY;
34use crate::hybrid::{MLDSA44_CRYPTOSUITE_ID as MLDSA44, SLHDSA128_CRYPTOSUITE_ID as SLHDSA128};
35use crate::multikey;
36
37pub const ED25519_SIGNATURE_SIZE: usize = 64;
38pub const MLDSA44_SIGNATURE_SIZE: usize = 2420;
39pub const MLDSA44_PUBLIC_KEY_SIZE: usize = 1312;
40pub const SLHDSA128_SIGNATURE_SIZE: usize = 7856;
41pub const SLHDSA128_PUBLIC_KEY_SIZE: usize = 32;
42/// The cryptosuites a proof set can carry, in the order they are written.
43/// The most bytes base58Encode writes (an SLH-DSA signature is 7,856).
44pub const MAX_BASE58_ENCODE_BYTES: usize = 8192;
45pub const PROOF_SET_SUITES: [&str; 3] = [EDDSA, MLDSA44, SLHDSA128];
46const SLHDSA128_ALG: &str = multikey::SLHDSA128;
47
48/// The Ed25519 group order L, little-endian (from
49/// test-vectors/ed25519-strict/vector.json, field "l").
50const GROUP_ORDER_LE: [u8; 32] = [
51    0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14,
52    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10,
53];
54
55fn value_error(msg: impl Into<String>) -> CoreError {
56    CoreError::Json(msg.into())
57}
58
59fn weak(msg: impl Into<String>) -> CoreError {
60    CoreError::Crypto(msg.into())
61}
62
63/// Python's `str()` of a JSON value: text as it is, anything else as `repr`.
64fn py_str(v: Option<&Value>) -> String {
65    match v {
66        Some(Value::String(s)) => s.clone(),
67        other => crate::grant_chain::py_repr(other),
68    }
69}
70
71// ---------------------------------------------------------------------------
72// Strict Ed25519 (vouch.crypto.ed25519_check)
73// ---------------------------------------------------------------------------
74
75/// Why a 32-byte encoding is refused as a point (`what` names it in the
76/// text): y not below p, or a point of small order. None when neither.
77fn point_encoding_problem(encoded: &[u8; 32], what: &str) -> Option<String> {
78    if !crate::keys::is_canonical_point_encoding(encoded) {
79        return Some(format!("{what} is not a canonical encoding"));
80    }
81    // A point on the curve decodes; a small-order one is weak. (An encoding
82    // off the curve is not of small order: the public key check names it.)
83    match ed25519_dalek::VerifyingKey::from_bytes(encoded) {
84        Ok(point) if point.is_weak() => Some(format!("{what} is a small-order point")),
85        _ => None,
86    }
87}
88
89/// Why the strict rules refuse an Ed25519 public key, or None: not 32
90/// bytes, y >= p, a point of small order, or not a point on the curve.
91pub fn ed25519_public_key_problem(raw: &[u8]) -> Option<String> {
92    let Ok(encoded) = <[u8; 32]>::try_from(raw) else {
93        return Some("Ed25519 public key must be 32 bytes".into());
94    };
95    if let Some(problem) = point_encoding_problem(&encoded, "Ed25519 public key") {
96        return Some(problem);
97    }
98    if ed25519_dalek::VerifyingKey::from_bytes(&encoded).is_err() {
99        return Some("Ed25519 public key is not a point on the curve".into());
100    }
101    None
102}
103
104/// Why the strict rules refuse a 64-byte Ed25519 signature, or None: R not
105/// canonical or of small order, or S not below the group order L.
106pub fn ed25519_signature_problem(signature: &[u8]) -> Option<String> {
107    if signature.len() != ED25519_SIGNATURE_SIZE {
108        return Some("Ed25519 signature must be 64 bytes".into());
109    }
110    let mut r = [0u8; 32];
111    r.copy_from_slice(&signature[..32]);
112    if let Some(problem) = point_encoding_problem(&r, "Ed25519 signature R") {
113        return Some(problem);
114    }
115    // S as a little-endian number, compared with L from the top byte down.
116    let s = &signature[32..];
117    for i in (0..32).rev() {
118        if s[i] != GROUP_ORDER_LE[i] {
119            return (s[i] > GROUP_ORDER_LE[i])
120                .then(|| "Ed25519 signature S is not below the group order".into());
121        }
122    }
123    Some("Ed25519 signature S is not below the group order".into())
124}
125
126fn check_public_key(raw: &[u8]) -> Result<()> {
127    ed25519_public_key_problem(raw).map_or(Ok(()), |p| Err(weak(p)))
128}
129
130// ---------------------------------------------------------------------------
131// base58btc and base64url, with the reference's refusals
132// ---------------------------------------------------------------------------
133
134const B58_ALPHABET: &str = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
135
136fn b58decode(s: &str) -> Result<Vec<u8>> {
137    if s.chars().count() > multikey::MAX_BASE58_LEN {
138        return Err(value_error(format!(
139            "base58 value is longer than {} characters",
140            multikey::MAX_BASE58_LEN
141        )));
142    }
143    if let Some(bad) = s.chars().find(|c| !B58_ALPHABET.contains(*c)) {
144        return Err(value_error(format!(
145            "Invalid base58 character: {}",
146            crate::grant_chain::py_repr_str(&bad.to_string())
147        )));
148    }
149    if s.is_empty() {
150        return Ok(Vec::new());
151    }
152    multikey::decode_base58_bounded(s)
153}
154
155fn b58decode_exact(s: &str, size: usize) -> Result<Vec<u8>> {
156    let decoded = b58decode(s)?;
157    if decoded.len() != size {
158        return Err(value_error(format!(
159            "base58 value decodes to {} bytes, expected {size}",
160            decoded.len()
161        )));
162    }
163    Ok(decoded)
164}
165
166fn is_b64u_body(body: &str) -> bool {
167    body.bytes()
168        .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
169}
170
171/// The base64url text (no padding) of `n` bytes is this long.
172const fn b64u_len(n: usize) -> usize {
173    (n * 4).div_ceil(3)
174}
175
176// ---------------------------------------------------------------------------
177// proofValue encodings
178// ---------------------------------------------------------------------------
179
180/// The 64-byte Ed25519 signature in an eddsa-jcs-2022 proofValue: base58btc
181/// ("z"), exactly 64 bytes, and a signature the strict rules accept.
182pub fn decode_eddsa_proof_value(proof_value: Option<&Value>) -> Result<Vec<u8>> {
183    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); proof_value);
184    let Some(text) = proof_value
185        .and_then(Value::as_str)
186        .filter(|t| t.starts_with('z'))
187    else {
188        return Err(value_error("Missing or malformed proofValue"));
189    };
190    let signature = b58decode_exact(&text[1..], ED25519_SIGNATURE_SIZE)?;
191    if let Some(problem) = ed25519_signature_problem(&signature) {
192        return Err(weak(problem));
193    }
194    Ok(signature)
195}
196
197/// A post-quantum proofValue: base64url without padding ("u"), exactly the
198/// length the signature encodes to, canonical trailing bits.
199fn decode_pq_proof_value(
200    proof_value: Option<&Value>,
201    size: usize,
202    short: &str,
203    long: &str,
204) -> Result<Vec<u8>> {
205    let text = match proof_value {
206        Some(Value::String(t)) if !t.is_empty() => t,
207        _ => return Err(value_error(format!("{short} proof missing proofValue"))),
208    };
209    let Some(body) = text.strip_prefix('u') else {
210        return Err(value_error(format!(
211            "an {long} proofValue is multibase base64url (u)"
212        )));
213    };
214    if body.len() != b64u_len(size) || !is_b64u_body(body) {
215        return Err(value_error(format!(
216            "{long} proofValue is not a {size}-byte base64url value"
217        )));
218    }
219    match URL_SAFE_NO_PAD.decode(body) {
220        Ok(sig) if sig.len() == size => Ok(sig),
221        _ => Err(value_error(format!(
222            "{long} proofValue is not canonical base64url"
223        ))),
224    }
225}
226
227pub fn decode_mldsa44_proof_value(proof_value: Option<&Value>) -> Result<Vec<u8>> {
228    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); proof_value);
229    decode_pq_proof_value(proof_value, MLDSA44_SIGNATURE_SIZE, "ML-DSA", "ML-DSA-44")
230}
231
232pub fn decode_slhdsa128_proof_value(proof_value: Option<&Value>) -> Result<Vec<u8>> {
233    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); proof_value);
234    decode_pq_proof_value(proof_value, SLHDSA128_SIGNATURE_SIZE, "SLH-DSA", "SLH-DSA")
235}
236
237// ---------------------------------------------------------------------------
238// The signing input
239// ---------------------------------------------------------------------------
240
241fn object<'a>(v: &'a Value, what: &str) -> Result<&'a Map<String, Value>> {
242    v.as_object()
243        .ok_or_else(|| value_error(format!("{what} must be a JSON object")))
244}
245
246/// The document with no `proof` member.
247pub fn unsecured_document(document: &Value) -> Result<Value> {
248    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); document);
249    let mut doc = object(document, "credential")?.clone();
250    doc.remove("proof");
251    Ok(Value::Object(doc))
252}
253
254/// A proof carrying an `@context` that is not the document's is refused.
255fn check_proof_context(document: &Value, proof: &Map<String, Value>) -> Result<()> {
256    // A document with no @context reads as null, as the reference's
257    // `document.get("@context")` does.
258    match proof.get("@context") {
259        Some(ctx) if document.get("@context").unwrap_or(&Value::Null) != ctx => Err(value_error(
260            "the proof's @context is not the document's @context",
261        )),
262        _ => Ok(()),
263    }
264}
265
266/// The 64-byte Data Integrity signing input of `document` under the unsigned
267/// `proof` (its proofValue, if any, left out).
268pub fn hash_data(document: &Value, proof: &Map<String, Value>) -> Result<[u8; 64]> {
269    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); document, proof);
270    let base = unsecured_document(document)?;
271    check_proof_context(&base, proof)?;
272    data_integrity::hash_data(&base, proof)
273}
274
275/// The pre-alignment signing input (one SHA-256 over the document with the
276/// unsigned proof attached).
277pub fn legacy_digest(document: &Value, proof: &Map<String, Value>) -> Result<[u8; 32]> {
278    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); document, proof);
279    object(document, "credential")?;
280    let mut unsigned = proof.clone();
281    unsigned.remove("proofValue");
282    data_integrity::legacy_proof_digest(document, &unsigned)
283}
284
285fn unsigned_proof(
286    cryptosuite: &str,
287    created: &str,
288    verification_method: &str,
289    proof_purpose: &str,
290) -> Map<String, Value> {
291    let mut proof = Map::new();
292    proof.insert("type".into(), PROOF_TYPE.into());
293    proof.insert("cryptosuite".into(), cryptosuite.into());
294    proof.insert("created".into(), created.into());
295    proof.insert("verificationMethod".into(), verification_method.into());
296    proof.insert("proofPurpose".into(), proof_purpose.into());
297    proof
298}
299
300/// Attach a signature to an unsigned proof of its cryptosuite: base58btc
301/// for Ed25519, base64url for ML-DSA-44 and SLH-DSA-SHA2-128s.
302pub fn attach(proof: &Map<String, Value>, signature: &[u8]) -> Result<Value> {
303    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); proof);
304    let suite = proof
305        .get("cryptosuite")
306        .and_then(Value::as_str)
307        .unwrap_or("");
308    let value = match suite {
309        EDDSA => {
310            if signature.len() != ED25519_SIGNATURE_SIZE {
311                return Err(value_error(
312                    "the signing backend returned no valid Ed25519 signature",
313                ));
314            }
315            format!("z{}", bs58::encode(signature).into_string())
316        }
317        MLDSA44 | SLHDSA128 => {
318            let (size, name) = if suite == MLDSA44 {
319                (MLDSA44_SIGNATURE_SIZE, "ML-DSA-44")
320            } else {
321                (SLHDSA128_SIGNATURE_SIZE, "SLH-DSA")
322            };
323            if signature.len() != size {
324                return Err(value_error(format!(
325                    "unexpected {name} sig size {}, want {size}",
326                    signature.len()
327                )));
328            }
329            format!("u{}", URL_SAFE_NO_PAD.encode(signature))
330        }
331        other => {
332            return Err(value_error(format!(
333                "no proof of cryptosuite {}",
334                crate::grant_chain::py_repr_str(other)
335            )))
336        }
337    };
338    let mut out = proof.clone();
339    out.insert("proofValue".into(), Value::String(value));
340    Ok(Value::Object(out))
341}
342
343// ---------------------------------------------------------------------------
344// Verification (the reference's primitives: no issuer binding)
345// ---------------------------------------------------------------------------
346
347/// Verify the single eddsa-jcs-2022 proof of `document` with `public_key`.
348/// Ok(false) is a signature that does not verify; Err is a malformed proof
349/// or a key or signature the strict rules refuse. The pre-alignment signing
350/// input is accepted too.
351pub fn verify_eddsa(document: &Value, public_key: &[u8]) -> Result<bool> {
352    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); document);
353    let proof = document
354        .get("proof")
355        .and_then(Value::as_object)
356        .ok_or_else(|| value_error("Credential has no proof object"))?;
357    if proof.get("type").and_then(Value::as_str) != Some(PROOF_TYPE) {
358        return Err(value_error(format!(
359            "Unexpected proof type: {}",
360            py_str(proof.get("type"))
361        )));
362    }
363    if proof.get("cryptosuite").and_then(Value::as_str) != Some(EDDSA) {
364        return Err(value_error(format!(
365            "Unexpected cryptosuite: {}",
366            py_str(proof.get("cryptosuite"))
367        )));
368    }
369    let signature = decode_eddsa_proof_value(proof.get("proofValue"))?;
370    check_public_key(public_key)?;
371    let mut unsigned = proof.clone();
372    unsigned.remove("proofValue");
373    let base = unsecured_document(document)?;
374    check_proof_context(&base, &unsigned)?;
375    if crate::keys::verify(public_key, &hash_data(document, &unsigned)?, &signature)? {
376        return Ok(true);
377    }
378    crate::keys::verify(public_key, &legacy_digest(document, &unsigned)?, &signature)
379}
380
381/// The suites of a document's proof as a verifier counts them: one
382/// eddsa-jcs-2022 proof object is that suite; a proof set (exactly one
383/// eddsa-jcs-2022 proof, at least one post-quantum proof, at most one of
384/// each) is its members' suites in [`PROOF_SET_SUITES`] order; else none.
385pub fn proof_suites(document: &Value) -> Vec<&'static str> {
386    crate::nesting::deep_guard!(Vec::new(); document);
387    match document.get("proof") {
388        Some(Value::Object(p)) => {
389            if p.get("cryptosuite").and_then(Value::as_str) == Some(EDDSA) {
390                vec![EDDSA]
391            } else {
392                Vec::new()
393            }
394        }
395        Some(Value::Array(items)) => {
396            let mut found: Vec<&'static str> = Vec::new();
397            for member in items {
398                let suite = member.get("cryptosuite").and_then(Value::as_str);
399                let suite = match suite {
400                    Some(MLDSA44_LEGACY) => Some(MLDSA44),
401                    other => other,
402                };
403                let Some(known) = suite.and_then(|s| PROOF_SET_SUITES.iter().find(|k| **k == s))
404                else {
405                    return Vec::new();
406                };
407                if found.contains(known) {
408                    return Vec::new();
409                }
410                found.push(known);
411            }
412            if !found.contains(&EDDSA) || found.len() < 2 {
413                return Vec::new();
414            }
415            PROOF_SET_SUITES
416                .iter()
417                .copied()
418                .filter(|s| found.contains(s))
419                .collect()
420        }
421        _ => Vec::new(),
422    }
423}
424
425/// Which members of a proof set verified.
426#[derive(Default)]
427struct Seen {
428    eddsa: bool,
429    mldsa44: bool,
430    slhdsa128: bool,
431}
432
433fn verify_pq(
434    base: &Value,
435    proof: &Map<String, Value>,
436    public_key: &[u8],
437    mldsa: bool,
438) -> Result<bool> {
439    if proof.get("type").and_then(Value::as_str) != Some(PROOF_TYPE) {
440        return Err(value_error(format!(
441            "Unexpected proof type: {}",
442            py_str(proof.get("type"))
443        )));
444    }
445    let (size, name) = if mldsa {
446        (MLDSA44_PUBLIC_KEY_SIZE, "ML-DSA-44")
447    } else {
448        (SLHDSA128_PUBLIC_KEY_SIZE, SLHDSA128_ALG)
449    };
450    if public_key.len() != size {
451        return Err(value_error(format!(
452            "{name} public key must be {size} bytes"
453        )));
454    }
455    let signature = if mldsa {
456        decode_mldsa44_proof_value(proof.get("proofValue"))?
457    } else {
458        decode_slhdsa128_proof_value(proof.get("proofValue"))?
459    };
460    let mut unsigned = proof.clone();
461    unsigned.remove("proofValue");
462    check_proof_context(base, &unsigned)?;
463    let signing_input = data_integrity::hash_data(base, &unsigned)?;
464    if !mldsa {
465        return Ok(crate::slh::verify(public_key, &signing_input, &signature).unwrap_or(false));
466    }
467    if crate::pq::verify(public_key, &signing_input, &signature).unwrap_or(false) {
468        return Ok(true);
469    }
470    let legacy = data_integrity::legacy_proof_digest(base, &unsigned)?;
471    Ok(crate::pq::verify(public_key, &legacy, &signature).unwrap_or(false))
472}
473
474fn verify_members(
475    document: &Value,
476    ed25519: &[u8],
477    mldsa44: Option<&[u8]>,
478    slhdsa128: Option<&[u8]>,
479) -> Result<Option<Seen>> {
480    let Some(proofs) = document.get("proof").and_then(Value::as_array) else {
481        return Err(value_error("A dual proof requires a proof array"));
482    };
483    if proof_suites(document).len() < 2 {
484        return Ok(None);
485    }
486    let base = unsecured_document(document)?;
487    let mut seen = Seen::default();
488    for proof in proofs {
489        let Some(member) = proof.as_object() else {
490            continue;
491        };
492        match member.get("cryptosuite").and_then(Value::as_str) {
493            Some(EDDSA) => {
494                let mut candidate = base.as_object().cloned().unwrap_or_default();
495                candidate.insert("proof".into(), proof.clone());
496                if !verify_eddsa(&Value::Object(candidate), ed25519)? {
497                    return Ok(None);
498                }
499                seen.eddsa = true;
500            }
501            Some(MLDSA44 | MLDSA44_LEGACY) => {
502                let Some(key) = mldsa44 else {
503                    return Ok(None);
504                };
505                if !verify_pq(&base, member, key, true)? {
506                    return Ok(None);
507                }
508                seen.mldsa44 = true;
509            }
510            Some(SLHDSA128) => {
511                let Some(key) = slhdsa128 else {
512                    return Ok(None);
513                };
514                if !verify_pq(&base, member, key, false)? {
515                    return Ok(None);
516                }
517                seen.slhdsa128 = true;
518            }
519            _ => {}
520        }
521    }
522    Ok(Some(seen))
523}
524
525/// Verify a proof set: the Ed25519 proof and every post-quantum proof must
526/// verify, and a post-quantum proof whose key is not given fails the set.
527pub fn verify_proof_set(
528    document: &Value,
529    ed25519: &[u8],
530    mldsa44: Option<&[u8]>,
531    slhdsa128: Option<&[u8]>,
532) -> Result<bool> {
533    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); document);
534    Ok(verify_members(document, ed25519, mldsa44, slhdsa128)?
535        .is_some_and(|s| s.eddsa && (s.mldsa44 || s.slhdsa128)))
536}
537
538/// Verify a proof set of exactly the Ed25519 and the ML-DSA-44 proof.
539pub fn verify_dual(document: &Value, ed25519: &[u8], mldsa44: &[u8]) -> Result<bool> {
540    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); document);
541    Ok(verify_members(document, ed25519, Some(mldsa44), None)?
542        .is_some_and(|s| s.eddsa && s.mldsa44))
543}
544
545// ---------------------------------------------------------------------------
546// Multikey (vouch.crypto.multikey)
547// ---------------------------------------------------------------------------
548
549fn prefix_hex(prefix: &[u8]) -> String {
550    prefix.iter().map(|b| format!("{b:02x}")).collect()
551}
552
553/// A public-key Multikey's algorithm and raw key, with the reference's
554/// refusals: only a public-key codec, the algorithm's exact length, a strict
555/// Ed25519 key, an SLH-DSA key in base64url ("u") and the others in
556/// base58btc ("z").
557pub fn multikey_decode(multikey: &str) -> Result<(&'static str, Vec<u8>)> {
558    if let Some(body) = multikey.strip_prefix('u') {
559        let refused =
560            || value_error("a base64url Multikey must be an SLH-DSA-SHA2-128s public key");
561        if body.len() != 46 || !is_b64u_body(body) {
562            return Err(refused());
563        }
564        let decoded = URL_SAFE_NO_PAD
565            .decode(body)
566            .map_err(|_| value_error("Multikey is not canonical base64url"))?;
567        if decoded[..2] == multikey::SLHDSA128_PRIV_PREFIX {
568            return Err(value_error(format!(
569                "multicodec {} is a private key, not a public key",
570                prefix_hex(&decoded[..2])
571            )));
572        }
573        if decoded[..2] != multikey::SLHDSA128_PUB_PREFIX {
574            return Err(refused());
575        }
576        return Ok((SLHDSA128_ALG, decoded[2..].to_vec()));
577    }
578    let Some(body) = multikey.strip_prefix('z') else {
579        return Err(value_error(
580            "Multikey must use base58btc encoding (z-prefix), or base64url (u-prefix) for SLH-DSA",
581        ));
582    };
583    let decoded = b58decode(body)?;
584    if decoded.len() < 2 {
585        return Err(value_error("Multikey too short"));
586    }
587    let prefix = [decoded[0], decoded[1]];
588    let (alg, public) = match prefix {
589        p if p == multikey::ED25519_PUB_PREFIX => ("Ed25519", true),
590        p if p == multikey::ED25519_PRIV_PREFIX => ("Ed25519", false),
591        p if p == multikey::MLDSA44_PUB_PREFIX => ("ML-DSA-44", true),
592        p if p == multikey::MLDSA44_PRIV_PREFIX => ("ML-DSA-44", false),
593        p if p == multikey::SLHDSA128_PUB_PREFIX => (SLHDSA128_ALG, true),
594        p if p == multikey::SLHDSA128_PRIV_PREFIX => (SLHDSA128_ALG, false),
595        _ => {
596            return Err(value_error(format!(
597                "Unknown multicodec prefix: {}",
598                prefix_hex(&prefix)
599            )))
600        }
601    };
602    if !public {
603        return Err(value_error(format!(
604            "multicodec {} is a private key, not a public key",
605            prefix_hex(&prefix)
606        )));
607    }
608    if alg == SLHDSA128_ALG {
609        return Err(value_error(
610            "an SLH-DSA-SHA2-128s Multikey is base64url (u-prefix)",
611        ));
612    }
613    let raw = decoded[2..].to_vec();
614    let want = if alg == "Ed25519" {
615        32
616    } else {
617        MLDSA44_PUBLIC_KEY_SIZE
618    };
619    if raw.len() != want {
620        return Err(value_error(format!(
621            "{alg} public key must be {want} bytes, got {}",
622            raw.len()
623        )));
624    }
625    if alg == "Ed25519" {
626        check_public_key(&raw)?;
627    }
628    Ok((alg, raw))
629}
630
631/// A raw public key as a Multikey (no strict checks, as the reference).
632pub fn multikey_encode(algorithm: &str, raw: &[u8]) -> Result<String> {
633    let (want, prefix) = match algorithm {
634        "Ed25519" => (32, multikey::ED25519_PUB_PREFIX),
635        "ML-DSA-44" => (MLDSA44_PUBLIC_KEY_SIZE, multikey::MLDSA44_PUB_PREFIX),
636        SLHDSA128_ALG => (SLHDSA128_PUBLIC_KEY_SIZE, multikey::SLHDSA128_PUB_PREFIX),
637        other => {
638            return Err(value_error(format!(
639                "no Multikey for algorithm {}",
640                crate::grant_chain::py_repr_str(other)
641            )))
642        }
643    };
644    if raw.len() != want {
645        return Err(value_error(format!(
646            "{algorithm} public key must be {want} bytes, got {}",
647            raw.len()
648        )));
649    }
650    let mut bytes = prefix.to_vec();
651    bytes.extend_from_slice(raw);
652    Ok(if algorithm == SLHDSA128_ALG {
653        format!("u{}", URL_SAFE_NO_PAD.encode(bytes))
654    } else {
655        format!("z{}", bs58::encode(bytes).into_string())
656    })
657}
658
659/// The (ML-DSA-44, SLH-DSA) verificationMethods that pair with an Ed25519
660/// one: the `#key-2` and `#key-3` slots of the same DID.
661pub fn paired_methods(verification_method: &str) -> (String, String) {
662    let base = if let Some(b) = verification_method.strip_suffix("#key-1") {
663        b
664    } else if let Some(i) = verification_method.find('#') {
665        &verification_method[..i]
666    } else {
667        verification_method
668    };
669    (format!("{base}#key-2"), format!("{base}#key-3"))
670}
671
672// ---------------------------------------------------------------------------
673// Secret keys as secretKeyMultibase (vouch.keys.keyfile)
674// ---------------------------------------------------------------------------
675
676const ED25519_SECRET_SIZE: usize = 32;
677const MLDSA44_SECRET_SIZE: usize = crate::pq::MLDSA44_SECRET_LEN;
678const SLHDSA128_SECRET_SIZE: usize = crate::slh::SLHDSA128_SECRET_LEN;
679
680/// A secret key as a `secretKeyMultibase` value: the private-key multicodec
681/// and the key, base58btc ("z") for Ed25519 (the 32-byte seed) and ML-DSA-44
682/// (the 2560-byte packed key), base64url ("u") for SLH-DSA-SHA2-128s.
683pub fn secret_multikey_encode(algorithm: &str, raw: &[u8]) -> Result<zeroize::Zeroizing<String>> {
684    let mut bytes = zeroize::Zeroizing::new(Vec::with_capacity(raw.len() + 2));
685    let base58 = match (algorithm, raw.len()) {
686        ("Ed25519", ED25519_SECRET_SIZE) => {
687            bytes.extend_from_slice(&multikey::ED25519_PRIV_PREFIX);
688            true
689        }
690        ("ML-DSA-44", MLDSA44_SECRET_SIZE) => {
691            bytes.extend_from_slice(&multikey::MLDSA44_PRIV_PREFIX);
692            true
693        }
694        (SLHDSA128_ALG, SLHDSA128_SECRET_SIZE) => {
695            bytes.extend_from_slice(&multikey::SLHDSA128_PRIV_PREFIX);
696            false
697        }
698        _ => {
699            return Err(value_error(format!(
700                "cannot encode a {}-byte {algorithm} secret key",
701                raw.len()
702            )))
703        }
704    };
705    bytes.extend_from_slice(raw);
706    // The text is written straight into one buffer sized up front, so no
707    // temporary string or regrown buffer is left holding the key; the buffer
708    // is wiped when the answer is dropped.
709    let encode_error = |e: &dyn core::fmt::Display| value_error(format!("encode: {e}"));
710    let mut text = zeroize::Zeroizing::new(Vec::new());
711    if base58 {
712        // At most 1.5 characters per byte (bs58's own bound).
713        text.resize(1 + bytes.len() + (bytes.len() + 1) / 2, 0);
714        text[0] = b'z';
715        let n = bs58::encode(&bytes[..])
716            .onto(&mut text[1..])
717            .map_err(|e| encode_error(&e))?;
718        text.truncate(1 + n);
719    } else {
720        let size = base64::encoded_len(bytes.len(), false)
721            .ok_or_else(|| value_error("encode: the key is too long"))?;
722        text.resize(1 + size, 0);
723        text[0] = b'u';
724        let n = URL_SAFE_NO_PAD
725            .encode_slice(&bytes[..], &mut text[1..])
726            .map_err(|e| encode_error(&e))?;
727        text.truncate(1 + n);
728    }
729    match String::from_utf8(core::mem::take(&mut *text)) {
730        Ok(text) => Ok(zeroize::Zeroizing::new(text)),
731        Err(e) => {
732            // Never reached: both alphabets are ASCII.
733            zeroize::Zeroize::zeroize(&mut e.into_bytes());
734            Err(value_error("encode: the text is not ASCII"))
735        }
736    }
737}
738
739/// Read a `secretKeyMultibase` value: its algorithm and raw secret key, with
740/// the reference's refusals (a public key, an unknown codec, a wrong size).
741pub fn secret_multikey_decode(
742    value: Option<&Value>,
743) -> Result<(&'static str, zeroize::Zeroizing<Vec<u8>>)> {
744    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); value);
745    use base64::engine::{
746        general_purpose::GeneralPurpose, DecodePaddingMode, GeneralPurposeConfig,
747    };
748    let text = match value {
749        Some(Value::String(t)) => t.as_str(),
750        _ => "",
751    };
752    if let Some(body) = text.strip_prefix('u') {
753        if body.len() < 3 || !is_b64u_body(body) || body.is_empty() {
754            return Err(value_error("secretKeyMultibase is not base64url"));
755        }
756        if body.len() > 4 * SLHDSA128_SECRET_SIZE {
757            return Err(value_error("secretKeyMultibase is too long"));
758        }
759        if body.len() % 4 == 1 {
760            return Err(value_error("secretKeyMultibase is not base64url"));
761        }
762        // Read as the reference does (unused trailing bits allowed), then
763        // require the one canonical spelling.
764        let lax = GeneralPurpose::new(
765            &base64::alphabet::URL_SAFE,
766            GeneralPurposeConfig::new()
767                .with_decode_allow_trailing_bits(true)
768                .with_decode_padding_mode(DecodePaddingMode::RequireNone),
769        );
770        let raw = zeroize::Zeroizing::new(
771            lax.decode(body)
772                .map_err(|_| value_error("secretKeyMultibase is not base64url"))?,
773        );
774        if URL_SAFE_NO_PAD.encode(&raw[..]) != body {
775            return Err(value_error("secretKeyMultibase is not canonical base64url"));
776        }
777        if raw.len() >= 2 && raw[..2] == multikey::SLHDSA128_PUB_PREFIX {
778            return Err(value_error(
779                "secretKeyMultibase carries a public key, not a secret key",
780            ));
781        }
782        if raw.len() < 2 || raw[..2] != multikey::SLHDSA128_PRIV_PREFIX {
783            return Err(value_error(
784                "secretKeyMultibase carries an unknown key type",
785            ));
786        }
787        let secret = zeroize::Zeroizing::new(raw[2..].to_vec());
788        if secret.len() != SLHDSA128_SECRET_SIZE {
789            return Err(value_error(format!(
790                "an {SLHDSA128_ALG} secret key is {SLHDSA128_SECRET_SIZE} bytes, this one is {}",
791                secret.len()
792            )));
793        }
794        return Ok((SLHDSA128_ALG, secret));
795    }
796    let Some(body) = text.strip_prefix('z') else {
797        return Err(value_error(
798            "secretKeyMultibase must use base58btc encoding (z-prefix), or base64url (u-prefix) for an SLH-DSA key",
799        ));
800    };
801    if text.chars().count() > multikey::MAX_BASE58_LEN {
802        return Err(value_error("secretKeyMultibase is too long"));
803    }
804    let raw = zeroize::Zeroizing::new(
805        b58decode(body).map_err(|_| value_error("secretKeyMultibase is not base58btc"))?,
806    );
807    for (prefix, algorithm, size) in [
808        (
809            multikey::ED25519_PRIV_PREFIX,
810            "Ed25519",
811            ED25519_SECRET_SIZE,
812        ),
813        (
814            multikey::MLDSA44_PRIV_PREFIX,
815            "ML-DSA-44",
816            MLDSA44_SECRET_SIZE,
817        ),
818    ] {
819        if raw.starts_with(&prefix) {
820            let secret = zeroize::Zeroizing::new(raw[2..].to_vec());
821            if secret.len() != size {
822                return Err(value_error(format!(
823                    "an {algorithm} secret key is {size} bytes, this one is {}",
824                    secret.len()
825                )));
826            }
827            return Ok((algorithm, secret));
828        }
829    }
830    if raw.starts_with(&multikey::ED25519_PUB_PREFIX)
831        || raw.starts_with(&multikey::MLDSA44_PUB_PREFIX)
832    {
833        return Err(value_error(
834            "secretKeyMultibase carries a public key, not a secret key",
835        ));
836    }
837    if raw.starts_with(&multikey::SLHDSA128_PRIV_PREFIX) {
838        return Err(value_error(
839            "an SLH-DSA secretKeyMultibase is base64url (u-prefix)",
840        ));
841    }
842    Err(value_error(
843        "secretKeyMultibase carries an unknown key type",
844    ))
845}
846
847// ---------------------------------------------------------------------------
848// JSON entry
849// ---------------------------------------------------------------------------
850
851fn bytes_field(request: &Value, name: &str) -> Result<Vec<u8>> {
852    let text = request
853        .get(name)
854        .and_then(Value::as_str)
855        .ok_or_else(|| value_error(format!("{name} is required (standard base64)")))?;
856    STANDARD
857        .decode(text)
858        .map_err(|_| value_error(format!("{name} must be standard base64")))
859}
860
861fn optional_bytes(request: &Value, name: &str) -> Result<Option<Vec<u8>>> {
862    match request.get(name) {
863        None | Some(Value::Null) => Ok(None),
864        Some(_) => bytes_field(request, name).map(Some),
865    }
866}
867
868fn text_field<'a>(request: &'a Value, name: &str) -> Result<&'a str> {
869    request
870        .get(name)
871        .and_then(Value::as_str)
872        .ok_or_else(|| value_error(format!("{name} must be text")))
873}
874
875fn proof_field(request: &Value) -> Result<&Map<String, Value>> {
876    request
877        .get("proof")
878        .and_then(Value::as_object)
879        .ok_or_else(|| value_error("proof must be a JSON object"))
880}
881
882/// The proof rules, `{"op": ...}` in (bytes in standard base64):
883///
884/// * `hashData` `{document, proof}` -> `{hashData}`: the signing input.
885/// * `legacyDigest` `{document, proof}` -> `{digest}`.
886/// * `contentDigest` `{document}` -> `{digest}`: SHA-256 of the JCS form of
887///   the document without its proof.
888/// * `prepare` `{document, verificationMethod, created, proofPurpose?,
889///   cryptosuite?}` -> `{proof, signingInput}`: the unsigned proof
890///   (eddsa-jcs-2022 unless named) and what to sign.
891/// * `attach` `{proof, signature}` -> `{proof}`.
892/// * `verify` `{document, publicKey}` -> `{valid}`: the eddsa-jcs-2022 proof.
893/// * `verifySet` `{document, ed25519Key, mldsa44Key?, slhdsa128Key?,
894///   dual?}` -> `{valid}`: a proof set (`dual`: exactly Ed25519 and
895///   ML-DSA-44).
896/// * `proofSuites` `{document}` -> `{suites}`.
897/// * `decodeProofValue` `{cryptosuite, proofValue}` -> `{signature}`.
898/// * `multikeyDecode` `{multikey}` -> `{algorithm, publicKey}`.
899/// * `multikeyEncode` `{algorithm, publicKey}` -> `{multikey}`.
900/// * `ed25519KeyProblem` `{publicKey}` / `ed25519SignatureProblem`
901///   `{signature}` -> `{problem}` (null when the strict rules accept it).
902/// * `ed25519Verify` `{publicKey, message, signature}` -> `{valid}`: strict;
903///   a refused key or signature is not valid.
904/// * `mldsa44KeysMatch` `{publicKey, secretKey}` -> `{match}`.
905/// * `mldsa44PublicFromSecret` `{secretKey}` -> `{publicKey}` (null when the
906///   bytes are no secret key).
907/// * `pairedMethods` `{verificationMethod}` -> `{mldsa44, slhdsa128}`.
908/// * `secretMultikeyEncode` `{algorithm, secretKey}` ->
909///   `{secretKeyMultibase}`; `secretMultikeyDecode` `{secretKeyMultibase}` ->
910///   `{algorithm, secretKey}` (the key file's secret-key form; the request
911///   text is wiped, the answer holds the secret for the host to wipe).
912/// * `base58Encode` `{bytes}` -> `{text}`; `base58Decode` `{text, size?}` ->
913///   `{bytes}` (the reference's refusals, longer than 8192 characters
914///   refused).
915/// * `keyFrom` `{key, algorithm?}` -> `{publicKey}` (null when the value is
916///   not a usable key of the algorithm, Ed25519 unless named).
917/// * `documentKey` `{document, did, verificationMethod, algorithm}` ->
918///   `{publicKey}`: the assertion key a DID document gives the DID.
919/// * `methodKey` `{method, algorithm}` -> `{publicKey}`: one verification
920///   method's key, its type and material checked strictly (no document
921///   rules: for display and tooling).
922/// * `documentPublishes` `{document, did}` -> `{mldsa44, slhdsa128}`.
923pub fn rules_json(request: &Value) -> Result<Value> {
924    crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); request);
925    let op = request
926        .get("op")
927        .and_then(Value::as_str)
928        .ok_or_else(|| value_error("op is required"))?;
929    let document = || request.get("document").unwrap_or(&Value::Null);
930    match op {
931        "hashData" => {
932            let mut proof = proof_field(request)?.clone();
933            proof.remove("proofValue");
934            Ok(json!({"hashData": STANDARD.encode(hash_data(document(), &proof)?)}))
935        }
936        "legacyDigest" => Ok(json!({
937            "digest": STANDARD.encode(legacy_digest(document(), proof_field(request)?)?)
938        })),
939        "contentDigest" => {
940            let base = unsecured_document(document())?;
941            let digest = Sha256::digest(crate::jcs::canonicalize(&base));
942            Ok(json!({"digest": STANDARD.encode(digest)}))
943        }
944        "prepare" => {
945            let suite = match request.get("cryptosuite") {
946                None | Some(Value::Null) => EDDSA,
947                Some(Value::String(s)) if PROOF_SET_SUITES.contains(&s.as_str()) => {
948                    PROOF_SET_SUITES.iter().find(|k| **k == s).copied().unwrap()
949                }
950                Some(other) => {
951                    return Err(value_error(format!(
952                        "no proof of cryptosuite {}",
953                        crate::grant_chain::py_repr(Some(other))
954                    )))
955                }
956            };
957            let purpose = match request.get("proofPurpose") {
958                None | Some(Value::Null) => "assertionMethod",
959                Some(_) => text_field(request, "proofPurpose")?,
960            };
961            let proof = unsigned_proof(
962                suite,
963                text_field(request, "created")?,
964                text_field(request, "verificationMethod")?,
965                purpose,
966            );
967            let signing_input = hash_data(document(), &proof)?;
968            Ok(json!({"proof": proof, "signingInput": STANDARD.encode(signing_input)}))
969        }
970        "attach" => Ok(json!({
971            "proof": attach(proof_field(request)?, &bytes_field(request, "signature")?)?
972        })),
973        "verify" => Ok(json!({
974            "valid": verify_eddsa(document(), &bytes_field(request, "publicKey")?)?
975        })),
976        "verifySet" => {
977            let ed = bytes_field(request, "ed25519Key")?;
978            let ml = optional_bytes(request, "mldsa44Key")?;
979            let valid = if request.get("dual").and_then(Value::as_bool) == Some(true) {
980                let ml = ml.ok_or_else(|| value_error("mldsa44Key is required"))?;
981                verify_dual(document(), &ed, &ml)?
982            } else {
983                verify_proof_set(
984                    document(),
985                    &ed,
986                    ml.as_deref(),
987                    optional_bytes(request, "slhdsa128Key")?.as_deref(),
988                )?
989            };
990            Ok(json!({ "valid": valid }))
991        }
992        "proofSuites" => Ok(json!({"suites": proof_suites(document())})),
993        "decodeProofValue" => {
994            let value = request.get("proofValue");
995            let signature = match text_field(request, "cryptosuite")? {
996                EDDSA => decode_eddsa_proof_value(value)?,
997                MLDSA44 | MLDSA44_LEGACY => decode_mldsa44_proof_value(value)?,
998                SLHDSA128 => decode_slhdsa128_proof_value(value)?,
999                other => {
1000                    return Err(value_error(format!(
1001                        "no proof of cryptosuite {}",
1002                        crate::grant_chain::py_repr_str(other)
1003                    )))
1004                }
1005            };
1006            Ok(json!({"signature": STANDARD.encode(signature)}))
1007        }
1008        "multikeyDecode" => {
1009            let (algorithm, raw) = match request.get("multikey") {
1010                Some(Value::String(m)) => multikey_decode(m)?,
1011                _ => {
1012                    return Err(value_error(
1013                        "Multikey must use base58btc encoding (z-prefix), or base64url (u-prefix) for SLH-DSA",
1014                    ))
1015                }
1016            };
1017            Ok(json!({"algorithm": algorithm, "publicKey": STANDARD.encode(raw)}))
1018        }
1019        "multikeyEncode" => Ok(json!({
1020            "multikey": multikey_encode(
1021                text_field(request, "algorithm")?,
1022                &bytes_field(request, "publicKey")?,
1023            )?
1024        })),
1025        "ed25519KeyProblem" => Ok(json!({
1026            "problem": ed25519_public_key_problem(&bytes_field(request, "publicKey")?)
1027        })),
1028        "ed25519SignatureProblem" => Ok(json!({
1029            "problem": ed25519_signature_problem(&bytes_field(request, "signature")?)
1030        })),
1031        "ed25519Verify" => {
1032            let key = bytes_field(request, "publicKey")?;
1033            let signature = bytes_field(request, "signature")?;
1034            let message = bytes_field(request, "message")?;
1035            let valid = ed25519_public_key_problem(&key).is_none()
1036                && ed25519_signature_problem(&signature).is_none()
1037                && crate::keys::verify(&key, &message, &signature).unwrap_or(false);
1038            Ok(json!({ "valid": valid }))
1039        }
1040        "mldsa44KeysMatch" => {
1041            let secret = zeroize::Zeroizing::new(bytes_field(request, "secretKey")?);
1042            Ok(json!({"match": crate::mldsa_check::mldsa44_keys_match(
1043                &bytes_field(request, "publicKey")?,
1044                &secret,
1045            )}))
1046        }
1047        "mldsa44PublicFromSecret" => {
1048            let secret = zeroize::Zeroizing::new(bytes_field(request, "secretKey")?);
1049            Ok(
1050                json!({"publicKey": crate::mldsa_check::mldsa44_public_from_secret(&secret)
1051                .map(|p| STANDARD.encode(p))}),
1052            )
1053        }
1054        "keyFrom" => {
1055            // A key as a caller writes one (Multikey text, or a JWK object or
1056            // its JSON text for Ed25519), read the reference's way: None when
1057            // it is not a usable key of the algorithm.
1058            let key = request.get("key").unwrap_or(&Value::Null);
1059            let raw = match request.get("algorithm").and_then(Value::as_str) {
1060                None | Some("Ed25519") => match crate::decision::key_entry_from_json(key) {
1061                    crate::decision::KeyEntry::Ed25519(k) => Some(k),
1062                    _ => None,
1063                },
1064                Some("ML-DSA-44") => crate::decision::mldsa44_key_from_json(key),
1065                Some(SLHDSA128_ALG) => crate::decision::slhdsa128_key_from_json(key),
1066                Some(other) => {
1067                    return Err(value_error(format!(
1068                        "no key of algorithm {}",
1069                        crate::grant_chain::py_repr_str(other)
1070                    )))
1071                }
1072            };
1073            Ok(json!({"publicKey": raw.map(|k| STANDARD.encode(k))}))
1074        }
1075        "documentKey" => {
1076            // The key a DID document lets `did` use for assertions under
1077            // `verificationMethod` (refused with the reference's text).
1078            // An algorithm that is not text matches no key; it is quoted as the
1079            // reference quotes it, after the document's own checks.
1080            let algorithm = py_str(request.get("algorithm"));
1081            // A DID that is not text is never the document's id, and a
1082            // method that is not text is never a key of the DID: the
1083            // reference's first two rules, in its order.
1084            let Some(did) = request.get("did").and_then(Value::as_str) else {
1085                return Err(CoreError::InvalidDid(
1086                    "the DID document's id is not the DID".into(),
1087                ));
1088            };
1089            let method = request
1090                .get("verificationMethod")
1091                .and_then(Value::as_str)
1092                .unwrap_or("");
1093            let raw = crate::did_document::assertion_key(document(), did, method, &algorithm)?;
1094            Ok(json!({"publicKey": STANDARD.encode(raw)}))
1095        }
1096        "methodKey" => {
1097            let method = request
1098                .get("method")
1099                .and_then(Value::as_object)
1100                .ok_or_else(|| value_error("method must be a JSON object"))?;
1101            let algorithm = py_str(request.get("algorithm"));
1102            let raw = crate::did_document::method_key(method, &algorithm)?;
1103            Ok(json!({"publicKey": STANDARD.encode(raw)}))
1104        }
1105        "documentPublishes" => {
1106            let did = text_field(request, "did")?;
1107            Ok(json!({
1108                "mldsa44": crate::did_document::publishes_mldsa44_assertion_key(document(), did),
1109                "slhdsa128": crate::did_document::publishes_slhdsa128_assertion_key(document(), did),
1110            }))
1111        }
1112        "secretMultikeyEncode" => {
1113            let secret = zeroize::Zeroizing::new(bytes_field(request, "secretKey")?);
1114            let text = secret_multikey_encode(text_field(request, "algorithm")?, &secret)?;
1115            Ok(json!({ "secretKeyMultibase": text.as_str() }))
1116        }
1117        "secretMultikeyDecode" => {
1118            let (algorithm, secret) = secret_multikey_decode(request.get("secretKeyMultibase"))?;
1119            Ok(json!({"algorithm": algorithm, "secretKey": STANDARD.encode(&secret[..])}))
1120        }
1121        "base58Encode" => {
1122            // Base58 costs time in the square of the length: the cap is far
1123            // above any key or signature.
1124            let raw = bytes_field(request, "bytes")?;
1125            if raw.len() > MAX_BASE58_ENCODE_BYTES {
1126                return Err(value_error(format!(
1127                    "base58 input too long: {} bytes > {MAX_BASE58_ENCODE_BYTES}",
1128                    raw.len()
1129                )));
1130            }
1131            Ok(json!({"text": bs58::encode(raw).into_string()}))
1132        }
1133        "base58Decode" => {
1134            let text = text_field(request, "text")?;
1135            let raw = match request.get("size") {
1136                None | Some(Value::Null) => b58decode(text)?,
1137                Some(n) => b58decode_exact(
1138                    text,
1139                    n.as_u64()
1140                        .ok_or_else(|| value_error("size must be a whole number"))?
1141                        as usize,
1142                )?,
1143            };
1144            Ok(json!({"bytes": STANDARD.encode(raw)}))
1145        }
1146        "pairedMethods" => {
1147            let (ml, slh) = paired_methods(text_field(request, "verificationMethod")?);
1148            Ok(json!({"mldsa44": ml, "slhdsa128": slh}))
1149        }
1150        other => Err(value_error(format!(
1151            "unknown proof op {}",
1152            crate::grant_chain::py_repr_str(other)
1153        ))),
1154    }
1155}
1156
1157/// [`rules_json`] on a request text that may hold a secret key: the text and
1158/// every string of the parsed request are wiped once the rule has run.
1159pub fn rules_json_text(request: String) -> Result<Value> {
1160    let request = zeroize::Zeroizing::new(request);
1161    // Read as deep as the reference canonicalizes (a document nested 499
1162    // levels is signed and verified like any other).
1163    let mut value = crate::jcs::parse_deep(&request)?;
1164    let out = rules_json(&value);
1165    crate::jcs::wipe_strings(&mut value);
1166    out
1167}
1168
1169#[cfg(test)]
1170mod tests {
1171    use super::*;
1172    use crate::keys::Ed25519KeyPair;
1173
1174    fn vector(rel: &str) -> Value {
1175        let path = format!("{}/../../test-vectors/{rel}", env!("CARGO_MANIFEST_DIR"));
1176        serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap()
1177    }
1178
1179    #[test]
1180    fn base58_encode_is_capped_above_any_key_or_signature() {
1181        use base64::{engine::general_purpose::STANDARD, Engine};
1182        let encode = |n: usize| {
1183            rules_json(&json!({"op": "base58Encode", "bytes": STANDARD.encode(vec![1u8; n])}))
1184        };
1185        assert!(encode(SLHDSA128_SIGNATURE_SIZE).is_ok());
1186        assert!(encode(MAX_BASE58_ENCODE_BYTES).is_ok());
1187        let err = encode(MAX_BASE58_ENCODE_BYTES + 1).unwrap_err();
1188        assert!(
1189            err.to_string()
1190                .contains("base58 input too long: 8193 bytes > 8192"),
1191            "{err}"
1192        );
1193    }
1194
1195    #[test]
1196    fn group_order_is_the_vectors() {
1197        let v = vector("ed25519-strict/vector.json");
1198        // l as little-endian bytes, from its decimal text.
1199        let mut n: Vec<u32> = v["l"]
1200            .as_str()
1201            .unwrap()
1202            .bytes()
1203            .map(|b| (b - b'0') as u32)
1204            .collect();
1205        let mut le = Vec::new();
1206        while !(n.is_empty() || n.len() == 1 && n[0] == 0) {
1207            let mut rem = 0u32;
1208            let mut q = Vec::new();
1209            for d in &n {
1210                let cur = rem * 10 + d;
1211                if !q.is_empty() || cur / 256 != 0 {
1212                    q.push(cur / 256);
1213                }
1214                rem = cur % 256;
1215            }
1216            le.push(rem as u8);
1217            n = q;
1218        }
1219        le.resize(32, 0);
1220        assert_eq!(le, GROUP_ORDER_LE);
1221    }
1222
1223    #[test]
1224    fn strict_public_keys_match_the_vector() {
1225        let v = vector("ed25519-strict/vector.json");
1226        for case in v["publicKeys"].as_array().unwrap() {
1227            let raw = hex::decode(case["hex"].as_str().unwrap()).unwrap();
1228            let problem = ed25519_public_key_problem(&raw);
1229            assert_eq!(
1230                problem.is_none(),
1231                case["valid"].as_bool().unwrap(),
1232                "{}: {problem:?}",
1233                case["name"]
1234            );
1235        }
1236    }
1237
1238    #[test]
1239    fn sign_prepare_attach_verify_round_trip() {
1240        let kp = Ed25519KeyPair::from_seed(&[7u8; 32]);
1241        let doc = json!({"@context": ["https://www.w3.org/ns/credentials/v2"], "a": 1});
1242        let prepared = rules_json(&json!({
1243            "op": "prepare", "document": doc, "verificationMethod": "did:example:1#key-1",
1244            "created": "2026-01-01T00:00:00Z",
1245        }))
1246        .unwrap();
1247        let input = STANDARD
1248            .decode(prepared["signingInput"].as_str().unwrap())
1249            .unwrap();
1250        let sig = kp.sign(&input);
1251        let proof = rules_json(&json!({
1252            "op": "attach", "proof": prepared["proof"], "signature": STANDARD.encode(sig),
1253        }))
1254        .unwrap()["proof"]
1255            .clone();
1256        let mut signed = doc.clone();
1257        signed["proof"] = proof.clone();
1258        // The same proof the core's own builder writes.
1259        let built = data_integrity::build_proof(
1260            &doc,
1261            &kp.seed(),
1262            &data_integrity::BuildProofOptions::new("did:example:1#key-1", "2026-01-01T00:00:00Z"),
1263        )
1264        .unwrap();
1265        assert_eq!(proof, built);
1266        let pk = STANDARD.encode(kp.public_key());
1267        let ok = rules_json(&json!({"op": "verify", "document": signed, "publicKey": pk})).unwrap();
1268        assert_eq!(ok["valid"], json!(true));
1269        signed["a"] = json!(2);
1270        let bad =
1271            rules_json(&json!({"op": "verify", "document": signed, "publicKey": pk})).unwrap();
1272        assert_eq!(bad["valid"], json!(false));
1273        // A proof @context that is not the document's is refused.
1274        signed["a"] = json!(1);
1275        signed["proof"]["@context"] = json!(["https://example.com"]);
1276        let err =
1277            rules_json(&json!({"op": "verify", "document": signed, "publicKey": pk})).unwrap_err();
1278        assert_eq!(
1279            err,
1280            CoreError::Json("the proof's @context is not the document's @context".into())
1281        );
1282    }
1283
1284    #[test]
1285    fn multikey_round_trips_and_refuses_private_codecs() {
1286        let kp = Ed25519KeyPair::from_seed(&[9u8; 32]);
1287        let mk = multikey_encode("Ed25519", &kp.public_key()).unwrap();
1288        assert_eq!(
1289            mk,
1290            multikey::encode_ed25519_public(&kp.public_key()).unwrap()
1291        );
1292        assert_eq!(
1293            multikey_decode(&mk).unwrap(),
1294            ("Ed25519", kp.public_key().to_vec())
1295        );
1296        let mut private = multikey::ED25519_PRIV_PREFIX.to_vec();
1297        private.extend_from_slice(&[1u8; 32]);
1298        let text = format!("z{}", bs58::encode(private).into_string());
1299        assert_eq!(
1300            multikey_decode(&text).unwrap_err(),
1301            CoreError::Json("multicodec 8026 is a private key, not a public key".into())
1302        );
1303        assert_eq!(
1304            multikey_decode("z0OIl").unwrap_err(),
1305            CoreError::Json("Invalid base58 character: '0'".into())
1306        );
1307    }
1308
1309    #[test]
1310    fn paired_methods_follow_the_slots() {
1311        assert_eq!(
1312            paired_methods("did:web:a#key-1"),
1313            ("did:web:a#key-2".into(), "did:web:a#key-3".into())
1314        );
1315        assert_eq!(
1316            paired_methods("did:web:a#k"),
1317            ("did:web:a#key-2".into(), "did:web:a#key-3".into())
1318        );
1319        assert_eq!(
1320            paired_methods("did:web:a"),
1321            ("did:web:a#key-2".into(), "did:web:a#key-3".into())
1322        );
1323    }
1324
1325    #[test]
1326    fn jwk_x_is_base64url_with_its_own_padding_only() {
1327        let kp = Ed25519KeyPair::from_seed(&[3u8; 32]);
1328        let url = URL_SAFE_NO_PAD.encode(kp.public_key());
1329        let read = |x: &str| {
1330            rules_json(&json!({"op": "keyFrom", "key": {"kty": "OKP", "crv": "Ed25519", "x": x}}))
1331                .unwrap()["publicKey"]
1332                .clone()
1333        };
1334        let want = json!(STANDARD.encode(kp.public_key()));
1335        assert_eq!(read(&url), want);
1336        assert_eq!(read(&format!("{url}=")), want);
1337        // The standard alphabet ("+" and "/"), other padding, white space:
1338        // refused (RFC 7517/7518 base64url only).
1339        let standard = format!("+/{}", &url[2..]);
1340        for bad in [
1341            standard,
1342            format!("{url}=="),
1343            format!("{url}==="),
1344            format!("{url}\n"),
1345            format!(" {url}"),
1346        ] {
1347            assert_eq!(read(&bad), json!(null), "{bad:?}");
1348        }
1349    }
1350
1351    #[test]
1352    fn document_key_checks_run_in_the_reference_order() {
1353        let doc = json!({"id": "did:web:a.example", "verificationMethod": []});
1354        let err = |did: Value, vm: Value| {
1355            rules_json(&json!({"op": "documentKey", "document": doc, "did": did,
1356                               "verificationMethod": vm, "algorithm": "Ed25519"}))
1357            .unwrap_err()
1358            .to_string()
1359        };
1360        assert!(err(json!(5), json!(5)).ends_with("the DID document's id is not the DID"));
1361        assert!(err(json!("did:web:a.example"), json!(5)).ends_with("not a key of this DID"));
1362    }
1363
1364    #[test]
1365    fn a_missing_document_context_reads_as_null() {
1366        let kp = Ed25519KeyPair::from_seed(&[4u8; 32]);
1367        let doc = json!({"a": 1});
1368        let mut proof = data_integrity::build_proof(
1369            &doc,
1370            &kp.seed(),
1371            &data_integrity::BuildProofOptions::new("did:example:1#key-1", "2026-01-01T00:00:00Z"),
1372        )
1373        .unwrap();
1374        proof["@context"] = Value::Null;
1375        let mut signed = doc.clone();
1376        signed["proof"] = proof;
1377        let got = rules_json(&json!({"op": "verify", "document": signed,
1378                                     "publicKey": STANDARD.encode(kp.public_key())}))
1379        .unwrap();
1380        assert_eq!(got["valid"], json!(false));
1381    }
1382
1383    #[test]
1384    #[cfg_attr(not(feature = "std"), ignore = "the std build's 512-level allowance")]
1385    fn a_deep_document_signs_through_the_text_entry() {
1386        let deep = format!("{}{}", "[".repeat(300), "]".repeat(300));
1387        let text = format!(
1388            r#"{{"op":"prepare","document":{{"a":{deep}}},"verificationMethod":"did:example:1#key-1","created":"2026-01-01T00:00:00Z"}}"#
1389        );
1390        assert!(rules_json_text(text).is_ok());
1391    }
1392
1393    #[test]
1394    #[cfg_attr(feature = "std", ignore = "checks the no_std build")]
1395    fn no_std_text_entry_refuses_past_the_cap_before_parsing() {
1396        for n in [32, 129, 600] {
1397            let deep = format!("{}{}", "[".repeat(n), "]".repeat(n));
1398            let text = format!(
1399                r#"{{"op":"prepare","document":{{"a":{deep}}},"verificationMethod":"did:example:1#key-1","created":"2026-01-01T00:00:00Z"}}"#
1400            );
1401            assert_eq!(
1402                rules_json_text(text).unwrap_err(),
1403                crate::nesting::too_deep(),
1404                "{n} levels"
1405            );
1406        }
1407    }
1408
1409    #[test]
1410    fn wipe_strings_clears_every_string() {
1411        let mut v = json!({"seed": "c2VjcmV0", "nested": [{"k": "abc"}], "n": 1});
1412        crate::jcs::wipe_strings(&mut v);
1413        assert_eq!(v["seed"], json!(""));
1414        assert_eq!(v["nested"][0]["k"], json!(""));
1415        assert_eq!(v["n"], json!(1));
1416    }
1417}