Skip to main content

vouch_core/
decision.rs

1//! The verifier's decision, with no I/O: accept or refuse a Vouch Credential,
2//! and why, exactly as the Python reference `vouch.verifier` decides it.
3//!
4//! The host language does every fetch (DID documents, did:webvh logs, status
5//! lists) and keeps the replay store. It hands this module what it fetched,
6//! the caller's trust settings and the clock; this module gives back the same
7//! verdict and the same refusal text as `vouch.verifier.Verifier.verify`.
8//!
9//! The order of the checks is the reference's, the same on every path:
10//!
11//! 1. the credential's shape ([`structure_problem`]): contexts, types, issuer,
12//!    vouchVersion, intent and its resource, the validity window, and the
13//!    credential's own binding fields; then the trusted issuers (when the
14//!    caller limits them); then every proof's own fields ([`read_proofs`])
15//!    and the cryptosuites the verifier requires (`requireSuites`);
16//! 2. for a delegation chain, before any key is looked up: the size guard
17//!    and any depth budget, the trusted roots, and the link fields alone
18//!    (each link continues the one before it, the chain starts at a trusted
19//!    root, and every grant is bound to the grant before it);
20//! 3. the issuer's keys, then the proof (or every proof of a proof set), with
21//!    the post-quantum rule: a single classical proof is refused when the
22//!    caller requires post-quantum, supplies a post-quantum key, or the
23//!    issuer's DID document publishes one; and a proof set must carry the
24//!    proof of every post-quantum suite whose key was supplied or published;
25//! 4. the delegation chain's signed grants
26//!    ([`crate::delegation::verify_delegation_chain_with`]);
27//! 5. the credential's status, then each grant's status;
28//! 6. the replay key ([`ReplayIdentity`]): the host marks it in its store.
29
30use std::collections::BTreeMap;
31
32use serde_json::{json, Map, Value};
33
34use crate::data_integrity;
35use crate::delegation::ChainOptions;
36use crate::did_document;
37use crate::error::{CoreError, Result};
38use crate::grant_chain;
39use crate::hybrid;
40use crate::keys;
41use crate::multikey;
42use crate::pq;
43use crate::status_list;
44use crate::time::{check_clock_skew, parse_protocol_time_ns, window_state_ns, WindowState};
45
46/// The refusal when the issuer's key cannot be established.
47pub const REASON_NO_KEY: &str = "no key to check the signature with";
48/// The refusal when a chained credential arrives and no trusted roots are
49/// known ("<root DID>" is replaced by the chain's starting point, see
50/// [`untrusted_root_reason`]).
51pub const REASON_UNTRUSTED_START: &str =
52    "the chain's starting point is not trusted: run `vouch trust <root DID>`";
53/// The refusal when the chain starts somewhere the trusted roots do not name.
54pub const REASON_START_NOT_LISTED: &str = "the chain's starting point is not trusted: run \
55     `vouch trust <root DID>` (it is not one of the trusted roots)";
56/// The refusal when a chain is larger than the verifier's budget.
57pub const REASON_BUDGET: &str = "verifier_budget_exceeded";
58/// The refusal when the caller named trusted roots and a credential without
59/// a delegation chain comes from an issuer that is not one of them.
60pub const REASON_CHAIN_REQUIRED: &str = "delegation_chain_required";
61/// The refusal a host gives when its replay store already holds the key.
62pub const REASON_REPLAYED: &str = "this credential was already used";
63/// Credentials valid this long or less (12 hours) are single use.
64pub const DEFAULT_MAX_REPLAY_WINDOW_SECONDS: f64 = 12.0 * 60.0 * 60.0;
65/// The clock skew the reference verifier allows by default, in seconds.
66pub const DEFAULT_CLOCK_SKEW_SECONDS: i64 = 30;
67/// The start of the error a caller gets when it handed over the issuer's
68/// Ed25519 key, the credential carries a post-quantum proof, and no ML-DSA-44
69/// key is known (the reference raises `MissingMLDSA44KeyError`). Bindings
70/// raise their own error type when an error starts with this text.
71pub const MISSING_MLDSA44_KEY: &str = "missing_mldsa44_key";
72
73const VC_CONTEXT_V2: &str = "https://www.w3.org/ns/credentials/v2";
74const REQUIRED_TYPES: [&str; 2] = ["VerifiableCredential", "VouchCredential"];
75const SUPPORTED_VOUCH_VERSIONS: [&str; 1] = ["1.0"];
76const ASSERTION: &str = "assertionMethod";
77const ROOT_PLACEHOLDER: &str = "<root DID>";
78const VALUE_ERROR: &str = "ValueError";
79const WEAK_KEY_ERROR: &str = "WeakKeyError";
80const NS_PER_SECOND: i128 = 1_000_000_000;
81
82/// The group order L of edwards25519, little-endian (an Ed25519 signature's S
83/// must be below it).
84const GROUP_ORDER_LE: [u8; 32] = [
85    237, 211, 245, 92, 26, 99, 18, 88, 214, 156, 247, 162, 222, 249, 222, 20, 0, 0, 0, 0, 0, 0, 0,
86    0, 0, 0, 0, 0, 0, 0, 0, 16,
87];
88
89// ---------------------------------------------------------------------------
90// Inputs and outputs
91// ---------------------------------------------------------------------------
92
93/// A key the caller named for a DID. A key that is present but cannot be
94/// used is still the only key for that DID: the reference never falls back
95/// to another source for it.
96#[derive(Debug, Clone, PartialEq, Eq)]
97pub enum KeyEntry {
98    /// A strict Ed25519 public key (32 raw bytes).
99    Ed25519(Vec<u8>),
100    /// The caller named something for the DID that is not a usable key.
101    Unusable,
102}
103
104/// The trusted starting points for a delegation chain, normalized
105/// ([`crate::did_web::normalize_root`]): the DIDs, and the keys a `{did: key}`
106/// map gave for some of them (used for those issuers too).
107#[derive(Debug, Clone, Default, PartialEq, Eq)]
108pub struct TrustedRoots {
109    pub dids: Vec<String>,
110    pub keys: BTreeMap<String, KeyEntry>,
111}
112
113/// Everything one verification decision needs. The host fetched every
114/// document and status list; nothing here is fetched.
115#[derive(Debug, Clone)]
116pub struct DecisionInput {
117    /// The credential as the host received it (an object; anything else is
118    /// refused as "the credential is not a JSON object").
119    pub credential: Value,
120    /// The verifier's clock, a protocol time.
121    pub now: String,
122    /// Allowed clock drift, 0 to 120 seconds.
123    pub clock_skew_seconds: i64,
124    /// The issuer's key handed over by the caller (offline verification).
125    pub public_key: Option<KeyEntry>,
126    /// The issuer's ML-DSA-44 key handed over by the caller: `Some(None)` is
127    /// a key that is not a 1312-byte ML-DSA-44 key. Supplying one requires
128    /// the post-quantum proof.
129    pub mldsa44_public_key: Option<Option<Vec<u8>>>,
130    /// The issuer's SLH-DSA-SHA2-128s key handed over by the caller:
131    /// `Some(None)` is a key that is not a 32-byte SLH-DSA key. Supplying one
132    /// requires the SLH-DSA proof.
133    pub slhdsa128_public_key: Option<Option<Vec<u8>>>,
134    /// The caller's trusted keys by DID (the reference's `trusted_keys`):
135    /// for a DID listed here, this is the only key.
136    pub trusted_keys: BTreeMap<String, KeyEntry>,
137    /// The answers of the caller's key resolver, by DID (a resolver that
138    /// answered nothing is left out). Asked after the trusted keys.
139    pub resolved_keys: BTreeMap<String, KeyEntry>,
140    /// ML-DSA-44 keys (1312 bytes) by DID, from the caller's ML-DSA-44 key
141    /// resolver. Asked first for every signer.
142    pub mldsa44_keys: BTreeMap<String, Vec<u8>>,
143    /// SLH-DSA-SHA2-128s keys (32 bytes) by DID, from the caller's SLH-DSA
144    /// key resolver. Asked first for every signer.
145    pub slhdsa128_keys: BTreeMap<String, Vec<u8>>,
146    /// DID documents the host fetched, by DID: did:web documents, and the
147    /// latest verified state of did:webvh logs. A DID whose fetch failed is
148    /// left out.
149    pub documents: BTreeMap<String, Value>,
150    /// The trusted starting points for a delegation chain. None (or an empty
151    /// list) means none are known, so a chained credential is refused.
152    pub trusted_roots: Option<TrustedRoots>,
153    /// Require the post-quantum proof on the credential and every grant.
154    pub require_post_quantum: bool,
155    /// The cryptosuites the credential's proofs must include (the
156    /// verifier's `credential.requireSuites` setting). Empty: no such rule.
157    pub require_suites: Vec<hybrid::Suite>,
158    /// When given, intent.resource must equal it.
159    pub expected_resource: Option<String>,
160    /// Check credentialStatus (the reference's default is true).
161    pub check_status: bool,
162    /// The status list credentials the host fetched, by URL. A URL missing
163    /// here is a list that could not be fetched (status_unavailable).
164    pub status_lists: Map<String, Value>,
165    /// An explicit most links a delegation chain may have.
166    pub max_depth: Option<usize>,
167    /// Credentials valid this long or less are single use (seconds, > 0).
168    pub max_replay_window_seconds: f64,
169    /// When given, only these issuers are accepted (a verifier that requires
170    /// a trusted issuer).
171    pub allowed_issuers: Option<Vec<String>>,
172    /// With trusted roots named, refuse a credential without a delegation
173    /// chain unless a root issued it ([`REASON_CHAIN_REQUIRED`]), so leaving
174    /// the chain off never steps outside a grant. A host that applies its
175    /// own chain rule turns it off in the request.
176    pub chain_required_outside_roots: bool,
177    /// The host verified the grant chain handed over beside a sub-grant
178    /// (one that names its parent by `parentGrantDigest`) on its own. Only
179    /// then does a sub-grant from a non-root skip
180    /// [`REASON_CHAIN_REQUIRED`]; a digest alone proves nothing, since it
181    /// is not looked up here.
182    pub grant_chain_checked_apart: bool,
183}
184
185impl DecisionInput {
186    /// A decision request with the reference's defaults: 30 seconds of skew,
187    /// status checked, a 12-hour replay window, nothing trusted and nothing
188    /// fetched.
189    pub fn new(credential: Value, now: impl Into<String>) -> Self {
190        Self {
191            credential,
192            now: now.into(),
193            clock_skew_seconds: DEFAULT_CLOCK_SKEW_SECONDS,
194            public_key: None,
195            mldsa44_public_key: None,
196            slhdsa128_public_key: None,
197            trusted_keys: BTreeMap::new(),
198            resolved_keys: BTreeMap::new(),
199            mldsa44_keys: BTreeMap::new(),
200            slhdsa128_keys: BTreeMap::new(),
201            documents: BTreeMap::new(),
202            trusted_roots: None,
203            require_post_quantum: false,
204            require_suites: Vec::new(),
205            expected_resource: None,
206            check_status: true,
207            status_lists: Map::new(),
208            max_depth: None,
209            max_replay_window_seconds: DEFAULT_MAX_REPLAY_WINDOW_SECONDS,
210            allowed_issuers: None,
211            chain_required_outside_roots: false,
212            grant_chain_checked_apart: false,
213        }
214    }
215}
216
217/// What a host keeps in its replay store for an accepted credential.
218#[derive(Debug, Clone, PartialEq)]
219pub struct ReplayIdentity {
220    /// The replay key ([`crate::credentials::replay_key`]).
221    pub key: String,
222    /// Seconds since the epoch until which the key is kept: validUntil plus
223    /// the clock skew.
224    pub expires_at: f64,
225    /// False when the credential is valid longer than the replay window: it
226    /// is meant to be shown many times, so the host neither refuses nor
227    /// remembers it.
228    pub single_use: bool,
229}
230
231/// The verdict.
232#[derive(Debug, Clone, PartialEq)]
233pub struct Decision {
234    pub valid: bool,
235    /// None when valid, else the reference's refusal text.
236    pub reason: Option<String>,
237    /// The verified passport (only when valid), in the JSON shape
238    /// [`passport`] gives.
239    pub passport: Option<Value>,
240    /// The replay identity (only when valid).
241    pub replay: Option<ReplayIdentity>,
242    /// The Ed25519 key the credential verified under (only when valid), so
243    /// a host can check what the issuer's key also signs (a session voucher
244    /// it must not have issued to itself, an equivocation proof).
245    pub issuer_key: Option<Vec<u8>>,
246}
247
248impl Decision {
249    fn refuse(reason: impl Into<String>) -> Self {
250        Self {
251            valid: false,
252            reason: Some(reason.into()),
253            passport: None,
254            replay: None,
255            issuer_key: None,
256        }
257    }
258}
259
260// ---------------------------------------------------------------------------
261// Small rules
262// ---------------------------------------------------------------------------
263
264/// The refusal for a delegation chain whose starting point is not trusted. It
265/// names the chain's starting point in the `vouch trust` command when that is
266/// a DID made of plain characters (`did:[a-z0-9]+:[A-Za-z0-9._:%-]{1,200}`),
267/// otherwise it says "<root DID>".
268pub fn untrusted_root_reason(root: Option<&str>, roots_given: bool) -> String {
269    let template = if roots_given {
270        REASON_START_NOT_LISTED
271    } else {
272        REASON_UNTRUSTED_START
273    };
274    match root {
275        Some(r) if showable_did(r) => template.replace(ROOT_PLACEHOLDER, r),
276        _ => template.to_string(),
277    }
278}
279
280fn showable_did(s: &str) -> bool {
281    let Some(rest) = s.strip_prefix("did:") else {
282        return false;
283    };
284    let Some((method, id)) = rest.split_once(':') else {
285        return false;
286    };
287    !method.is_empty()
288        && method
289            .bytes()
290            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit())
291        && (1..=200).contains(&id.len())
292        && id
293            .bytes()
294            .all(|b| b.is_ascii_alphanumeric() || b"._:%-".contains(&b))
295}
296
297/// The issuer DID the reference reads: a string, or the `id` of an issuer
298/// object, that starts with "did:" and is longer than "did:".
299pub fn issuer_did(credential: &Value) -> Option<&str> {
300    let issuer = match credential.get("issuer") {
301        Some(Value::Object(o)) => o.get("id"),
302        other => other,
303    };
304    issuer
305        .and_then(Value::as_str)
306        .filter(|s| s.starts_with("did:") && s.len() > 4)
307}
308
309fn has_did_document(did: &str) -> bool {
310    did.starts_with("did:web:") || did.starts_with("did:webvh:")
311}
312
313/// A protocol time, or None when the value is not one.
314fn protocol_time(v: &Value) -> Option<i128> {
315    v.as_str().and_then(|s| parse_protocol_time_ns(s).ok())
316}
317
318/// The first rule of a Vouch Credential's shape that `cred` breaks, in the
319/// reference's words, or None.
320pub fn structure_problem(
321    credential: &Value,
322    now: i128,
323    skew: i128,
324    expected_resource: Option<&str>,
325) -> Option<String> {
326    let Some(cred) = credential.as_object() else {
327        return Some("the credential is not a JSON object".into());
328    };
329    let first_context = cred
330        .get("@context")
331        .and_then(Value::as_array)
332        .and_then(|c| c.first());
333    if first_context.and_then(Value::as_str) != Some(VC_CONTEXT_V2) {
334        return Some("the credential's @context does not start with the VC 2.0 context".into());
335    }
336    let types_ok = cred.get("type").and_then(Value::as_array).is_some_and(|t| {
337        REQUIRED_TYPES
338            .iter()
339            .all(|want| t.iter().any(|x| x.as_str() == Some(want)))
340    });
341    if !types_ok {
342        return Some(
343            "the credential's type must include VerifiableCredential and VouchCredential".into(),
344        );
345    }
346    if issuer_did(credential).is_none() {
347        return Some("the credential's issuer is not a DID".into());
348    }
349    let Some(subject) = cred.get("credentialSubject").and_then(Value::as_object) else {
350        return Some("credentialSubject is not an object".into());
351    };
352    let version_ok = subject
353        .get("vouchVersion")
354        .and_then(Value::as_str)
355        .is_some_and(|v| SUPPORTED_VOUCH_VERSIONS.contains(&v));
356    if !version_ok {
357        return Some("credentialSubject.vouchVersion is missing or not supported".into());
358    }
359    let Some(intent) = subject.get("intent").and_then(Value::as_object) else {
360        return Some("credentialSubject.intent is not an object".into());
361    };
362    let resource = match intent.get("resource").and_then(Value::as_str) {
363        Some(r) if !r.is_empty() => r,
364        _ => return Some("intent.resource is missing or is not a non-empty string".into()),
365    };
366    if expected_resource.is_some_and(|want| want != resource) {
367        return Some("intent.resource is not the expected resource".into());
368    }
369    let (Some(Value::String(vf)), Some(Value::String(vu))) =
370        (cred.get("validFrom"), cred.get("validUntil"))
371    else {
372        return Some("the credential has no validity window".into());
373    };
374    let (Ok(from), Ok(until)) = (parse_protocol_time_ns(vf), parse_protocol_time_ns(vu)) else {
375        return Some("the credential's validity window is not valid times".into());
376    };
377    match window_state_ns(now, Some(from), Some(until), skew) {
378        WindowState::Inverted => {
379            return Some("the credential's validity window ends before it starts".into())
380        }
381        WindowState::Expired => return Some("the credential expired".into()),
382        WindowState::NotYetValid => return Some("the credential is not yet valid".into()),
383        WindowState::Ok => {}
384    }
385    grant_chain::binding_fields_problem(&credential["credentialSubject"]).map(String::from)
386}
387
388/// A credential's proofs, sorted by kind.
389#[derive(Debug, Clone)]
390pub struct Proofs {
391    /// "single" or "set".
392    pub kind: &'static str,
393    pub eddsa: Option<Value>,
394    pub mldsa: Option<Value>,
395    pub slhdsa: Option<Value>,
396}
397
398impl Proofs {
399    fn vm_of(p: Option<&Value>) -> Option<String> {
400        p.and_then(|p| p.get("verificationMethod"))
401            .and_then(Value::as_str)
402            .map(String::from)
403    }
404
405    /// The verificationMethod of the Ed25519 proof.
406    pub fn ed_vm(&self) -> Option<String> {
407        Self::vm_of(self.eddsa.as_ref())
408    }
409
410    /// The verificationMethod of the ML-DSA-44 proof of a set.
411    pub fn ml_vm(&self) -> Option<String> {
412        Self::vm_of(self.mldsa.as_ref())
413    }
414
415    /// The verificationMethod of the SLH-DSA proof of a set.
416    pub fn slh_vm(&self) -> Option<String> {
417        Self::vm_of(self.slhdsa.as_ref())
418    }
419
420    /// The suites of the proofs, in a fixed order.
421    pub fn suites(&self) -> Vec<hybrid::Suite> {
422        let mut out = Vec::new();
423        if self.eddsa.is_some() {
424            out.push(hybrid::Suite::Eddsa);
425        }
426        if self.mldsa.is_some() {
427            out.push(hybrid::Suite::Mldsa44);
428        }
429        if self.slhdsa.is_some() {
430            out.push(hybrid::Suite::Slhdsa128);
431        }
432        out
433    }
434
435    /// The proofValue the replay key is made from: the Ed25519 proof's.
436    pub fn replay_proof_value(&self) -> String {
437        self.eddsa
438            .as_ref()
439            .and_then(|p| p.get("proofValue"))
440            .and_then(Value::as_str)
441            .unwrap_or_default()
442            .to_string()
443    }
444}
445
446fn proof_problem(proof: &Value, issuer: &str, now: i128, skew: i128) -> Option<&'static str> {
447    let Some(p) = proof.as_object() else {
448        return Some("a proof is not an object");
449    };
450    if p.get("type").and_then(Value::as_str) != Some(data_integrity::PROOF_TYPE) {
451        return Some("a proof is not a DataIntegrityProof");
452    }
453    let suite = p.get("cryptosuite").and_then(Value::as_str).unwrap_or("");
454    // The earlier composite proof is refused: the post-quantum profile is
455    // a proof set of separate proofs only.
456    if hybrid::Suite::of(suite).is_none() {
457        return Some(hybrid::REASON_UNSUPPORTED_CRYPTOSUITE);
458    }
459    if p.get("proofPurpose").and_then(Value::as_str) != Some(ASSERTION) {
460        return Some("a proof's purpose is not assertionMethod");
461    }
462    let bound = p
463        .get("verificationMethod")
464        .and_then(Value::as_str)
465        .is_some_and(|vm| vm.split('#').next() == Some(issuer));
466    if !bound {
467        return Some("a proof's verificationMethod does not belong to the issuer");
468    }
469    if p.get("proofValue")
470        .and_then(Value::as_str)
471        .is_none_or(str::is_empty)
472    {
473        return Some("a proof has no proofValue");
474    }
475    if let Some(created) = p.get("created") {
476        if protocol_time(created).is_none() {
477            return Some("a proof's created is not a valid time");
478        }
479    }
480    if let Some(expires) = p.get("expires") {
481        let Some(e) = protocol_time(expires) else {
482            return Some("a proof's expires is not a valid time");
483        };
484        if window_state_ns(now, None, Some(e), skew) != WindowState::Ok {
485            return Some("a proof expired");
486        }
487    }
488    None
489}
490
491/// The reason a `proof` array that is not a proof set is refused.
492pub const REASON_PROOF_SET_SHAPE: &str =
493    "a proof set must be one eddsa-jcs-2022 proof and one proof of each post-quantum suite it carries";
494
495/// The credential's proofs, sorted by kind, or the first rule a proof breaks
496/// (every proof's type, cryptosuite, purpose, verificationMethod, proofValue,
497/// created and expires; then the shape: one eddsa-jcs-2022 proof, or a set of
498/// exactly one eddsa-jcs-2022 proof and one proof of each post-quantum suite
499/// it carries, ML-DSA-44 and/or SLH-DSA-SHA2-128s).
500pub fn read_proofs(
501    cred: &Value,
502    issuer: &str,
503    now: i128,
504    skew: i128,
505) -> std::result::Result<Proofs, &'static str> {
506    match cred.get("proof") {
507        Some(raw @ Value::Object(_)) => {
508            if let Some(problem) = proof_problem(raw, issuer, now, skew) {
509                return Err(problem);
510            }
511            match hybrid::Suite::of_proof(raw) {
512                Some(hybrid::Suite::Eddsa) => Ok(Proofs {
513                    kind: "single",
514                    eddsa: Some(raw.clone()),
515                    mldsa: None,
516                    slhdsa: None,
517                }),
518                Some(hybrid::Suite::Slhdsa128) => {
519                    Err("an SLH-DSA proof needs its eddsa-jcs-2022 partner in a proof set")
520                }
521                _ => Err("an ML-DSA-44 proof needs its eddsa-jcs-2022 partner in a proof set"),
522            }
523        }
524        Some(Value::Array(items)) => {
525            for p in items {
526                if let Some(problem) = proof_problem(p, issuer, now, skew) {
527                    return Err(problem);
528                }
529            }
530            let Some(members) = hybrid::set_members(items) else {
531                return Err(REASON_PROOF_SET_SHAPE);
532            };
533            Ok(Proofs {
534                kind: "set",
535                eddsa: Some(members.eddsa.clone()),
536                mldsa: members.mldsa44.cloned(),
537                slhdsa: members.slhdsa128.cloned(),
538            })
539        }
540        _ => Err("the credential has no proof"),
541    }
542}
543
544// ---------------------------------------------------------------------------
545// Keys
546// ---------------------------------------------------------------------------
547
548/// The keys found for one signer.
549#[derive(Debug, Clone, Default, PartialEq, Eq)]
550pub struct SignerKeys {
551    pub ed25519: Option<Vec<u8>>,
552    pub mldsa44: Option<Vec<u8>>,
553    pub slhdsa128: Option<Vec<u8>>,
554    /// The signer's DID document publishes an ML-DSA-44 assertion key, so
555    /// the ML-DSA-44 proof is required.
556    pub publishes_mldsa44: bool,
557    /// The signer's DID document publishes an SLH-DSA-SHA2-128s assertion
558    /// key, so the SLH-DSA proof is required.
559    pub publishes_slhdsa128: bool,
560}
561
562/// A strict Ed25519 key, or None.
563fn strict_ed25519(raw: &[u8]) -> Option<Vec<u8>> {
564    keys::strict_verifying_key(raw).ok().map(|_| raw.to_vec())
565}
566
567/// The key a did:key DID encodes (strict Ed25519), or None.
568fn did_key_key(did: &str) -> Option<Vec<u8>> {
569    let mk = did.strip_prefix("did:key:")?;
570    let decoded = multikey::decode(mk).ok()?;
571    (decoded.algorithm == "Ed25519").then_some(decoded.raw_key)
572}
573
574/// The keys of every source in the reference's order, merged: the caller's
575/// trusted keys, then the trusted roots' keys, then the key resolver's
576/// answers. The first source that names a DID is the only one used for it.
577fn effective_keys(input: &DecisionInput) -> BTreeMap<String, KeyEntry> {
578    let mut merged = input.resolved_keys.clone();
579    if let Some(roots) = &input.trusted_roots {
580        for (did, key) in &roots.keys {
581            merged.insert(did.clone(), key.clone());
582        }
583    }
584    for (did, key) in &input.trusted_keys {
585        merged.insert(did.clone(), key.clone());
586    }
587    merged
588}
589
590struct KeySource<'a> {
591    keys: BTreeMap<String, KeyEntry>,
592    mldsa44: &'a BTreeMap<String, Vec<u8>>,
593    slhdsa128: &'a BTreeMap<String, Vec<u8>>,
594    documents: &'a BTreeMap<String, Value>,
595}
596
597impl KeySource<'_> {
598    /// A signer's keys: the post-quantum key resolvers first; then the
599    /// caller's key for the DID (the only one used for it; for a did:key it
600    /// must be the key the DID encodes); then the did:key itself; then the
601    /// did:web or did:webvh document's assertionMethod keys the proof names.
602    fn keys(
603        &self,
604        did: &str,
605        ed_vm: Option<&str>,
606        ml_vm: Option<&str>,
607        slh_vm: Option<&str>,
608    ) -> SignerKeys {
609        // An unusable answer (an empty key) is no key to check with; the
610        // requirement it brings is read from the maps directly.
611        let mut found = SignerKeys {
612            mldsa44: self.mldsa44.get(did).filter(|k| !k.is_empty()).cloned(),
613            slhdsa128: self.slhdsa128.get(did).filter(|k| !k.is_empty()).cloned(),
614            ..Default::default()
615        };
616        let own = if did.starts_with("did:key:") {
617            match did_key_key(did) {
618                Some(k) => Some(k),
619                None => return found, // a did:key that does not decode has no key
620            }
621        } else {
622            None
623        };
624        if let Some(entry) = self.keys.get(did) {
625            found.ed25519 = match entry {
626                KeyEntry::Ed25519(k) => match &own {
627                    Some(o) if o != k => None,
628                    _ => strict_ed25519(k),
629                },
630                KeyEntry::Unusable => None,
631            };
632            return found;
633        }
634        if let Some(k) = own {
635            found.ed25519 = Some(k);
636            return found;
637        }
638        if has_did_document(did) {
639            let Some(doc) = self.documents.get(did) else {
640                return found;
641            };
642            if doc.get("id").and_then(Value::as_str) != Some(did) {
643                return found;
644            }
645            found.publishes_mldsa44 = did_document::publishes_mldsa44_assertion_key(doc, did);
646            if let Some(vm) = ed_vm {
647                found.ed25519 = did_document::assertion_key(doc, did, vm, did_document::ED25519)
648                    .ok()
649                    .and_then(|k| strict_ed25519(&k));
650            }
651            found.publishes_slhdsa128 = did_document::publishes_slhdsa128_assertion_key(doc, did);
652            if let (Some(vm), None) = (ml_vm, &found.mldsa44) {
653                found.mldsa44 =
654                    did_document::assertion_key(doc, did, vm, did_document::MLDSA44).ok();
655            }
656            if let (Some(vm), None) = (slh_vm, &found.slhdsa128) {
657                found.slhdsa128 =
658                    did_document::assertion_key(doc, did, vm, did_document::SLHDSA128).ok();
659            }
660        }
661        found
662    }
663}
664
665/// A JWK member decoded the way the reference's JWK reader decodes it: a
666/// body that leaves one character over is refused, padding is optional but
667/// when given is exactly the body's padding, and only trailing padding is
668/// read.
669fn jwk_base64url_decode(text: &str) -> Option<Vec<u8>> {
670    use base64::engine::{
671        general_purpose::GeneralPurpose, DecodePaddingMode, GeneralPurposeConfig,
672    };
673    use base64::{alphabet::URL_SAFE, Engine};
674    let body = text.trim_end_matches('=');
675    // Padding is optional, but when present it is exactly what the body
676    // needs (the reference refuses "x===" padding on a 43-character body).
677    let padding = text.len() - body.len();
678    if body.len() % 4 == 1 || (padding != 0 && padding != (4 - body.len() % 4) % 4) {
679        return None;
680    }
681    if body.contains('=') {
682        return None;
683    }
684    let engine = GeneralPurpose::new(
685        &URL_SAFE,
686        GeneralPurposeConfig::new()
687            .with_decode_allow_trailing_bits(true)
688            .with_decode_padding_mode(DecodePaddingMode::Indifferent),
689    );
690    engine.decode(body).ok()
691}
692
693/// A key the caller wrote as the reference reads it: a Multikey string
694/// ("z..."), or a JWK (an object, or its JSON text) of an Ed25519 public key.
695/// Every form is checked with the strict Ed25519 rules. Anything else is
696/// [`KeyEntry::Unusable`].
697pub fn key_entry_from_json(v: &Value) -> KeyEntry {
698    let jwk = match v {
699        Value::String(s) if s.starts_with('z') => {
700            return match multikey::decode(s) {
701                Ok(d) if d.algorithm == "Ed25519" => KeyEntry::Ed25519(d.raw_key),
702                _ => KeyEntry::Unusable,
703            };
704        }
705        Value::String(s) => match serde_json::from_str::<Value>(s) {
706            Ok(Value::Object(o)) => o,
707            _ => return KeyEntry::Unusable,
708        },
709        Value::Object(o) => o.clone(),
710        _ => return KeyEntry::Unusable,
711    };
712    if jwk.get("kty").and_then(Value::as_str) != Some("OKP")
713        || jwk.get("crv").and_then(Value::as_str) != Some("Ed25519")
714    {
715        return KeyEntry::Unusable;
716    }
717    let Some(x) = jwk.get("x").and_then(Value::as_str) else {
718        return KeyEntry::Unusable;
719    };
720    match jwk_base64url_decode(x).and_then(|raw| strict_ed25519(&raw)) {
721        Some(k) => KeyEntry::Ed25519(k),
722        None => KeyEntry::Unusable,
723    }
724}
725
726/// An ML-DSA-44 key as the reference reads one in text: a Multikey string of
727/// the ML-DSA-44 codec. None for anything else.
728pub fn mldsa44_key_from_json(v: &Value) -> Option<Vec<u8>> {
729    let s = v.as_str().filter(|s| s.starts_with('z'))?;
730    let d = multikey::decode(s).ok()?;
731    (d.algorithm == "ML-DSA-44").then_some(d.raw_key)
732}
733
734/// An SLH-DSA-SHA2-128s key in text: a Multikey string of the
735/// SLH-DSA-SHA2-128s codec ("u", base64url). None for anything else.
736pub fn slhdsa128_key_from_json(v: &Value) -> Option<Vec<u8>> {
737    let s = v.as_str().filter(|s| s.starts_with('u'))?;
738    let d = multikey::decode(s).ok()?;
739    (d.algorithm == multikey::SLHDSA128).then_some(d.raw_key)
740}
741
742// ---------------------------------------------------------------------------
743// Signatures, with the reference's malformed-input answers
744// ---------------------------------------------------------------------------
745
746/// The reference's strict Ed25519 signature rule: R is a canonical encoding
747/// of a curve point that is not of small order, and S is below L.
748fn strict_signature(sig: &[u8]) -> bool {
749    if sig.len() != keys::ED25519_SIGNATURE_LEN {
750        return false;
751    }
752    let mut r = [0u8; 32];
753    r.copy_from_slice(&sig[..32]);
754    if !keys::is_canonical_point_encoding(&r) {
755        return false;
756    }
757    match ed25519_dalek::VerifyingKey::from_bytes(&r) {
758        Ok(point) if !point.is_weak() => {}
759        _ => return false,
760    }
761    // S < L, comparing little-endian from the most significant byte.
762    for i in (0..32).rev() {
763        let s = sig[32 + i];
764        if s != GROUP_ORDER_LE[i] {
765            return s < GROUP_ORDER_LE[i];
766        }
767    }
768    false
769}
770
771/// `Err(exception name)` where the reference raises on a malformed proof
772/// (the verifier then answers "the credential is malformed (<name>)").
773type Checked = std::result::Result<bool, &'static str>;
774
775fn context_matches(document: &Value, proof: &Value) -> bool {
776    proof
777        .as_object()
778        .is_none_or(|p| data_integrity::proof_context_matches(document, p))
779}
780
781fn without_proof(cred: &Value) -> Value {
782    let mut base = cred.clone();
783    if let Some(o) = base.as_object_mut() {
784        o.remove("proof");
785    }
786    base
787}
788
789/// One eddsa-jcs-2022 proof, as `vouch.data_integrity.verify_proof` checks it.
790fn verify_ed25519_proof(cred: &Value, key: &[u8]) -> Checked {
791    let pv = cred
792        .get("proof")
793        .and_then(|p| p.get("proofValue"))
794        .and_then(Value::as_str)
795        .unwrap_or("");
796    let Some(body) = pv.strip_prefix('z') else {
797        return Err(VALUE_ERROR);
798    };
799    let sig = match multikey::decode_base58_bounded(body) {
800        Ok(s) if s.len() == keys::ED25519_SIGNATURE_LEN => s,
801        _ => return Err(VALUE_ERROR),
802    };
803    if !strict_signature(&sig) {
804        return Err(WEAK_KEY_ERROR);
805    }
806    if !context_matches(&without_proof(cred), &cred["proof"]) {
807        return Err(VALUE_ERROR);
808    }
809    data_integrity::verify_proof(cred, key).map_err(|_| VALUE_ERROR)
810}
811
812/// One post-quantum member of a set, as the reference checks it: a member
813/// that is malformed (its type, its key's length, its proofValue, its
814/// @context) is an error, a signature that does not verify is false.
815fn verify_pq_member(base: &Value, obj: &Map<String, Value>, key: &[u8]) -> Checked {
816    let suite = obj.get("cryptosuite").and_then(Value::as_str).unwrap_or("");
817    let slh = suite == hybrid::SLHDSA128_CRYPTOSUITE_ID;
818    let key_len = if slh {
819        crate::slh::SLHDSA128_PUBLIC_LEN
820    } else {
821        pq::MLDSA44_PUBLIC_LEN
822    };
823    if obj.get("type").and_then(Value::as_str) != Some(data_integrity::PROOF_TYPE)
824        || key.len() != key_len
825    {
826        return Err(VALUE_ERROR);
827    }
828    let pv = obj.get("proofValue").and_then(Value::as_str).unwrap_or("");
829    let sig = if slh {
830        hybrid::decode_slhdsa128_proof_value(pv)
831    } else {
832        hybrid::decode_mldsa44_proof_value(pv)
833    }
834    .map_err(|_| VALUE_ERROR)?;
835    if !data_integrity::proof_context_matches(base, obj) {
836        return Err(VALUE_ERROR);
837    }
838    let mut unsigned = obj.clone();
839    unsigned.remove("proofValue");
840    let input = data_integrity::hash_data(base, &unsigned).map_err(|_| VALUE_ERROR)?;
841    if slh {
842        return crate::slh::verify(key, &input, &sig).map_err(|_| VALUE_ERROR);
843    }
844    let mut ok = pq::verify(key, &input, &sig).map_err(|_| VALUE_ERROR)?;
845    if !ok {
846        let legacy =
847            data_integrity::legacy_proof_digest(base, &unsigned).map_err(|_| VALUE_ERROR)?;
848        ok = pq::verify(key, &legacy, &sig).map_err(|_| VALUE_ERROR)?;
849    }
850    Ok(ok)
851}
852
853/// A proof set, as `vouch.data_integrity_hybrid.verify_dual` checks it: the
854/// members in order, each one verified with its key, the Ed25519 member and
855/// at least one post-quantum member present. A post-quantum member with no
856/// key fails the set.
857fn verify_proof_set(cred: &Value, ed: &[u8], ml: Option<&[u8]>, slh: Option<&[u8]>) -> Checked {
858    let Some(items) = cred.get("proof").and_then(Value::as_array) else {
859        return Err(VALUE_ERROR);
860    };
861    let base = without_proof(cred);
862    let (mut ed_ok, mut pq_ok) = (false, false);
863    for p in items {
864        let Some(obj) = p.as_object() else { continue };
865        match hybrid::Suite::of_proof(p) {
866            Some(hybrid::Suite::Eddsa) => {
867                let mut candidate = base.clone();
868                candidate["proof"] = p.clone();
869                if !verify_ed25519_proof(&candidate, ed)? {
870                    return Ok(false);
871                }
872                ed_ok = true;
873            }
874            Some(suite) => {
875                let key = if suite == hybrid::Suite::Mldsa44 {
876                    ml
877                } else {
878                    slh
879                };
880                let Some(key) = key else {
881                    return Ok(false);
882                };
883                if !verify_pq_member(&base, obj, key)? {
884                    return Ok(false);
885                }
886                pq_ok = true;
887            }
888            None => {}
889        }
890    }
891    Ok(ed_ok && pq_ok)
892}
893
894enum ProofCheck {
895    Ok,
896    Refused(String),
897    MissingMldsa44Key,
898}
899
900/// The credential's proof (or its proof set) with the signer's keys.
901fn check_proofs(
902    cred: &Value,
903    proofs: &Proofs,
904    keys: &SignerKeys,
905    required: hybrid::Required,
906    explicit: bool,
907) -> ProofCheck {
908    let ed = keys.ed25519.as_deref().unwrap_or_default();
909    let verdict = if proofs.kind == "single" {
910        if required.any() {
911            return ProofCheck::Refused("a post-quantum proof is required".into());
912        }
913        verify_ed25519_proof(cred, ed)
914    } else {
915        if !required.met_by(&proofs.suites()) {
916            return ProofCheck::Refused(hybrid::REASON_REQUIRED_SUITE_MISSING.into());
917        }
918        if proofs.mldsa.is_some() && keys.mldsa44.is_none() {
919            if explicit {
920                return ProofCheck::MissingMldsa44Key;
921            }
922            return ProofCheck::Refused(
923                "no ML-DSA-44 key to check the post-quantum proof with".into(),
924            );
925        }
926        if proofs.slhdsa.is_some() && keys.slhdsa128.is_none() {
927            return ProofCheck::Refused(
928                "no SLH-DSA key to check the post-quantum proof with".into(),
929            );
930        }
931        verify_proof_set(cred, ed, keys.mldsa44.as_deref(), keys.slhdsa128.as_deref())
932    };
933    match verdict {
934        Ok(true) => ProofCheck::Ok,
935        Ok(false) => ProofCheck::Refused("the signature does not verify".into()),
936        Err(name) => ProofCheck::Refused(format!("the credential is malformed ({name})")),
937    }
938}
939
940// ---------------------------------------------------------------------------
941// Status
942// ---------------------------------------------------------------------------
943
944/// The verificationMethods a status list's proof names: (its eddsa-jcs-2022
945/// proof's, its ML-DSA-44 proof's).
946fn list_proof_methods(list: &Value) -> (Option<String>, Option<String>) {
947    let vm = |p: &Value| {
948        p.get("verificationMethod")
949            .and_then(Value::as_str)
950            .map(String::from)
951    };
952    let suite = |p: &Value| {
953        p.get("cryptosuite")
954            .and_then(Value::as_str)
955            .unwrap_or_default()
956            .to_string()
957    };
958    match list.get("proof") {
959        Some(p @ Value::Object(_)) => (vm(p), None),
960        Some(Value::Array(items)) => (
961            items
962                .iter()
963                .find(|p| suite(p) == hybrid::EDDSA_CRYPTOSUITE_ID)
964                .and_then(vm),
965            items
966                .iter()
967                .find(|p| suite(p) == hybrid::MLDSA44_CRYPTOSUITE_ID)
968                .and_then(vm),
969        ),
970        _ => (None, None),
971    }
972}
973
974/// The keys for one status list's proofs, as the reference's resolver gives
975/// them: for each proof, the verificationMethod it names is resolved on its
976/// own (the issuer's key already found for the same method, else the
977/// issuer's key from the same sources), and the answer must be a key of the
978/// proof's kind.
979fn list_keys(
980    list: Option<&Value>,
981    issuer: &str,
982    known: Option<(&Proofs, &SignerKeys)>,
983    source: &KeySource,
984) -> (Option<Vec<u8>>, Option<Vec<u8>>) {
985    let Some(list) = list else {
986        return (None, None);
987    };
988    // Each proof's method is resolved for its own kind of key, so an
989    // ML-DSA-44 method never answers with the issuer's Ed25519 key.
990    let resolve_ed = |vm: &str| -> Option<Vec<u8>> {
991        if let Some((proofs, keys)) = known {
992            if Some(vm) == proofs.ed_vm().as_deref() && keys.ed25519.is_some() {
993                return keys.ed25519.clone();
994            }
995        }
996        source.keys(issuer, Some(vm), None, None).ed25519
997    };
998    let resolve_ml = |vm: &str| -> Option<Vec<u8>> {
999        if let Some((proofs, keys)) = known {
1000            if Some(vm) == proofs.ml_vm().as_deref() && keys.mldsa44.is_some() {
1001                return keys.mldsa44.clone();
1002            }
1003        }
1004        source.keys(issuer, None, Some(vm), None).mldsa44
1005    };
1006    let (ed_vm, ml_vm) = list_proof_methods(list);
1007    // Only a method of the issuer's own DID resolves.
1008    let own = |vm: Option<String>| vm.filter(|v| v.split('#').next() == Some(issuer));
1009    let ed = own(ed_vm)
1010        .and_then(|vm| resolve_ed(&vm))
1011        .and_then(|k| strict_ed25519(&k));
1012    let ml = own(ml_vm)
1013        .and_then(|vm| resolve_ml(&vm))
1014        .filter(|k| k.len() == pq::MLDSA44_PUBLIC_LEN);
1015    (ed, ml)
1016}
1017
1018/// What a status list must carry: with `requirePostQuantum`, a post-quantum
1019/// suite in `requireSuites`, or a post-quantum key required of the list's
1020/// issuer (pinned, handed over, from a lookup or published), a list signed
1021/// with Ed25519 alone does not decide revocation.
1022fn list_requirement(input: &DecisionInput, issuer_requires_pq: bool) -> hybrid::Required {
1023    hybrid::Required {
1024        post_quantum: issuer_requires_pq
1025            || input.require_post_quantum
1026            || input
1027                .require_suites
1028                .iter()
1029                .any(|s| *s != hybrid::Suite::Eddsa),
1030        ..Default::default()
1031    }
1032}
1033
1034/// The status reason for one credential (the verifier's own credential, or
1035/// a grant), or None when its status is good. `known` carries the keys and
1036/// proofs already found for the verifier's own credential.
1037///
1038/// The entries are checked in order, as the reference checks them, and each
1039/// list is checked with the keys its own proofs name (two lists may be
1040/// signed with different keys of the issuer).
1041fn status_reason(
1042    checked: &Value,
1043    known: Option<(&Proofs, &SignerKeys)>,
1044    source: &KeySource,
1045    input: &DecisionInput,
1046    issuer_requires_pq: bool,
1047) -> Result<Option<String>> {
1048    let Some(raw) = checked.get("credentialStatus") else {
1049        return Ok(None);
1050    };
1051    let unavailable = || Ok(Some(status_list::STATUS_UNAVAILABLE.to_string()));
1052    let entries: Vec<&Value> = match raw {
1053        Value::Object(_) => vec![raw],
1054        Value::Array(items) => items.iter().collect(),
1055        _ => Vec::new(),
1056    };
1057    if entries.is_empty() || entries.len() > status_list::MAX_STATUS_ENTRIES {
1058        return unavailable();
1059    }
1060    let issuer = issuer_did(checked).unwrap_or_default().to_string();
1061    for entry in entries {
1062        let list = entry
1063            .get("statusListCredential")
1064            .and_then(Value::as_str)
1065            .and_then(|url| input.status_lists.get(url));
1066        let (ed_key, ml_key) = list_keys(list, &issuer, known, source);
1067        let mut one = checked.clone();
1068        one["credentialStatus"] = entry.clone();
1069        let result = status_list::check_credential_status_required(
1070            &one,
1071            &input.status_lists,
1072            ed_key.as_deref(),
1073            ml_key.as_deref(),
1074            &input.now,
1075            input.clock_skew_seconds,
1076            list_requirement(input, issuer_requires_pq),
1077        )?;
1078        if !result.ok {
1079            return Ok(Some(result.reason.to_string()));
1080        }
1081    }
1082    Ok(None)
1083}
1084
1085// ---------------------------------------------------------------------------
1086// Replay
1087// ---------------------------------------------------------------------------
1088
1089fn check_replay_window(seconds: f64) -> Result<f64> {
1090    if !seconds.is_finite() || seconds <= 0.0 {
1091        return Err(CoreError::Json(
1092            "max_replay_window must be a positive, finite number of seconds".into(),
1093        ));
1094    }
1095    Ok(seconds)
1096}
1097
1098fn window_seconds(cred: &Value) -> Result<f64> {
1099    let t = |k: &str| {
1100        cred.get(k)
1101            .and_then(Value::as_str)
1102            .ok_or_else(|| CoreError::Json(format!("credential missing {k}")))
1103            .and_then(parse_protocol_time_ns)
1104    };
1105    Ok((t("validUntil")? - t("validFrom")?) as f64 / NS_PER_SECOND as f64)
1106}
1107
1108/// True when a credential's validity window is longer than the replay
1109/// window: it is meant to be shown many times, so it is not tracked.
1110pub fn replay_window_too_long(credential: &Value, max_replay_window_seconds: f64) -> Result<bool> {
1111    Ok(window_seconds(credential)? > check_replay_window(max_replay_window_seconds)?)
1112}
1113
1114fn identity_from(
1115    cred: &Value,
1116    proofs: &Proofs,
1117    skew_seconds: i64,
1118    max_window: f64,
1119) -> Result<ReplayIdentity> {
1120    let issuer = issuer_did(cred).unwrap_or_default();
1121    let key = crate::credentials::replay_key(issuer, &proofs.replay_proof_value())?;
1122    let until = cred
1123        .get("validUntil")
1124        .and_then(Value::as_str)
1125        .ok_or_else(|| CoreError::Json("credential missing validUntil".into()))?;
1126    // As the reference computes it: validUntil read to the microsecond, as
1127    // seconds (micros / 10^6, one correctly rounded division), plus the skew.
1128    let until_micros = parse_protocol_time_ns(until)?.div_euclid(1000);
1129    Ok(ReplayIdentity {
1130        key,
1131        expires_at: until_micros as f64 / 1e6 + skew_seconds as f64,
1132        single_use: !replay_window_too_long(cred, max_window)?,
1133    })
1134}
1135
1136/// `(replay key, keep-until)` for a credential that has already verified
1137/// (the reference's `vouch.verifier.replay_identity`), with whether it is
1138/// single use under `max_replay_window_seconds`.
1139///
1140/// Errors: a skew outside 0..120, a malformed `now` or validity window, a
1141/// replay window that is not a positive number, or proofs of a shape the
1142/// verifier refuses (the error is that refusal).
1143pub fn replay_identity(
1144    credential: &Value,
1145    now_iso: &str,
1146    clock_skew_seconds: i64,
1147    max_replay_window_seconds: f64,
1148) -> Result<ReplayIdentity> {
1149    let skew = check_clock_skew(clock_skew_seconds)?;
1150    let now = parse_protocol_time_ns(now_iso)?.div_euclid(1000) * 1000;
1151    check_replay_window(max_replay_window_seconds)?;
1152    let issuer = issuer_did(credential).unwrap_or_default();
1153    let proofs =
1154        read_proofs(credential, issuer, now, skew).map_err(|p| CoreError::Json(p.into()))?;
1155    identity_from(
1156        credential,
1157        &proofs,
1158        clock_skew_seconds,
1159        max_replay_window_seconds,
1160    )
1161}
1162
1163// ---------------------------------------------------------------------------
1164// The passport
1165// ---------------------------------------------------------------------------
1166
1167/// The verified passport: who signed what, for how long, and the grants of
1168/// its delegation chain, each read from the signed grant itself.
1169pub fn passport(cred: &Value, grants: &[&Value]) -> Value {
1170    let chain: Vec<Value> = grants
1171        .iter()
1172        .map(|g| {
1173            let intent = g["credentialSubject"]["intent"].clone();
1174            let bound: String = crate::delegation::parent_proof_binding_value(g)
1175                .chars()
1176                .take(64)
1177                .collect();
1178            json!({
1179                "issuer": issuer_did(g).unwrap_or_default(),
1180                "subject": intent.get("delegatee").cloned().unwrap_or(json!("")),
1181                "intent": intent,
1182                "validFrom": g.get("validFrom").cloned().unwrap_or(Value::Null),
1183                "validUntil": g.get("validUntil").cloned().unwrap_or(Value::Null),
1184                "parentProofValue": bound,
1185            })
1186        })
1187        .collect();
1188    let subject = &cred["credentialSubject"];
1189    let rep = subject
1190        .get("reputationScore")
1191        .and_then(|v| {
1192            if v.is_i64() || v.is_u64() {
1193                v.as_i64()
1194            } else {
1195                None
1196            }
1197        })
1198        .filter(|r| (0..=100).contains(r));
1199    let text = |v: Option<&Value>| v.and_then(Value::as_str).unwrap_or_default().to_string();
1200    json!({
1201        "sub": text(subject.get("id")),
1202        "iss": issuer_did(cred).unwrap_or_default(),
1203        "validFrom": cred["validFrom"],
1204        "validUntil": cred["validUntil"],
1205        "credentialId": text(cred.get("id")),
1206        "intent": subject["intent"],
1207        "reputationScore": rep,
1208        "delegationChain": chain,
1209        "parentGrantDigest": subject.get(grant_chain::PARENT_GRANT_DIGEST).filter(|d| d.is_string()),
1210    })
1211}
1212
1213// ---------------------------------------------------------------------------
1214// The decision
1215// ---------------------------------------------------------------------------
1216
1217fn chain_root(chain: &[Value]) -> Option<&str> {
1218    chain.first()?.get("issuer")?.as_str()
1219}
1220
1221/// What the link fields alone say about a chain, before any key or document
1222/// is looked up (the reference's `_chain_prefilter`).
1223fn chain_prefilter(cred: &Value, chain: &[Value], root_dids: &[String]) -> Option<&'static str> {
1224    for link in chain {
1225        let ok = link.get("issuer").is_some_and(Value::is_string)
1226            && link.get("subject").is_some_and(Value::is_string);
1227        if !ok {
1228            return Some(grant_chain::REASON_MALFORMED);
1229        }
1230    }
1231    for i in 1..chain.len() {
1232        if chain[i - 1]["subject"] != chain[i]["issuer"] {
1233            return Some("delegation_subject_issuer_mismatch");
1234        }
1235    }
1236    if chain[chain.len() - 1]["subject"].as_str() != issuer_did(cred) {
1237        return Some("delegation_subject_issuer_mismatch");
1238    }
1239    let root = chain[0]["issuer"].as_str().unwrap_or_default();
1240    if !root_dids.iter().any(|d| d == root) {
1241        return Some("untrusted_principal");
1242    }
1243    if chain
1244        .iter()
1245        .all(|l| matches!(l.get("parentCredential"), Some(Value::Object(_))))
1246    {
1247        return grant_chain::chain_binding_problem(chain);
1248    }
1249    None
1250}
1251
1252/// The reference reads the verifier's clock as a Python `datetime`, which
1253/// holds microseconds: digits past the sixth are dropped (toward the past).
1254/// The validity bounds are still compared at full precision.
1255fn at_microseconds(input: &DecisionInput) -> Result<DecisionInput> {
1256    let ns = parse_protocol_time_ns(&input.now)?;
1257    let micros = ns.div_euclid(1000) * 1000;
1258    let mut out = input.clone();
1259    out.now = format_time_micros(micros)?;
1260    Ok(out)
1261}
1262
1263/// A protocol time with exactly six fraction digits.
1264pub(crate) fn format_time_micros(ns: i128) -> Result<String> {
1265    let whole = crate::issuance::format_protocol_time(ns)?;
1266    let micros = ns.rem_euclid(NS_PER_SECOND) / 1000;
1267    Ok(format!("{}.{micros:06}Z", whole.trim_end_matches('Z')))
1268}
1269
1270type Precheck<'a> = (Proofs, Option<&'a Vec<Value>>, Vec<String>);
1271
1272/// The checks that need nothing fetched, in the reference's order: the
1273/// shape, the trusted issuers, every proof's own fields, and for a
1274/// delegation chain the size guard and depth budget, the trusted roots and
1275/// the link fields. `Ok(Err(reason))` is a refusal.
1276fn precheck(input: &DecisionInput) -> Result<std::result::Result<Precheck<'_>, String>> {
1277    let skew = check_clock_skew(input.clock_skew_seconds)?;
1278    let now = parse_protocol_time_ns(&input.now)?;
1279    if !input.credential.is_object() {
1280        return Ok(Err("the credential is not a JSON object".into()));
1281    }
1282    check_replay_window(input.max_replay_window_seconds)?;
1283    let cred = &input.credential;
1284    let root_dids: Vec<String> = input
1285        .trusted_roots
1286        .as_ref()
1287        .map(|r| r.dids.clone())
1288        .unwrap_or_default();
1289    if let Some(problem) = structure_problem(cred, now, skew, input.expected_resource.as_deref()) {
1290        return Ok(Err(problem));
1291    }
1292    let issuer = issuer_did(cred).unwrap_or_default().to_string();
1293    if let Some(allowed) = &input.allowed_issuers {
1294        if !allowed.contains(&issuer) {
1295            return Ok(Err("the issuer is not one of the trusted keys".into()));
1296        }
1297    }
1298    let proofs = match read_proofs(cred, &issuer, now, skew) {
1299        Ok(p) => p,
1300        Err(problem) => return Ok(Err(problem.into())),
1301    };
1302    // The verifier's requireSuites setting: every suite it names must be
1303    // among the credential's proofs.
1304    let carried = proofs.suites();
1305    if input.require_suites.iter().any(|s| !carried.contains(s)) {
1306        return Ok(Err(hybrid::REASON_REQUIRED_SUITE_MISSING.into()));
1307    }
1308    let chain = cred["credentialSubject"]
1309        .get("delegationChain")
1310        .and_then(Value::as_array)
1311        .filter(|c| !c.is_empty());
1312    // A sub-grant names its parent grant by digest instead of carrying a
1313    // chain. The digest is not looked up here, so it excuses the missing
1314    // chain only when the host says it verified the grant chain handed over
1315    // beside the credential (grantChainCheckedApart).
1316    let names_parent = input.grant_chain_checked_apart
1317        && cred["credentialSubject"]
1318            .as_object()
1319            .is_some_and(|s| s.contains_key(grant_chain::PARENT_GRANT_DIGEST));
1320    if chain.is_none()
1321        && !names_parent
1322        && input.chain_required_outside_roots
1323        && !root_dids.is_empty()
1324        && !root_dids.contains(&issuer)
1325    {
1326        return Ok(Err(REASON_CHAIN_REQUIRED.into()));
1327    }
1328    if let Some(chain) = chain {
1329        let as_value = Value::Array(chain.clone());
1330        match crate::attenuation::chain_budget_exceeded(&as_value, input.max_depth) {
1331            Ok(None) => {}
1332            Ok(Some(_)) => return Ok(Err(REASON_BUDGET.into())),
1333            Err(_) => return Ok(Err(grant_chain::REASON_MALFORMED.into())),
1334        }
1335        if root_dids.is_empty() {
1336            return Ok(Err(untrusted_root_reason(chain_root(chain), false)));
1337        }
1338        if let Some(early) = chain_prefilter(cred, chain, &root_dids) {
1339            if early == "untrusted_principal" {
1340                return Ok(Err(untrusted_root_reason(chain_root(chain), true)));
1341            }
1342            return Ok(Err(early.into()));
1343        }
1344    }
1345    Ok(Ok((proofs, chain, root_dids)))
1346}
1347
1348/// Decide whether to accept a credential, as `vouch.verifier.Verifier.verify`
1349/// decides it, with everything the host fetched in `input`.
1350///
1351/// Errors (a caller mistake, never a verdict): a skew outside 0..120, a
1352/// malformed `now`, a replay window that is not a positive number, and
1353/// [`MISSING_MLDSA44_KEY`] when the caller handed over the issuer's Ed25519
1354/// key, the credential carries a post-quantum proof, and no ML-DSA-44 key is
1355/// known.
1356pub fn decide(input: &DecisionInput) -> Result<Decision> {
1357    let input = &at_microseconds(input)?;
1358    let (proofs, chain, root_dids) = match precheck(input)? {
1359        Ok(pre) => pre,
1360        Err(reason) => return Ok(Decision::refuse(reason)),
1361    };
1362    let cred = &input.credential;
1363    let issuer = issuer_did(cred).unwrap_or_default().to_string();
1364
1365    let source = KeySource {
1366        keys: effective_keys(input),
1367        mldsa44: &input.mldsa44_keys,
1368        slhdsa128: &input.slhdsa128_keys,
1369        documents: &input.documents,
1370    };
1371
1372    // The delegation chain's signed grants, from the trusted root down,
1373    // before the credential issuer's own key is looked up (as the reference
1374    // verifier does).
1375    let mut grants: Vec<&Value> = Vec::new();
1376    if let Some(chain) = chain {
1377        let grant_keys: BTreeMap<String, Vec<u8>> = source
1378            .keys
1379            .iter()
1380            .map(|(did, entry)| {
1381                let raw = match entry {
1382                    KeyEntry::Ed25519(k) => k.clone(),
1383                    // Present but unusable: the only key for the DID, and no key.
1384                    KeyEntry::Unusable => Vec::new(),
1385                };
1386                (did.clone(), raw)
1387            })
1388            .collect();
1389        let documents: BTreeMap<String, Value> = input
1390            .documents
1391            .iter()
1392            .filter(|(did, _)| has_did_document(did))
1393            .map(|(d, v)| (d.clone(), v.clone()))
1394            .collect();
1395        let opts = ChainOptions {
1396            trusted_roots: Some(&root_dids),
1397            grant_keys: Some(&grant_keys),
1398            mldsa_keys: Some(&input.mldsa44_keys),
1399            slhdsa_keys: Some(&input.slhdsa128_keys),
1400            grant_documents: Some(&documents),
1401            require_pq: input.require_post_quantum,
1402            require_suites: &input.require_suites,
1403            max_depth: input.max_depth,
1404            ..Default::default()
1405        };
1406        if let Some(reason) = crate::delegation::verify_delegation_chain_with(
1407            cred,
1408            &input.now,
1409            input.clock_skew_seconds,
1410            &opts,
1411        ) {
1412            if reason == "untrusted_principal" {
1413                return Ok(Decision::refuse(untrusted_root_reason(
1414                    chain_root(chain),
1415                    true,
1416                )));
1417            }
1418            return Ok(Decision::refuse(reason));
1419        }
1420        grants = chain.iter().map(|l| &l["parentCredential"]).collect();
1421    }
1422
1423    // The issuer's keys.
1424    let explicit = input.public_key.is_some();
1425    let mut keys = match &input.public_key {
1426        Some(KeyEntry::Unusable) => {
1427            return Ok(Decision::refuse(
1428                "the public key given is not a usable Ed25519 key",
1429            ))
1430        }
1431        Some(KeyEntry::Ed25519(k)) => {
1432            let Some(pinned) = strict_ed25519(k) else {
1433                return Ok(Decision::refuse(
1434                    "the public key given is not a usable Ed25519 key",
1435                ));
1436            };
1437            if issuer.starts_with("did:key:") && did_key_key(&issuer).as_ref() != Some(&pinned) {
1438                return Ok(Decision::refuse(
1439                    "the public key given is not the did:key issuer's key",
1440                ));
1441            }
1442            // A post-quantum key the caller's lookup answered for the issuer
1443            // still counts: handing over the Ed25519 key does not turn the
1444            // post-quantum requirement off.
1445            SignerKeys {
1446                ed25519: Some(pinned),
1447                mldsa44: input
1448                    .mldsa44_keys
1449                    .get(&issuer)
1450                    .filter(|k| !k.is_empty())
1451                    .cloned(),
1452                slhdsa128: input
1453                    .slhdsa128_keys
1454                    .get(&issuer)
1455                    .filter(|k| !k.is_empty())
1456                    .cloned(),
1457                ..Default::default()
1458            }
1459        }
1460        None => {
1461            let (ml_vm, slh_vm) = if proofs.kind != "single" {
1462                (proofs.ml_vm(), proofs.slh_vm())
1463            } else {
1464                (None, None)
1465            };
1466            let found = source.keys(
1467                &issuer,
1468                proofs.ed_vm().as_deref(),
1469                ml_vm.as_deref(),
1470                slh_vm.as_deref(),
1471            );
1472            if found.ed25519.is_none() {
1473                return Ok(Decision::refuse(REASON_NO_KEY));
1474            }
1475            found
1476        }
1477    };
1478    if let Some(given) = &input.mldsa44_public_key {
1479        match given {
1480            Some(k) if k.len() == pq::MLDSA44_PUBLIC_LEN => keys.mldsa44 = Some(k.clone()),
1481            _ => {
1482                return Ok(Decision::refuse(
1483                    "the ML-DSA-44 public key given is not a 1312-byte key",
1484                ))
1485            }
1486        }
1487    }
1488    if let Some(given) = &input.slhdsa128_public_key {
1489        match given {
1490            Some(k) if k.len() == crate::slh::SLHDSA128_PUBLIC_LEN => {
1491                keys.slhdsa128 = Some(k.clone())
1492            }
1493            _ => {
1494                return Ok(Decision::refuse(
1495                    "the SLH-DSA public key given is not a 32-byte key",
1496                ))
1497            }
1498        }
1499    }
1500    // A post-quantum key the caller handed over, one its key resolver
1501    // answered for the issuer, or one the issuer's DID document publishes
1502    // for assertions, makes that suite's proof required, so it cannot be
1503    // dropped from a credential.
1504    let resolved_ml = input.mldsa44_keys.contains_key(&issuer);
1505    let resolved_slh = input.slhdsa128_keys.contains_key(&issuer);
1506    let required = hybrid::Required {
1507        post_quantum: input.require_post_quantum,
1508        mldsa44: input.mldsa44_public_key.is_some() || keys.publishes_mldsa44 || resolved_ml,
1509        slhdsa128: input.slhdsa128_public_key.is_some() || keys.publishes_slhdsa128 || resolved_slh,
1510    };
1511    match check_proofs(cred, &proofs, &keys, required, explicit) {
1512        ProofCheck::Ok => {}
1513        ProofCheck::Refused(reason) => return Ok(Decision::refuse(reason)),
1514        ProofCheck::MissingMldsa44Key => {
1515            return Err(CoreError::Json(format!(
1516                "{MISSING_MLDSA44_KEY}: this credential carries an ML-DSA-44 post-quantum \
1517                 proof; pass the ML-DSA-44 public key or publish it in the issuer's DID \
1518                 document. A did:key identifier encodes only the Ed25519 key."
1519            )))
1520        }
1521    }
1522
1523    // The credential's own status, then every grant's, each against a list
1524    // signed by that credential's issuer.
1525    if input.check_status {
1526        if let Some(reason) =
1527            status_reason(cred, Some((&proofs, &keys)), &source, input, required.any())?
1528        {
1529            return Ok(Decision::refuse(reason));
1530        }
1531        for grant in &grants {
1532            // A grant issuer whose post-quantum key is known (pinned or from
1533            // a lookup) needs that proof on its lists too.
1534            let grant_issuer = issuer_did(grant).unwrap_or_default();
1535            let grant_pq = input.mldsa44_keys.contains_key(grant_issuer)
1536                || input.slhdsa128_keys.contains_key(grant_issuer);
1537            if let Some(reason) = status_reason(grant, None, &source, input, grant_pq)? {
1538                return Ok(Decision::refuse(format!("delegation_{reason}")));
1539            }
1540        }
1541    }
1542
1543    Ok(Decision {
1544        valid: true,
1545        reason: None,
1546        passport: Some(passport(cred, &grants)),
1547        replay: Some(identity_from(
1548            cred,
1549            &proofs,
1550            input.clock_skew_seconds,
1551            input.max_replay_window_seconds,
1552        )?),
1553        issuer_key: keys.ed25519.clone(),
1554    })
1555}
1556
1557/// The most DIDs a fetch plan names (the issuer and the chain's grant
1558/// issuers whose keys come from a DID document or log).
1559pub const MAX_FETCH_DIDS: usize = 32;
1560/// The most status list URLs a fetch plan names (the credential's and its
1561/// verified grants').
1562pub const MAX_FETCH_STATUS_LISTS: usize = 32;
1563
1564/// Which fetches a plan is for.
1565#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1566pub enum FetchPhase {
1567    /// Before anything is fetched: the DID documents and did:webvh logs the
1568    /// keys come from.
1569    Documents,
1570    /// After the documents are in: the status lists, named only once every
1571    /// signature has verified.
1572    StatusLists,
1573}
1574
1575/// What a host fetches before [`decide`], and whether it needs to.
1576#[derive(Debug, Clone, Default, PartialEq, Eq)]
1577pub struct FetchPlan {
1578    /// The verdict, when the checks that need nothing fetched already refuse
1579    /// the credential (or, for [`FetchPhase::StatusLists`], when the
1580    /// signatures or the chain refuse it). The host fetches nothing and
1581    /// gives this refusal.
1582    pub refusal: Option<String>,
1583    /// DIDs whose DID document (did:web) or log (did:webvh) to fetch.
1584    pub dids: Vec<String>,
1585    /// Status list URLs to fetch.
1586    pub status_lists: Vec<String>,
1587    /// True when more were needed than the plan names (see
1588    /// [`MAX_FETCH_DIDS`], [`MAX_FETCH_STATUS_LISTS`]); what is left out is
1589    /// simply not there, as a failed fetch.
1590    pub truncated: bool,
1591}
1592
1593fn push_unique(
1594    list: &mut Vec<String>,
1595    seen: &mut std::collections::BTreeSet<String>,
1596    item: &str,
1597    cap: usize,
1598    truncated: &mut bool,
1599) {
1600    if item.is_empty() || seen.contains(item) {
1601        return;
1602    }
1603    if list.len() >= cap {
1604        *truncated = true;
1605        return;
1606    }
1607    seen.insert(item.to_string());
1608    list.push(item.to_string());
1609}
1610
1611fn status_urls(c: &Value) -> Vec<&str> {
1612    let entries: Vec<&Value> = match c.get("credentialStatus") {
1613        Some(e @ Value::Object(_)) => vec![e],
1614        Some(Value::Array(a)) => a.iter().take(status_list::MAX_STATUS_ENTRIES).collect(),
1615        _ => Vec::new(),
1616    };
1617    entries
1618        .iter()
1619        .filter_map(|e| e.get("statusListCredential").and_then(Value::as_str))
1620        .collect()
1621}
1622
1623/// What a host has to fetch for [`decide`], in two phases, from the same
1624/// input it will decide with (the trust settings included).
1625///
1626/// [`FetchPhase::Documents`] first runs every check that needs nothing
1627/// fetched (the shape, the trusted issuers, the proofs' own fields, and for a
1628/// delegation chain the 1 MiB size guard, the depth budget, the trusted roots
1629/// and the link fields). When they refuse, the plan is that refusal and
1630/// nothing to fetch. Otherwise it names the did:web and did:webvh DIDs whose
1631/// keys are not already known: the issuer (unless its key was handed over)
1632/// and each grant issuer of the chain.
1633///
1634/// [`FetchPhase::StatusLists`] runs [`decide`] with the documents the host
1635/// put in `input` and the status check off. When the credential is refused
1636/// (a signature, a key, or the chain), the plan is that refusal. Otherwise it
1637/// names the status lists of the credential and of its verified grants.
1638///
1639/// Every list is deduplicated and capped. The host stays in charge of its
1640/// own fetch budget, as the reference is: one time budget for every fetch of
1641/// a verification (the reference's default is 20 seconds, at most 10 per
1642/// fetch), SSRF rules for every URL, and a size cap on every response. A
1643/// fetch that fails or runs out of time is left out of the input, which the
1644/// decision reads as "no key" or "status_unavailable".
1645pub fn fetch_plan(input: &DecisionInput, phase: FetchPhase) -> Result<FetchPlan> {
1646    let input = &at_microseconds(input)?;
1647    let mut plan = FetchPlan::default();
1648    match phase {
1649        FetchPhase::Documents => {
1650            let (_, chain, _) = match precheck(input)? {
1651                Ok(pre) => pre,
1652                Err(reason) => {
1653                    plan.refusal = Some(reason);
1654                    return Ok(plan);
1655                }
1656            };
1657            let known = effective_keys(input);
1658            let mut seen = std::collections::BTreeSet::new();
1659            let mut wanted: Vec<&str> = Vec::new();
1660            if input.public_key.is_none() {
1661                wanted.extend(issuer_did(&input.credential));
1662            }
1663            for link in chain.into_iter().flatten() {
1664                wanted.extend(link.get("issuer").and_then(Value::as_str));
1665            }
1666            for did in wanted {
1667                if has_did_document(did) && !known.contains_key(did) {
1668                    push_unique(
1669                        &mut plan.dids,
1670                        &mut seen,
1671                        did,
1672                        MAX_FETCH_DIDS,
1673                        &mut plan.truncated,
1674                    );
1675                }
1676            }
1677        }
1678        FetchPhase::StatusLists => {
1679            let mut without_status = input.clone();
1680            without_status.check_status = false;
1681            // A caller error (a post-quantum proof with no ML-DSA-44 key
1682            // handed over) is the same error decide gives.
1683            let decision = decide(&without_status)?;
1684            if !decision.valid {
1685                plan.refusal = decision.reason;
1686                return Ok(plan);
1687            }
1688            if !input.check_status {
1689                return Ok(plan);
1690            }
1691            let mut seen = std::collections::BTreeSet::new();
1692            let cred = &input.credential;
1693            let mut urls = status_urls(cred);
1694            if let Some(chain) = cred["credentialSubject"]
1695                .get("delegationChain")
1696                .and_then(Value::as_array)
1697            {
1698                for link in chain {
1699                    urls.extend(status_urls(&link["parentCredential"]));
1700                }
1701            }
1702            for url in urls {
1703                push_unique(
1704                    &mut plan.status_lists,
1705                    &mut seen,
1706                    url,
1707                    MAX_FETCH_STATUS_LISTS,
1708                    &mut plan.truncated,
1709                );
1710            }
1711        }
1712    }
1713    Ok(plan)
1714}
1715
1716// ---------------------------------------------------------------------------
1717// JSON in, JSON out (for the bindings)
1718// ---------------------------------------------------------------------------
1719
1720const REQUEST_MEMBERS: [&str; 27] = [
1721    "credential",
1722    "now",
1723    "clockSkewSeconds",
1724    "publicKey",
1725    "mldsa44PublicKey",
1726    "slhdsa128PublicKey",
1727    "trustedKeys",
1728    "resolvedKeys",
1729    "mldsa44Keys",
1730    "slhdsa128Keys",
1731    "documents",
1732    "didLogs",
1733    "didLogsB64",
1734    "seenVersionIds",
1735    "limits",
1736    "logNow",
1737    "trustedRoots",
1738    "requirePostQuantum",
1739    "requireSuites",
1740    "expectedResource",
1741    "checkStatus",
1742    "statusLists",
1743    "maxDepth",
1744    "maxReplayWindowSeconds",
1745    "requireTrustedIssuer",
1746    "chainRequiredOutsideRoots",
1747    "grantChainCheckedApart",
1748];
1749
1750fn bad(msg: impl Into<String>) -> CoreError {
1751    CoreError::Json(msg.into())
1752}
1753
1754fn present<'a>(obj: &'a Map<String, Value>, name: &str) -> Option<&'a Value> {
1755    obj.get(name).filter(|v| !v.is_null())
1756}
1757
1758/// The request members that tighten a check. Written as null they are an
1759/// error, never "not set": a host that serialized an unset or failed setting
1760/// as null must not get the permissive default. Leave a member out to mean
1761/// the default.
1762const TIGHTENING_MEMBERS: [&str; 15] = [
1763    "trustedRoots",
1764    "trustedKeys",
1765    "publicKey",
1766    "mldsa44Keys",
1767    "slhdsa128Keys",
1768    "requirePostQuantum",
1769    "requireSuites",
1770    "requireTrustedIssuer",
1771    "expectedResource",
1772    "checkStatus",
1773    "chainRequiredOutsideRoots",
1774    "grantChainCheckedApart",
1775    "mldsa44PublicKey",
1776    "slhdsa128PublicKey",
1777    "maxDepth",
1778];
1779
1780fn refuse_null_tightening(obj: &Map<String, Value>) -> Result<()> {
1781    for name in TIGHTENING_MEMBERS {
1782        if matches!(obj.get(name), Some(Value::Null)) {
1783            return Err(bad(format!(
1784                "{name} must not be null: leave it out for the default"
1785            )));
1786        }
1787    }
1788    Ok(())
1789}
1790
1791/// Read a credential handed over as JSON text with the one strict reader:
1792/// a member named twice, a number that is not finite or text that is not
1793/// JSON is no credential (null), so every SDK sees the same object.
1794fn credential_from_text(text: &str) -> Value {
1795    crate::authority_state::parse_json_no_duplicates(text).unwrap_or(Value::Null)
1796}
1797
1798fn bool_member(obj: &Map<String, Value>, name: &str, default: bool) -> Result<bool> {
1799    match present(obj, name) {
1800        None => Ok(default),
1801        Some(Value::Bool(b)) => Ok(*b),
1802        Some(_) => Err(bad(format!("{name} must be true or false"))),
1803    }
1804}
1805
1806fn object_member<'a>(
1807    obj: &'a Map<String, Value>,
1808    name: &str,
1809) -> Result<Option<&'a Map<String, Value>>> {
1810    match present(obj, name) {
1811        None => Ok(None),
1812        Some(Value::Object(m)) => Ok(Some(m)),
1813        Some(_) => Err(bad(format!("{name} must be a JSON object"))),
1814    }
1815}
1816
1817fn string_list(v: &Value, name: &str) -> Result<Vec<String>> {
1818    v.as_array()
1819        .and_then(|a| {
1820            a.iter()
1821                .map(|x| x.as_str().map(String::from))
1822                .collect::<Option<Vec<_>>>()
1823        })
1824        .ok_or_else(|| bad(format!("{name} must be a list of strings")))
1825}
1826
1827/// Trusted roots as the reference reads them: a DID or domain, a list of
1828/// them, or a `{did: key}` map (its keys are also used for those issuers).
1829/// Every root is normalized ([`crate::did_web::normalize_root`]).
1830pub fn trusted_roots_from_json(v: &Value) -> Result<Option<TrustedRoots>> {
1831    let norm = crate::did_web::normalize_root;
1832    match v {
1833        Value::Null => Ok(None),
1834        Value::String(s) => Ok(Some(TrustedRoots {
1835            dids: vec![norm(s)?],
1836            keys: BTreeMap::new(),
1837        })),
1838        Value::Array(_) => Ok(Some(TrustedRoots {
1839            dids: string_list(v, "trustedRoots")?
1840                .iter()
1841                .map(|s| norm(s))
1842                .collect::<Result<_>>()?,
1843            keys: BTreeMap::new(),
1844        })),
1845        Value::Object(m) => {
1846            let mut roots = TrustedRoots::default();
1847            for (did, key) in m {
1848                let did = norm(did)?;
1849                if !roots.dids.contains(&did) {
1850                    roots.dids.push(did.clone());
1851                }
1852                roots.keys.insert(did, key_entry_from_json(key));
1853            }
1854            Ok(Some(roots))
1855        }
1856        _ => Err(bad(
1857            "trustedRoots must be a {did: key} map or a list of DIDs",
1858        )),
1859    }
1860}
1861
1862/// The caller's trusted keys as the reference's `Verifier(trusted_roots=...)`
1863/// reads them: each DID (or bare domain) normalized, each key a JWK in JSON
1864/// text. An entry whose DID does not normalize, or whose key is not JWK text
1865/// (a JSON object with a `kty`), is dropped, so the DID falls back to the
1866/// other sources. A JWK that is not a usable Ed25519 key stays, as no key.
1867fn trusted_key_map(obj: &Map<String, Value>) -> Result<BTreeMap<String, KeyEntry>> {
1868    let mut out = BTreeMap::new();
1869    for (did, v) in object_member(obj, "trustedKeys")?.into_iter().flatten() {
1870        let Ok(did) = crate::did_web::normalize_root(did) else {
1871            continue;
1872        };
1873        // Every value is the DID's only key: a Multikey, a JWK (object or
1874        // text), or anything else as an unusable key, which refuses the DID
1875        // instead of falling back to the key a did:key carries.
1876        out.insert(did, key_entry_from_json(v));
1877    }
1878    Ok(out)
1879}
1880
1881fn key_map(obj: &Map<String, Value>, name: &str) -> Result<BTreeMap<String, KeyEntry>> {
1882    Ok(object_member(obj, name)?
1883        .map(|m| {
1884            m.iter()
1885                // A resolver that answered nothing (null) is left out.
1886                .filter(|(_, v)| !v.is_null())
1887                .map(|(did, v)| (did.clone(), key_entry_from_json(v)))
1888                .collect()
1889        })
1890        .unwrap_or_default())
1891}
1892
1893/// [`decide`] as one JSON request, for the bindings. The did:webvh logs in
1894/// the request are checked against `clock` unless it gives `logNow`.
1895///
1896/// The request is an object with:
1897///
1898/// - `credential`: the credential (an object, or its JSON text);
1899/// - `now` (required): the verifier's clock; `clockSkewSeconds` (default 30);
1900/// - `publicKey`: the issuer's key handed over (a Multikey, or a JWK object
1901///   or text); `mldsa44PublicKey`: the issuer's ML-DSA-44 Multikey;
1902///   `slhdsa128PublicKey`: the issuer's SLH-DSA-SHA2-128s Multikey (giving
1903///   a post-quantum key requires that suite's proof);
1904/// - `trustedKeys`, `resolvedKeys`: keys by DID (the caller's trusted keys,
1905///   and the key resolver's answers; null means "no answer");
1906///   `mldsa44Keys`, `slhdsa128Keys`: post-quantum Multikeys by DID;
1907/// - `documents`: did:web (or did:webvh) DID documents by DID, as fetched;
1908/// - `didLogs` / `didLogsB64`: did:webvh logs (`did.jsonl`) by DID, as text
1909///   or base64; `seenVersionIds`: the latest versionId seen before, by DID;
1910///   `limits`, `logNow`: as for the did:webvh requests;
1911/// - `trustedRoots`: a DID or domain, a list, or a `{did: key}` map;
1912/// - `requirePostQuantum`; `requireSuites` (a list of cryptosuite
1913///   identifiers the credential's proofs must include, from
1914///   `eddsa-jcs-2022`, `mldsa44-jcs-2024` and `slhdsa128-jcs-2024`; a
1915///   credential without one of them is refused with
1916///   [`hybrid::REASON_REQUIRED_SUITE_MISSING`]);
1917/// - `expectedResource`, `checkStatus` (default
1918///   true), `statusLists` (URL to the fetched list), `maxDepth`,
1919///   `maxReplayWindowSeconds` (default 43200), `requireTrustedIssuer`
1920///   (accept only issuers `trustedKeys` names; with no `trustedRoots`, the
1921///   `trustedKeys` DIDs are also the chain's trusted roots),
1922///   `chainRequiredOutsideRoots` (default true: with `trustedRoots` named,
1923///   a credential without a delegation chain is refused unless a root
1924///   issued it; false for a host that applies its own chain rule).
1925///
1926/// Returns `{"valid", "reason", "passport", "replay": {"key", "expiresAt",
1927/// "singleUse"}, "didLogVersions", "didLogErrors"}`. Errors on a malformed
1928/// request and as [`decide`] does.
1929pub fn decide_json_with_clock(request: &Value, clock: crate::did_webvh::LogClock) -> Result<Value> {
1930    let obj = request
1931        .as_object()
1932        .ok_or_else(|| bad("the request must be a JSON object"))?;
1933    let (input, logs) = read_request(obj, clock, &[])?;
1934    let decision = decide(&input)?;
1935    let (versions, errors) = match &logs {
1936        Some(set) => crate::did_webvh::grant_log_json(&set.outcomes()),
1937        None => (json!({}), json!({})),
1938    };
1939    Ok(json!({
1940        "valid": decision.valid,
1941        "reason": decision.reason,
1942        "passport": decision.passport,
1943        "replay": decision.replay.map(|r| json!({
1944            "key": r.key,
1945            "expiresAt": r.expires_at,
1946            "singleUse": r.single_use,
1947        })),
1948        "issuerKey": decision
1949            .issuer_key
1950            .as_deref()
1951            .map(multikey::encode_ed25519_public)
1952            .transpose()?,
1953        "didLogVersions": versions,
1954        "didLogErrors": errors,
1955    }))
1956}
1957
1958/// Read a decision request (see [`decide_json_with_clock`]); `extra` names
1959/// members another entry point reads itself.
1960fn read_request(
1961    obj: &Map<String, Value>,
1962    clock: crate::did_webvh::LogClock,
1963    extra: &[&str],
1964) -> Result<(DecisionInput, Option<crate::did_webvh::LogSet>)> {
1965    use crate::did_webvh::{base64_decode, is_did_webvh, LogClock, LogSet};
1966
1967    if let Some(name) = obj
1968        .keys()
1969        .find(|k| !REQUEST_MEMBERS.contains(&k.as_str()) && !extra.contains(&k.as_str()))
1970    {
1971        return Err(bad(format!(
1972            "the request holds an unknown member {:?}",
1973            name.chars().take(40).collect::<String>()
1974        )));
1975    }
1976    refuse_null_tightening(obj)?;
1977    let credential = match obj.get("credential") {
1978        Some(Value::String(text)) => credential_from_text(text),
1979        Some(v) => v.clone(),
1980        None => return Err(bad("credential is required")),
1981    };
1982    let now = obj
1983        .get("now")
1984        .and_then(Value::as_str)
1985        .ok_or_else(|| bad("now must be a protocol time"))?;
1986    let mut input = DecisionInput::new(credential, now);
1987    match obj.get("clockSkewSeconds") {
1988        None => {}
1989        // A skew written as null is not "the default": the reference refuses it.
1990        Some(Value::Null) => return Err(bad("clockSkewSeconds must be a whole number of seconds")),
1991        Some(v) => input.clock_skew_seconds = crate::time::clock_skew_from_json(v)?,
1992    }
1993    input.public_key = present(obj, "publicKey").map(key_entry_from_json);
1994    input.mldsa44_public_key = present(obj, "mldsa44PublicKey").map(mldsa44_key_from_json);
1995    input.slhdsa128_public_key = present(obj, "slhdsa128PublicKey").map(slhdsa128_key_from_json);
1996    input.trusted_keys = trusted_key_map(obj)?;
1997    input.resolved_keys = key_map(obj, "resolvedKeys")?;
1998    if let Some(m) = object_member(obj, "mldsa44Keys")? {
1999        for (did, v) in m {
2000            // A lookup that answered nothing (null) is left out. Any other
2001            // answer that is not an ML-DSA-44 Multikey is an unusable key:
2002            // its proof is still required, and nothing checks it, so the
2003            // credential is refused.
2004            if !v.is_null() {
2005                let k = mldsa44_key_from_json(v).unwrap_or_default();
2006                input.mldsa44_keys.insert(did.clone(), k);
2007            }
2008        }
2009    }
2010    if let Some(m) = object_member(obj, "slhdsa128Keys")? {
2011        for (did, v) in m {
2012            // As for ML-DSA-44: null is no answer, anything else that is
2013            // not an SLH-DSA-SHA2-128s Multikey is an unusable key.
2014            if !v.is_null() {
2015                let k = slhdsa128_key_from_json(v).unwrap_or_default();
2016                input.slhdsa128_keys.insert(did.clone(), k);
2017            }
2018        }
2019    }
2020    if let Some(m) = object_member(obj, "documents")? {
2021        for (did, doc) in m {
2022            if !has_did_document(did) {
2023                return Err(bad(
2024                    "documents holds a DID that is not did:web or did:webvh",
2025                ));
2026            }
2027            if !doc.is_null() {
2028                input.documents.insert(did.clone(), doc.clone());
2029            }
2030        }
2031    }
2032    // did:webvh logs: each is verified in full, and its latest state is the
2033    // DID's document.
2034    let clock = match present(obj, "logNow") {
2035        None => clock,
2036        Some(v) => LogClock::At(parse_protocol_time_ns(
2037            v.as_str()
2038                .ok_or_else(|| bad("logNow must be a protocol time"))?,
2039        )?),
2040    };
2041    let mut logs: Option<LogSet> = None;
2042    let texts = object_member(obj, "didLogs")?;
2043    let b64s = object_member(obj, "didLogsB64")?;
2044    if texts.is_some() || b64s.is_some() {
2045        let mut set = LogSet::new(clock)?;
2046        if let Some(limits) = present(obj, "limits") {
2047            set = set.with_limits(crate::did_webvh::Limits::from_json(limits)?);
2048        }
2049        let mut given: Vec<(String, Vec<u8>)> = Vec::new();
2050        for (did, v) in texts.into_iter().flatten() {
2051            let t = v
2052                .as_str()
2053                .ok_or_else(|| bad("didLogs must map DIDs to log text"))?;
2054            given.push((did.clone(), t.as_bytes().to_vec()));
2055        }
2056        for (did, v) in b64s.into_iter().flatten() {
2057            let t = v
2058                .as_str()
2059                .ok_or_else(|| bad("didLogsB64 must map DIDs to base64 logs"))?;
2060            given.push((did.clone(), base64_decode(t, "a didLogsB64 log")?));
2061        }
2062        for (did, log) in given {
2063            if !is_did_webvh(&did) {
2064                return Err(bad("didLogs holds a DID that is not a did:webvh DID"));
2065            }
2066            if set.contains(&did) || input.documents.contains_key(&did) {
2067                return Err(bad(
2068                    "give each DID's log once, in didLogs, didLogsB64 or documents",
2069                ));
2070            }
2071            set = set.with_log(&did, log);
2072        }
2073        if let Some(m) = object_member(obj, "seenVersionIds")? {
2074            for (did, v) in m {
2075                let seen = v
2076                    .as_str()
2077                    .ok_or_else(|| bad("seenVersionIds must map DIDs to versionIds"))?;
2078                set = set.with_seen_version_id(did, seen)?;
2079            }
2080        }
2081        logs = Some(set);
2082    }
2083    if let Some(v) = present(obj, "trustedRoots") {
2084        input.trusted_roots = trusted_roots_from_json(v)?;
2085    }
2086    input.require_post_quantum = bool_member(obj, "requirePostQuantum", false)?;
2087    if let Some(v) = present(obj, "requireSuites") {
2088        input.require_suites = hybrid::required_suites_from_json(v)?;
2089    }
2090    input.expected_resource = match present(obj, "expectedResource") {
2091        None => None,
2092        Some(Value::String(s)) => Some(s.clone()),
2093        Some(_) => return Err(bad("expectedResource must be a string")),
2094    };
2095    input.check_status = bool_member(obj, "checkStatus", true)?;
2096    if let Some(m) = object_member(obj, "statusLists")? {
2097        input.status_lists = m.clone();
2098    }
2099    input.max_depth = match present(obj, "maxDepth") {
2100        None => None,
2101        Some(v) => Some(
2102            v.as_u64()
2103                .and_then(|d| usize::try_from(d).ok())
2104                .ok_or_else(|| bad("maxDepth must be a non-negative whole number"))?,
2105        ),
2106    };
2107    if let Some(v) = present(obj, "maxReplayWindowSeconds") {
2108        input.max_replay_window_seconds = match v {
2109            Value::Number(n) => n.as_f64().unwrap_or(f64::NAN),
2110            _ => return Err(bad("max_replay_window must be a number of seconds")),
2111        };
2112    }
2113    // A verifier that requires a trusted issuer accepts only the issuers its
2114    // trusted keys name; with no trusted roots given, those DIDs are also the
2115    // chain's trusted starting points (the reference's Verifier object).
2116    if bool_member(obj, "requireTrustedIssuer", false)? {
2117        input.allowed_issuers = Some(input.trusted_keys.keys().cloned().collect());
2118    }
2119    if present(obj, "trustedRoots").is_none() && !input.trusted_keys.is_empty() {
2120        input.trusted_roots = Some(TrustedRoots {
2121            dids: input.trusted_keys.keys().cloned().collect(),
2122            keys: BTreeMap::new(),
2123        });
2124    }
2125    // Named roots require a chain from any other issuer, unless the host
2126    // applies its own chain rule and says so.
2127    input.chain_required_outside_roots =
2128        input.trusted_roots.is_some() && bool_member(obj, "chainRequiredOutsideRoots", true)?;
2129    input.grant_chain_checked_apart = bool_member(obj, "grantChainCheckedApart", false)?;
2130
2131    if let Some(set) = &logs {
2132        for did in obj
2133            .get("didLogs")
2134            .and_then(Value::as_object)
2135            .into_iter()
2136            .chain(obj.get("didLogsB64").and_then(Value::as_object))
2137            .flat_map(|m| m.keys())
2138        {
2139            if let Some(Ok(resolution)) = set.resolve(did) {
2140                input.documents.insert(did.clone(), resolution.document);
2141            }
2142        }
2143    }
2144
2145    Ok((input, logs))
2146}
2147
2148/// [`decide_json_with_clock`] with did:webvh logs checked against the system
2149/// clock.
2150pub fn decide_json(request: &Value) -> Result<Value> {
2151    decide_json_with_clock(request, crate::did_webvh::LogClock::System)
2152}
2153
2154/// [`fetch_plan`] as JSON: the request is a decision request (see
2155/// [`decide_json_with_clock`]) plus `"phase"`: `"documents"` (the default)
2156/// or `"statusLists"`. Returns `{"refusal", "dids", "statusLists",
2157/// "truncated"}`.
2158pub fn fetch_plan_json_with_clock(
2159    request: &Value,
2160    clock: crate::did_webvh::LogClock,
2161) -> Result<Value> {
2162    let obj = request
2163        .as_object()
2164        .ok_or_else(|| bad("the request must be a JSON object"))?;
2165    let phase = match present(obj, "phase").map(|v| v.as_str()) {
2166        None | Some(Some("documents")) => FetchPhase::Documents,
2167        Some(Some("statusLists")) => FetchPhase::StatusLists,
2168        _ => return Err(bad("phase must be \"documents\" or \"statusLists\"")),
2169    };
2170    let (input, _logs) = read_request(obj, clock, &["phase"])?;
2171    let plan = fetch_plan(&input, phase)?;
2172    Ok(json!({
2173        "refusal": plan.refusal,
2174        "dids": plan.dids,
2175        "statusLists": plan.status_lists,
2176        "truncated": plan.truncated,
2177    }))
2178}
2179
2180/// [`fetch_plan_json_with_clock`] with did:webvh logs checked against the
2181/// system clock.
2182pub fn fetch_plan_json(request: &Value) -> Result<Value> {
2183    fetch_plan_json_with_clock(request, crate::did_webvh::LogClock::System)
2184}
2185
2186/// [`replay_identity`] as JSON: `{"credential", "now", "clockSkewSeconds"
2187/// (default 30), "maxReplayWindowSeconds" (default 43200)}` to `{"key",
2188/// "expiresAt", "singleUse"}`.
2189pub fn replay_identity_json(request: &Value) -> Result<Value> {
2190    let obj = request
2191        .as_object()
2192        .ok_or_else(|| bad("the request must be a JSON object"))?;
2193    let credential = obj
2194        .get("credential")
2195        .filter(|c| c.is_object())
2196        .ok_or_else(|| bad("credential must be a JSON object"))?;
2197    let now = obj
2198        .get("now")
2199        .and_then(Value::as_str)
2200        .ok_or_else(|| bad("now must be a protocol time"))?;
2201    let skew = match present(obj, "clockSkewSeconds") {
2202        None => DEFAULT_CLOCK_SKEW_SECONDS,
2203        Some(v) => crate::time::clock_skew_from_json(v)?,
2204    };
2205    let window = match present(obj, "maxReplayWindowSeconds") {
2206        None => DEFAULT_MAX_REPLAY_WINDOW_SECONDS,
2207        Some(v) => v
2208            .as_f64()
2209            .ok_or_else(|| bad("max_replay_window must be a number of seconds"))?,
2210    };
2211    let r = replay_identity(credential, now, skew, window)?;
2212    Ok(json!({"key": r.key, "expiresAt": r.expires_at, "singleUse": r.single_use}))
2213}
2214
2215/// A credential's shape, dates and proof fields, with no signature checked:
2216/// `{"credential", "now", "clockSkewSeconds" (default 30),
2217/// "expectedResource"}` to `{"problem"}` (null when nothing is wrong). This
2218/// never says who made the credential; it is for rejecting junk early or
2219/// showing a credential, never for trusting one.
2220pub fn structure_only_json(request: &Value) -> Result<Value> {
2221    let obj = request
2222        .as_object()
2223        .ok_or_else(|| bad("the request must be a JSON object"))?;
2224    let credential = match obj.get("credential") {
2225        Some(Value::String(text)) => credential_from_text(text),
2226        Some(v) => v.clone(),
2227        None => return Err(bad("credential is required")),
2228    };
2229    let now = obj
2230        .get("now")
2231        .and_then(Value::as_str)
2232        .ok_or_else(|| bad("now must be a protocol time"))?;
2233    let now = parse_protocol_time_ns(now)?.div_euclid(1000) * 1000;
2234    let skew = match obj.get("clockSkewSeconds") {
2235        None => DEFAULT_CLOCK_SKEW_SECONDS,
2236        Some(v) => crate::time::clock_skew_from_json(v)?,
2237    };
2238    let skew = check_clock_skew(skew)?;
2239    let expected = match present(obj, "expectedResource") {
2240        None => None,
2241        Some(Value::String(s)) => Some(s.as_str()),
2242        Some(_) => return Err(bad("expectedResource must be a string")),
2243    };
2244    if !credential.is_object() {
2245        return Ok(json!({"problem": "the credential is not a JSON object"}));
2246    }
2247    if let Some(problem) = structure_problem(&credential, now, skew, expected) {
2248        return Ok(json!({ "problem": problem }));
2249    }
2250    let issuer = issuer_did(&credential).unwrap_or_default().to_string();
2251    Ok(match read_proofs(&credential, &issuer, now, skew) {
2252        Ok(_) => json!({ "problem": null }),
2253        Err(problem) => json!({ "problem": problem }),
2254    })
2255}
2256
2257/// Only the embedded delegation chain of a credential, as the reference's
2258/// `verify_delegation_chain` checks it. The request is a decision request
2259/// (see [`decide_json_with_clock`]); the keys, documents, ML-DSA-44 keys,
2260/// trusted roots, `requirePostQuantum` and `maxDepth` are read, and
2261/// `linksOnly: true` runs only the checks that need no key, and
2262/// `throughLink: n` checks only the links before index n (for a host that
2263/// looks grant issuers' keys up one at a time). The answer is
2264/// `{"reason"}`, null when the chain is valid or absent. With no trusted
2265/// roots a chain is "untrusted_principal". The credential's own signature,
2266/// window and status are not checked.
2267pub fn delegation_chain_json_with_clock(
2268    request: &Value,
2269    clock: crate::did_webvh::LogClock,
2270) -> Result<Value> {
2271    let obj = request
2272        .as_object()
2273        .ok_or_else(|| bad("the request must be a JSON object"))?;
2274    let (input, _logs) = read_request(obj, clock, &["linksOnly", "throughLink"])?;
2275    let input = at_microseconds(&input)?;
2276    let cred = &input.credential;
2277    if !cred.is_object() {
2278        return Ok(json!({ "reason": grant_chain::REASON_MALFORMED }));
2279    }
2280    let links_only = bool_member(obj, "linksOnly", false)?;
2281    let through_link = match present(obj, "throughLink") {
2282        None => None,
2283        Some(v) => Some(
2284            v.as_u64()
2285                .and_then(|n| usize::try_from(n).ok())
2286                .ok_or_else(|| bad("throughLink must be a non-negative whole number"))?,
2287        ),
2288    };
2289    let grant_keys: BTreeMap<String, Vec<u8>> = effective_keys(&input)
2290        .into_iter()
2291        .map(|(did, entry)| {
2292            let raw = match entry {
2293                KeyEntry::Ed25519(k) => k,
2294                // Present but unusable: the only key for the DID, and no key.
2295                KeyEntry::Unusable => Vec::new(),
2296            };
2297            (did, raw)
2298        })
2299        .collect();
2300    let documents: BTreeMap<String, Value> = input
2301        .documents
2302        .iter()
2303        .filter(|(did, _)| has_did_document(did))
2304        .map(|(d, v)| (d.clone(), v.clone()))
2305        .collect();
2306    let roots: Vec<String> = input
2307        .trusted_roots
2308        .as_ref()
2309        .map(|r| r.dids.clone())
2310        .unwrap_or_default();
2311    let opts = ChainOptions {
2312        // No roots named trusts nobody: the chain's start is not trusted.
2313        trusted_roots: Some(&roots),
2314        grant_keys: Some(&grant_keys),
2315        mldsa_keys: Some(&input.mldsa44_keys),
2316        slhdsa_keys: Some(&input.slhdsa128_keys),
2317        grant_documents: Some(&documents),
2318        require_pq: input.require_post_quantum,
2319        require_suites: &input.require_suites,
2320        max_depth: input.max_depth,
2321        through_link,
2322        ..Default::default()
2323    };
2324    // `linksOnly`: only the checks that need no key, so a host asks for no
2325    // key and fetches nothing for a chain these refuse.
2326    let check = if links_only {
2327        crate::delegation::chain_links_problem
2328    } else {
2329        crate::delegation::verify_delegation_chain_with
2330    };
2331    let reason = check(cred, &input.now, input.clock_skew_seconds, &opts);
2332    Ok(json!({ "reason": reason }))
2333}
2334
2335/// A trusted root as a DID (`{"root"}` to `{"did"}`): a full DID as it is,
2336/// a bare domain as its did:web. Errors with the reference's refusal when it
2337/// is neither.
2338pub fn normalize_root_json(request: &Value) -> Result<Value> {
2339    let root = request
2340        .get("root")
2341        .and_then(Value::as_str)
2342        .ok_or_else(|| bad("a trusted root is a DID or a domain name"))?;
2343    Ok(json!({ "did": crate::did_web::normalize_root(root)? }))
2344}
2345
2346#[cfg(test)]
2347mod tests {
2348    use super::*;
2349
2350    #[test]
2351    fn showable_dids() {
2352        assert!(showable_did("did:web:example.com"));
2353        assert!(showable_did("did:key:z6Mk"));
2354        assert!(!showable_did("did:Web:example.com"));
2355        assert!(!showable_did("did:web:"));
2356        assert!(!showable_did("did:web:a b"));
2357        assert!(!showable_did(&format!("did:web:{}", "a".repeat(201))));
2358        assert_eq!(
2359            untrusted_root_reason(Some("did:web:root.example"), true),
2360            "the chain's starting point is not trusted: run `vouch trust did:web:root.example` \
2361             (it is not one of the trusted roots)"
2362        );
2363        assert_eq!(
2364            untrusted_root_reason(Some("did:web:a b"), false),
2365            REASON_UNTRUSTED_START
2366        );
2367    }
2368
2369    #[test]
2370    fn group_order_matches_the_curve() {
2371        // S = L - 1 is accepted, S = L refused; R is the base point's
2372        // encoding (y = 4/5), a canonical point of large order.
2373        let mut sig = [0u8; 64];
2374        let base = ed25519_dalek::SigningKey::from_bytes(&[7u8; 32]).verifying_key();
2375        sig[..32].copy_from_slice(base.as_bytes());
2376        sig[32..].copy_from_slice(&GROUP_ORDER_LE);
2377        assert!(!strict_signature(&sig));
2378        sig[32] -= 1;
2379        assert!(strict_signature(&sig));
2380    }
2381
2382    #[test]
2383    fn bad_requests_are_errors() {
2384        let cred = json!({});
2385        let mut input = DecisionInput::new(cred, "2026-01-01T00:00:00Z");
2386        input.max_replay_window_seconds = 0.0;
2387        assert!(decide(&input).is_err());
2388        input.max_replay_window_seconds = 10.0;
2389        input.clock_skew_seconds = 121;
2390        assert!(decide(&input).is_err());
2391        let not_object = DecisionInput::new(json!([1]), "2026-01-01T00:00:00Z");
2392        assert_eq!(
2393            decide(&not_object).unwrap().reason.as_deref(),
2394            Some("the credential is not a JSON object")
2395        );
2396    }
2397
2398    #[test]
2399    fn jwk_x_padding_matches_the_reference() {
2400        // A 43-character x takes no padding or exactly one "="; any other
2401        // count of trailing "=" signs is refused, as the reference does.
2402        let key = ed25519_dalek::SigningKey::from_bytes(&[7u8; 32]).verifying_key();
2403        let body = base64::Engine::encode(
2404            &base64::engine::general_purpose::URL_SAFE_NO_PAD,
2405            key.as_bytes(),
2406        );
2407        assert_eq!(body.len(), 43);
2408        let entry =
2409            |x: String| key_entry_from_json(&json!({"kty": "OKP", "crv": "Ed25519", "x": x}));
2410        for (pad, usable) in [(0, true), (1, true), (2, false), (3, false), (4, false)] {
2411            let got = entry(format!("{body}{}", "=".repeat(pad)));
2412            assert_eq!(
2413                matches!(got, KeyEntry::Ed25519(_)),
2414                usable,
2415                "{pad} padding signs"
2416            );
2417        }
2418        assert!(matches!(entry(format!("={body}")), KeyEntry::Unusable));
2419        assert!(matches!(
2420            entry(format!("{}={}", &body[..20], &body[20..])),
2421            KeyEntry::Unusable
2422        ));
2423    }
2424}