1use 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
44pub const REASON_NO_KEY: &str = "no key to check the signature with";
46pub const REASON_UNTRUSTED_START: &str =
50 "the chain's starting point is not trusted: run `vouch trust <root DID>`";
51pub 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)";
54pub const REASON_BUDGET: &str = "verifier_budget_exceeded";
56pub const REASON_CHAIN_REQUIRED: &str = "delegation_chain_required";
59pub const REASON_REPLAYED: &str = "this credential was already used";
61pub const DEFAULT_MAX_REPLAY_WINDOW_SECONDS: f64 = 12.0 * 60.0 * 60.0;
63pub const DEFAULT_CLOCK_SKEW_SECONDS: i64 = 30;
65pub 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
80const 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#[derive(Debug, Clone, PartialEq, Eq)]
95pub enum KeyEntry {
96 Ed25519(Vec<u8>),
98 Unusable,
100}
101
102#[derive(Debug, Clone, Default, PartialEq, Eq)]
106pub struct TrustedRoots {
107 pub dids: Vec<String>,
108 pub keys: BTreeMap<String, KeyEntry>,
109}
110
111#[derive(Debug, Clone)]
114pub struct DecisionInput {
115 pub credential: Value,
118 pub now: String,
120 pub clock_skew_seconds: i64,
122 pub public_key: Option<KeyEntry>,
124 pub mldsa44_public_key: Option<Option<Vec<u8>>>,
128 pub trusted_keys: BTreeMap<String, KeyEntry>,
131 pub resolved_keys: BTreeMap<String, KeyEntry>,
134 pub mldsa44_keys: BTreeMap<String, Vec<u8>>,
137 pub documents: BTreeMap<String, Value>,
141 pub trusted_roots: Option<TrustedRoots>,
144 pub require_post_quantum: bool,
146 pub expected_resource: Option<String>,
148 pub check_status: bool,
150 pub status_lists: Map<String, Value>,
153 pub max_depth: Option<usize>,
155 pub max_replay_window_seconds: f64,
157 pub allowed_issuers: Option<Vec<String>>,
160 pub chain_required_outside_roots: bool,
166}
167
168impl DecisionInput {
169 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#[derive(Debug, Clone, PartialEq)]
198pub struct ReplayIdentity {
199 pub key: String,
201 pub expires_at: f64,
204 pub single_use: bool,
208}
209
210#[derive(Debug, Clone, PartialEq)]
212pub struct Decision {
213 pub valid: bool,
214 pub reason: Option<String>,
216 pub passport: Option<Value>,
219 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
234pub 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
271pub 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
287fn protocol_time(v: &Value) -> Option<i128> {
289 v.as_str().and_then(|s| parse_protocol_time_ns(s).ok())
290}
291
292pub 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#[derive(Debug, Clone)]
364pub struct Proofs {
365 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 pub fn ed_vm(&self) -> Option<String> {
380 Self::vm_of(self.eddsa.as_ref())
381 }
382
383 pub fn ml_vm(&self) -> Option<String> {
385 Self::vm_of(self.mldsa.as_ref())
386 }
387
388 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 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
448pub 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#[derive(Debug, Clone, Default, PartialEq, Eq)]
520pub struct SignerKeys {
521 pub ed25519: Option<Vec<u8>>,
522 pub mldsa44: Option<Vec<u8>>,
523 pub publishes_mldsa44: bool,
526}
527
528fn strict_ed25519(raw: &[u8]) -> Option<Vec<u8>> {
530 keys::strict_verifying_key(raw).ok().map(|_| raw.to_vec())
531}
532
533fn 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
540fn 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 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, }
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
616fn 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
640pub 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
673pub 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
681fn 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 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
710type 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
728fn 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
751fn 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
804fn 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
836fn 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
870fn 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 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
908fn 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
957fn 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
980pub 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 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
1008pub 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
1035pub 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
1085fn chain_root(chain: &[Value]) -> Option<&str> {
1090 chain.first()?.get("issuer")?.as_str()
1091}
1092
1093fn 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
1124fn 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
1135pub(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
1144fn 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
1205pub 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 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 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 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 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
1364pub const MAX_FETCH_DIDS: usize = 32;
1367pub const MAX_FETCH_STATUS_LISTS: usize = 32;
1370
1371#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1373pub enum FetchPhase {
1374 Documents,
1377 StatusLists,
1380}
1381
1382#[derive(Debug, Clone, Default, PartialEq, Eq)]
1384pub struct FetchPlan {
1385 pub refusal: Option<String>,
1390 pub dids: Vec<String>,
1392 pub status_lists: Vec<String>,
1394 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
1430pub 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 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
1523const 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
1590pub 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
1625fn 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 .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
1659pub 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
1712fn 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 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 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 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 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 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
1882pub fn decide_json(request: &Value) -> Result<Value> {
1885 decide_json_with_clock(request, crate::did_webvh::LogClock::System)
1886}
1887
1888pub 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
1914pub fn fetch_plan_json(request: &Value) -> Result<Value> {
1917 fetch_plan_json_with_clock(request, crate::did_webvh::LogClock::System)
1918}
1919
1920pub 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 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(¬_object).unwrap().reason.as_deref(),
1997 Some("the credential is not a JSON object")
1998 );
1999 }
2000}