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