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 match p.get("verificationMethod").and_then(|v| v.as_str()) {
256 Some(vm) if vm.split('#').next() == Some(issuer) => None,
257 _ => Some("proof verificationMethod is not a key of the issuer"),
258 }
259}
260
261pub fn no_key_source(keys: &Keys<'_>) -> bool {
264 match keys {
265 Keys::Embedded | Keys::Pinned(_) => true,
266 Keys::Map(m) => m.is_empty(),
267 _ => false,
268 }
269}
270
271pub fn pin_if_keyless<'a>(keys: Keys<'a>, did: Option<&'a str>) -> Keys<'a> {
276 match did {
277 Some(d) if !d.is_empty() && no_key_source(&keys) => Keys::Pinned(d),
278 _ => keys,
279 }
280}
281
282pub fn resolve_issuer_key(issuer: &str, keys: Keys<'_>) -> core::result::Result<Vec<u8>, String> {
286 resolve_issuer_key_trusted(issuer, keys, None)
287}
288
289pub fn resolve_issuer_key_trusted(
295 issuer: &str,
296 keys: Keys<'_>,
297 trusted: Option<&HashSet<String>>,
298) -> core::result::Result<Vec<u8>, String> {
299 let is_did_key = issuer.starts_with("did:key:");
300 let embedded = if is_did_key {
301 match crate::keys::did_key_to_ed25519(issuer) {
302 Ok(k) if k.len() == 32 => Some(k),
303 _ => return Err("did:key issuer does not carry a usable Ed25519 key".into()),
304 }
305 } else {
306 None
307 };
308 let short: String = issuer.chars().take(80).collect();
309 if no_key_source(&keys) {
310 let e = embedded.ok_or_else(|| format!("no key supplied for issuer {short}"))?;
311 let pinned = matches!(keys, Keys::Pinned(d) if d == issuer);
312 let named = trusted.is_some_and(|t| !t.is_empty() && t.contains(issuer));
313 if pinned || named {
314 return Ok(e);
315 }
316 return Err(
317 "no key source: pass keys, a non-empty trusted issuer set, or pin the \
318 expected issuer; any freshly minted did:key would verify otherwise"
319 .into(),
320 );
321 }
322 let candidate: Vec<u8> = match keys {
323 Keys::Embedded | Keys::Pinned(_) => unreachable!("handled above"),
324 Keys::Bare(k) => {
325 if embedded.is_none() {
326 return Err(
327 "a bare key is accepted only for a did:key issuer; pass {issuer_did: key}"
328 .into(),
329 );
330 }
331 k.to_vec()
332 }
333 Keys::One(did, k) => {
334 if !did.starts_with("did:") {
335 return Err("key map must be keyed by DID".into());
336 }
337 if did != issuer {
338 return Err(format!("issuer {short} is not in the key map"));
339 }
340 k.to_vec()
341 }
342 Keys::Map(m) => {
343 if m.is_empty() || !m.keys().all(|d| d.starts_with("did:")) {
344 return Err("key map must be keyed by DID".into());
345 }
346 match m.get(issuer) {
347 Some(k) => k.clone(),
348 None => return Err(format!("issuer {short} is not in the key map")),
349 }
350 }
351 Keys::Resolver(f) => match f(issuer) {
352 Some(k) => k,
353 None => return Err(format!("resolver has no key for issuer {short}")),
354 },
355 };
356 if candidate.len() != 32 {
357 return Err("unusable public key".into());
358 }
359 if let Some(e) = embedded {
360 if e != candidate {
361 return Err("key does not match the key inside the did:key issuer".into());
362 }
363 }
364 Ok(candidate)
365}
366
367pub fn window_reason(
369 credential: &Value,
370 window: Window,
371 now_ns: i128,
372 skew_seconds: i64,
373) -> Option<String> {
374 crate::nesting::deep_guard!(Some(crate::nesting::TOO_DEEP.into()); credential);
375 let obj = credential.as_object()?;
376 let vf_present = obj.contains_key("validFrom");
377 let vu_present = obj.contains_key("validUntil");
378 if window == Window::Required && !(vf_present && vu_present) {
379 return Some("validFrom and validUntil are required".into());
380 }
381 if window == Window::FromRequired && !vf_present {
382 return Some("validFrom is required".into());
383 }
384 let vf = if vf_present {
385 match time_ns(obj.get("validFrom")) {
386 Some(t) => Some(t),
387 None => return Some("validFrom is not a strict protocol time".into()),
388 }
389 } else {
390 None
391 };
392 let vu = if vu_present {
393 match time_ns(obj.get("validUntil")) {
394 Some(t) => Some(t),
395 None => return Some("validUntil is not a strict protocol time".into()),
396 }
397 } else {
398 None
399 };
400 let skew = match time::check_clock_skew(skew_seconds) {
401 Ok(s) => s,
402 Err(_) => return Some("now or clock skew is not acceptable".into()),
403 };
404 match time::window_state_ns(now_ns, vf, vu, skew) {
405 time::WindowState::Ok => None,
406 s => Some(format!("credential window: {}", s.as_str())),
407 }
408}
409
410#[derive(Clone, Copy)]
412pub struct VerifyOptions<'a> {
413 pub window: Window,
414 pub clock_skew_seconds: i64,
415 pub trusted_issuers: Option<&'a HashSet<String>>,
416 pub max_bytes: usize,
417}
418
419impl Default for VerifyOptions<'_> {
420 fn default() -> Self {
421 Self {
422 window: Window::Required,
423 clock_skew_seconds: 0,
424 trusted_issuers: None,
425 max_bytes: MAX_CREDENTIAL_BYTES,
426 }
427 }
428}
429
430impl VerifyOptions<'_> {
431 pub fn window(window: Window) -> Self {
433 Self {
434 window,
435 ..Self::default()
436 }
437 }
438}
439
440pub fn verify_robotics_credential(
444 credential: &Value,
445 keys: Keys<'_>,
446 expected_type: Option<&str>,
447 now_ns: i128,
448 opts: VerifyOptions<'_>,
449) -> core::result::Result<Verified, String> {
450 crate::nesting::deep_guard!(Err(crate::nesting::TOO_DEEP.into()); credential);
451 let obj = credential
452 .as_object()
453 .ok_or_else(|| "credential is not an object".to_string())?;
454 if let Some(big) = input_too_large(credential, opts.max_bytes) {
455 return Err(big);
456 }
457 let types: Vec<&str> = match obj.get("type") {
458 Some(Value::String(s)) => vec![s.as_str()],
459 Some(Value::Array(a)) if a.iter().all(|t| t.is_string()) => {
460 a.iter().filter_map(|t| t.as_str()).collect()
461 }
462 _ => return Err("type is not a string or list of strings".into()),
463 };
464 if let Some(want) = expected_type {
465 if !types.contains(&want) {
466 return Err(format!("not a {want}"));
467 }
468 }
469 let subject = match obj.get("credentialSubject") {
470 Some(s @ Value::Object(_)) => s,
471 _ => return Err("credentialSubject is not an object".into()),
472 };
473 let issuer = match issuer_id(obj.get("issuer")) {
474 Some(i) if i.starts_with("did:") => i,
475 _ => return Err("issuer is not a DID".into()),
476 };
477 let proof = match obj.get("proof") {
478 Some(p @ Value::Object(_)) => p,
479 _ => return Err("no proof".into()),
480 };
481 if let Some(why) = proof_unbound_reason(proof, issuer) {
482 return Err(why.into());
483 }
484 if let Keys::Pinned(d) = keys {
485 if d != issuer {
486 return Err("issuer is not the expected issuer".into());
487 }
488 }
489 let key = resolve_issuer_key_trusted(issuer, keys, opts.trusted_issuers)?;
490 match data_integrity::verify_proof(credential, &key) {
491 Ok(true) => {}
492 Ok(false) => return Err("proof does not verify".into()),
493 Err(_) => return Err("malformed proof".into()),
494 }
495 if let Some(why) = window_reason(credential, opts.window, now_ns, opts.clock_skew_seconds) {
496 return Err(why);
497 }
498 if let Some(trusted) = opts.trusted_issuers {
499 if !trusted.contains(issuer) {
500 return Err("issuer is not trusted".into());
501 }
502 }
503 Ok(Verified {
504 issuer: issuer.to_string(),
505 subject: subject.clone(),
506 })
507}
508
509pub fn collect_verified(
519 credentials: &[Value],
520 keys: Keys<'_>,
521 expected_type: &str,
522 now_ns: i128,
523 window: Window,
524 role_field: Option<&str>,
525 trusted: Option<&HashSet<String>>,
526) -> Vec<VerifiedPair> {
527 let mut out = Vec::new();
528 if no_key_source(&keys) && !matches!(keys, Keys::Pinned(_)) && trusted.is_none() {
529 return out;
530 }
531 for c in credentials {
532 if crate::nesting::too_deep_here(c) {
535 continue;
536 }
537 let v = match verify_robotics_credential(
538 c,
539 keys,
540 Some(expected_type),
541 now_ns,
542 VerifyOptions {
543 trusted_issuers: trusted,
544 ..VerifyOptions::window(window)
545 },
546 ) {
547 Ok(v) => v,
548 Err(_) => continue,
549 };
550 if let Some(field) = role_field {
551 if v.subject.get(field).and_then(|x| x.as_str()) != Some(v.issuer.as_str()) {
552 continue;
553 }
554 }
555 out.push(VerifiedPair {
556 issuer: v.issuer,
557 subject: v.subject,
558 _sealed: (),
559 });
560 }
561 out
562}
563
564pub fn iter_pairs(pairs: &[VerifiedPair]) -> impl Iterator<Item = (&str, &Value)> {
566 pairs
567 .iter()
568 .filter(|p| p.issuer.starts_with("did:") && p.subject.is_object())
569 .map(|p| (p.issuer.as_str(), &p.subject))
570}
571
572#[cfg(test)]
573mod tests {
574 use super::*;
575 use crate::data_integrity::{sign, BuildProofOptions};
576 use crate::keys::Ed25519KeyPair;
577 use serde_json::json;
578
579 const NOW: &str = "2026-06-01T00:00:00Z";
580
581 fn signed(seed: &[u8], issuer: &str, vm: &str) -> Value {
582 let cred = json!({
583 "@context": ["https://www.w3.org/ns/credentials/v2"],
584 "type": ["VerifiableCredential", "X"],
585 "issuer": issuer,
586 "validFrom": "2026-01-01T00:00:00Z",
587 "credentialSubject": {"id": issuer},
588 });
589 sign(
590 &cred,
591 seed,
592 &BuildProofOptions::new(vm.to_string(), "2026-01-01T00:00:00Z"),
593 )
594 .unwrap()
595 }
596
597 fn now() -> i128 {
598 require_now(NOW).unwrap()
599 }
600
601 #[test]
602 fn binds_did_web_issuer_to_its_map_key_only() {
603 let seed = [3u8; 32];
604 let pk = Ed25519KeyPair::from_seed(&seed).public_key().to_vec();
605 let did = "did:web:a.example";
606 let c = signed(&seed, did, "did:web:a.example#key-1");
607 let opts = VerifyOptions::window(Window::FromRequired);
608 assert!(
609 verify_robotics_credential(&c, Keys::One(did, &pk), Some("X"), now(), opts).is_ok()
610 );
611 assert!(verify_robotics_credential(&c, Keys::Bare(&pk), Some("X"), now(), opts).is_err());
612 assert!(verify_robotics_credential(
613 &c,
614 Keys::One("did:web:b", &pk),
615 Some("X"),
616 now(),
617 opts
618 )
619 .is_err());
620 let wrong_vm = signed(&seed, did, "did:web:evil.example#key-1");
621 assert!(
622 verify_robotics_credential(&wrong_vm, Keys::One(did, &pk), Some("X"), now(), opts)
623 .is_err()
624 );
625 }
626
627 #[test]
628 fn did_key_issuer_uses_its_own_key() {
629 let seed = [4u8; 32];
630 let pk = Ed25519KeyPair::from_seed(&seed).public_key().to_vec();
631 let did = crate::keys::ed25519_to_did_key(&pk).unwrap();
632 let c = signed(&seed, &did, &format!("{did}#k"));
633 let opts = VerifyOptions::window(Window::FromRequired);
634 assert!(verify_robotics_credential(&c, Keys::Embedded, Some("X"), now(), opts).is_err());
636 assert!(verify_robotics_credential(&c, Keys::Pinned(&did), Some("X"), now(), opts).is_ok());
637 assert!(verify_robotics_credential(
638 &c,
639 Keys::Pinned("did:key:z6MkOther"),
640 Some("X"),
641 now(),
642 opts
643 )
644 .is_err());
645 let named: HashSet<String> = [did.clone()].into_iter().collect();
646 let empty: HashSet<String> = HashSet::new();
647 let with = |t| VerifyOptions {
648 trusted_issuers: Some(t),
649 ..opts
650 };
651 assert!(
652 verify_robotics_credential(&c, Keys::Embedded, Some("X"), now(), with(&named)).is_ok()
653 );
654 assert!(
655 verify_robotics_credential(&c, Keys::Embedded, Some("X"), now(), with(&empty)).is_err()
656 );
657 let empty_map = BTreeMap::new();
658 assert!(
659 verify_robotics_credential(&c, Keys::Map(&empty_map), Some("X"), now(), opts).is_err()
660 );
661 assert!(verify_robotics_credential(&c, Keys::Bare(&pk), Some("X"), now(), opts).is_ok());
662 let other = Ed25519KeyPair::from_seed(&[5u8; 32]).public_key().to_vec();
663 assert!(
664 verify_robotics_credential(&c, Keys::Bare(&other), Some("X"), now(), opts).is_err()
665 );
666 }
667
668 #[test]
669 fn collect_needs_a_key_map_or_a_member_set() {
670 let seed = [6u8; 32];
671 let pk = Ed25519KeyPair::from_seed(&seed).public_key().to_vec();
672 let did = crate::keys::ed25519_to_did_key(&pk).unwrap();
673 let c = signed(&seed, &did, &format!("{did}#k"));
674 let creds = vec![c];
675 let none = collect_verified(
676 &creds,
677 Keys::Embedded,
678 "X",
679 now(),
680 Window::IfPresent,
681 None,
682 None,
683 );
684 assert!(none.is_empty());
685 let members: HashSet<String> = [did.clone()].into_iter().collect();
686 let some = collect_verified(
687 &creds,
688 Keys::Embedded,
689 "X",
690 now(),
691 Window::IfPresent,
692 None,
693 Some(&members),
694 );
695 assert_eq!(some.len(), 1);
696 assert_eq!(some[0].issuer(), did);
697 }
698
699 #[test]
700 fn strict_ints_stop_at_two_to_the_53_minus_one() {
701 assert!(is_strict_int(&serde_json::json!(9007199254740991_i64)));
702 assert!(!is_strict_int(&serde_json::json!(9007199254740992_i64)));
703 assert!(!is_strict_int(&serde_json::json!(-9007199254740992_i64)));
704 assert!(!is_strict_int(
705 &serde_json::from_str::<Value>("5.0").unwrap()
706 ));
707 assert!(!is_strict_int(&serde_json::json!(true)));
708 }
709
710 #[test]
711 fn window_modes_and_strict_bounds() {
712 let mut c = json!({"validFrom": "2026-01-01T00:00:00Z"});
713 assert!(window_reason(&c, Window::Required, now(), 0).is_some());
714 assert!(window_reason(&c, Window::FromRequired, now(), 0).is_none());
715 c["validUntil"] = json!(5);
716 assert!(window_reason(&c, Window::IfPresent, now(), 0).is_some());
717 c["validUntil"] = json!("2025-01-01T00:00:00Z");
718 assert!(window_reason(&c, Window::IfPresent, now(), 0).is_some());
719 assert!(window_reason(&json!({}), Window::FromRequired, now(), 0).is_some());
720 assert!(window_reason(&json!({}), Window::IfPresent, now(), 0).is_none());
721 }
722}
723
724#[cfg(test)]
726pub(crate) mod test_keys {
727 use super::*;
728
729 pub const TNOW: &str = "2026-01-01T00:30:00Z";
731
732 pub fn kd<'a>(credential: &'a Value, key: &'a [u8]) -> Keys<'a> {
735 match issuer_id(credential.get("issuer")) {
736 Some(i) => Keys::One(i, key),
737 None => Keys::Bare(key),
738 }
739 }
740
741 pub fn any_did(key: &[u8]) -> impl Fn(&str) -> Option<Vec<u8>> + '_ {
744 move |_| Some(key.to_vec())
745 }
746}