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