1#[allow(unused_imports)]
38use crate::prelude::*;
39
40use crate::collections::HashSet;
41use alloc::collections::BTreeMap;
42
43use serde_json::Value;
44
45use crate::attenuation::json_nesting_exceeds;
46use crate::data_integrity;
47use crate::error::{CoreError, Result};
48use crate::time;
49
50pub const MAX_NESTING: usize = 128;
52pub const MAX_CREDENTIAL_BYTES: usize = 1024 * 1024;
54pub const ASSERTION_METHOD: &str = "assertionMethod";
56
57#[derive(Debug, Clone, Copy, PartialEq, Eq)]
60pub enum Window {
61 Required,
63 FromRequired,
65 IfPresent,
67}
68
69#[derive(Clone, Copy)]
71pub enum Keys<'a> {
72 Embedded,
75 Pinned(&'a str),
79 Bare(&'a [u8]),
82 One(&'a str, &'a [u8]),
84 Map(&'a BTreeMap<String, Vec<u8>>),
86 Resolver(&'a dyn Fn(&str) -> Option<Vec<u8>>),
88}
89
90impl<'a> Keys<'a> {
91 pub fn map_of<I, S, K>(entries: I) -> BTreeMap<String, Vec<u8>>
93 where
94 I: IntoIterator<Item = (S, K)>,
95 S: Into<String>,
96 K: AsRef<[u8]>,
97 {
98 entries
99 .into_iter()
100 .map(|(d, k)| (d.into(), k.as_ref().to_vec()))
101 .collect()
102 }
103}
104
105#[derive(Debug, Clone)]
108pub struct Verified {
109 pub issuer: String,
110 pub subject: Value,
111}
112
113#[derive(Debug, Clone, PartialEq)]
120pub struct VerifiedPair {
121 issuer: String,
122 subject: Value,
123 _sealed: (),
124}
125
126impl VerifiedPair {
127 pub fn issuer(&self) -> &str {
129 &self.issuer
130 }
131 pub fn subject(&self) -> &Value {
133 &self.subject
134 }
135 #[cfg(test)]
136 pub(crate) fn for_test(issuer: &str, subject: Value) -> Self {
137 Self {
138 issuer: issuer.to_string(),
139 subject,
140 _sealed: (),
141 }
142 }
143}
144
145pub fn require_now(now_iso: &str) -> Result<i128> {
147 if now_iso.is_empty() {
148 return Err(CoreError::Json(
149 "now is required: pass the verifier's clock as a protocol time".into(),
150 ));
151 }
152 time::parse_protocol_time_ns(now_iso).map_err(|_| {
153 CoreError::Json("now must be a protocol time such as 2026-01-01T00:00:00Z".into())
154 })
155}
156
157pub fn issuer_id(value: Option<&Value>) -> Option<&str> {
160 match value {
161 Some(Value::String(s)) if !s.is_empty() => Some(s),
162 Some(Value::Object(o)) => match o.get("id") {
163 Some(Value::String(s)) if !s.is_empty() => Some(s),
164 _ => None,
165 },
166 _ => None,
167 }
168}
169
170pub const MAX_SAFE_INT: i64 = (1_i64 << 53) - 1;
174
175pub fn is_strict_int(v: &Value) -> bool {
178 strict_int(Some(v)).is_some()
179}
180
181pub fn strict_int(v: Option<&Value>) -> Option<i64> {
183 v.and_then(|x| {
184 if x.is_i64() || x.is_u64() {
185 x.as_i64()
186 } else {
187 None
188 }
189 })
190 .filter(|n| (-MAX_SAFE_INT..=MAX_SAFE_INT).contains(n))
191}
192
193pub fn finite_number(v: Option<&Value>) -> Option<f64> {
195 v.and_then(|x| if x.is_number() { x.as_f64() } else { None })
196 .filter(|n| n.is_finite())
197}
198
199pub fn time_ns(v: Option<&Value>) -> Option<i128> {
201 v.and_then(|x| x.as_str())
202 .and_then(|s| time::parse_protocol_time_ns(s).ok())
203}
204
205pub fn approx_size(value: &Value, limit: usize) -> usize {
208 let mut total: usize = 0;
209 let mut stack: Vec<&Value> = vec![value];
210 while let Some(node) = stack.pop() {
211 match node {
212 Value::Object(o) => {
213 total += 2 + o.len();
214 for (k, v) in o {
215 total += k.chars().count() + 3;
216 stack.push(v);
217 }
218 }
219 Value::Array(a) => {
220 total += 2 + a.len();
221 stack.extend(a.iter());
222 }
223 Value::String(s) => total += s.chars().count() + 2,
224 _ => total += 24,
225 }
226 if total > limit {
227 return total;
228 }
229 }
230 total
231}
232
233pub fn input_too_large(value: &Value, max_bytes: usize) -> Option<String> {
235 crate::nesting::deep_guard!(Some(crate::nesting::TOO_DEEP.into()); value);
236 if json_nesting_exceeds(value, MAX_NESTING) {
237 return Some(format!("input nests more than {MAX_NESTING} levels"));
238 }
239 if approx_size(value, max_bytes) > max_bytes {
240 return Some(format!("input larger than {max_bytes} bytes"));
241 }
242 None
243}
244
245pub fn proof_unbound_reason(proof: &Value, issuer: &str) -> Option<&'static str> {
247 crate::nesting::deep_guard!(Some(crate::nesting::TOO_DEEP); proof);
248 let p = match proof.as_object() {
249 Some(p) => p,
250 None => return Some("proof is not an object"),
251 };
252 if p.get("proofPurpose").and_then(|v| v.as_str()) != Some(ASSERTION_METHOD) {
253 return Some("proofPurpose is not assertionMethod");
254 }
255 if crate::verification_method::proof_method_names(p, issuer) {
256 None
257 } else {
258 Some("proof verificationMethod is not a key of the issuer")
259 }
260}
261
262pub fn no_key_source(keys: &Keys<'_>) -> bool {
265 match keys {
266 Keys::Embedded | Keys::Pinned(_) => true,
267 Keys::Map(m) => m.is_empty(),
268 _ => false,
269 }
270}
271
272pub fn pin_if_keyless<'a>(keys: Keys<'a>, did: Option<&'a str>) -> Keys<'a> {
277 match did {
278 Some(d) if !d.is_empty() && no_key_source(&keys) => Keys::Pinned(d),
279 _ => keys,
280 }
281}
282
283pub fn resolve_issuer_key(issuer: &str, keys: Keys<'_>) -> core::result::Result<Vec<u8>, String> {
287 resolve_issuer_key_trusted(issuer, keys, None)
288}
289
290pub fn resolve_issuer_key_trusted(
296 issuer: &str,
297 keys: Keys<'_>,
298 trusted: Option<&HashSet<String>>,
299) -> core::result::Result<Vec<u8>, String> {
300 let is_did_key = issuer.starts_with("did:key:");
301 let embedded = if is_did_key {
302 match crate::keys::did_key_to_ed25519(issuer) {
303 Ok(k) if k.len() == 32 => Some(k),
304 _ => return Err("did:key issuer does not carry a usable Ed25519 key".into()),
305 }
306 } else {
307 None
308 };
309 let short: String = issuer.chars().take(80).collect();
310 if no_key_source(&keys) {
311 let e = embedded.ok_or_else(|| format!("no key supplied for issuer {short}"))?;
312 let pinned = matches!(keys, Keys::Pinned(d) if d == issuer);
313 let named = trusted.is_some_and(|t| !t.is_empty() && t.contains(issuer));
314 if pinned || named {
315 return Ok(e);
316 }
317 return Err(
318 "no key source: pass keys, a non-empty trusted issuer set, or pin the \
319 expected issuer; any freshly minted did:key would verify otherwise"
320 .into(),
321 );
322 }
323 let candidate: Vec<u8> = match keys {
324 Keys::Embedded | Keys::Pinned(_) => unreachable!("handled above"),
325 Keys::Bare(k) => {
326 if embedded.is_none() {
327 return Err(
328 "a bare key is accepted only for a did:key issuer; pass {issuer_did: key}"
329 .into(),
330 );
331 }
332 k.to_vec()
333 }
334 Keys::One(did, k) => {
335 if !did.starts_with("did:") {
336 return Err("key map must be keyed by DID".into());
337 }
338 if did != issuer {
339 return Err(format!("issuer {short} is not in the key map"));
340 }
341 k.to_vec()
342 }
343 Keys::Map(m) => {
344 if m.is_empty() || !m.keys().all(|d| d.starts_with("did:")) {
345 return Err("key map must be keyed by DID".into());
346 }
347 match m.get(issuer) {
348 Some(k) => k.clone(),
349 None => return Err(format!("issuer {short} is not in the key map")),
350 }
351 }
352 Keys::Resolver(f) => match f(issuer) {
353 Some(k) => k,
354 None => return Err(format!("resolver has no key for issuer {short}")),
355 },
356 };
357 if candidate.len() != 32 {
358 return Err("unusable public key".into());
359 }
360 if let Some(e) = embedded {
361 if e != candidate {
362 return Err("key does not match the key inside the did:key issuer".into());
363 }
364 }
365 Ok(candidate)
366}
367
368pub fn window_reason(
370 credential: &Value,
371 window: Window,
372 now_ns: i128,
373 skew_seconds: i64,
374) -> Option<String> {
375 crate::nesting::deep_guard!(Some(crate::nesting::TOO_DEEP.into()); credential);
376 let obj = credential.as_object()?;
377 let vf_present = obj.contains_key("validFrom");
378 let vu_present = obj.contains_key("validUntil");
379 if window == Window::Required && !(vf_present && vu_present) {
380 return Some("validFrom and validUntil are required".into());
381 }
382 if window == Window::FromRequired && !vf_present {
383 return Some("validFrom is required".into());
384 }
385 let vf = if vf_present {
386 match time_ns(obj.get("validFrom")) {
387 Some(t) => Some(t),
388 None => return Some("validFrom is not a strict protocol time".into()),
389 }
390 } else {
391 None
392 };
393 let vu = if vu_present {
394 match time_ns(obj.get("validUntil")) {
395 Some(t) => Some(t),
396 None => return Some("validUntil is not a strict protocol time".into()),
397 }
398 } else {
399 None
400 };
401 let skew = match time::check_clock_skew(skew_seconds) {
402 Ok(s) => s,
403 Err(_) => return Some("now or clock skew is not acceptable".into()),
404 };
405 match time::window_state_ns(now_ns, vf, vu, skew) {
406 time::WindowState::Ok => None,
407 s => Some(format!("credential window: {}", s.as_str())),
408 }
409}
410
411#[derive(Clone, Copy)]
413pub struct VerifyOptions<'a> {
414 pub window: Window,
415 pub clock_skew_seconds: i64,
416 pub trusted_issuers: Option<&'a HashSet<String>>,
417 pub max_bytes: usize,
418}
419
420impl Default for VerifyOptions<'_> {
421 fn default() -> Self {
422 Self {
423 window: Window::Required,
424 clock_skew_seconds: 0,
425 trusted_issuers: None,
426 max_bytes: MAX_CREDENTIAL_BYTES,
427 }
428 }
429}
430
431impl VerifyOptions<'_> {
432 pub fn window(window: Window) -> Self {
434 Self {
435 window,
436 ..Self::default()
437 }
438 }
439}
440
441pub fn verify_robotics_credential(
445 credential: &Value,
446 keys: Keys<'_>,
447 expected_type: Option<&str>,
448 now_ns: i128,
449 opts: VerifyOptions<'_>,
450) -> core::result::Result<Verified, String> {
451 crate::nesting::deep_guard!(Err(crate::nesting::TOO_DEEP.into()); credential);
452 let obj = credential
453 .as_object()
454 .ok_or_else(|| "credential is not an object".to_string())?;
455 if let Some(big) = input_too_large(credential, opts.max_bytes) {
456 return Err(big);
457 }
458 let types: Vec<&str> = match obj.get("type") {
459 Some(Value::String(s)) => vec![s.as_str()],
460 Some(Value::Array(a)) if a.iter().all(|t| t.is_string()) => {
461 a.iter().filter_map(|t| t.as_str()).collect()
462 }
463 _ => return Err("type is not a string or list of strings".into()),
464 };
465 if let Some(want) = expected_type {
466 if !types.contains(&want) {
467 return Err(format!("not a {want}"));
468 }
469 }
470 let subject = match obj.get("credentialSubject") {
471 Some(s @ Value::Object(_)) => s,
472 _ => return Err("credentialSubject is not an object".into()),
473 };
474 let issuer = match issuer_id(obj.get("issuer")) {
475 Some(i) if i.starts_with("did:") => i,
476 _ => return Err("issuer is not a DID".into()),
477 };
478 let proof = match obj.get("proof") {
479 Some(p @ Value::Object(_)) => p,
480 _ => return Err("no proof".into()),
481 };
482 if let Some(why) = proof_unbound_reason(proof, issuer) {
483 return Err(why.into());
484 }
485 if let Keys::Pinned(d) = keys {
486 if d != issuer {
487 return Err("issuer is not the expected issuer".into());
488 }
489 }
490 let key = resolve_issuer_key_trusted(issuer, keys, opts.trusted_issuers)?;
491 match data_integrity::verify_proof(credential, &key) {
492 Ok(true) => {}
493 Ok(false) => return Err("proof does not verify".into()),
494 Err(_) => return Err("malformed proof".into()),
495 }
496 if let Some(why) = window_reason(credential, opts.window, now_ns, opts.clock_skew_seconds) {
497 return Err(why);
498 }
499 if let Some(trusted) = opts.trusted_issuers {
500 if !trusted.contains(issuer) {
501 return Err("issuer is not trusted".into());
502 }
503 }
504 Ok(Verified {
505 issuer: issuer.to_string(),
506 subject: subject.clone(),
507 })
508}
509
510pub fn collect_verified(
520 credentials: &[Value],
521 keys: Keys<'_>,
522 expected_type: &str,
523 now_ns: i128,
524 window: Window,
525 role_field: Option<&str>,
526 trusted: Option<&HashSet<String>>,
527) -> Vec<VerifiedPair> {
528 let mut out = Vec::new();
529 if no_key_source(&keys) && !matches!(keys, Keys::Pinned(_)) && trusted.is_none() {
530 return out;
531 }
532 for c in credentials {
533 if crate::nesting::too_deep_here(c) {
536 continue;
537 }
538 let v = match verify_robotics_credential(
539 c,
540 keys,
541 Some(expected_type),
542 now_ns,
543 VerifyOptions {
544 trusted_issuers: trusted,
545 ..VerifyOptions::window(window)
546 },
547 ) {
548 Ok(v) => v,
549 Err(_) => continue,
550 };
551 if let Some(field) = role_field {
552 if v.subject.get(field).and_then(|x| x.as_str()) != Some(v.issuer.as_str()) {
553 continue;
554 }
555 }
556 out.push(VerifiedPair {
557 issuer: v.issuer,
558 subject: v.subject,
559 _sealed: (),
560 });
561 }
562 out
563}
564
565pub fn iter_pairs(pairs: &[VerifiedPair]) -> impl Iterator<Item = (&str, &Value)> {
567 pairs
568 .iter()
569 .filter(|p| p.issuer.starts_with("did:") && p.subject.is_object())
570 .map(|p| (p.issuer.as_str(), &p.subject))
571}
572
573#[cfg(test)]
574mod tests {
575 use super::*;
576 use crate::data_integrity::{sign, BuildProofOptions};
577 use crate::keys::Ed25519KeyPair;
578 use serde_json::json;
579
580 const NOW: &str = "2026-06-01T00:00:00Z";
581
582 fn signed(seed: &[u8], issuer: &str, vm: &str) -> Value {
583 let cred = json!({
584 "@context": ["https://www.w3.org/ns/credentials/v2"],
585 "type": ["VerifiableCredential", "X"],
586 "issuer": issuer,
587 "validFrom": "2026-01-01T00:00:00Z",
588 "credentialSubject": {"id": issuer},
589 });
590 sign(
591 &cred,
592 seed,
593 &BuildProofOptions::new(vm.to_string(), "2026-01-01T00:00:00Z"),
594 )
595 .unwrap()
596 }
597
598 fn now() -> i128 {
599 require_now(NOW).unwrap()
600 }
601
602 #[test]
603 fn binds_did_web_issuer_to_its_map_key_only() {
604 let seed = [3u8; 32];
605 let pk = Ed25519KeyPair::from_seed(&seed).public_key().to_vec();
606 let did = "did:web:a.example";
607 let c = signed(&seed, did, "did:web:a.example#key-1");
608 let opts = VerifyOptions::window(Window::FromRequired);
609 assert!(
610 verify_robotics_credential(&c, Keys::One(did, &pk), Some("X"), now(), opts).is_ok()
611 );
612 assert!(verify_robotics_credential(&c, Keys::Bare(&pk), Some("X"), now(), opts).is_err());
613 assert!(verify_robotics_credential(
614 &c,
615 Keys::One("did:web:b", &pk),
616 Some("X"),
617 now(),
618 opts
619 )
620 .is_err());
621 let wrong_vm = signed(&seed, did, "did:web:evil.example#key-1");
622 assert!(
623 verify_robotics_credential(&wrong_vm, Keys::One(did, &pk), Some("X"), now(), opts)
624 .is_err()
625 );
626 }
627
628 #[test]
629 fn did_key_issuer_uses_its_own_key() {
630 let seed = [4u8; 32];
631 let pk = Ed25519KeyPair::from_seed(&seed).public_key().to_vec();
632 let did = crate::keys::ed25519_to_did_key(&pk).unwrap();
633 let c = signed(
634 &seed,
635 &did,
636 &crate::verification_method::ed25519_method(&did),
637 );
638 let opts = VerifyOptions::window(Window::FromRequired);
639 assert!(verify_robotics_credential(&c, Keys::Embedded, Some("X"), now(), opts).is_err());
641 assert!(verify_robotics_credential(&c, Keys::Pinned(&did), Some("X"), now(), opts).is_ok());
642 assert!(verify_robotics_credential(
643 &c,
644 Keys::Pinned("did:key:z6MkOther"),
645 Some("X"),
646 now(),
647 opts
648 )
649 .is_err());
650 let named: HashSet<String> = [did.clone()].into_iter().collect();
651 let empty: HashSet<String> = HashSet::new();
652 let with = |t| VerifyOptions {
653 trusted_issuers: Some(t),
654 ..opts
655 };
656 assert!(
657 verify_robotics_credential(&c, Keys::Embedded, Some("X"), now(), with(&named)).is_ok()
658 );
659 assert!(
660 verify_robotics_credential(&c, Keys::Embedded, Some("X"), now(), with(&empty)).is_err()
661 );
662 let empty_map = BTreeMap::new();
663 assert!(
664 verify_robotics_credential(&c, Keys::Map(&empty_map), Some("X"), now(), opts).is_err()
665 );
666 assert!(verify_robotics_credential(&c, Keys::Bare(&pk), Some("X"), now(), opts).is_ok());
667 let other = Ed25519KeyPair::from_seed(&[5u8; 32]).public_key().to_vec();
668 assert!(
669 verify_robotics_credential(&c, Keys::Bare(&other), Some("X"), now(), opts).is_err()
670 );
671 }
672
673 #[test]
674 fn did_key_proof_names_its_key_by_value_or_key_1_only() {
675 let seed = [4u8; 32];
676 let pk = Ed25519KeyPair::from_seed(&seed).public_key().to_vec();
677 let did = crate::keys::ed25519_to_did_key(&pk).unwrap();
678 let mb = did.strip_prefix("did:key:").unwrap().to_string();
679 let other_mb =
680 crate::keys::ed25519_to_did_key(&Ed25519KeyPair::from_seed(&[5u8; 32]).public_key())
681 .unwrap()
682 .strip_prefix("did:key:")
683 .unwrap()
684 .to_string();
685 let opts = VerifyOptions::window(Window::FromRequired);
686 let check = |vm: String| {
687 verify_robotics_credential(
688 &signed(&seed, &did, &vm),
689 Keys::Pinned(&did),
690 Some("X"),
691 now(),
692 opts,
693 )
694 .is_ok()
695 };
696 assert!(check(format!("{did}#{mb}")));
697 assert!(check(format!("{did}#key-1")));
698 assert!(!check(format!("{did}#{other_mb}")));
699 assert!(!check(format!("{did}#k")));
700 assert!(!check(did.clone()));
701 }
702
703 #[test]
704 fn collect_needs_a_key_map_or_a_member_set() {
705 let seed = [6u8; 32];
706 let pk = Ed25519KeyPair::from_seed(&seed).public_key().to_vec();
707 let did = crate::keys::ed25519_to_did_key(&pk).unwrap();
708 let c = signed(
709 &seed,
710 &did,
711 &crate::verification_method::ed25519_method(&did),
712 );
713 let creds = vec![c];
714 let none = collect_verified(
715 &creds,
716 Keys::Embedded,
717 "X",
718 now(),
719 Window::IfPresent,
720 None,
721 None,
722 );
723 assert!(none.is_empty());
724 let members: HashSet<String> = [did.clone()].into_iter().collect();
725 let some = collect_verified(
726 &creds,
727 Keys::Embedded,
728 "X",
729 now(),
730 Window::IfPresent,
731 None,
732 Some(&members),
733 );
734 assert_eq!(some.len(), 1);
735 assert_eq!(some[0].issuer(), did);
736 }
737
738 #[test]
739 fn strict_ints_stop_at_two_to_the_53_minus_one() {
740 assert!(is_strict_int(&serde_json::json!(9007199254740991_i64)));
741 assert!(!is_strict_int(&serde_json::json!(9007199254740992_i64)));
742 assert!(!is_strict_int(&serde_json::json!(-9007199254740992_i64)));
743 assert!(!is_strict_int(
744 &serde_json::from_str::<Value>("5.0").unwrap()
745 ));
746 assert!(!is_strict_int(&serde_json::json!(true)));
747 }
748
749 #[test]
750 fn window_modes_and_strict_bounds() {
751 let mut c = json!({"validFrom": "2026-01-01T00:00:00Z"});
752 assert!(window_reason(&c, Window::Required, now(), 0).is_some());
753 assert!(window_reason(&c, Window::FromRequired, now(), 0).is_none());
754 c["validUntil"] = json!(5);
755 assert!(window_reason(&c, Window::IfPresent, now(), 0).is_some());
756 c["validUntil"] = json!("2025-01-01T00:00:00Z");
757 assert!(window_reason(&c, Window::IfPresent, now(), 0).is_some());
758 assert!(window_reason(&json!({}), Window::FromRequired, now(), 0).is_some());
759 assert!(window_reason(&json!({}), Window::IfPresent, now(), 0).is_none());
760 }
761}
762
763#[cfg(test)]
765pub(crate) mod test_keys {
766 use super::*;
767
768 pub const TNOW: &str = "2026-01-01T00:30:00Z";
770
771 pub fn kd<'a>(credential: &'a Value, key: &'a [u8]) -> Keys<'a> {
774 match issuer_id(credential.get("issuer")) {
775 Some(i) => Keys::One(i, key),
776 None => Keys::Bare(key),
777 }
778 }
779
780 pub fn any_did(key: &[u8]) -> impl Fn(&str) -> Option<Vec<u8>> + '_ {
783 move |_| Some(key.to_vec())
784 }
785}