1#[allow(unused_imports)]
31use crate::prelude::*;
32
33use alloc::collections::BTreeMap;
34
35use serde_json::{json, Map, Value};
36
37use crate::data_integrity;
38use crate::delegation::ChainOptions;
39use crate::did_document;
40use crate::error::{CoreError, Result};
41use crate::grant_chain;
42use crate::hybrid;
43use crate::keys;
44use crate::multikey;
45use crate::pq;
46use crate::status_list;
47use crate::time::{check_clock_skew, parse_protocol_time_ns, window_state_ns, WindowState};
48
49pub const REASON_NO_KEY: &str = "no key to check the signature with";
51pub const REASON_UNTRUSTED_START: &str =
55 "the chain's starting point is not trusted: run `vouch trust <root DID>`";
56pub const REASON_START_NOT_LISTED: &str = "the chain's starting point is not trusted: run \
58 `vouch trust <root DID>` (it is not one of the trusted roots)";
59pub const REASON_BUDGET: &str = "verifier_budget_exceeded";
61pub const REASON_CHAIN_REQUIRED: &str = "delegation_chain_required";
64pub const REASON_REPLAYED: &str = "this credential was already used";
66pub const DEFAULT_MAX_REPLAY_WINDOW_SECONDS: f64 = 12.0 * 60.0 * 60.0;
68pub const DEFAULT_CLOCK_SKEW_SECONDS: i64 = 30;
70pub const MISSING_MLDSA44_KEY: &str = "missing_mldsa44_key";
75
76const VC_CONTEXT_V2: &str = "https://www.w3.org/ns/credentials/v2";
77const REQUIRED_TYPES: [&str; 2] = ["VerifiableCredential", "VouchCredential"];
78const SUPPORTED_VOUCH_VERSIONS: [&str; 1] = ["1.0"];
79const ASSERTION: &str = "assertionMethod";
80const ROOT_PLACEHOLDER: &str = "<root DID>";
81const VALUE_ERROR: &str = "ValueError";
82const WEAK_KEY_ERROR: &str = "WeakKeyError";
83const NS_PER_SECOND: i128 = 1_000_000_000;
84
85const GROUP_ORDER_LE: [u8; 32] = [
88 237, 211, 245, 92, 26, 99, 18, 88, 214, 156, 247, 162, 222, 249, 222, 20, 0, 0, 0, 0, 0, 0, 0,
89 0, 0, 0, 0, 0, 0, 0, 0, 16,
90];
91
92#[derive(Debug, Clone, PartialEq, Eq)]
100pub enum KeyEntry {
101 Ed25519(Vec<u8>),
103 Unusable,
105}
106
107#[derive(Debug, Clone, Default, PartialEq, Eq)]
111pub struct TrustedRoots {
112 pub dids: Vec<String>,
113 pub keys: BTreeMap<String, KeyEntry>,
114}
115
116#[derive(Debug, Clone)]
119pub struct DecisionInput {
120 pub credential: Value,
123 pub now: String,
125 pub clock_skew_seconds: i64,
127 pub public_key: Option<KeyEntry>,
129 pub mldsa44_public_key: Option<Option<Vec<u8>>>,
133 pub slhdsa128_public_key: Option<Option<Vec<u8>>>,
137 pub trusted_keys: BTreeMap<String, KeyEntry>,
140 pub resolved_keys: BTreeMap<String, KeyEntry>,
143 pub mldsa44_keys: BTreeMap<String, Vec<u8>>,
146 pub slhdsa128_keys: BTreeMap<String, Vec<u8>>,
149 pub documents: BTreeMap<String, Value>,
153 pub trusted_roots: Option<TrustedRoots>,
156 pub require_post_quantum: bool,
158 pub require_suites: Vec<hybrid::Suite>,
161 pub expected_resource: Option<String>,
163 pub check_status: bool,
165 pub status_lists: Map<String, Value>,
168 pub max_depth: Option<usize>,
170 pub max_replay_window_seconds: f64,
172 pub allowed_issuers: Option<Vec<String>>,
175 pub chain_required_outside_roots: bool,
180 pub grant_chain_checked_apart: bool,
186}
187
188impl DecisionInput {
189 pub fn new(credential: Value, now: impl Into<String>) -> Self {
193 Self {
194 credential,
195 now: now.into(),
196 clock_skew_seconds: DEFAULT_CLOCK_SKEW_SECONDS,
197 public_key: None,
198 mldsa44_public_key: None,
199 slhdsa128_public_key: None,
200 trusted_keys: BTreeMap::new(),
201 resolved_keys: BTreeMap::new(),
202 mldsa44_keys: BTreeMap::new(),
203 slhdsa128_keys: BTreeMap::new(),
204 documents: BTreeMap::new(),
205 trusted_roots: None,
206 require_post_quantum: false,
207 require_suites: Vec::new(),
208 expected_resource: None,
209 check_status: true,
210 status_lists: Map::new(),
211 max_depth: None,
212 max_replay_window_seconds: DEFAULT_MAX_REPLAY_WINDOW_SECONDS,
213 allowed_issuers: None,
214 chain_required_outside_roots: false,
215 grant_chain_checked_apart: false,
216 }
217 }
218}
219
220#[derive(Debug, Clone, PartialEq)]
222pub struct ReplayIdentity {
223 pub key: String,
225 pub expires_at: f64,
228 pub single_use: bool,
232}
233
234#[derive(Debug, Clone, PartialEq)]
236pub struct Decision {
237 pub valid: bool,
238 pub reason: Option<String>,
240 pub passport: Option<Value>,
243 pub replay: Option<ReplayIdentity>,
245 pub issuer_key: Option<Vec<u8>>,
249}
250
251impl Decision {
252 fn refuse(reason: impl Into<String>) -> Self {
253 Self {
254 valid: false,
255 reason: Some(reason.into()),
256 passport: None,
257 replay: None,
258 issuer_key: None,
259 }
260 }
261}
262
263pub fn untrusted_root_reason(root: Option<&str>, roots_given: bool) -> String {
272 let template = if roots_given {
273 REASON_START_NOT_LISTED
274 } else {
275 REASON_UNTRUSTED_START
276 };
277 match root {
278 Some(r) if showable_did(r) => template.replace(ROOT_PLACEHOLDER, r),
279 _ => template.to_string(),
280 }
281}
282
283fn showable_did(s: &str) -> bool {
284 let Some(rest) = s.strip_prefix("did:") else {
285 return false;
286 };
287 let Some((method, id)) = rest.split_once(':') else {
288 return false;
289 };
290 !method.is_empty()
291 && method
292 .bytes()
293 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit())
294 && (1..=200).contains(&id.len())
295 && id
296 .bytes()
297 .all(|b| b.is_ascii_alphanumeric() || b"._:%-".contains(&b))
298}
299
300pub fn issuer_did(credential: &Value) -> Option<&str> {
303 let issuer = match credential.get("issuer") {
304 Some(Value::Object(o)) => o.get("id"),
305 other => other,
306 };
307 issuer
308 .and_then(Value::as_str)
309 .filter(|s| s.starts_with("did:") && s.len() > 4)
310}
311
312fn has_did_document(did: &str) -> bool {
313 did.starts_with("did:web:") || did.starts_with("did:webvh:")
314}
315
316fn protocol_time(v: &Value) -> Option<i128> {
318 v.as_str().and_then(|s| parse_protocol_time_ns(s).ok())
319}
320
321pub fn structure_problem(
324 credential: &Value,
325 now: i128,
326 skew: i128,
327 expected_resource: Option<&str>,
328) -> Option<String> {
329 crate::nesting::deep_guard!(Some(crate::nesting::TOO_DEEP.into()); credential);
330 let Some(cred) = credential.as_object() else {
331 return Some("the credential is not a JSON object".into());
332 };
333 let first_context = cred
334 .get("@context")
335 .and_then(Value::as_array)
336 .and_then(|c| c.first());
337 if first_context.and_then(Value::as_str) != Some(VC_CONTEXT_V2) {
338 return Some("the credential's @context does not start with the VC 2.0 context".into());
339 }
340 let types_ok = cred.get("type").and_then(Value::as_array).is_some_and(|t| {
341 REQUIRED_TYPES
342 .iter()
343 .all(|want| t.iter().any(|x| x.as_str() == Some(want)))
344 });
345 if !types_ok {
346 return Some(
347 "the credential's type must include VerifiableCredential and VouchCredential".into(),
348 );
349 }
350 if issuer_did(credential).is_none() {
351 return Some("the credential's issuer is not a DID".into());
352 }
353 let Some(subject) = cred.get("credentialSubject").and_then(Value::as_object) else {
354 return Some("credentialSubject is not an object".into());
355 };
356 let version_ok = subject
357 .get("vouchVersion")
358 .and_then(Value::as_str)
359 .is_some_and(|v| SUPPORTED_VOUCH_VERSIONS.contains(&v));
360 if !version_ok {
361 return Some("credentialSubject.vouchVersion is missing or not supported".into());
362 }
363 let Some(intent) = subject.get("intent").and_then(Value::as_object) else {
364 return Some("credentialSubject.intent is not an object".into());
365 };
366 let resource = match intent.get("resource").and_then(Value::as_str) {
367 Some(r) if !r.is_empty() => r,
368 _ => return Some("intent.resource is missing or is not a non-empty string".into()),
369 };
370 if expected_resource.is_some_and(|want| want != resource) {
371 return Some("intent.resource is not the expected resource".into());
372 }
373 let (Some(Value::String(vf)), Some(Value::String(vu))) =
374 (cred.get("validFrom"), cred.get("validUntil"))
375 else {
376 return Some("the credential has no validity window".into());
377 };
378 let (Ok(from), Ok(until)) = (parse_protocol_time_ns(vf), parse_protocol_time_ns(vu)) else {
379 return Some("the credential's validity window is not valid times".into());
380 };
381 match window_state_ns(now, Some(from), Some(until), skew) {
382 WindowState::Inverted => {
383 return Some("the credential's validity window ends before it starts".into())
384 }
385 WindowState::Expired => return Some("the credential expired".into()),
386 WindowState::NotYetValid => return Some("the credential is not yet valid".into()),
387 WindowState::Ok => {}
388 }
389 grant_chain::binding_fields_problem(&credential["credentialSubject"]).map(String::from)
390}
391
392#[derive(Debug, Clone)]
394pub struct Proofs {
395 pub kind: &'static str,
397 pub eddsa: Option<Value>,
398 pub mldsa: Option<Value>,
399 pub slhdsa: Option<Value>,
400}
401
402impl Proofs {
403 fn vm_of(p: Option<&Value>) -> Option<String> {
404 p.and_then(|p| p.get("verificationMethod"))
405 .and_then(Value::as_str)
406 .map(String::from)
407 }
408
409 pub fn ed_vm(&self) -> Option<String> {
411 crate::nesting::deep_guard!(None; self);
412 Self::vm_of(self.eddsa.as_ref())
413 }
414
415 pub fn ml_vm(&self) -> Option<String> {
417 crate::nesting::deep_guard!(None; self);
418 Self::vm_of(self.mldsa.as_ref())
419 }
420
421 pub fn slh_vm(&self) -> Option<String> {
423 crate::nesting::deep_guard!(None; self);
424 Self::vm_of(self.slhdsa.as_ref())
425 }
426
427 pub fn suites(&self) -> Vec<hybrid::Suite> {
429 crate::nesting::deep_guard!(Vec::new(); self);
430 let mut out = Vec::new();
431 if self.eddsa.is_some() {
432 out.push(hybrid::Suite::Eddsa);
433 }
434 if self.mldsa.is_some() {
435 out.push(hybrid::Suite::Mldsa44);
436 }
437 if self.slhdsa.is_some() {
438 out.push(hybrid::Suite::Slhdsa128);
439 }
440 out
441 }
442
443 pub fn replay_proof_value(&self) -> String {
445 crate::nesting::deep_guard!(String::new(); self);
446 self.eddsa
447 .as_ref()
448 .and_then(|p| p.get("proofValue"))
449 .and_then(Value::as_str)
450 .unwrap_or_default()
451 .to_string()
452 }
453}
454
455fn proof_problem(proof: &Value, issuer: &str, now: i128, skew: i128) -> Option<&'static str> {
456 let Some(p) = proof.as_object() else {
457 return Some("a proof is not an object");
458 };
459 if p.get("type").and_then(Value::as_str) != Some(data_integrity::PROOF_TYPE) {
460 return Some("a proof is not a DataIntegrityProof");
461 }
462 let suite = p.get("cryptosuite").and_then(Value::as_str).unwrap_or("");
463 if hybrid::Suite::of(suite).is_none() {
466 return Some(hybrid::REASON_UNSUPPORTED_CRYPTOSUITE);
467 }
468 if p.get("proofPurpose").and_then(Value::as_str) != Some(ASSERTION) {
469 return Some("a proof's purpose is not assertionMethod");
470 }
471 let bound = crate::verification_method::proof_method_names(p, issuer);
472 if !bound {
473 return Some("a proof's verificationMethod does not belong to the issuer");
474 }
475 if p.get("proofValue")
476 .and_then(Value::as_str)
477 .is_none_or(str::is_empty)
478 {
479 return Some("a proof has no proofValue");
480 }
481 if let Some(created) = p.get("created") {
482 if protocol_time(created).is_none() {
483 return Some("a proof's created is not a valid time");
484 }
485 }
486 if let Some(expires) = p.get("expires") {
487 let Some(e) = protocol_time(expires) else {
488 return Some("a proof's expires is not a valid time");
489 };
490 if window_state_ns(now, None, Some(e), skew) != WindowState::Ok {
491 return Some("a proof expired");
492 }
493 }
494 None
495}
496
497pub const REASON_PROOF_SET_SHAPE: &str =
499 "a proof set must be one eddsa-jcs-2022 proof and one proof of each post-quantum suite it carries";
500
501pub fn read_proofs(
507 cred: &Value,
508 issuer: &str,
509 now: i128,
510 skew: i128,
511) -> core::result::Result<Proofs, &'static str> {
512 crate::nesting::deep_guard!(Err(crate::nesting::TOO_DEEP); cred);
513 match cred.get("proof") {
514 Some(raw @ Value::Object(_)) => {
515 if let Some(problem) = proof_problem(raw, issuer, now, skew) {
516 return Err(problem);
517 }
518 match hybrid::Suite::of_proof(raw) {
519 Some(hybrid::Suite::Eddsa) => Ok(Proofs {
520 kind: "single",
521 eddsa: Some(raw.clone()),
522 mldsa: None,
523 slhdsa: None,
524 }),
525 Some(hybrid::Suite::Slhdsa128) => {
526 Err("an SLH-DSA proof needs its eddsa-jcs-2022 partner in a proof set")
527 }
528 _ => Err("an ML-DSA-44 proof needs its eddsa-jcs-2022 partner in a proof set"),
529 }
530 }
531 Some(Value::Array(items)) => {
532 for p in items {
533 if let Some(problem) = proof_problem(p, issuer, now, skew) {
534 return Err(problem);
535 }
536 }
537 let Some(members) = hybrid::set_members(items) else {
538 return Err(REASON_PROOF_SET_SHAPE);
539 };
540 Ok(Proofs {
541 kind: "set",
542 eddsa: Some(members.eddsa.clone()),
543 mldsa: members.mldsa44.cloned(),
544 slhdsa: members.slhdsa128.cloned(),
545 })
546 }
547 _ => Err("the credential has no proof"),
548 }
549}
550
551#[derive(Debug, Clone, Default, PartialEq, Eq)]
557pub struct SignerKeys {
558 pub ed25519: Option<Vec<u8>>,
559 pub mldsa44: Option<Vec<u8>>,
560 pub slhdsa128: Option<Vec<u8>>,
561 pub publishes_mldsa44: bool,
564 pub publishes_slhdsa128: bool,
567}
568
569fn strict_ed25519(raw: &[u8]) -> Option<Vec<u8>> {
571 keys::strict_verifying_key(raw).ok().map(|_| raw.to_vec())
572}
573
574fn did_key_key(did: &str) -> Option<Vec<u8>> {
576 let mk = did.strip_prefix("did:key:")?;
577 let decoded = multikey::decode(mk).ok()?;
578 (decoded.algorithm == "Ed25519").then_some(decoded.raw_key)
579}
580
581fn effective_keys(input: &DecisionInput) -> BTreeMap<String, KeyEntry> {
585 let mut merged = input.resolved_keys.clone();
586 if let Some(roots) = &input.trusted_roots {
587 for (did, key) in &roots.keys {
588 merged.insert(did.clone(), key.clone());
589 }
590 }
591 for (did, key) in &input.trusted_keys {
592 merged.insert(did.clone(), key.clone());
593 }
594 merged
595}
596
597struct KeySource<'a> {
598 keys: BTreeMap<String, KeyEntry>,
599 mldsa44: &'a BTreeMap<String, Vec<u8>>,
600 slhdsa128: &'a BTreeMap<String, Vec<u8>>,
601 documents: &'a BTreeMap<String, Value>,
602}
603
604impl KeySource<'_> {
605 fn keys(
610 &self,
611 did: &str,
612 ed_vm: Option<&str>,
613 ml_vm: Option<&str>,
614 slh_vm: Option<&str>,
615 ) -> SignerKeys {
616 let mut found = SignerKeys {
619 mldsa44: self.mldsa44.get(did).filter(|k| !k.is_empty()).cloned(),
620 slhdsa128: self.slhdsa128.get(did).filter(|k| !k.is_empty()).cloned(),
621 ..Default::default()
622 };
623 let own = if did.starts_with("did:key:") {
624 match did_key_key(did) {
625 Some(k) => Some(k),
626 None => return found, }
628 } else {
629 None
630 };
631 if let Some(entry) = self.keys.get(did) {
632 found.ed25519 = match entry {
633 KeyEntry::Ed25519(k) => match &own {
634 Some(o) if o != k => None,
635 _ => strict_ed25519(k),
636 },
637 KeyEntry::Unusable => None,
638 };
639 return found;
640 }
641 if let Some(k) = own {
642 found.ed25519 = Some(k);
643 return found;
644 }
645 if has_did_document(did) {
646 let Some(doc) = self.documents.get(did) else {
647 return found;
648 };
649 if doc.get("id").and_then(Value::as_str) != Some(did) {
650 return found;
651 }
652 found.publishes_mldsa44 = did_document::publishes_mldsa44_assertion_key(doc, did);
653 if let Some(vm) = ed_vm {
654 found.ed25519 = did_document::assertion_key(doc, did, vm, did_document::ED25519)
655 .ok()
656 .and_then(|k| strict_ed25519(&k));
657 }
658 found.publishes_slhdsa128 = did_document::publishes_slhdsa128_assertion_key(doc, did);
659 if let (Some(vm), None) = (ml_vm, &found.mldsa44) {
660 found.mldsa44 =
661 did_document::assertion_key(doc, did, vm, did_document::MLDSA44).ok();
662 }
663 if let (Some(vm), None) = (slh_vm, &found.slhdsa128) {
664 found.slhdsa128 =
665 did_document::assertion_key(doc, did, vm, did_document::SLHDSA128).ok();
666 }
667 }
668 found
669 }
670}
671
672fn jwk_base64url_decode(text: &str) -> Option<Vec<u8>> {
677 use base64::engine::{
678 general_purpose::GeneralPurpose, DecodePaddingMode, GeneralPurposeConfig,
679 };
680 use base64::{alphabet::URL_SAFE, Engine};
681 let body = text.trim_end_matches('=');
682 let padding = text.len() - body.len();
685 if body.len() % 4 == 1 || (padding != 0 && padding != (4 - body.len() % 4) % 4) {
686 return None;
687 }
688 if body.contains('=') {
689 return None;
690 }
691 let engine = GeneralPurpose::new(
692 &URL_SAFE,
693 GeneralPurposeConfig::new()
694 .with_decode_allow_trailing_bits(true)
695 .with_decode_padding_mode(DecodePaddingMode::Indifferent),
696 );
697 engine.decode(body).ok()
698}
699
700pub fn key_entry_from_json(v: &Value) -> KeyEntry {
705 crate::nesting::deep_guard!(KeyEntry::Unusable; v);
706 let jwk = match v {
707 Value::String(s) if s.starts_with('z') => {
708 return match multikey::decode(s) {
709 Ok(d) if d.algorithm == "Ed25519" => KeyEntry::Ed25519(d.raw_key),
710 _ => KeyEntry::Unusable,
711 };
712 }
713 Value::String(s) if crate::nesting::check_text(s.as_bytes()).is_err() => {
714 return KeyEntry::Unusable
715 }
716 Value::String(s) => match serde_json::from_str::<Value>(s) {
717 Ok(Value::Object(o)) => o,
718 _ => return KeyEntry::Unusable,
719 },
720 Value::Object(o) => o.clone(),
721 _ => return KeyEntry::Unusable,
722 };
723 if jwk.get("kty").and_then(Value::as_str) != Some("OKP")
724 || jwk.get("crv").and_then(Value::as_str) != Some("Ed25519")
725 {
726 return KeyEntry::Unusable;
727 }
728 let Some(x) = jwk.get("x").and_then(Value::as_str) else {
729 return KeyEntry::Unusable;
730 };
731 match jwk_base64url_decode(x).and_then(|raw| strict_ed25519(&raw)) {
732 Some(k) => KeyEntry::Ed25519(k),
733 None => KeyEntry::Unusable,
734 }
735}
736
737pub fn mldsa44_key_from_json(v: &Value) -> Option<Vec<u8>> {
740 crate::nesting::deep_guard!(None; v);
741 let s = v.as_str().filter(|s| s.starts_with('z'))?;
742 let d = multikey::decode(s).ok()?;
743 (d.algorithm == "ML-DSA-44").then_some(d.raw_key)
744}
745
746pub fn slhdsa128_key_from_json(v: &Value) -> Option<Vec<u8>> {
749 crate::nesting::deep_guard!(None; v);
750 let s = v.as_str().filter(|s| s.starts_with('u'))?;
751 let d = multikey::decode(s).ok()?;
752 (d.algorithm == multikey::SLHDSA128).then_some(d.raw_key)
753}
754
755fn strict_signature(sig: &[u8]) -> bool {
762 if sig.len() != keys::ED25519_SIGNATURE_LEN {
763 return false;
764 }
765 let mut r = [0u8; 32];
766 r.copy_from_slice(&sig[..32]);
767 if !keys::is_canonical_point_encoding(&r) {
768 return false;
769 }
770 match ed25519_dalek::VerifyingKey::from_bytes(&r) {
771 Ok(point) if !point.is_weak() => {}
772 _ => return false,
773 }
774 for i in (0..32).rev() {
776 let s = sig[32 + i];
777 if s != GROUP_ORDER_LE[i] {
778 return s < GROUP_ORDER_LE[i];
779 }
780 }
781 false
782}
783
784type Checked = core::result::Result<bool, &'static str>;
787
788fn context_matches(document: &Value, proof: &Value) -> bool {
789 proof
790 .as_object()
791 .is_none_or(|p| data_integrity::proof_context_matches(document, p))
792}
793
794fn without_proof(cred: &Value) -> Value {
795 let mut base = cred.clone();
796 if let Some(o) = base.as_object_mut() {
797 o.remove("proof");
798 }
799 base
800}
801
802fn verify_ed25519_proof(cred: &Value, key: &[u8]) -> Checked {
804 let pv = cred
805 .get("proof")
806 .and_then(|p| p.get("proofValue"))
807 .and_then(Value::as_str)
808 .unwrap_or("");
809 let Some(body) = pv.strip_prefix('z') else {
810 return Err(VALUE_ERROR);
811 };
812 let sig = match multikey::decode_base58_bounded(body) {
813 Ok(s) if s.len() == keys::ED25519_SIGNATURE_LEN => s,
814 _ => return Err(VALUE_ERROR),
815 };
816 if !strict_signature(&sig) {
817 return Err(WEAK_KEY_ERROR);
818 }
819 if !context_matches(&without_proof(cred), &cred["proof"]) {
820 return Err(VALUE_ERROR);
821 }
822 data_integrity::verify_proof(cred, key).map_err(|_| VALUE_ERROR)
823}
824
825fn verify_pq_member(base: &Value, obj: &Map<String, Value>, key: &[u8]) -> Checked {
829 let suite = obj.get("cryptosuite").and_then(Value::as_str).unwrap_or("");
830 let slh = suite == hybrid::SLHDSA128_CRYPTOSUITE_ID;
831 let key_len = if slh {
832 crate::slh::SLHDSA128_PUBLIC_LEN
833 } else {
834 pq::MLDSA44_PUBLIC_LEN
835 };
836 if obj.get("type").and_then(Value::as_str) != Some(data_integrity::PROOF_TYPE)
837 || key.len() != key_len
838 {
839 return Err(VALUE_ERROR);
840 }
841 let pv = obj.get("proofValue").and_then(Value::as_str).unwrap_or("");
842 let sig = if slh {
843 hybrid::decode_slhdsa128_proof_value(pv)
844 } else {
845 hybrid::decode_mldsa44_proof_value(pv)
846 }
847 .map_err(|_| VALUE_ERROR)?;
848 if !data_integrity::proof_context_matches(base, obj) {
849 return Err(VALUE_ERROR);
850 }
851 let mut unsigned = obj.clone();
852 unsigned.remove("proofValue");
853 let input = data_integrity::hash_data(base, &unsigned).map_err(|_| VALUE_ERROR)?;
854 if slh {
855 return crate::slh::verify(key, &input, &sig).map_err(|_| VALUE_ERROR);
856 }
857 let mut ok = pq::verify(key, &input, &sig).map_err(|_| VALUE_ERROR)?;
858 if !ok {
859 let legacy =
860 data_integrity::legacy_proof_digest(base, &unsigned).map_err(|_| VALUE_ERROR)?;
861 ok = pq::verify(key, &legacy, &sig).map_err(|_| VALUE_ERROR)?;
862 }
863 Ok(ok)
864}
865
866fn verify_proof_set(cred: &Value, ed: &[u8], ml: Option<&[u8]>, slh: Option<&[u8]>) -> Checked {
871 let Some(items) = cred.get("proof").and_then(Value::as_array) else {
872 return Err(VALUE_ERROR);
873 };
874 let base = without_proof(cred);
875 let (mut ed_ok, mut pq_ok) = (false, false);
876 for p in items {
877 let Some(obj) = p.as_object() else { continue };
878 match hybrid::Suite::of_proof(p) {
879 Some(hybrid::Suite::Eddsa) => {
880 let mut candidate = base.clone();
881 candidate["proof"] = p.clone();
882 if !verify_ed25519_proof(&candidate, ed)? {
883 return Ok(false);
884 }
885 ed_ok = true;
886 }
887 Some(suite) => {
888 let key = if suite == hybrid::Suite::Mldsa44 {
889 ml
890 } else {
891 slh
892 };
893 let Some(key) = key else {
894 return Ok(false);
895 };
896 if !verify_pq_member(&base, obj, key)? {
897 return Ok(false);
898 }
899 pq_ok = true;
900 }
901 None => {}
902 }
903 }
904 Ok(ed_ok && pq_ok)
905}
906
907enum ProofCheck {
908 Ok,
909 Refused(String),
910 MissingMldsa44Key,
911}
912
913fn check_proofs(
915 cred: &Value,
916 proofs: &Proofs,
917 keys: &SignerKeys,
918 required: hybrid::Required,
919 explicit: bool,
920) -> ProofCheck {
921 let ed = keys.ed25519.as_deref().unwrap_or_default();
922 let verdict = if proofs.kind == "single" {
923 if required.any() {
924 return ProofCheck::Refused("a post-quantum proof is required".into());
925 }
926 verify_ed25519_proof(cred, ed)
927 } else {
928 if !required.met_by(&proofs.suites()) {
929 return ProofCheck::Refused(hybrid::REASON_REQUIRED_SUITE_MISSING.into());
930 }
931 if proofs.mldsa.is_some() && keys.mldsa44.is_none() {
932 if explicit {
933 return ProofCheck::MissingMldsa44Key;
934 }
935 return ProofCheck::Refused(
936 "no ML-DSA-44 key to check the post-quantum proof with".into(),
937 );
938 }
939 if proofs.slhdsa.is_some() && keys.slhdsa128.is_none() {
940 return ProofCheck::Refused(
941 "no SLH-DSA key to check the post-quantum proof with".into(),
942 );
943 }
944 verify_proof_set(cred, ed, keys.mldsa44.as_deref(), keys.slhdsa128.as_deref())
945 };
946 match verdict {
947 Ok(true) => ProofCheck::Ok,
948 Ok(false) => ProofCheck::Refused("the signature does not verify".into()),
949 Err(name) => ProofCheck::Refused(format!("the credential is malformed ({name})")),
950 }
951}
952
953fn list_proof_methods(list: &Value) -> (Option<String>, Option<String>) {
960 let vm = |p: &Value| {
961 p.get("verificationMethod")
962 .and_then(Value::as_str)
963 .map(String::from)
964 };
965 let suite = |p: &Value| {
966 p.get("cryptosuite")
967 .and_then(Value::as_str)
968 .unwrap_or_default()
969 .to_string()
970 };
971 match list.get("proof") {
972 Some(p @ Value::Object(_)) => (vm(p), None),
973 Some(Value::Array(items)) => (
974 items
975 .iter()
976 .find(|p| suite(p) == hybrid::EDDSA_CRYPTOSUITE_ID)
977 .and_then(vm),
978 items
979 .iter()
980 .find(|p| suite(p) == hybrid::MLDSA44_CRYPTOSUITE_ID)
981 .and_then(vm),
982 ),
983 _ => (None, None),
984 }
985}
986
987fn list_keys(
993 list: Option<&Value>,
994 issuer: &str,
995 known: Option<(&Proofs, &SignerKeys)>,
996 source: &KeySource,
997) -> (Option<Vec<u8>>, Option<Vec<u8>>) {
998 let Some(list) = list else {
999 return (None, None);
1000 };
1001 let resolve_ed = |vm: &str| -> Option<Vec<u8>> {
1004 if let Some((proofs, keys)) = known {
1005 if Some(vm) == proofs.ed_vm().as_deref() && keys.ed25519.is_some() {
1006 return keys.ed25519.clone();
1007 }
1008 }
1009 source.keys(issuer, Some(vm), None, None).ed25519
1010 };
1011 let resolve_ml = |vm: &str| -> Option<Vec<u8>> {
1012 if let Some((proofs, keys)) = known {
1013 if Some(vm) == proofs.ml_vm().as_deref() && keys.mldsa44.is_some() {
1014 return keys.mldsa44.clone();
1015 }
1016 }
1017 source.keys(issuer, None, Some(vm), None).mldsa44
1018 };
1019 let (ed_vm, ml_vm) = list_proof_methods(list);
1020 let own =
1022 |vm: Option<String>| vm.filter(|v| crate::verification_method::method_did(v) == issuer);
1023 let ed = ed_vm
1024 .filter(|v| crate::verification_method::ed25519_method_names(v, issuer))
1025 .and_then(|vm| resolve_ed(&vm))
1026 .and_then(|k| strict_ed25519(&k));
1027 let ml = own(ml_vm)
1028 .and_then(|vm| resolve_ml(&vm))
1029 .filter(|k| k.len() == pq::MLDSA44_PUBLIC_LEN);
1030 (ed, ml)
1031}
1032
1033fn list_requirement(input: &DecisionInput, issuer_requires_pq: bool) -> hybrid::Required {
1038 hybrid::Required {
1039 post_quantum: issuer_requires_pq
1040 || input.require_post_quantum
1041 || input
1042 .require_suites
1043 .iter()
1044 .any(|s| *s != hybrid::Suite::Eddsa),
1045 ..Default::default()
1046 }
1047}
1048
1049fn status_reason(
1057 checked: &Value,
1058 known: Option<(&Proofs, &SignerKeys)>,
1059 source: &KeySource,
1060 input: &DecisionInput,
1061 issuer_requires_pq: bool,
1062) -> Result<Option<String>> {
1063 let Some(raw) = checked.get("credentialStatus") else {
1064 return Ok(None);
1065 };
1066 let unavailable = || Ok(Some(status_list::STATUS_UNAVAILABLE.to_string()));
1067 let entries: Vec<&Value> = match raw {
1068 Value::Object(_) => vec![raw],
1069 Value::Array(items) => items.iter().collect(),
1070 _ => Vec::new(),
1071 };
1072 if entries.is_empty() || entries.len() > status_list::MAX_STATUS_ENTRIES {
1073 return unavailable();
1074 }
1075 let issuer = issuer_did(checked).unwrap_or_default().to_string();
1076 for entry in entries {
1077 let list = entry
1078 .get("statusListCredential")
1079 .and_then(Value::as_str)
1080 .and_then(|url| input.status_lists.get(url));
1081 let (ed_key, ml_key) = list_keys(list, &issuer, known, source);
1082 let mut one = checked.clone();
1083 one["credentialStatus"] = entry.clone();
1084 let result = status_list::check_credential_status_required(
1085 &one,
1086 &input.status_lists,
1087 ed_key.as_deref(),
1088 ml_key.as_deref(),
1089 &input.now,
1090 input.clock_skew_seconds,
1091 list_requirement(input, issuer_requires_pq),
1092 )?;
1093 if !result.ok {
1094 return Ok(Some(result.reason.to_string()));
1095 }
1096 }
1097 Ok(None)
1098}
1099
1100fn check_replay_window(seconds: f64) -> Result<f64> {
1105 if !seconds.is_finite() || seconds <= 0.0 {
1106 return Err(CoreError::Json(
1107 "max_replay_window must be a positive, finite number of seconds".into(),
1108 ));
1109 }
1110 Ok(seconds)
1111}
1112
1113fn window_seconds(cred: &Value) -> Result<f64> {
1114 let t = |k: &str| {
1115 cred.get(k)
1116 .and_then(Value::as_str)
1117 .ok_or_else(|| CoreError::Json(format!("credential missing {k}")))
1118 .and_then(parse_protocol_time_ns)
1119 };
1120 Ok((t("validUntil")? - t("validFrom")?) as f64 / NS_PER_SECOND as f64)
1121}
1122
1123pub fn replay_window_too_long(credential: &Value, max_replay_window_seconds: f64) -> Result<bool> {
1126 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
1127 Ok(window_seconds(credential)? > check_replay_window(max_replay_window_seconds)?)
1128}
1129
1130fn identity_from(
1131 cred: &Value,
1132 proofs: &Proofs,
1133 skew_seconds: i64,
1134 max_window: f64,
1135) -> Result<ReplayIdentity> {
1136 let issuer = issuer_did(cred).unwrap_or_default();
1137 let key = crate::credentials::replay_key(issuer, &proofs.replay_proof_value())?;
1138 let until = cred
1139 .get("validUntil")
1140 .and_then(Value::as_str)
1141 .ok_or_else(|| CoreError::Json("credential missing validUntil".into()))?;
1142 let until_micros = parse_protocol_time_ns(until)?.div_euclid(1000);
1145 Ok(ReplayIdentity {
1146 key,
1147 expires_at: until_micros as f64 / 1e6 + skew_seconds as f64,
1148 single_use: !replay_window_too_long(cred, max_window)?,
1149 })
1150}
1151
1152pub fn replay_identity(
1160 credential: &Value,
1161 now_iso: &str,
1162 clock_skew_seconds: i64,
1163 max_replay_window_seconds: f64,
1164) -> Result<ReplayIdentity> {
1165 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
1166 let skew = check_clock_skew(clock_skew_seconds)?;
1167 let now = parse_protocol_time_ns(now_iso)?.div_euclid(1000) * 1000;
1168 check_replay_window(max_replay_window_seconds)?;
1169 let issuer = issuer_did(credential).unwrap_or_default();
1170 let proofs =
1171 read_proofs(credential, issuer, now, skew).map_err(|p| CoreError::Json(p.into()))?;
1172 identity_from(
1173 credential,
1174 &proofs,
1175 clock_skew_seconds,
1176 max_replay_window_seconds,
1177 )
1178}
1179
1180pub fn passport(cred: &Value, grants: &[&Value]) -> Value {
1187 crate::nesting::deep_guard!(Value::Null; cred, grants);
1188 let chain: Vec<Value> = grants
1189 .iter()
1190 .map(|g| {
1191 let intent = g["credentialSubject"]["intent"].clone();
1192 let bound: String = crate::delegation::parent_proof_binding_value(g)
1193 .chars()
1194 .take(64)
1195 .collect();
1196 json!({
1197 "issuer": issuer_did(g).unwrap_or_default(),
1198 "subject": intent.get("delegatee").cloned().unwrap_or(json!("")),
1199 "intent": intent,
1200 "validFrom": g.get("validFrom").cloned().unwrap_or(Value::Null),
1201 "validUntil": g.get("validUntil").cloned().unwrap_or(Value::Null),
1202 "parentProofValue": bound,
1203 })
1204 })
1205 .collect();
1206 let subject = &cred["credentialSubject"];
1207 let rep = subject
1208 .get("reputationScore")
1209 .and_then(|v| {
1210 if v.is_i64() || v.is_u64() {
1211 v.as_i64()
1212 } else {
1213 None
1214 }
1215 })
1216 .filter(|r| (0..=100).contains(r));
1217 let text = |v: Option<&Value>| v.and_then(Value::as_str).unwrap_or_default().to_string();
1218 json!({
1219 "sub": text(subject.get("id")),
1220 "iss": issuer_did(cred).unwrap_or_default(),
1221 "validFrom": cred["validFrom"],
1222 "validUntil": cred["validUntil"],
1223 "credentialId": text(cred.get("id")),
1224 "intent": subject["intent"],
1225 "reputationScore": rep,
1226 "delegationChain": chain,
1227 "parentGrantDigest": subject.get(grant_chain::PARENT_GRANT_DIGEST).filter(|d| d.is_string()),
1228 })
1229}
1230
1231fn chain_root(chain: &[Value]) -> Option<&str> {
1236 chain.first()?.get("issuer")?.as_str()
1237}
1238
1239fn chain_prefilter(cred: &Value, chain: &[Value], root_dids: &[String]) -> Option<&'static str> {
1242 for link in chain {
1243 let ok = link.get("issuer").is_some_and(Value::is_string)
1244 && link.get("subject").is_some_and(Value::is_string);
1245 if !ok {
1246 return Some(grant_chain::REASON_MALFORMED);
1247 }
1248 }
1249 for i in 1..chain.len() {
1250 if chain[i - 1]["subject"] != chain[i]["issuer"] {
1251 return Some("delegation_subject_issuer_mismatch");
1252 }
1253 }
1254 if chain[chain.len() - 1]["subject"].as_str() != issuer_did(cred) {
1255 return Some("delegation_subject_issuer_mismatch");
1256 }
1257 let root = chain[0]["issuer"].as_str().unwrap_or_default();
1258 if !root_dids.iter().any(|d| d == root) {
1259 return Some("untrusted_principal");
1260 }
1261 if chain
1262 .iter()
1263 .all(|l| matches!(l.get("parentCredential"), Some(Value::Object(_))))
1264 {
1265 return grant_chain::chain_binding_problem(chain);
1266 }
1267 None
1268}
1269
1270fn at_microseconds(input: &DecisionInput) -> Result<DecisionInput> {
1274 let ns = parse_protocol_time_ns(&input.now)?;
1275 let micros = ns.div_euclid(1000) * 1000;
1276 let mut out = input.clone();
1277 out.now = format_time_micros(micros)?;
1278 Ok(out)
1279}
1280
1281pub(crate) fn format_time_micros(ns: i128) -> Result<String> {
1283 let whole = crate::issuance::format_protocol_time(ns)?;
1284 let micros = ns.rem_euclid(NS_PER_SECOND) / 1000;
1285 Ok(format!("{}.{micros:06}Z", whole.trim_end_matches('Z')))
1286}
1287
1288type Precheck<'a> = (Proofs, Option<&'a Vec<Value>>, Vec<String>);
1289
1290fn precheck(input: &DecisionInput) -> Result<core::result::Result<Precheck<'_>, String>> {
1295 let skew = check_clock_skew(input.clock_skew_seconds)?;
1296 let now = parse_protocol_time_ns(&input.now)?;
1297 if !input.credential.is_object() {
1298 return Ok(Err("the credential is not a JSON object".into()));
1299 }
1300 check_replay_window(input.max_replay_window_seconds)?;
1301 let cred = &input.credential;
1302 let root_dids: Vec<String> = input
1303 .trusted_roots
1304 .as_ref()
1305 .map(|r| r.dids.clone())
1306 .unwrap_or_default();
1307 if let Some(problem) = structure_problem(cred, now, skew, input.expected_resource.as_deref()) {
1308 return Ok(Err(problem));
1309 }
1310 let issuer = issuer_did(cred).unwrap_or_default().to_string();
1311 if let Some(allowed) = &input.allowed_issuers {
1312 if !allowed.contains(&issuer) {
1313 return Ok(Err("the issuer is not one of the trusted keys".into()));
1314 }
1315 }
1316 let proofs = match read_proofs(cred, &issuer, now, skew) {
1317 Ok(p) => p,
1318 Err(problem) => return Ok(Err(problem.into())),
1319 };
1320 let carried = proofs.suites();
1323 if input.require_suites.iter().any(|s| !carried.contains(s)) {
1324 return Ok(Err(hybrid::REASON_REQUIRED_SUITE_MISSING.into()));
1325 }
1326 let chain = cred["credentialSubject"]
1327 .get("delegationChain")
1328 .and_then(Value::as_array)
1329 .filter(|c| !c.is_empty());
1330 let names_parent = input.grant_chain_checked_apart
1335 && cred["credentialSubject"]
1336 .as_object()
1337 .is_some_and(|s| s.contains_key(grant_chain::PARENT_GRANT_DIGEST));
1338 if chain.is_none()
1339 && !names_parent
1340 && input.chain_required_outside_roots
1341 && !root_dids.is_empty()
1342 && !root_dids.contains(&issuer)
1343 {
1344 return Ok(Err(REASON_CHAIN_REQUIRED.into()));
1345 }
1346 if let Some(chain) = chain {
1347 let as_value = Value::Array(chain.clone());
1348 match crate::attenuation::chain_budget_exceeded(&as_value, input.max_depth) {
1349 Ok(None) => {}
1350 Ok(Some(_)) => return Ok(Err(REASON_BUDGET.into())),
1351 Err(_) => return Ok(Err(grant_chain::REASON_MALFORMED.into())),
1352 }
1353 if root_dids.is_empty() {
1354 return Ok(Err(untrusted_root_reason(chain_root(chain), false)));
1355 }
1356 if let Some(early) = chain_prefilter(cred, chain, &root_dids) {
1357 if early == "untrusted_principal" {
1358 return Ok(Err(untrusted_root_reason(chain_root(chain), true)));
1359 }
1360 return Ok(Err(early.into()));
1361 }
1362 }
1363 Ok(Ok((proofs, chain, root_dids)))
1364}
1365
1366pub fn decide(input: &DecisionInput) -> Result<Decision> {
1375 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); input);
1376 let input = &at_microseconds(input)?;
1377 let (proofs, chain, root_dids) = match precheck(input)? {
1378 Ok(pre) => pre,
1379 Err(reason) => return Ok(Decision::refuse(reason)),
1380 };
1381 let cred = &input.credential;
1382 let issuer = issuer_did(cred).unwrap_or_default().to_string();
1383
1384 let source = KeySource {
1385 keys: effective_keys(input),
1386 mldsa44: &input.mldsa44_keys,
1387 slhdsa128: &input.slhdsa128_keys,
1388 documents: &input.documents,
1389 };
1390
1391 let mut grants: Vec<&Value> = Vec::new();
1395 if let Some(chain) = chain {
1396 let grant_keys: BTreeMap<String, Vec<u8>> = source
1397 .keys
1398 .iter()
1399 .map(|(did, entry)| {
1400 let raw = match entry {
1401 KeyEntry::Ed25519(k) => k.clone(),
1402 KeyEntry::Unusable => Vec::new(),
1404 };
1405 (did.clone(), raw)
1406 })
1407 .collect();
1408 let documents: BTreeMap<String, Value> = input
1409 .documents
1410 .iter()
1411 .filter(|(did, _)| has_did_document(did))
1412 .map(|(d, v)| (d.clone(), v.clone()))
1413 .collect();
1414 let opts = ChainOptions {
1415 trusted_roots: Some(&root_dids),
1416 grant_keys: Some(&grant_keys),
1417 mldsa_keys: Some(&input.mldsa44_keys),
1418 slhdsa_keys: Some(&input.slhdsa128_keys),
1419 grant_documents: Some(&documents),
1420 require_pq: input.require_post_quantum,
1421 require_suites: &input.require_suites,
1422 max_depth: input.max_depth,
1423 ..Default::default()
1424 };
1425 if let Some(reason) = crate::delegation::verify_delegation_chain_with(
1426 cred,
1427 &input.now,
1428 input.clock_skew_seconds,
1429 &opts,
1430 ) {
1431 if reason == "untrusted_principal" {
1432 return Ok(Decision::refuse(untrusted_root_reason(
1433 chain_root(chain),
1434 true,
1435 )));
1436 }
1437 return Ok(Decision::refuse(reason));
1438 }
1439 grants = chain.iter().map(|l| &l["parentCredential"]).collect();
1440 }
1441
1442 let explicit = input.public_key.is_some();
1444 let mut keys = match &input.public_key {
1445 Some(KeyEntry::Unusable) => {
1446 return Ok(Decision::refuse(
1447 "the public key given is not a usable Ed25519 key",
1448 ))
1449 }
1450 Some(KeyEntry::Ed25519(k)) => {
1451 let Some(pinned) = strict_ed25519(k) else {
1452 return Ok(Decision::refuse(
1453 "the public key given is not a usable Ed25519 key",
1454 ));
1455 };
1456 if issuer.starts_with("did:key:") && did_key_key(&issuer).as_ref() != Some(&pinned) {
1457 return Ok(Decision::refuse(
1458 "the public key given is not the did:key issuer's key",
1459 ));
1460 }
1461 SignerKeys {
1465 ed25519: Some(pinned),
1466 mldsa44: input
1467 .mldsa44_keys
1468 .get(&issuer)
1469 .filter(|k| !k.is_empty())
1470 .cloned(),
1471 slhdsa128: input
1472 .slhdsa128_keys
1473 .get(&issuer)
1474 .filter(|k| !k.is_empty())
1475 .cloned(),
1476 ..Default::default()
1477 }
1478 }
1479 None => {
1480 let (ml_vm, slh_vm) = if proofs.kind != "single" {
1481 (proofs.ml_vm(), proofs.slh_vm())
1482 } else {
1483 (None, None)
1484 };
1485 let found = source.keys(
1486 &issuer,
1487 proofs.ed_vm().as_deref(),
1488 ml_vm.as_deref(),
1489 slh_vm.as_deref(),
1490 );
1491 if found.ed25519.is_none() {
1492 return Ok(Decision::refuse(REASON_NO_KEY));
1493 }
1494 found
1495 }
1496 };
1497 if let Some(given) = &input.mldsa44_public_key {
1498 match given {
1499 Some(k) if k.len() == pq::MLDSA44_PUBLIC_LEN => keys.mldsa44 = Some(k.clone()),
1500 _ => {
1501 return Ok(Decision::refuse(
1502 "the ML-DSA-44 public key given is not a 1312-byte key",
1503 ))
1504 }
1505 }
1506 }
1507 if let Some(given) = &input.slhdsa128_public_key {
1508 match given {
1509 Some(k) if k.len() == crate::slh::SLHDSA128_PUBLIC_LEN => {
1510 keys.slhdsa128 = Some(k.clone())
1511 }
1512 _ => {
1513 return Ok(Decision::refuse(
1514 "the SLH-DSA public key given is not a 32-byte key",
1515 ))
1516 }
1517 }
1518 }
1519 let resolved_ml = input.mldsa44_keys.contains_key(&issuer);
1524 let resolved_slh = input.slhdsa128_keys.contains_key(&issuer);
1525 let required = hybrid::Required {
1526 post_quantum: input.require_post_quantum,
1527 mldsa44: input.mldsa44_public_key.is_some() || keys.publishes_mldsa44 || resolved_ml,
1528 slhdsa128: input.slhdsa128_public_key.is_some() || keys.publishes_slhdsa128 || resolved_slh,
1529 };
1530 match check_proofs(cred, &proofs, &keys, required, explicit) {
1531 ProofCheck::Ok => {}
1532 ProofCheck::Refused(reason) => return Ok(Decision::refuse(reason)),
1533 ProofCheck::MissingMldsa44Key => {
1534 return Err(CoreError::Json(format!(
1535 "{MISSING_MLDSA44_KEY}: this credential carries an ML-DSA-44 post-quantum \
1536 proof; pass the ML-DSA-44 public key or publish it in the issuer's DID \
1537 document. A did:key identifier encodes only the Ed25519 key."
1538 )))
1539 }
1540 }
1541
1542 if input.check_status {
1545 if let Some(reason) =
1546 status_reason(cred, Some((&proofs, &keys)), &source, input, required.any())?
1547 {
1548 return Ok(Decision::refuse(reason));
1549 }
1550 for grant in &grants {
1551 let grant_issuer = issuer_did(grant).unwrap_or_default();
1554 let grant_pq = input.mldsa44_keys.contains_key(grant_issuer)
1555 || input.slhdsa128_keys.contains_key(grant_issuer);
1556 if let Some(reason) = status_reason(grant, None, &source, input, grant_pq)? {
1557 return Ok(Decision::refuse(format!("delegation_{reason}")));
1558 }
1559 }
1560 }
1561
1562 Ok(Decision {
1563 valid: true,
1564 reason: None,
1565 passport: Some(passport(cred, &grants)),
1566 replay: Some(identity_from(
1567 cred,
1568 &proofs,
1569 input.clock_skew_seconds,
1570 input.max_replay_window_seconds,
1571 )?),
1572 issuer_key: keys.ed25519.clone(),
1573 })
1574}
1575
1576pub const MAX_FETCH_DIDS: usize = 32;
1579pub const MAX_FETCH_STATUS_LISTS: usize = 32;
1582
1583#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1585pub enum FetchPhase {
1586 Documents,
1589 StatusLists,
1592}
1593
1594#[derive(Debug, Clone, Default, PartialEq, Eq)]
1596pub struct FetchPlan {
1597 pub refusal: Option<String>,
1602 pub dids: Vec<String>,
1604 pub status_lists: Vec<String>,
1606 pub truncated: bool,
1610}
1611
1612fn push_unique(
1613 list: &mut Vec<String>,
1614 seen: &mut alloc::collections::BTreeSet<String>,
1615 item: &str,
1616 cap: usize,
1617 truncated: &mut bool,
1618) {
1619 if item.is_empty() || seen.contains(item) {
1620 return;
1621 }
1622 if list.len() >= cap {
1623 *truncated = true;
1624 return;
1625 }
1626 seen.insert(item.to_string());
1627 list.push(item.to_string());
1628}
1629
1630fn status_urls(c: &Value) -> Vec<&str> {
1631 let entries: Vec<&Value> = match c.get("credentialStatus") {
1632 Some(e @ Value::Object(_)) => vec![e],
1633 Some(Value::Array(a)) => a.iter().take(status_list::MAX_STATUS_ENTRIES).collect(),
1634 _ => Vec::new(),
1635 };
1636 entries
1637 .iter()
1638 .filter_map(|e| e.get("statusListCredential").and_then(Value::as_str))
1639 .collect()
1640}
1641
1642pub fn fetch_plan(input: &DecisionInput, phase: FetchPhase) -> Result<FetchPlan> {
1665 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); input);
1666 let input = &at_microseconds(input)?;
1667 let mut plan = FetchPlan::default();
1668 match phase {
1669 FetchPhase::Documents => {
1670 let (_, chain, _) = match precheck(input)? {
1671 Ok(pre) => pre,
1672 Err(reason) => {
1673 plan.refusal = Some(reason);
1674 return Ok(plan);
1675 }
1676 };
1677 let known = effective_keys(input);
1678 let mut seen = alloc::collections::BTreeSet::new();
1679 let mut wanted: Vec<&str> = Vec::new();
1680 if input.public_key.is_none() {
1681 wanted.extend(issuer_did(&input.credential));
1682 }
1683 for link in chain.into_iter().flatten() {
1684 wanted.extend(link.get("issuer").and_then(Value::as_str));
1685 }
1686 for did in wanted {
1687 if has_did_document(did) && !known.contains_key(did) {
1688 push_unique(
1689 &mut plan.dids,
1690 &mut seen,
1691 did,
1692 MAX_FETCH_DIDS,
1693 &mut plan.truncated,
1694 );
1695 }
1696 }
1697 }
1698 FetchPhase::StatusLists => {
1699 let mut without_status = input.clone();
1700 without_status.check_status = false;
1701 let decision = decide(&without_status)?;
1704 if !decision.valid {
1705 plan.refusal = decision.reason;
1706 return Ok(plan);
1707 }
1708 if !input.check_status {
1709 return Ok(plan);
1710 }
1711 let mut seen = alloc::collections::BTreeSet::new();
1712 let cred = &input.credential;
1713 let mut urls = status_urls(cred);
1714 if let Some(chain) = cred["credentialSubject"]
1715 .get("delegationChain")
1716 .and_then(Value::as_array)
1717 {
1718 for link in chain {
1719 urls.extend(status_urls(&link["parentCredential"]));
1720 }
1721 }
1722 for url in urls {
1723 push_unique(
1724 &mut plan.status_lists,
1725 &mut seen,
1726 url,
1727 MAX_FETCH_STATUS_LISTS,
1728 &mut plan.truncated,
1729 );
1730 }
1731 }
1732 }
1733 Ok(plan)
1734}
1735
1736const REQUEST_MEMBERS: [&str; 27] = [
1741 "credential",
1742 "now",
1743 "clockSkewSeconds",
1744 "publicKey",
1745 "mldsa44PublicKey",
1746 "slhdsa128PublicKey",
1747 "trustedKeys",
1748 "resolvedKeys",
1749 "mldsa44Keys",
1750 "slhdsa128Keys",
1751 "documents",
1752 "didLogs",
1753 "didLogsB64",
1754 "seenVersionIds",
1755 "limits",
1756 "logNow",
1757 "trustedRoots",
1758 "requirePostQuantum",
1759 "requireSuites",
1760 "expectedResource",
1761 "checkStatus",
1762 "statusLists",
1763 "maxDepth",
1764 "maxReplayWindowSeconds",
1765 "requireTrustedIssuer",
1766 "chainRequiredOutsideRoots",
1767 "grantChainCheckedApart",
1768];
1769
1770fn bad(msg: impl Into<String>) -> CoreError {
1771 CoreError::Json(msg.into())
1772}
1773
1774fn present<'a>(obj: &'a Map<String, Value>, name: &str) -> Option<&'a Value> {
1775 obj.get(name).filter(|v| !v.is_null())
1776}
1777
1778const TIGHTENING_MEMBERS: [&str; 15] = [
1783 "trustedRoots",
1784 "trustedKeys",
1785 "publicKey",
1786 "mldsa44Keys",
1787 "slhdsa128Keys",
1788 "requirePostQuantum",
1789 "requireSuites",
1790 "requireTrustedIssuer",
1791 "expectedResource",
1792 "checkStatus",
1793 "chainRequiredOutsideRoots",
1794 "grantChainCheckedApart",
1795 "mldsa44PublicKey",
1796 "slhdsa128PublicKey",
1797 "maxDepth",
1798];
1799
1800fn refuse_null_tightening(obj: &Map<String, Value>) -> Result<()> {
1801 for name in TIGHTENING_MEMBERS {
1802 if matches!(obj.get(name), Some(Value::Null)) {
1803 return Err(bad(format!(
1804 "{name} must not be null: leave it out for the default"
1805 )));
1806 }
1807 }
1808 Ok(())
1809}
1810
1811fn credential_from_text(text: &str) -> Value {
1815 crate::authority_state::parse_json_no_duplicates(text).unwrap_or(Value::Null)
1816}
1817
1818fn bool_member(obj: &Map<String, Value>, name: &str, default: bool) -> Result<bool> {
1819 match present(obj, name) {
1820 None => Ok(default),
1821 Some(Value::Bool(b)) => Ok(*b),
1822 Some(_) => Err(bad(format!("{name} must be true or false"))),
1823 }
1824}
1825
1826fn object_member<'a>(
1827 obj: &'a Map<String, Value>,
1828 name: &str,
1829) -> Result<Option<&'a Map<String, Value>>> {
1830 match present(obj, name) {
1831 None => Ok(None),
1832 Some(Value::Object(m)) => Ok(Some(m)),
1833 Some(_) => Err(bad(format!("{name} must be a JSON object"))),
1834 }
1835}
1836
1837fn string_list(v: &Value, name: &str) -> Result<Vec<String>> {
1838 v.as_array()
1839 .and_then(|a| {
1840 a.iter()
1841 .map(|x| x.as_str().map(String::from))
1842 .collect::<Option<Vec<_>>>()
1843 })
1844 .ok_or_else(|| bad(format!("{name} must be a list of strings")))
1845}
1846
1847pub fn trusted_roots_from_json(v: &Value) -> Result<Option<TrustedRoots>> {
1851 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); v);
1852 let norm = crate::did_web::normalize_root;
1853 match v {
1854 Value::Null => Ok(None),
1855 Value::String(s) => Ok(Some(TrustedRoots {
1856 dids: vec![norm(s)?],
1857 keys: BTreeMap::new(),
1858 })),
1859 Value::Array(_) => Ok(Some(TrustedRoots {
1860 dids: string_list(v, "trustedRoots")?
1861 .iter()
1862 .map(|s| norm(s))
1863 .collect::<Result<_>>()?,
1864 keys: BTreeMap::new(),
1865 })),
1866 Value::Object(m) => {
1867 let mut roots = TrustedRoots::default();
1868 for (did, key) in m {
1869 let did = norm(did)?;
1870 if !roots.dids.contains(&did) {
1871 roots.dids.push(did.clone());
1872 }
1873 roots.keys.insert(did, key_entry_from_json(key));
1874 }
1875 Ok(Some(roots))
1876 }
1877 _ => Err(bad(
1878 "trustedRoots must be a {did: key} map or a list of DIDs",
1879 )),
1880 }
1881}
1882
1883fn trusted_key_map(obj: &Map<String, Value>) -> Result<BTreeMap<String, KeyEntry>> {
1889 let mut out = BTreeMap::new();
1890 for (did, v) in object_member(obj, "trustedKeys")?.into_iter().flatten() {
1891 let Ok(did) = crate::did_web::normalize_root(did) else {
1892 continue;
1893 };
1894 out.insert(did, key_entry_from_json(v));
1898 }
1899 Ok(out)
1900}
1901
1902fn key_map(obj: &Map<String, Value>, name: &str) -> Result<BTreeMap<String, KeyEntry>> {
1903 Ok(object_member(obj, name)?
1904 .map(|m| {
1905 m.iter()
1906 .filter(|(_, v)| !v.is_null())
1908 .map(|(did, v)| (did.clone(), key_entry_from_json(v)))
1909 .collect()
1910 })
1911 .unwrap_or_default())
1912}
1913
1914pub fn decide_json_with_clock(request: &Value, clock: crate::did_webvh::LogClock) -> Result<Value> {
1951 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); request);
1952 let obj = request
1953 .as_object()
1954 .ok_or_else(|| bad("the request must be a JSON object"))?;
1955 let (input, logs) = read_request(obj, clock, &[])?;
1956 let decision = decide(&input)?;
1957 let (versions, errors) = match &logs {
1958 Some(set) => crate::did_webvh::grant_log_json(&set.outcomes()),
1959 None => (json!({}), json!({})),
1960 };
1961 Ok(json!({
1962 "valid": decision.valid,
1963 "reason": decision.reason,
1964 "passport": decision.passport,
1965 "replay": decision.replay.map(|r| json!({
1966 "key": r.key,
1967 "expiresAt": r.expires_at,
1968 "singleUse": r.single_use,
1969 })),
1970 "issuerKey": decision
1971 .issuer_key
1972 .as_deref()
1973 .map(multikey::encode_ed25519_public)
1974 .transpose()?,
1975 "didLogVersions": versions,
1976 "didLogErrors": errors,
1977 }))
1978}
1979
1980fn read_request(
1983 obj: &Map<String, Value>,
1984 clock: crate::did_webvh::LogClock,
1985 extra: &[&str],
1986) -> Result<(DecisionInput, Option<crate::did_webvh::LogSet>)> {
1987 use crate::did_webvh::{base64_decode, is_did_webvh, LogClock, LogSet};
1988
1989 if let Some(name) = obj
1990 .keys()
1991 .find(|k| !REQUEST_MEMBERS.contains(&k.as_str()) && !extra.contains(&k.as_str()))
1992 {
1993 return Err(bad(format!(
1994 "the request holds an unknown member {:?}",
1995 name.chars().take(40).collect::<String>()
1996 )));
1997 }
1998 refuse_null_tightening(obj)?;
1999 let credential = match obj.get("credential") {
2000 Some(Value::String(text)) => credential_from_text(text),
2001 Some(v) => v.clone(),
2002 None => return Err(bad("credential is required")),
2003 };
2004 let now = obj
2005 .get("now")
2006 .and_then(Value::as_str)
2007 .ok_or_else(|| bad("now must be a protocol time"))?;
2008 let mut input = DecisionInput::new(credential, now);
2009 match obj.get("clockSkewSeconds") {
2010 None => {}
2011 Some(Value::Null) => return Err(bad("clockSkewSeconds must be a whole number of seconds")),
2013 Some(v) => input.clock_skew_seconds = crate::time::clock_skew_from_json(v)?,
2014 }
2015 input.public_key = present(obj, "publicKey").map(key_entry_from_json);
2016 input.mldsa44_public_key = present(obj, "mldsa44PublicKey").map(mldsa44_key_from_json);
2017 input.slhdsa128_public_key = present(obj, "slhdsa128PublicKey").map(slhdsa128_key_from_json);
2018 input.trusted_keys = trusted_key_map(obj)?;
2019 input.resolved_keys = key_map(obj, "resolvedKeys")?;
2020 if let Some(m) = object_member(obj, "mldsa44Keys")? {
2021 for (did, v) in m {
2022 if !v.is_null() {
2027 let k = mldsa44_key_from_json(v).unwrap_or_default();
2028 input.mldsa44_keys.insert(did.clone(), k);
2029 }
2030 }
2031 }
2032 if let Some(m) = object_member(obj, "slhdsa128Keys")? {
2033 for (did, v) in m {
2034 if !v.is_null() {
2037 let k = slhdsa128_key_from_json(v).unwrap_or_default();
2038 input.slhdsa128_keys.insert(did.clone(), k);
2039 }
2040 }
2041 }
2042 if let Some(m) = object_member(obj, "documents")? {
2043 for (did, doc) in m {
2044 if !has_did_document(did) {
2045 return Err(bad(
2046 "documents holds a DID that is not did:web or did:webvh",
2047 ));
2048 }
2049 if !doc.is_null() {
2050 input.documents.insert(did.clone(), doc.clone());
2051 }
2052 }
2053 }
2054 let clock = match present(obj, "logNow") {
2057 None => clock,
2058 Some(v) => LogClock::At(parse_protocol_time_ns(
2059 v.as_str()
2060 .ok_or_else(|| bad("logNow must be a protocol time"))?,
2061 )?),
2062 };
2063 let mut logs: Option<LogSet> = None;
2064 let texts = object_member(obj, "didLogs")?;
2065 let b64s = object_member(obj, "didLogsB64")?;
2066 if texts.is_some() || b64s.is_some() {
2067 let mut set = LogSet::new(clock)?;
2068 if let Some(limits) = present(obj, "limits") {
2069 set = set.with_limits(crate::did_webvh::Limits::from_json(limits)?);
2070 }
2071 let mut given: Vec<(String, Vec<u8>)> = Vec::new();
2072 for (did, v) in texts.into_iter().flatten() {
2073 let t = v
2074 .as_str()
2075 .ok_or_else(|| bad("didLogs must map DIDs to log text"))?;
2076 given.push((did.clone(), t.as_bytes().to_vec()));
2077 }
2078 for (did, v) in b64s.into_iter().flatten() {
2079 let t = v
2080 .as_str()
2081 .ok_or_else(|| bad("didLogsB64 must map DIDs to base64 logs"))?;
2082 given.push((did.clone(), base64_decode(t, "a didLogsB64 log")?));
2083 }
2084 for (did, log) in given {
2085 if !is_did_webvh(&did) {
2086 return Err(bad("didLogs holds a DID that is not a did:webvh DID"));
2087 }
2088 if set.contains(&did) || input.documents.contains_key(&did) {
2089 return Err(bad(
2090 "give each DID's log once, in didLogs, didLogsB64 or documents",
2091 ));
2092 }
2093 set = set.with_log(&did, log);
2094 }
2095 if let Some(m) = object_member(obj, "seenVersionIds")? {
2096 for (did, v) in m {
2097 let seen = v
2098 .as_str()
2099 .ok_or_else(|| bad("seenVersionIds must map DIDs to versionIds"))?;
2100 set = set.with_seen_version_id(did, seen)?;
2101 }
2102 }
2103 logs = Some(set);
2104 }
2105 if let Some(v) = present(obj, "trustedRoots") {
2106 input.trusted_roots = trusted_roots_from_json(v)?;
2107 }
2108 input.require_post_quantum = bool_member(obj, "requirePostQuantum", false)?;
2109 if let Some(v) = present(obj, "requireSuites") {
2110 input.require_suites = hybrid::required_suites_from_json(v)?;
2111 }
2112 input.expected_resource = match present(obj, "expectedResource") {
2113 None => None,
2114 Some(Value::String(s)) => Some(s.clone()),
2115 Some(_) => return Err(bad("expectedResource must be a string")),
2116 };
2117 input.check_status = bool_member(obj, "checkStatus", true)?;
2118 if let Some(m) = object_member(obj, "statusLists")? {
2119 input.status_lists = m.clone();
2120 }
2121 input.max_depth = match present(obj, "maxDepth") {
2122 None => None,
2123 Some(v) => Some(
2124 v.as_u64()
2125 .and_then(|d| usize::try_from(d).ok())
2126 .ok_or_else(|| bad("maxDepth must be a non-negative whole number"))?,
2127 ),
2128 };
2129 if let Some(v) = present(obj, "maxReplayWindowSeconds") {
2130 input.max_replay_window_seconds = match v {
2131 Value::Number(n) => n.as_f64().unwrap_or(f64::NAN),
2132 _ => return Err(bad("max_replay_window must be a number of seconds")),
2133 };
2134 }
2135 if bool_member(obj, "requireTrustedIssuer", false)? {
2139 input.allowed_issuers = Some(input.trusted_keys.keys().cloned().collect());
2140 }
2141 if present(obj, "trustedRoots").is_none() && !input.trusted_keys.is_empty() {
2142 input.trusted_roots = Some(TrustedRoots {
2143 dids: input.trusted_keys.keys().cloned().collect(),
2144 keys: BTreeMap::new(),
2145 });
2146 }
2147 input.chain_required_outside_roots =
2150 input.trusted_roots.is_some() && bool_member(obj, "chainRequiredOutsideRoots", true)?;
2151 input.grant_chain_checked_apart = bool_member(obj, "grantChainCheckedApart", false)?;
2152
2153 if let Some(set) = &logs {
2154 for did in obj
2155 .get("didLogs")
2156 .and_then(Value::as_object)
2157 .into_iter()
2158 .chain(obj.get("didLogsB64").and_then(Value::as_object))
2159 .flat_map(|m| m.keys())
2160 {
2161 if let Some(Ok(resolution)) = set.resolve(did) {
2162 input.documents.insert(did.clone(), resolution.document);
2163 }
2164 }
2165 }
2166
2167 Ok((input, logs))
2168}
2169
2170pub fn decide_json(request: &Value) -> Result<Value> {
2173 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); request);
2174 decide_json_with_clock(request, crate::did_webvh::LogClock::System)
2175}
2176
2177pub fn fetch_plan_json_with_clock(
2182 request: &Value,
2183 clock: crate::did_webvh::LogClock,
2184) -> Result<Value> {
2185 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); request);
2186 let obj = request
2187 .as_object()
2188 .ok_or_else(|| bad("the request must be a JSON object"))?;
2189 let phase = match present(obj, "phase").map(|v| v.as_str()) {
2190 None | Some(Some("documents")) => FetchPhase::Documents,
2191 Some(Some("statusLists")) => FetchPhase::StatusLists,
2192 _ => return Err(bad("phase must be \"documents\" or \"statusLists\"")),
2193 };
2194 let (input, _logs) = read_request(obj, clock, &["phase"])?;
2195 let plan = fetch_plan(&input, phase)?;
2196 Ok(json!({
2197 "refusal": plan.refusal,
2198 "dids": plan.dids,
2199 "statusLists": plan.status_lists,
2200 "truncated": plan.truncated,
2201 }))
2202}
2203
2204pub fn fetch_plan_json(request: &Value) -> Result<Value> {
2207 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); request);
2208 fetch_plan_json_with_clock(request, crate::did_webvh::LogClock::System)
2209}
2210
2211pub fn replay_identity_json(request: &Value) -> Result<Value> {
2215 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); request);
2216 let obj = request
2217 .as_object()
2218 .ok_or_else(|| bad("the request must be a JSON object"))?;
2219 let credential = obj
2220 .get("credential")
2221 .filter(|c| c.is_object())
2222 .ok_or_else(|| bad("credential must be a JSON object"))?;
2223 let now = obj
2224 .get("now")
2225 .and_then(Value::as_str)
2226 .ok_or_else(|| bad("now must be a protocol time"))?;
2227 let skew = match present(obj, "clockSkewSeconds") {
2228 None => DEFAULT_CLOCK_SKEW_SECONDS,
2229 Some(v) => crate::time::clock_skew_from_json(v)?,
2230 };
2231 let window = match present(obj, "maxReplayWindowSeconds") {
2232 None => DEFAULT_MAX_REPLAY_WINDOW_SECONDS,
2233 Some(v) => v
2234 .as_f64()
2235 .ok_or_else(|| bad("max_replay_window must be a number of seconds"))?,
2236 };
2237 let r = replay_identity(credential, now, skew, window)?;
2238 Ok(json!({"key": r.key, "expiresAt": r.expires_at, "singleUse": r.single_use}))
2239}
2240
2241pub fn structure_only_json(request: &Value) -> Result<Value> {
2247 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); request);
2248 let obj = request
2249 .as_object()
2250 .ok_or_else(|| bad("the request must be a JSON object"))?;
2251 let credential = match obj.get("credential") {
2252 Some(Value::String(text)) => credential_from_text(text),
2253 Some(v) => v.clone(),
2254 None => return Err(bad("credential is required")),
2255 };
2256 let now = obj
2257 .get("now")
2258 .and_then(Value::as_str)
2259 .ok_or_else(|| bad("now must be a protocol time"))?;
2260 let now = parse_protocol_time_ns(now)?.div_euclid(1000) * 1000;
2261 let skew = match obj.get("clockSkewSeconds") {
2262 None => DEFAULT_CLOCK_SKEW_SECONDS,
2263 Some(v) => crate::time::clock_skew_from_json(v)?,
2264 };
2265 let skew = check_clock_skew(skew)?;
2266 let expected = match present(obj, "expectedResource") {
2267 None => None,
2268 Some(Value::String(s)) => Some(s.as_str()),
2269 Some(_) => return Err(bad("expectedResource must be a string")),
2270 };
2271 if !credential.is_object() {
2272 return Ok(json!({"problem": "the credential is not a JSON object"}));
2273 }
2274 if let Some(problem) = structure_problem(&credential, now, skew, expected) {
2275 return Ok(json!({ "problem": problem }));
2276 }
2277 let issuer = issuer_did(&credential).unwrap_or_default().to_string();
2278 Ok(match read_proofs(&credential, &issuer, now, skew) {
2279 Ok(_) => json!({ "problem": null }),
2280 Err(problem) => json!({ "problem": problem }),
2281 })
2282}
2283
2284pub fn delegation_chain_json_with_clock(
2295 request: &Value,
2296 clock: crate::did_webvh::LogClock,
2297) -> Result<Value> {
2298 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); request);
2299 let obj = request
2300 .as_object()
2301 .ok_or_else(|| bad("the request must be a JSON object"))?;
2302 let (input, _logs) = read_request(obj, clock, &["linksOnly", "throughLink"])?;
2303 let input = at_microseconds(&input)?;
2304 let cred = &input.credential;
2305 if !cred.is_object() {
2306 return Ok(json!({ "reason": grant_chain::REASON_MALFORMED }));
2307 }
2308 let links_only = bool_member(obj, "linksOnly", false)?;
2309 let through_link = match present(obj, "throughLink") {
2310 None => None,
2311 Some(v) => Some(
2312 v.as_u64()
2313 .and_then(|n| usize::try_from(n).ok())
2314 .ok_or_else(|| bad("throughLink must be a non-negative whole number"))?,
2315 ),
2316 };
2317 let grant_keys: BTreeMap<String, Vec<u8>> = effective_keys(&input)
2318 .into_iter()
2319 .map(|(did, entry)| {
2320 let raw = match entry {
2321 KeyEntry::Ed25519(k) => k,
2322 KeyEntry::Unusable => Vec::new(),
2324 };
2325 (did, raw)
2326 })
2327 .collect();
2328 let documents: BTreeMap<String, Value> = input
2329 .documents
2330 .iter()
2331 .filter(|(did, _)| has_did_document(did))
2332 .map(|(d, v)| (d.clone(), v.clone()))
2333 .collect();
2334 let roots: Vec<String> = input
2335 .trusted_roots
2336 .as_ref()
2337 .map(|r| r.dids.clone())
2338 .unwrap_or_default();
2339 let opts = ChainOptions {
2340 trusted_roots: Some(&roots),
2342 grant_keys: Some(&grant_keys),
2343 mldsa_keys: Some(&input.mldsa44_keys),
2344 slhdsa_keys: Some(&input.slhdsa128_keys),
2345 grant_documents: Some(&documents),
2346 require_pq: input.require_post_quantum,
2347 require_suites: &input.require_suites,
2348 max_depth: input.max_depth,
2349 through_link,
2350 ..Default::default()
2351 };
2352 let check = if links_only {
2355 crate::delegation::chain_links_problem
2356 } else {
2357 crate::delegation::verify_delegation_chain_with
2358 };
2359 let reason = check(cred, &input.now, input.clock_skew_seconds, &opts);
2360 Ok(json!({ "reason": reason }))
2361}
2362
2363pub fn normalize_root_json(request: &Value) -> Result<Value> {
2367 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); request);
2368 let root = request
2369 .get("root")
2370 .and_then(Value::as_str)
2371 .ok_or_else(|| bad("a trusted root is a DID or a domain name"))?;
2372 Ok(json!({ "did": crate::did_web::normalize_root(root)? }))
2373}
2374
2375crate::nesting::nested_fields!(DecisionInput; credential, documents, status_lists);
2377crate::nesting::nested_fields!(Proofs; eddsa, mldsa, slhdsa);
2378
2379#[cfg(test)]
2380mod tests {
2381 use super::*;
2382
2383 #[test]
2384 fn showable_dids() {
2385 assert!(showable_did("did:web:example.com"));
2386 assert!(showable_did("did:key:z6Mk"));
2387 assert!(!showable_did("did:Web:example.com"));
2388 assert!(!showable_did("did:web:"));
2389 assert!(!showable_did("did:web:a b"));
2390 assert!(!showable_did(&format!("did:web:{}", "a".repeat(201))));
2391 assert_eq!(
2392 untrusted_root_reason(Some("did:web:root.example"), true),
2393 "the chain's starting point is not trusted: run `vouch trust did:web:root.example` \
2394 (it is not one of the trusted roots)"
2395 );
2396 assert_eq!(
2397 untrusted_root_reason(Some("did:web:a b"), false),
2398 REASON_UNTRUSTED_START
2399 );
2400 }
2401
2402 #[test]
2403 fn group_order_matches_the_curve() {
2404 let mut sig = [0u8; 64];
2407 let base = ed25519_dalek::SigningKey::from_bytes(&[7u8; 32]).verifying_key();
2408 sig[..32].copy_from_slice(base.as_bytes());
2409 sig[32..].copy_from_slice(&GROUP_ORDER_LE);
2410 assert!(!strict_signature(&sig));
2411 sig[32] -= 1;
2412 assert!(strict_signature(&sig));
2413 }
2414
2415 #[test]
2416 fn bad_requests_are_errors() {
2417 let cred = json!({});
2418 let mut input = DecisionInput::new(cred, "2026-01-01T00:00:00Z");
2419 input.max_replay_window_seconds = 0.0;
2420 assert!(decide(&input).is_err());
2421 input.max_replay_window_seconds = 10.0;
2422 input.clock_skew_seconds = 121;
2423 assert!(decide(&input).is_err());
2424 let not_object = DecisionInput::new(json!([1]), "2026-01-01T00:00:00Z");
2425 assert_eq!(
2426 decide(¬_object).unwrap().reason.as_deref(),
2427 Some("the credential is not a JSON object")
2428 );
2429 }
2430
2431 #[test]
2432 fn jwk_x_padding_matches_the_reference() {
2433 let key = ed25519_dalek::SigningKey::from_bytes(&[7u8; 32]).verifying_key();
2436 let body = base64::Engine::encode(
2437 &base64::engine::general_purpose::URL_SAFE_NO_PAD,
2438 key.as_bytes(),
2439 );
2440 assert_eq!(body.len(), 43);
2441 let entry =
2442 |x: String| key_entry_from_json(&json!({"kty": "OKP", "crv": "Ed25519", "x": x}));
2443 for (pad, usable) in [(0, true), (1, true), (2, false), (3, false), (4, false)] {
2444 let got = entry(format!("{body}{}", "=".repeat(pad)));
2445 assert_eq!(
2446 matches!(got, KeyEntry::Ed25519(_)),
2447 usable,
2448 "{pad} padding signs"
2449 );
2450 }
2451 assert!(matches!(entry(format!("={body}")), KeyEntry::Unusable));
2452 assert!(matches!(
2453 entry(format!("{}={}", &body[..20], &body[20..])),
2454 KeyEntry::Unusable
2455 ));
2456 }
2457}