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