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 = p
472 .get("verificationMethod")
473 .and_then(Value::as_str)
474 .is_some_and(|vm| vm.split('#').next() == Some(issuer));
475 if !bound {
476 return Some("a proof's verificationMethod does not belong to the issuer");
477 }
478 if p.get("proofValue")
479 .and_then(Value::as_str)
480 .is_none_or(str::is_empty)
481 {
482 return Some("a proof has no proofValue");
483 }
484 if let Some(created) = p.get("created") {
485 if protocol_time(created).is_none() {
486 return Some("a proof's created is not a valid time");
487 }
488 }
489 if let Some(expires) = p.get("expires") {
490 let Some(e) = protocol_time(expires) else {
491 return Some("a proof's expires is not a valid time");
492 };
493 if window_state_ns(now, None, Some(e), skew) != WindowState::Ok {
494 return Some("a proof expired");
495 }
496 }
497 None
498}
499
500pub const REASON_PROOF_SET_SHAPE: &str =
502 "a proof set must be one eddsa-jcs-2022 proof and one proof of each post-quantum suite it carries";
503
504pub fn read_proofs(
510 cred: &Value,
511 issuer: &str,
512 now: i128,
513 skew: i128,
514) -> core::result::Result<Proofs, &'static str> {
515 crate::nesting::deep_guard!(Err(crate::nesting::TOO_DEEP); cred);
516 match cred.get("proof") {
517 Some(raw @ Value::Object(_)) => {
518 if let Some(problem) = proof_problem(raw, issuer, now, skew) {
519 return Err(problem);
520 }
521 match hybrid::Suite::of_proof(raw) {
522 Some(hybrid::Suite::Eddsa) => Ok(Proofs {
523 kind: "single",
524 eddsa: Some(raw.clone()),
525 mldsa: None,
526 slhdsa: None,
527 }),
528 Some(hybrid::Suite::Slhdsa128) => {
529 Err("an SLH-DSA proof needs its eddsa-jcs-2022 partner in a proof set")
530 }
531 _ => Err("an ML-DSA-44 proof needs its eddsa-jcs-2022 partner in a proof set"),
532 }
533 }
534 Some(Value::Array(items)) => {
535 for p in items {
536 if let Some(problem) = proof_problem(p, issuer, now, skew) {
537 return Err(problem);
538 }
539 }
540 let Some(members) = hybrid::set_members(items) else {
541 return Err(REASON_PROOF_SET_SHAPE);
542 };
543 Ok(Proofs {
544 kind: "set",
545 eddsa: Some(members.eddsa.clone()),
546 mldsa: members.mldsa44.cloned(),
547 slhdsa: members.slhdsa128.cloned(),
548 })
549 }
550 _ => Err("the credential has no proof"),
551 }
552}
553
554#[derive(Debug, Clone, Default, PartialEq, Eq)]
560pub struct SignerKeys {
561 pub ed25519: Option<Vec<u8>>,
562 pub mldsa44: Option<Vec<u8>>,
563 pub slhdsa128: Option<Vec<u8>>,
564 pub publishes_mldsa44: bool,
567 pub publishes_slhdsa128: bool,
570}
571
572fn strict_ed25519(raw: &[u8]) -> Option<Vec<u8>> {
574 keys::strict_verifying_key(raw).ok().map(|_| raw.to_vec())
575}
576
577fn did_key_key(did: &str) -> Option<Vec<u8>> {
579 let mk = did.strip_prefix("did:key:")?;
580 let decoded = multikey::decode(mk).ok()?;
581 (decoded.algorithm == "Ed25519").then_some(decoded.raw_key)
582}
583
584fn effective_keys(input: &DecisionInput) -> BTreeMap<String, KeyEntry> {
588 let mut merged = input.resolved_keys.clone();
589 if let Some(roots) = &input.trusted_roots {
590 for (did, key) in &roots.keys {
591 merged.insert(did.clone(), key.clone());
592 }
593 }
594 for (did, key) in &input.trusted_keys {
595 merged.insert(did.clone(), key.clone());
596 }
597 merged
598}
599
600struct KeySource<'a> {
601 keys: BTreeMap<String, KeyEntry>,
602 mldsa44: &'a BTreeMap<String, Vec<u8>>,
603 slhdsa128: &'a BTreeMap<String, Vec<u8>>,
604 documents: &'a BTreeMap<String, Value>,
605}
606
607impl KeySource<'_> {
608 fn keys(
613 &self,
614 did: &str,
615 ed_vm: Option<&str>,
616 ml_vm: Option<&str>,
617 slh_vm: Option<&str>,
618 ) -> SignerKeys {
619 let mut found = SignerKeys {
622 mldsa44: self.mldsa44.get(did).filter(|k| !k.is_empty()).cloned(),
623 slhdsa128: self.slhdsa128.get(did).filter(|k| !k.is_empty()).cloned(),
624 ..Default::default()
625 };
626 let own = if did.starts_with("did:key:") {
627 match did_key_key(did) {
628 Some(k) => Some(k),
629 None => return found, }
631 } else {
632 None
633 };
634 if let Some(entry) = self.keys.get(did) {
635 found.ed25519 = match entry {
636 KeyEntry::Ed25519(k) => match &own {
637 Some(o) if o != k => None,
638 _ => strict_ed25519(k),
639 },
640 KeyEntry::Unusable => None,
641 };
642 return found;
643 }
644 if let Some(k) = own {
645 found.ed25519 = Some(k);
646 return found;
647 }
648 if has_did_document(did) {
649 let Some(doc) = self.documents.get(did) else {
650 return found;
651 };
652 if doc.get("id").and_then(Value::as_str) != Some(did) {
653 return found;
654 }
655 found.publishes_mldsa44 = did_document::publishes_mldsa44_assertion_key(doc, did);
656 if let Some(vm) = ed_vm {
657 found.ed25519 = did_document::assertion_key(doc, did, vm, did_document::ED25519)
658 .ok()
659 .and_then(|k| strict_ed25519(&k));
660 }
661 found.publishes_slhdsa128 = did_document::publishes_slhdsa128_assertion_key(doc, did);
662 if let (Some(vm), None) = (ml_vm, &found.mldsa44) {
663 found.mldsa44 =
664 did_document::assertion_key(doc, did, vm, did_document::MLDSA44).ok();
665 }
666 if let (Some(vm), None) = (slh_vm, &found.slhdsa128) {
667 found.slhdsa128 =
668 did_document::assertion_key(doc, did, vm, did_document::SLHDSA128).ok();
669 }
670 }
671 found
672 }
673}
674
675fn jwk_base64url_decode(text: &str) -> Option<Vec<u8>> {
680 use base64::engine::{
681 general_purpose::GeneralPurpose, DecodePaddingMode, GeneralPurposeConfig,
682 };
683 use base64::{alphabet::URL_SAFE, Engine};
684 let body = text.trim_end_matches('=');
685 let padding = text.len() - body.len();
688 if body.len() % 4 == 1 || (padding != 0 && padding != (4 - body.len() % 4) % 4) {
689 return None;
690 }
691 if body.contains('=') {
692 return None;
693 }
694 let engine = GeneralPurpose::new(
695 &URL_SAFE,
696 GeneralPurposeConfig::new()
697 .with_decode_allow_trailing_bits(true)
698 .with_decode_padding_mode(DecodePaddingMode::Indifferent),
699 );
700 engine.decode(body).ok()
701}
702
703pub fn key_entry_from_json(v: &Value) -> KeyEntry {
708 crate::nesting::deep_guard!(KeyEntry::Unusable; v);
709 let jwk = match v {
710 Value::String(s) if s.starts_with('z') => {
711 return match multikey::decode(s) {
712 Ok(d) if d.algorithm == "Ed25519" => KeyEntry::Ed25519(d.raw_key),
713 _ => KeyEntry::Unusable,
714 };
715 }
716 Value::String(s) if crate::nesting::check_text(s.as_bytes()).is_err() => {
717 return KeyEntry::Unusable
718 }
719 Value::String(s) => match serde_json::from_str::<Value>(s) {
720 Ok(Value::Object(o)) => o,
721 _ => return KeyEntry::Unusable,
722 },
723 Value::Object(o) => o.clone(),
724 _ => return KeyEntry::Unusable,
725 };
726 if jwk.get("kty").and_then(Value::as_str) != Some("OKP")
727 || jwk.get("crv").and_then(Value::as_str) != Some("Ed25519")
728 {
729 return KeyEntry::Unusable;
730 }
731 let Some(x) = jwk.get("x").and_then(Value::as_str) else {
732 return KeyEntry::Unusable;
733 };
734 match jwk_base64url_decode(x).and_then(|raw| strict_ed25519(&raw)) {
735 Some(k) => KeyEntry::Ed25519(k),
736 None => KeyEntry::Unusable,
737 }
738}
739
740pub fn mldsa44_key_from_json(v: &Value) -> Option<Vec<u8>> {
743 crate::nesting::deep_guard!(None; v);
744 let s = v.as_str().filter(|s| s.starts_with('z'))?;
745 let d = multikey::decode(s).ok()?;
746 (d.algorithm == "ML-DSA-44").then_some(d.raw_key)
747}
748
749pub fn slhdsa128_key_from_json(v: &Value) -> Option<Vec<u8>> {
752 crate::nesting::deep_guard!(None; v);
753 let s = v.as_str().filter(|s| s.starts_with('u'))?;
754 let d = multikey::decode(s).ok()?;
755 (d.algorithm == multikey::SLHDSA128).then_some(d.raw_key)
756}
757
758fn strict_signature(sig: &[u8]) -> bool {
765 if sig.len() != keys::ED25519_SIGNATURE_LEN {
766 return false;
767 }
768 let mut r = [0u8; 32];
769 r.copy_from_slice(&sig[..32]);
770 if !keys::is_canonical_point_encoding(&r) {
771 return false;
772 }
773 match ed25519_dalek::VerifyingKey::from_bytes(&r) {
774 Ok(point) if !point.is_weak() => {}
775 _ => return false,
776 }
777 for i in (0..32).rev() {
779 let s = sig[32 + i];
780 if s != GROUP_ORDER_LE[i] {
781 return s < GROUP_ORDER_LE[i];
782 }
783 }
784 false
785}
786
787type Checked = core::result::Result<bool, &'static str>;
790
791fn context_matches(document: &Value, proof: &Value) -> bool {
792 proof
793 .as_object()
794 .is_none_or(|p| data_integrity::proof_context_matches(document, p))
795}
796
797fn without_proof(cred: &Value) -> Value {
798 let mut base = cred.clone();
799 if let Some(o) = base.as_object_mut() {
800 o.remove("proof");
801 }
802 base
803}
804
805fn verify_ed25519_proof(cred: &Value, key: &[u8]) -> Checked {
807 let pv = cred
808 .get("proof")
809 .and_then(|p| p.get("proofValue"))
810 .and_then(Value::as_str)
811 .unwrap_or("");
812 let Some(body) = pv.strip_prefix('z') else {
813 return Err(VALUE_ERROR);
814 };
815 let sig = match multikey::decode_base58_bounded(body) {
816 Ok(s) if s.len() == keys::ED25519_SIGNATURE_LEN => s,
817 _ => return Err(VALUE_ERROR),
818 };
819 if !strict_signature(&sig) {
820 return Err(WEAK_KEY_ERROR);
821 }
822 if !context_matches(&without_proof(cred), &cred["proof"]) {
823 return Err(VALUE_ERROR);
824 }
825 data_integrity::verify_proof(cred, key).map_err(|_| VALUE_ERROR)
826}
827
828fn verify_pq_member(base: &Value, obj: &Map<String, Value>, key: &[u8]) -> Checked {
832 let suite = obj.get("cryptosuite").and_then(Value::as_str).unwrap_or("");
833 let slh = suite == hybrid::SLHDSA128_CRYPTOSUITE_ID;
834 let key_len = if slh {
835 crate::slh::SLHDSA128_PUBLIC_LEN
836 } else {
837 pq::MLDSA44_PUBLIC_LEN
838 };
839 if obj.get("type").and_then(Value::as_str) != Some(data_integrity::PROOF_TYPE)
840 || key.len() != key_len
841 {
842 return Err(VALUE_ERROR);
843 }
844 let pv = obj.get("proofValue").and_then(Value::as_str).unwrap_or("");
845 let sig = if slh {
846 hybrid::decode_slhdsa128_proof_value(pv)
847 } else {
848 hybrid::decode_mldsa44_proof_value(pv)
849 }
850 .map_err(|_| VALUE_ERROR)?;
851 if !data_integrity::proof_context_matches(base, obj) {
852 return Err(VALUE_ERROR);
853 }
854 let mut unsigned = obj.clone();
855 unsigned.remove("proofValue");
856 let input = data_integrity::hash_data(base, &unsigned).map_err(|_| VALUE_ERROR)?;
857 if slh {
858 return crate::slh::verify(key, &input, &sig).map_err(|_| VALUE_ERROR);
859 }
860 let mut ok = pq::verify(key, &input, &sig).map_err(|_| VALUE_ERROR)?;
861 if !ok {
862 let legacy =
863 data_integrity::legacy_proof_digest(base, &unsigned).map_err(|_| VALUE_ERROR)?;
864 ok = pq::verify(key, &legacy, &sig).map_err(|_| VALUE_ERROR)?;
865 }
866 Ok(ok)
867}
868
869fn verify_proof_set(cred: &Value, ed: &[u8], ml: Option<&[u8]>, slh: Option<&[u8]>) -> Checked {
874 let Some(items) = cred.get("proof").and_then(Value::as_array) else {
875 return Err(VALUE_ERROR);
876 };
877 let base = without_proof(cred);
878 let (mut ed_ok, mut pq_ok) = (false, false);
879 for p in items {
880 let Some(obj) = p.as_object() else { continue };
881 match hybrid::Suite::of_proof(p) {
882 Some(hybrid::Suite::Eddsa) => {
883 let mut candidate = base.clone();
884 candidate["proof"] = p.clone();
885 if !verify_ed25519_proof(&candidate, ed)? {
886 return Ok(false);
887 }
888 ed_ok = true;
889 }
890 Some(suite) => {
891 let key = if suite == hybrid::Suite::Mldsa44 {
892 ml
893 } else {
894 slh
895 };
896 let Some(key) = key else {
897 return Ok(false);
898 };
899 if !verify_pq_member(&base, obj, key)? {
900 return Ok(false);
901 }
902 pq_ok = true;
903 }
904 None => {}
905 }
906 }
907 Ok(ed_ok && pq_ok)
908}
909
910enum ProofCheck {
911 Ok,
912 Refused(String),
913 MissingMldsa44Key,
914}
915
916fn check_proofs(
918 cred: &Value,
919 proofs: &Proofs,
920 keys: &SignerKeys,
921 required: hybrid::Required,
922 explicit: bool,
923) -> ProofCheck {
924 let ed = keys.ed25519.as_deref().unwrap_or_default();
925 let verdict = if proofs.kind == "single" {
926 if required.any() {
927 return ProofCheck::Refused("a post-quantum proof is required".into());
928 }
929 verify_ed25519_proof(cred, ed)
930 } else {
931 if !required.met_by(&proofs.suites()) {
932 return ProofCheck::Refused(hybrid::REASON_REQUIRED_SUITE_MISSING.into());
933 }
934 if proofs.mldsa.is_some() && keys.mldsa44.is_none() {
935 if explicit {
936 return ProofCheck::MissingMldsa44Key;
937 }
938 return ProofCheck::Refused(
939 "no ML-DSA-44 key to check the post-quantum proof with".into(),
940 );
941 }
942 if proofs.slhdsa.is_some() && keys.slhdsa128.is_none() {
943 return ProofCheck::Refused(
944 "no SLH-DSA key to check the post-quantum proof with".into(),
945 );
946 }
947 verify_proof_set(cred, ed, keys.mldsa44.as_deref(), keys.slhdsa128.as_deref())
948 };
949 match verdict {
950 Ok(true) => ProofCheck::Ok,
951 Ok(false) => ProofCheck::Refused("the signature does not verify".into()),
952 Err(name) => ProofCheck::Refused(format!("the credential is malformed ({name})")),
953 }
954}
955
956fn list_proof_methods(list: &Value) -> (Option<String>, Option<String>) {
963 let vm = |p: &Value| {
964 p.get("verificationMethod")
965 .and_then(Value::as_str)
966 .map(String::from)
967 };
968 let suite = |p: &Value| {
969 p.get("cryptosuite")
970 .and_then(Value::as_str)
971 .unwrap_or_default()
972 .to_string()
973 };
974 match list.get("proof") {
975 Some(p @ Value::Object(_)) => (vm(p), None),
976 Some(Value::Array(items)) => (
977 items
978 .iter()
979 .find(|p| suite(p) == hybrid::EDDSA_CRYPTOSUITE_ID)
980 .and_then(vm),
981 items
982 .iter()
983 .find(|p| suite(p) == hybrid::MLDSA44_CRYPTOSUITE_ID)
984 .and_then(vm),
985 ),
986 _ => (None, None),
987 }
988}
989
990fn list_keys(
996 list: Option<&Value>,
997 issuer: &str,
998 known: Option<(&Proofs, &SignerKeys)>,
999 source: &KeySource,
1000) -> (Option<Vec<u8>>, Option<Vec<u8>>) {
1001 let Some(list) = list else {
1002 return (None, None);
1003 };
1004 let resolve_ed = |vm: &str| -> Option<Vec<u8>> {
1007 if let Some((proofs, keys)) = known {
1008 if Some(vm) == proofs.ed_vm().as_deref() && keys.ed25519.is_some() {
1009 return keys.ed25519.clone();
1010 }
1011 }
1012 source.keys(issuer, Some(vm), None, None).ed25519
1013 };
1014 let resolve_ml = |vm: &str| -> Option<Vec<u8>> {
1015 if let Some((proofs, keys)) = known {
1016 if Some(vm) == proofs.ml_vm().as_deref() && keys.mldsa44.is_some() {
1017 return keys.mldsa44.clone();
1018 }
1019 }
1020 source.keys(issuer, None, Some(vm), None).mldsa44
1021 };
1022 let (ed_vm, ml_vm) = list_proof_methods(list);
1023 let own = |vm: Option<String>| vm.filter(|v| v.split('#').next() == Some(issuer));
1025 let ed = own(ed_vm)
1026 .and_then(|vm| resolve_ed(&vm))
1027 .and_then(|k| strict_ed25519(&k));
1028 let ml = own(ml_vm)
1029 .and_then(|vm| resolve_ml(&vm))
1030 .filter(|k| k.len() == pq::MLDSA44_PUBLIC_LEN);
1031 (ed, ml)
1032}
1033
1034fn list_requirement(input: &DecisionInput, issuer_requires_pq: bool) -> hybrid::Required {
1039 hybrid::Required {
1040 post_quantum: issuer_requires_pq
1041 || input.require_post_quantum
1042 || input
1043 .require_suites
1044 .iter()
1045 .any(|s| *s != hybrid::Suite::Eddsa),
1046 ..Default::default()
1047 }
1048}
1049
1050fn status_reason(
1058 checked: &Value,
1059 known: Option<(&Proofs, &SignerKeys)>,
1060 source: &KeySource,
1061 input: &DecisionInput,
1062 issuer_requires_pq: bool,
1063) -> Result<Option<String>> {
1064 let Some(raw) = checked.get("credentialStatus") else {
1065 return Ok(None);
1066 };
1067 let unavailable = || Ok(Some(status_list::STATUS_UNAVAILABLE.to_string()));
1068 let entries: Vec<&Value> = match raw {
1069 Value::Object(_) => vec![raw],
1070 Value::Array(items) => items.iter().collect(),
1071 _ => Vec::new(),
1072 };
1073 if entries.is_empty() || entries.len() > status_list::MAX_STATUS_ENTRIES {
1074 return unavailable();
1075 }
1076 let issuer = issuer_did(checked).unwrap_or_default().to_string();
1077 for entry in entries {
1078 let list = entry
1079 .get("statusListCredential")
1080 .and_then(Value::as_str)
1081 .and_then(|url| input.status_lists.get(url));
1082 let (ed_key, ml_key) = list_keys(list, &issuer, known, source);
1083 let mut one = checked.clone();
1084 one["credentialStatus"] = entry.clone();
1085 let result = status_list::check_credential_status_required(
1086 &one,
1087 &input.status_lists,
1088 ed_key.as_deref(),
1089 ml_key.as_deref(),
1090 &input.now,
1091 input.clock_skew_seconds,
1092 list_requirement(input, issuer_requires_pq),
1093 )?;
1094 if !result.ok {
1095 return Ok(Some(result.reason.to_string()));
1096 }
1097 }
1098 Ok(None)
1099}
1100
1101fn check_replay_window(seconds: f64) -> Result<f64> {
1106 if !seconds.is_finite() || seconds <= 0.0 {
1107 return Err(CoreError::Json(
1108 "max_replay_window must be a positive, finite number of seconds".into(),
1109 ));
1110 }
1111 Ok(seconds)
1112}
1113
1114fn window_seconds(cred: &Value) -> Result<f64> {
1115 let t = |k: &str| {
1116 cred.get(k)
1117 .and_then(Value::as_str)
1118 .ok_or_else(|| CoreError::Json(format!("credential missing {k}")))
1119 .and_then(parse_protocol_time_ns)
1120 };
1121 Ok((t("validUntil")? - t("validFrom")?) as f64 / NS_PER_SECOND as f64)
1122}
1123
1124pub fn replay_window_too_long(credential: &Value, max_replay_window_seconds: f64) -> Result<bool> {
1127 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
1128 Ok(window_seconds(credential)? > check_replay_window(max_replay_window_seconds)?)
1129}
1130
1131fn identity_from(
1132 cred: &Value,
1133 proofs: &Proofs,
1134 skew_seconds: i64,
1135 max_window: f64,
1136) -> Result<ReplayIdentity> {
1137 let issuer = issuer_did(cred).unwrap_or_default();
1138 let key = crate::credentials::replay_key(issuer, &proofs.replay_proof_value())?;
1139 let until = cred
1140 .get("validUntil")
1141 .and_then(Value::as_str)
1142 .ok_or_else(|| CoreError::Json("credential missing validUntil".into()))?;
1143 let until_micros = parse_protocol_time_ns(until)?.div_euclid(1000);
1146 Ok(ReplayIdentity {
1147 key,
1148 expires_at: until_micros as f64 / 1e6 + skew_seconds as f64,
1149 single_use: !replay_window_too_long(cred, max_window)?,
1150 })
1151}
1152
1153pub fn replay_identity(
1161 credential: &Value,
1162 now_iso: &str,
1163 clock_skew_seconds: i64,
1164 max_replay_window_seconds: f64,
1165) -> Result<ReplayIdentity> {
1166 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); credential);
1167 let skew = check_clock_skew(clock_skew_seconds)?;
1168 let now = parse_protocol_time_ns(now_iso)?.div_euclid(1000) * 1000;
1169 check_replay_window(max_replay_window_seconds)?;
1170 let issuer = issuer_did(credential).unwrap_or_default();
1171 let proofs =
1172 read_proofs(credential, issuer, now, skew).map_err(|p| CoreError::Json(p.into()))?;
1173 identity_from(
1174 credential,
1175 &proofs,
1176 clock_skew_seconds,
1177 max_replay_window_seconds,
1178 )
1179}
1180
1181pub fn passport(cred: &Value, grants: &[&Value]) -> Value {
1188 crate::nesting::deep_guard!(Value::Null; cred, grants);
1189 let chain: Vec<Value> = grants
1190 .iter()
1191 .map(|g| {
1192 let intent = g["credentialSubject"]["intent"].clone();
1193 let bound: String = crate::delegation::parent_proof_binding_value(g)
1194 .chars()
1195 .take(64)
1196 .collect();
1197 json!({
1198 "issuer": issuer_did(g).unwrap_or_default(),
1199 "subject": intent.get("delegatee").cloned().unwrap_or(json!("")),
1200 "intent": intent,
1201 "validFrom": g.get("validFrom").cloned().unwrap_or(Value::Null),
1202 "validUntil": g.get("validUntil").cloned().unwrap_or(Value::Null),
1203 "parentProofValue": bound,
1204 })
1205 })
1206 .collect();
1207 let subject = &cred["credentialSubject"];
1208 let rep = subject
1209 .get("reputationScore")
1210 .and_then(|v| {
1211 if v.is_i64() || v.is_u64() {
1212 v.as_i64()
1213 } else {
1214 None
1215 }
1216 })
1217 .filter(|r| (0..=100).contains(r));
1218 let text = |v: Option<&Value>| v.and_then(Value::as_str).unwrap_or_default().to_string();
1219 json!({
1220 "sub": text(subject.get("id")),
1221 "iss": issuer_did(cred).unwrap_or_default(),
1222 "validFrom": cred["validFrom"],
1223 "validUntil": cred["validUntil"],
1224 "credentialId": text(cred.get("id")),
1225 "intent": subject["intent"],
1226 "reputationScore": rep,
1227 "delegationChain": chain,
1228 "parentGrantDigest": subject.get(grant_chain::PARENT_GRANT_DIGEST).filter(|d| d.is_string()),
1229 })
1230}
1231
1232fn chain_root(chain: &[Value]) -> Option<&str> {
1237 chain.first()?.get("issuer")?.as_str()
1238}
1239
1240fn chain_prefilter(cred: &Value, chain: &[Value], root_dids: &[String]) -> Option<&'static str> {
1243 for link in chain {
1244 let ok = link.get("issuer").is_some_and(Value::is_string)
1245 && link.get("subject").is_some_and(Value::is_string);
1246 if !ok {
1247 return Some(grant_chain::REASON_MALFORMED);
1248 }
1249 }
1250 for i in 1..chain.len() {
1251 if chain[i - 1]["subject"] != chain[i]["issuer"] {
1252 return Some("delegation_subject_issuer_mismatch");
1253 }
1254 }
1255 if chain[chain.len() - 1]["subject"].as_str() != issuer_did(cred) {
1256 return Some("delegation_subject_issuer_mismatch");
1257 }
1258 let root = chain[0]["issuer"].as_str().unwrap_or_default();
1259 if !root_dids.iter().any(|d| d == root) {
1260 return Some("untrusted_principal");
1261 }
1262 if chain
1263 .iter()
1264 .all(|l| matches!(l.get("parentCredential"), Some(Value::Object(_))))
1265 {
1266 return grant_chain::chain_binding_problem(chain);
1267 }
1268 None
1269}
1270
1271fn at_microseconds(input: &DecisionInput) -> Result<DecisionInput> {
1275 let ns = parse_protocol_time_ns(&input.now)?;
1276 let micros = ns.div_euclid(1000) * 1000;
1277 let mut out = input.clone();
1278 out.now = format_time_micros(micros)?;
1279 Ok(out)
1280}
1281
1282pub(crate) fn format_time_micros(ns: i128) -> Result<String> {
1284 let whole = crate::issuance::format_protocol_time(ns)?;
1285 let micros = ns.rem_euclid(NS_PER_SECOND) / 1000;
1286 Ok(format!("{}.{micros:06}Z", whole.trim_end_matches('Z')))
1287}
1288
1289type Precheck<'a> = (Proofs, Option<&'a Vec<Value>>, Vec<String>);
1290
1291fn precheck(input: &DecisionInput) -> Result<core::result::Result<Precheck<'_>, String>> {
1296 let skew = check_clock_skew(input.clock_skew_seconds)?;
1297 let now = parse_protocol_time_ns(&input.now)?;
1298 if !input.credential.is_object() {
1299 return Ok(Err("the credential is not a JSON object".into()));
1300 }
1301 check_replay_window(input.max_replay_window_seconds)?;
1302 let cred = &input.credential;
1303 let root_dids: Vec<String> = input
1304 .trusted_roots
1305 .as_ref()
1306 .map(|r| r.dids.clone())
1307 .unwrap_or_default();
1308 if let Some(problem) = structure_problem(cred, now, skew, input.expected_resource.as_deref()) {
1309 return Ok(Err(problem));
1310 }
1311 let issuer = issuer_did(cred).unwrap_or_default().to_string();
1312 if let Some(allowed) = &input.allowed_issuers {
1313 if !allowed.contains(&issuer) {
1314 return Ok(Err("the issuer is not one of the trusted keys".into()));
1315 }
1316 }
1317 let proofs = match read_proofs(cred, &issuer, now, skew) {
1318 Ok(p) => p,
1319 Err(problem) => return Ok(Err(problem.into())),
1320 };
1321 let carried = proofs.suites();
1324 if input.require_suites.iter().any(|s| !carried.contains(s)) {
1325 return Ok(Err(hybrid::REASON_REQUIRED_SUITE_MISSING.into()));
1326 }
1327 let chain = cred["credentialSubject"]
1328 .get("delegationChain")
1329 .and_then(Value::as_array)
1330 .filter(|c| !c.is_empty());
1331 let names_parent = input.grant_chain_checked_apart
1336 && cred["credentialSubject"]
1337 .as_object()
1338 .is_some_and(|s| s.contains_key(grant_chain::PARENT_GRANT_DIGEST));
1339 if chain.is_none()
1340 && !names_parent
1341 && input.chain_required_outside_roots
1342 && !root_dids.is_empty()
1343 && !root_dids.contains(&issuer)
1344 {
1345 return Ok(Err(REASON_CHAIN_REQUIRED.into()));
1346 }
1347 if let Some(chain) = chain {
1348 let as_value = Value::Array(chain.clone());
1349 match crate::attenuation::chain_budget_exceeded(&as_value, input.max_depth) {
1350 Ok(None) => {}
1351 Ok(Some(_)) => return Ok(Err(REASON_BUDGET.into())),
1352 Err(_) => return Ok(Err(grant_chain::REASON_MALFORMED.into())),
1353 }
1354 if root_dids.is_empty() {
1355 return Ok(Err(untrusted_root_reason(chain_root(chain), false)));
1356 }
1357 if let Some(early) = chain_prefilter(cred, chain, &root_dids) {
1358 if early == "untrusted_principal" {
1359 return Ok(Err(untrusted_root_reason(chain_root(chain), true)));
1360 }
1361 return Ok(Err(early.into()));
1362 }
1363 }
1364 Ok(Ok((proofs, chain, root_dids)))
1365}
1366
1367pub fn decide(input: &DecisionInput) -> Result<Decision> {
1376 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); input);
1377 let input = &at_microseconds(input)?;
1378 let (proofs, chain, root_dids) = match precheck(input)? {
1379 Ok(pre) => pre,
1380 Err(reason) => return Ok(Decision::refuse(reason)),
1381 };
1382 let cred = &input.credential;
1383 let issuer = issuer_did(cred).unwrap_or_default().to_string();
1384
1385 let source = KeySource {
1386 keys: effective_keys(input),
1387 mldsa44: &input.mldsa44_keys,
1388 slhdsa128: &input.slhdsa128_keys,
1389 documents: &input.documents,
1390 };
1391
1392 let mut grants: Vec<&Value> = Vec::new();
1396 if let Some(chain) = chain {
1397 let grant_keys: BTreeMap<String, Vec<u8>> = source
1398 .keys
1399 .iter()
1400 .map(|(did, entry)| {
1401 let raw = match entry {
1402 KeyEntry::Ed25519(k) => k.clone(),
1403 KeyEntry::Unusable => Vec::new(),
1405 };
1406 (did.clone(), raw)
1407 })
1408 .collect();
1409 let documents: BTreeMap<String, Value> = input
1410 .documents
1411 .iter()
1412 .filter(|(did, _)| has_did_document(did))
1413 .map(|(d, v)| (d.clone(), v.clone()))
1414 .collect();
1415 let opts = ChainOptions {
1416 trusted_roots: Some(&root_dids),
1417 grant_keys: Some(&grant_keys),
1418 mldsa_keys: Some(&input.mldsa44_keys),
1419 slhdsa_keys: Some(&input.slhdsa128_keys),
1420 grant_documents: Some(&documents),
1421 require_pq: input.require_post_quantum,
1422 require_suites: &input.require_suites,
1423 max_depth: input.max_depth,
1424 ..Default::default()
1425 };
1426 if let Some(reason) = crate::delegation::verify_delegation_chain_with(
1427 cred,
1428 &input.now,
1429 input.clock_skew_seconds,
1430 &opts,
1431 ) {
1432 if reason == "untrusted_principal" {
1433 return Ok(Decision::refuse(untrusted_root_reason(
1434 chain_root(chain),
1435 true,
1436 )));
1437 }
1438 return Ok(Decision::refuse(reason));
1439 }
1440 grants = chain.iter().map(|l| &l["parentCredential"]).collect();
1441 }
1442
1443 let explicit = input.public_key.is_some();
1445 let mut keys = match &input.public_key {
1446 Some(KeyEntry::Unusable) => {
1447 return Ok(Decision::refuse(
1448 "the public key given is not a usable Ed25519 key",
1449 ))
1450 }
1451 Some(KeyEntry::Ed25519(k)) => {
1452 let Some(pinned) = strict_ed25519(k) else {
1453 return Ok(Decision::refuse(
1454 "the public key given is not a usable Ed25519 key",
1455 ));
1456 };
1457 if issuer.starts_with("did:key:") && did_key_key(&issuer).as_ref() != Some(&pinned) {
1458 return Ok(Decision::refuse(
1459 "the public key given is not the did:key issuer's key",
1460 ));
1461 }
1462 SignerKeys {
1466 ed25519: Some(pinned),
1467 mldsa44: input
1468 .mldsa44_keys
1469 .get(&issuer)
1470 .filter(|k| !k.is_empty())
1471 .cloned(),
1472 slhdsa128: input
1473 .slhdsa128_keys
1474 .get(&issuer)
1475 .filter(|k| !k.is_empty())
1476 .cloned(),
1477 ..Default::default()
1478 }
1479 }
1480 None => {
1481 let (ml_vm, slh_vm) = if proofs.kind != "single" {
1482 (proofs.ml_vm(), proofs.slh_vm())
1483 } else {
1484 (None, None)
1485 };
1486 let found = source.keys(
1487 &issuer,
1488 proofs.ed_vm().as_deref(),
1489 ml_vm.as_deref(),
1490 slh_vm.as_deref(),
1491 );
1492 if found.ed25519.is_none() {
1493 return Ok(Decision::refuse(REASON_NO_KEY));
1494 }
1495 found
1496 }
1497 };
1498 if let Some(given) = &input.mldsa44_public_key {
1499 match given {
1500 Some(k) if k.len() == pq::MLDSA44_PUBLIC_LEN => keys.mldsa44 = Some(k.clone()),
1501 _ => {
1502 return Ok(Decision::refuse(
1503 "the ML-DSA-44 public key given is not a 1312-byte key",
1504 ))
1505 }
1506 }
1507 }
1508 if let Some(given) = &input.slhdsa128_public_key {
1509 match given {
1510 Some(k) if k.len() == crate::slh::SLHDSA128_PUBLIC_LEN => {
1511 keys.slhdsa128 = Some(k.clone())
1512 }
1513 _ => {
1514 return Ok(Decision::refuse(
1515 "the SLH-DSA public key given is not a 32-byte key",
1516 ))
1517 }
1518 }
1519 }
1520 let resolved_ml = input.mldsa44_keys.contains_key(&issuer);
1525 let resolved_slh = input.slhdsa128_keys.contains_key(&issuer);
1526 let required = hybrid::Required {
1527 post_quantum: input.require_post_quantum,
1528 mldsa44: input.mldsa44_public_key.is_some() || keys.publishes_mldsa44 || resolved_ml,
1529 slhdsa128: input.slhdsa128_public_key.is_some() || keys.publishes_slhdsa128 || resolved_slh,
1530 };
1531 match check_proofs(cred, &proofs, &keys, required, explicit) {
1532 ProofCheck::Ok => {}
1533 ProofCheck::Refused(reason) => return Ok(Decision::refuse(reason)),
1534 ProofCheck::MissingMldsa44Key => {
1535 return Err(CoreError::Json(format!(
1536 "{MISSING_MLDSA44_KEY}: this credential carries an ML-DSA-44 post-quantum \
1537 proof; pass the ML-DSA-44 public key or publish it in the issuer's DID \
1538 document. A did:key identifier encodes only the Ed25519 key."
1539 )))
1540 }
1541 }
1542
1543 if input.check_status {
1546 if let Some(reason) =
1547 status_reason(cred, Some((&proofs, &keys)), &source, input, required.any())?
1548 {
1549 return Ok(Decision::refuse(reason));
1550 }
1551 for grant in &grants {
1552 let grant_issuer = issuer_did(grant).unwrap_or_default();
1555 let grant_pq = input.mldsa44_keys.contains_key(grant_issuer)
1556 || input.slhdsa128_keys.contains_key(grant_issuer);
1557 if let Some(reason) = status_reason(grant, None, &source, input, grant_pq)? {
1558 return Ok(Decision::refuse(format!("delegation_{reason}")));
1559 }
1560 }
1561 }
1562
1563 Ok(Decision {
1564 valid: true,
1565 reason: None,
1566 passport: Some(passport(cred, &grants)),
1567 replay: Some(identity_from(
1568 cred,
1569 &proofs,
1570 input.clock_skew_seconds,
1571 input.max_replay_window_seconds,
1572 )?),
1573 issuer_key: keys.ed25519.clone(),
1574 })
1575}
1576
1577pub const MAX_FETCH_DIDS: usize = 32;
1580pub const MAX_FETCH_STATUS_LISTS: usize = 32;
1583
1584#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1586pub enum FetchPhase {
1587 Documents,
1590 StatusLists,
1593}
1594
1595#[derive(Debug, Clone, Default, PartialEq, Eq)]
1597pub struct FetchPlan {
1598 pub refusal: Option<String>,
1603 pub dids: Vec<String>,
1605 pub status_lists: Vec<String>,
1607 pub truncated: bool,
1611}
1612
1613fn push_unique(
1614 list: &mut Vec<String>,
1615 seen: &mut alloc::collections::BTreeSet<String>,
1616 item: &str,
1617 cap: usize,
1618 truncated: &mut bool,
1619) {
1620 if item.is_empty() || seen.contains(item) {
1621 return;
1622 }
1623 if list.len() >= cap {
1624 *truncated = true;
1625 return;
1626 }
1627 seen.insert(item.to_string());
1628 list.push(item.to_string());
1629}
1630
1631fn status_urls(c: &Value) -> Vec<&str> {
1632 let entries: Vec<&Value> = match c.get("credentialStatus") {
1633 Some(e @ Value::Object(_)) => vec![e],
1634 Some(Value::Array(a)) => a.iter().take(status_list::MAX_STATUS_ENTRIES).collect(),
1635 _ => Vec::new(),
1636 };
1637 entries
1638 .iter()
1639 .filter_map(|e| e.get("statusListCredential").and_then(Value::as_str))
1640 .collect()
1641}
1642
1643pub fn fetch_plan(input: &DecisionInput, phase: FetchPhase) -> Result<FetchPlan> {
1666 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); input);
1667 let input = &at_microseconds(input)?;
1668 let mut plan = FetchPlan::default();
1669 match phase {
1670 FetchPhase::Documents => {
1671 let (_, chain, _) = match precheck(input)? {
1672 Ok(pre) => pre,
1673 Err(reason) => {
1674 plan.refusal = Some(reason);
1675 return Ok(plan);
1676 }
1677 };
1678 let known = effective_keys(input);
1679 let mut seen = alloc::collections::BTreeSet::new();
1680 let mut wanted: Vec<&str> = Vec::new();
1681 if input.public_key.is_none() {
1682 wanted.extend(issuer_did(&input.credential));
1683 }
1684 for link in chain.into_iter().flatten() {
1685 wanted.extend(link.get("issuer").and_then(Value::as_str));
1686 }
1687 for did in wanted {
1688 if has_did_document(did) && !known.contains_key(did) {
1689 push_unique(
1690 &mut plan.dids,
1691 &mut seen,
1692 did,
1693 MAX_FETCH_DIDS,
1694 &mut plan.truncated,
1695 );
1696 }
1697 }
1698 }
1699 FetchPhase::StatusLists => {
1700 let mut without_status = input.clone();
1701 without_status.check_status = false;
1702 let decision = decide(&without_status)?;
1705 if !decision.valid {
1706 plan.refusal = decision.reason;
1707 return Ok(plan);
1708 }
1709 if !input.check_status {
1710 return Ok(plan);
1711 }
1712 let mut seen = alloc::collections::BTreeSet::new();
1713 let cred = &input.credential;
1714 let mut urls = status_urls(cred);
1715 if let Some(chain) = cred["credentialSubject"]
1716 .get("delegationChain")
1717 .and_then(Value::as_array)
1718 {
1719 for link in chain {
1720 urls.extend(status_urls(&link["parentCredential"]));
1721 }
1722 }
1723 for url in urls {
1724 push_unique(
1725 &mut plan.status_lists,
1726 &mut seen,
1727 url,
1728 MAX_FETCH_STATUS_LISTS,
1729 &mut plan.truncated,
1730 );
1731 }
1732 }
1733 }
1734 Ok(plan)
1735}
1736
1737const REQUEST_MEMBERS: [&str; 27] = [
1742 "credential",
1743 "now",
1744 "clockSkewSeconds",
1745 "publicKey",
1746 "mldsa44PublicKey",
1747 "slhdsa128PublicKey",
1748 "trustedKeys",
1749 "resolvedKeys",
1750 "mldsa44Keys",
1751 "slhdsa128Keys",
1752 "documents",
1753 "didLogs",
1754 "didLogsB64",
1755 "seenVersionIds",
1756 "limits",
1757 "logNow",
1758 "trustedRoots",
1759 "requirePostQuantum",
1760 "requireSuites",
1761 "expectedResource",
1762 "checkStatus",
1763 "statusLists",
1764 "maxDepth",
1765 "maxReplayWindowSeconds",
1766 "requireTrustedIssuer",
1767 "chainRequiredOutsideRoots",
1768 "grantChainCheckedApart",
1769];
1770
1771fn bad(msg: impl Into<String>) -> CoreError {
1772 CoreError::Json(msg.into())
1773}
1774
1775fn present<'a>(obj: &'a Map<String, Value>, name: &str) -> Option<&'a Value> {
1776 obj.get(name).filter(|v| !v.is_null())
1777}
1778
1779const TIGHTENING_MEMBERS: [&str; 15] = [
1784 "trustedRoots",
1785 "trustedKeys",
1786 "publicKey",
1787 "mldsa44Keys",
1788 "slhdsa128Keys",
1789 "requirePostQuantum",
1790 "requireSuites",
1791 "requireTrustedIssuer",
1792 "expectedResource",
1793 "checkStatus",
1794 "chainRequiredOutsideRoots",
1795 "grantChainCheckedApart",
1796 "mldsa44PublicKey",
1797 "slhdsa128PublicKey",
1798 "maxDepth",
1799];
1800
1801fn refuse_null_tightening(obj: &Map<String, Value>) -> Result<()> {
1802 for name in TIGHTENING_MEMBERS {
1803 if matches!(obj.get(name), Some(Value::Null)) {
1804 return Err(bad(format!(
1805 "{name} must not be null: leave it out for the default"
1806 )));
1807 }
1808 }
1809 Ok(())
1810}
1811
1812fn credential_from_text(text: &str) -> Value {
1816 crate::authority_state::parse_json_no_duplicates(text).unwrap_or(Value::Null)
1817}
1818
1819fn bool_member(obj: &Map<String, Value>, name: &str, default: bool) -> Result<bool> {
1820 match present(obj, name) {
1821 None => Ok(default),
1822 Some(Value::Bool(b)) => Ok(*b),
1823 Some(_) => Err(bad(format!("{name} must be true or false"))),
1824 }
1825}
1826
1827fn object_member<'a>(
1828 obj: &'a Map<String, Value>,
1829 name: &str,
1830) -> Result<Option<&'a Map<String, Value>>> {
1831 match present(obj, name) {
1832 None => Ok(None),
1833 Some(Value::Object(m)) => Ok(Some(m)),
1834 Some(_) => Err(bad(format!("{name} must be a JSON object"))),
1835 }
1836}
1837
1838fn string_list(v: &Value, name: &str) -> Result<Vec<String>> {
1839 v.as_array()
1840 .and_then(|a| {
1841 a.iter()
1842 .map(|x| x.as_str().map(String::from))
1843 .collect::<Option<Vec<_>>>()
1844 })
1845 .ok_or_else(|| bad(format!("{name} must be a list of strings")))
1846}
1847
1848pub fn trusted_roots_from_json(v: &Value) -> Result<Option<TrustedRoots>> {
1852 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); v);
1853 let norm = crate::did_web::normalize_root;
1854 match v {
1855 Value::Null => Ok(None),
1856 Value::String(s) => Ok(Some(TrustedRoots {
1857 dids: vec![norm(s)?],
1858 keys: BTreeMap::new(),
1859 })),
1860 Value::Array(_) => Ok(Some(TrustedRoots {
1861 dids: string_list(v, "trustedRoots")?
1862 .iter()
1863 .map(|s| norm(s))
1864 .collect::<Result<_>>()?,
1865 keys: BTreeMap::new(),
1866 })),
1867 Value::Object(m) => {
1868 let mut roots = TrustedRoots::default();
1869 for (did, key) in m {
1870 let did = norm(did)?;
1871 if !roots.dids.contains(&did) {
1872 roots.dids.push(did.clone());
1873 }
1874 roots.keys.insert(did, key_entry_from_json(key));
1875 }
1876 Ok(Some(roots))
1877 }
1878 _ => Err(bad(
1879 "trustedRoots must be a {did: key} map or a list of DIDs",
1880 )),
1881 }
1882}
1883
1884fn trusted_key_map(obj: &Map<String, Value>) -> Result<BTreeMap<String, KeyEntry>> {
1890 let mut out = BTreeMap::new();
1891 for (did, v) in object_member(obj, "trustedKeys")?.into_iter().flatten() {
1892 let Ok(did) = crate::did_web::normalize_root(did) else {
1893 continue;
1894 };
1895 out.insert(did, key_entry_from_json(v));
1899 }
1900 Ok(out)
1901}
1902
1903fn key_map(obj: &Map<String, Value>, name: &str) -> Result<BTreeMap<String, KeyEntry>> {
1904 Ok(object_member(obj, name)?
1905 .map(|m| {
1906 m.iter()
1907 .filter(|(_, v)| !v.is_null())
1909 .map(|(did, v)| (did.clone(), key_entry_from_json(v)))
1910 .collect()
1911 })
1912 .unwrap_or_default())
1913}
1914
1915pub fn decide_json_with_clock(request: &Value, clock: crate::did_webvh::LogClock) -> Result<Value> {
1952 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); request);
1953 let obj = request
1954 .as_object()
1955 .ok_or_else(|| bad("the request must be a JSON object"))?;
1956 let (input, logs) = read_request(obj, clock, &[])?;
1957 let decision = decide(&input)?;
1958 let (versions, errors) = match &logs {
1959 Some(set) => crate::did_webvh::grant_log_json(&set.outcomes()),
1960 None => (json!({}), json!({})),
1961 };
1962 Ok(json!({
1963 "valid": decision.valid,
1964 "reason": decision.reason,
1965 "passport": decision.passport,
1966 "replay": decision.replay.map(|r| json!({
1967 "key": r.key,
1968 "expiresAt": r.expires_at,
1969 "singleUse": r.single_use,
1970 })),
1971 "issuerKey": decision
1972 .issuer_key
1973 .as_deref()
1974 .map(multikey::encode_ed25519_public)
1975 .transpose()?,
1976 "didLogVersions": versions,
1977 "didLogErrors": errors,
1978 }))
1979}
1980
1981fn read_request(
1984 obj: &Map<String, Value>,
1985 clock: crate::did_webvh::LogClock,
1986 extra: &[&str],
1987) -> Result<(DecisionInput, Option<crate::did_webvh::LogSet>)> {
1988 use crate::did_webvh::{base64_decode, is_did_webvh, LogClock, LogSet};
1989
1990 if let Some(name) = obj
1991 .keys()
1992 .find(|k| !REQUEST_MEMBERS.contains(&k.as_str()) && !extra.contains(&k.as_str()))
1993 {
1994 return Err(bad(format!(
1995 "the request holds an unknown member {:?}",
1996 name.chars().take(40).collect::<String>()
1997 )));
1998 }
1999 refuse_null_tightening(obj)?;
2000 let credential = match obj.get("credential") {
2001 Some(Value::String(text)) => credential_from_text(text),
2002 Some(v) => v.clone(),
2003 None => return Err(bad("credential is required")),
2004 };
2005 let now = obj
2006 .get("now")
2007 .and_then(Value::as_str)
2008 .ok_or_else(|| bad("now must be a protocol time"))?;
2009 let mut input = DecisionInput::new(credential, now);
2010 match obj.get("clockSkewSeconds") {
2011 None => {}
2012 Some(Value::Null) => return Err(bad("clockSkewSeconds must be a whole number of seconds")),
2014 Some(v) => input.clock_skew_seconds = crate::time::clock_skew_from_json(v)?,
2015 }
2016 input.public_key = present(obj, "publicKey").map(key_entry_from_json);
2017 input.mldsa44_public_key = present(obj, "mldsa44PublicKey").map(mldsa44_key_from_json);
2018 input.slhdsa128_public_key = present(obj, "slhdsa128PublicKey").map(slhdsa128_key_from_json);
2019 input.trusted_keys = trusted_key_map(obj)?;
2020 input.resolved_keys = key_map(obj, "resolvedKeys")?;
2021 if let Some(m) = object_member(obj, "mldsa44Keys")? {
2022 for (did, v) in m {
2023 if !v.is_null() {
2028 let k = mldsa44_key_from_json(v).unwrap_or_default();
2029 input.mldsa44_keys.insert(did.clone(), k);
2030 }
2031 }
2032 }
2033 if let Some(m) = object_member(obj, "slhdsa128Keys")? {
2034 for (did, v) in m {
2035 if !v.is_null() {
2038 let k = slhdsa128_key_from_json(v).unwrap_or_default();
2039 input.slhdsa128_keys.insert(did.clone(), k);
2040 }
2041 }
2042 }
2043 if let Some(m) = object_member(obj, "documents")? {
2044 for (did, doc) in m {
2045 if !has_did_document(did) {
2046 return Err(bad(
2047 "documents holds a DID that is not did:web or did:webvh",
2048 ));
2049 }
2050 if !doc.is_null() {
2051 input.documents.insert(did.clone(), doc.clone());
2052 }
2053 }
2054 }
2055 let clock = match present(obj, "logNow") {
2058 None => clock,
2059 Some(v) => LogClock::At(parse_protocol_time_ns(
2060 v.as_str()
2061 .ok_or_else(|| bad("logNow must be a protocol time"))?,
2062 )?),
2063 };
2064 let mut logs: Option<LogSet> = None;
2065 let texts = object_member(obj, "didLogs")?;
2066 let b64s = object_member(obj, "didLogsB64")?;
2067 if texts.is_some() || b64s.is_some() {
2068 let mut set = LogSet::new(clock)?;
2069 if let Some(limits) = present(obj, "limits") {
2070 set = set.with_limits(crate::did_webvh::Limits::from_json(limits)?);
2071 }
2072 let mut given: Vec<(String, Vec<u8>)> = Vec::new();
2073 for (did, v) in texts.into_iter().flatten() {
2074 let t = v
2075 .as_str()
2076 .ok_or_else(|| bad("didLogs must map DIDs to log text"))?;
2077 given.push((did.clone(), t.as_bytes().to_vec()));
2078 }
2079 for (did, v) in b64s.into_iter().flatten() {
2080 let t = v
2081 .as_str()
2082 .ok_or_else(|| bad("didLogsB64 must map DIDs to base64 logs"))?;
2083 given.push((did.clone(), base64_decode(t, "a didLogsB64 log")?));
2084 }
2085 for (did, log) in given {
2086 if !is_did_webvh(&did) {
2087 return Err(bad("didLogs holds a DID that is not a did:webvh DID"));
2088 }
2089 if set.contains(&did) || input.documents.contains_key(&did) {
2090 return Err(bad(
2091 "give each DID's log once, in didLogs, didLogsB64 or documents",
2092 ));
2093 }
2094 set = set.with_log(&did, log);
2095 }
2096 if let Some(m) = object_member(obj, "seenVersionIds")? {
2097 for (did, v) in m {
2098 let seen = v
2099 .as_str()
2100 .ok_or_else(|| bad("seenVersionIds must map DIDs to versionIds"))?;
2101 set = set.with_seen_version_id(did, seen)?;
2102 }
2103 }
2104 logs = Some(set);
2105 }
2106 if let Some(v) = present(obj, "trustedRoots") {
2107 input.trusted_roots = trusted_roots_from_json(v)?;
2108 }
2109 input.require_post_quantum = bool_member(obj, "requirePostQuantum", false)?;
2110 if let Some(v) = present(obj, "requireSuites") {
2111 input.require_suites = hybrid::required_suites_from_json(v)?;
2112 }
2113 input.expected_resource = match present(obj, "expectedResource") {
2114 None => None,
2115 Some(Value::String(s)) => Some(s.clone()),
2116 Some(_) => return Err(bad("expectedResource must be a string")),
2117 };
2118 input.check_status = bool_member(obj, "checkStatus", true)?;
2119 if let Some(m) = object_member(obj, "statusLists")? {
2120 input.status_lists = m.clone();
2121 }
2122 input.max_depth = match present(obj, "maxDepth") {
2123 None => None,
2124 Some(v) => Some(
2125 v.as_u64()
2126 .and_then(|d| usize::try_from(d).ok())
2127 .ok_or_else(|| bad("maxDepth must be a non-negative whole number"))?,
2128 ),
2129 };
2130 if let Some(v) = present(obj, "maxReplayWindowSeconds") {
2131 input.max_replay_window_seconds = match v {
2132 Value::Number(n) => n.as_f64().unwrap_or(f64::NAN),
2133 _ => return Err(bad("max_replay_window must be a number of seconds")),
2134 };
2135 }
2136 if bool_member(obj, "requireTrustedIssuer", false)? {
2140 input.allowed_issuers = Some(input.trusted_keys.keys().cloned().collect());
2141 }
2142 if present(obj, "trustedRoots").is_none() && !input.trusted_keys.is_empty() {
2143 input.trusted_roots = Some(TrustedRoots {
2144 dids: input.trusted_keys.keys().cloned().collect(),
2145 keys: BTreeMap::new(),
2146 });
2147 }
2148 input.chain_required_outside_roots =
2151 input.trusted_roots.is_some() && bool_member(obj, "chainRequiredOutsideRoots", true)?;
2152 input.grant_chain_checked_apart = bool_member(obj, "grantChainCheckedApart", false)?;
2153
2154 if let Some(set) = &logs {
2155 for did in obj
2156 .get("didLogs")
2157 .and_then(Value::as_object)
2158 .into_iter()
2159 .chain(obj.get("didLogsB64").and_then(Value::as_object))
2160 .flat_map(|m| m.keys())
2161 {
2162 if let Some(Ok(resolution)) = set.resolve(did) {
2163 input.documents.insert(did.clone(), resolution.document);
2164 }
2165 }
2166 }
2167
2168 Ok((input, logs))
2169}
2170
2171pub fn decide_json(request: &Value) -> Result<Value> {
2174 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); request);
2175 decide_json_with_clock(request, crate::did_webvh::LogClock::System)
2176}
2177
2178pub fn fetch_plan_json_with_clock(
2183 request: &Value,
2184 clock: crate::did_webvh::LogClock,
2185) -> Result<Value> {
2186 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); request);
2187 let obj = request
2188 .as_object()
2189 .ok_or_else(|| bad("the request must be a JSON object"))?;
2190 let phase = match present(obj, "phase").map(|v| v.as_str()) {
2191 None | Some(Some("documents")) => FetchPhase::Documents,
2192 Some(Some("statusLists")) => FetchPhase::StatusLists,
2193 _ => return Err(bad("phase must be \"documents\" or \"statusLists\"")),
2194 };
2195 let (input, _logs) = read_request(obj, clock, &["phase"])?;
2196 let plan = fetch_plan(&input, phase)?;
2197 Ok(json!({
2198 "refusal": plan.refusal,
2199 "dids": plan.dids,
2200 "statusLists": plan.status_lists,
2201 "truncated": plan.truncated,
2202 }))
2203}
2204
2205pub fn fetch_plan_json(request: &Value) -> Result<Value> {
2208 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); request);
2209 fetch_plan_json_with_clock(request, crate::did_webvh::LogClock::System)
2210}
2211
2212pub fn replay_identity_json(request: &Value) -> Result<Value> {
2216 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); request);
2217 let obj = request
2218 .as_object()
2219 .ok_or_else(|| bad("the request must be a JSON object"))?;
2220 let credential = obj
2221 .get("credential")
2222 .filter(|c| c.is_object())
2223 .ok_or_else(|| bad("credential must be a JSON object"))?;
2224 let now = obj
2225 .get("now")
2226 .and_then(Value::as_str)
2227 .ok_or_else(|| bad("now must be a protocol time"))?;
2228 let skew = match present(obj, "clockSkewSeconds") {
2229 None => DEFAULT_CLOCK_SKEW_SECONDS,
2230 Some(v) => crate::time::clock_skew_from_json(v)?,
2231 };
2232 let window = match present(obj, "maxReplayWindowSeconds") {
2233 None => DEFAULT_MAX_REPLAY_WINDOW_SECONDS,
2234 Some(v) => v
2235 .as_f64()
2236 .ok_or_else(|| bad("max_replay_window must be a number of seconds"))?,
2237 };
2238 let r = replay_identity(credential, now, skew, window)?;
2239 Ok(json!({"key": r.key, "expiresAt": r.expires_at, "singleUse": r.single_use}))
2240}
2241
2242pub fn structure_only_json(request: &Value) -> Result<Value> {
2248 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); request);
2249 let obj = request
2250 .as_object()
2251 .ok_or_else(|| bad("the request must be a JSON object"))?;
2252 let credential = match obj.get("credential") {
2253 Some(Value::String(text)) => credential_from_text(text),
2254 Some(v) => v.clone(),
2255 None => return Err(bad("credential is required")),
2256 };
2257 let now = obj
2258 .get("now")
2259 .and_then(Value::as_str)
2260 .ok_or_else(|| bad("now must be a protocol time"))?;
2261 let now = parse_protocol_time_ns(now)?.div_euclid(1000) * 1000;
2262 let skew = match obj.get("clockSkewSeconds") {
2263 None => DEFAULT_CLOCK_SKEW_SECONDS,
2264 Some(v) => crate::time::clock_skew_from_json(v)?,
2265 };
2266 let skew = check_clock_skew(skew)?;
2267 let expected = match present(obj, "expectedResource") {
2268 None => None,
2269 Some(Value::String(s)) => Some(s.as_str()),
2270 Some(_) => return Err(bad("expectedResource must be a string")),
2271 };
2272 if !credential.is_object() {
2273 return Ok(json!({"problem": "the credential is not a JSON object"}));
2274 }
2275 if let Some(problem) = structure_problem(&credential, now, skew, expected) {
2276 return Ok(json!({ "problem": problem }));
2277 }
2278 let issuer = issuer_did(&credential).unwrap_or_default().to_string();
2279 Ok(match read_proofs(&credential, &issuer, now, skew) {
2280 Ok(_) => json!({ "problem": null }),
2281 Err(problem) => json!({ "problem": problem }),
2282 })
2283}
2284
2285pub fn delegation_chain_json_with_clock(
2296 request: &Value,
2297 clock: crate::did_webvh::LogClock,
2298) -> Result<Value> {
2299 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); request);
2300 let obj = request
2301 .as_object()
2302 .ok_or_else(|| bad("the request must be a JSON object"))?;
2303 let (input, _logs) = read_request(obj, clock, &["linksOnly", "throughLink"])?;
2304 let input = at_microseconds(&input)?;
2305 let cred = &input.credential;
2306 if !cred.is_object() {
2307 return Ok(json!({ "reason": grant_chain::REASON_MALFORMED }));
2308 }
2309 let links_only = bool_member(obj, "linksOnly", false)?;
2310 let through_link = match present(obj, "throughLink") {
2311 None => None,
2312 Some(v) => Some(
2313 v.as_u64()
2314 .and_then(|n| usize::try_from(n).ok())
2315 .ok_or_else(|| bad("throughLink must be a non-negative whole number"))?,
2316 ),
2317 };
2318 let grant_keys: BTreeMap<String, Vec<u8>> = effective_keys(&input)
2319 .into_iter()
2320 .map(|(did, entry)| {
2321 let raw = match entry {
2322 KeyEntry::Ed25519(k) => k,
2323 KeyEntry::Unusable => Vec::new(),
2325 };
2326 (did, raw)
2327 })
2328 .collect();
2329 let documents: BTreeMap<String, Value> = input
2330 .documents
2331 .iter()
2332 .filter(|(did, _)| has_did_document(did))
2333 .map(|(d, v)| (d.clone(), v.clone()))
2334 .collect();
2335 let roots: Vec<String> = input
2336 .trusted_roots
2337 .as_ref()
2338 .map(|r| r.dids.clone())
2339 .unwrap_or_default();
2340 let opts = ChainOptions {
2341 trusted_roots: Some(&roots),
2343 grant_keys: Some(&grant_keys),
2344 mldsa_keys: Some(&input.mldsa44_keys),
2345 slhdsa_keys: Some(&input.slhdsa128_keys),
2346 grant_documents: Some(&documents),
2347 require_pq: input.require_post_quantum,
2348 require_suites: &input.require_suites,
2349 max_depth: input.max_depth,
2350 through_link,
2351 ..Default::default()
2352 };
2353 let check = if links_only {
2356 crate::delegation::chain_links_problem
2357 } else {
2358 crate::delegation::verify_delegation_chain_with
2359 };
2360 let reason = check(cred, &input.now, input.clock_skew_seconds, &opts);
2361 Ok(json!({ "reason": reason }))
2362}
2363
2364pub fn normalize_root_json(request: &Value) -> Result<Value> {
2368 crate::nesting::deep_guard!(Err(crate::nesting::too_deep()); request);
2369 let root = request
2370 .get("root")
2371 .and_then(Value::as_str)
2372 .ok_or_else(|| bad("a trusted root is a DID or a domain name"))?;
2373 Ok(json!({ "did": crate::did_web::normalize_root(root)? }))
2374}
2375
2376crate::nesting::nested_fields!(DecisionInput; credential, documents, status_lists);
2378crate::nesting::nested_fields!(Proofs; eddsa, mldsa, slhdsa);
2379
2380#[cfg(test)]
2381mod tests {
2382 use super::*;
2383
2384 #[test]
2385 fn showable_dids() {
2386 assert!(showable_did("did:web:example.com"));
2387 assert!(showable_did("did:key:z6Mk"));
2388 assert!(!showable_did("did:Web:example.com"));
2389 assert!(!showable_did("did:web:"));
2390 assert!(!showable_did("did:web:a b"));
2391 assert!(!showable_did(&format!("did:web:{}", "a".repeat(201))));
2392 assert_eq!(
2393 untrusted_root_reason(Some("did:web:root.example"), true),
2394 "the chain's starting point is not trusted: run `vouch trust did:web:root.example` \
2395 (it is not one of the trusted roots)"
2396 );
2397 assert_eq!(
2398 untrusted_root_reason(Some("did:web:a b"), false),
2399 REASON_UNTRUSTED_START
2400 );
2401 }
2402
2403 #[test]
2404 fn group_order_matches_the_curve() {
2405 let mut sig = [0u8; 64];
2408 let base = ed25519_dalek::SigningKey::from_bytes(&[7u8; 32]).verifying_key();
2409 sig[..32].copy_from_slice(base.as_bytes());
2410 sig[32..].copy_from_slice(&GROUP_ORDER_LE);
2411 assert!(!strict_signature(&sig));
2412 sig[32] -= 1;
2413 assert!(strict_signature(&sig));
2414 }
2415
2416 #[test]
2417 fn bad_requests_are_errors() {
2418 let cred = json!({});
2419 let mut input = DecisionInput::new(cred, "2026-01-01T00:00:00Z");
2420 input.max_replay_window_seconds = 0.0;
2421 assert!(decide(&input).is_err());
2422 input.max_replay_window_seconds = 10.0;
2423 input.clock_skew_seconds = 121;
2424 assert!(decide(&input).is_err());
2425 let not_object = DecisionInput::new(json!([1]), "2026-01-01T00:00:00Z");
2426 assert_eq!(
2427 decide(¬_object).unwrap().reason.as_deref(),
2428 Some("the credential is not a JSON object")
2429 );
2430 }
2431
2432 #[test]
2433 fn jwk_x_padding_matches_the_reference() {
2434 let key = ed25519_dalek::SigningKey::from_bytes(&[7u8; 32]).verifying_key();
2437 let body = base64::Engine::encode(
2438 &base64::engine::general_purpose::URL_SAFE_NO_PAD,
2439 key.as_bytes(),
2440 );
2441 assert_eq!(body.len(), 43);
2442 let entry =
2443 |x: String| key_entry_from_json(&json!({"kty": "OKP", "crv": "Ed25519", "x": x}));
2444 for (pad, usable) in [(0, true), (1, true), (2, false), (3, false), (4, false)] {
2445 let got = entry(format!("{body}{}", "=".repeat(pad)));
2446 assert_eq!(
2447 matches!(got, KeyEntry::Ed25519(_)),
2448 usable,
2449 "{pad} padding signs"
2450 );
2451 }
2452 assert!(matches!(entry(format!("={body}")), KeyEntry::Unusable));
2453 assert!(matches!(
2454 entry(format!("{}={}", &body[..20], &body[20..])),
2455 KeyEntry::Unusable
2456 ));
2457 }
2458}