#[allow(unused_imports)]
use crate::prelude::*;
use crate::collections::HashSet;
use alloc::collections::BTreeMap;
use serde_json::Value;
use crate::attenuation::json_nesting_exceeds;
use crate::data_integrity;
use crate::error::{CoreError, Result};
use crate::time;
pub const MAX_NESTING: usize = 128;
pub const MAX_CREDENTIAL_BYTES: usize = 1024 * 1024;
pub const ASSERTION_METHOD: &str = "assertionMethod";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Window {
Required,
FromRequired,
IfPresent,
}
#[derive(Clone, Copy)]
pub enum Keys<'a> {
Embedded,
Pinned(&'a str),
Bare(&'a [u8]),
One(&'a str, &'a [u8]),
Map(&'a BTreeMap<String, Vec<u8>>),
Resolver(&'a dyn Fn(&str) -> Option<Vec<u8>>),
}
impl<'a> Keys<'a> {
pub fn map_of<I, S, K>(entries: I) -> BTreeMap<String, Vec<u8>>
where
I: IntoIterator<Item = (S, K)>,
S: Into<String>,
K: AsRef<[u8]>,
{
entries
.into_iter()
.map(|(d, k)| (d.into(), k.as_ref().to_vec()))
.collect()
}
}
#[derive(Debug, Clone)]
pub struct Verified {
pub issuer: String,
pub subject: Value,
}
#[derive(Debug, Clone, PartialEq)]
pub struct VerifiedPair {
issuer: String,
subject: Value,
_sealed: (),
}
impl VerifiedPair {
pub fn issuer(&self) -> &str {
&self.issuer
}
pub fn subject(&self) -> &Value {
&self.subject
}
#[cfg(test)]
pub(crate) fn for_test(issuer: &str, subject: Value) -> Self {
Self {
issuer: issuer.to_string(),
subject,
_sealed: (),
}
}
}
pub fn require_now(now_iso: &str) -> Result<i128> {
if now_iso.is_empty() {
return Err(CoreError::Json(
"now is required: pass the verifier's clock as a protocol time".into(),
));
}
time::parse_protocol_time_ns(now_iso).map_err(|_| {
CoreError::Json("now must be a protocol time such as 2026-01-01T00:00:00Z".into())
})
}
pub fn issuer_id(value: Option<&Value>) -> Option<&str> {
match value {
Some(Value::String(s)) if !s.is_empty() => Some(s),
Some(Value::Object(o)) => match o.get("id") {
Some(Value::String(s)) if !s.is_empty() => Some(s),
_ => None,
},
_ => None,
}
}
pub const MAX_SAFE_INT: i64 = (1_i64 << 53) - 1;
pub fn is_strict_int(v: &Value) -> bool {
strict_int(Some(v)).is_some()
}
pub fn strict_int(v: Option<&Value>) -> Option<i64> {
v.and_then(|x| {
if x.is_i64() || x.is_u64() {
x.as_i64()
} else {
None
}
})
.filter(|n| (-MAX_SAFE_INT..=MAX_SAFE_INT).contains(n))
}
pub fn finite_number(v: Option<&Value>) -> Option<f64> {
v.and_then(|x| if x.is_number() { x.as_f64() } else { None })
.filter(|n| n.is_finite())
}
pub fn time_ns(v: Option<&Value>) -> Option<i128> {
v.and_then(|x| x.as_str())
.and_then(|s| time::parse_protocol_time_ns(s).ok())
}
pub fn approx_size(value: &Value, limit: usize) -> usize {
let mut total: usize = 0;
let mut stack: Vec<&Value> = vec![value];
while let Some(node) = stack.pop() {
match node {
Value::Object(o) => {
total += 2 + o.len();
for (k, v) in o {
total += k.chars().count() + 3;
stack.push(v);
}
}
Value::Array(a) => {
total += 2 + a.len();
stack.extend(a.iter());
}
Value::String(s) => total += s.chars().count() + 2,
_ => total += 24,
}
if total > limit {
return total;
}
}
total
}
pub fn input_too_large(value: &Value, max_bytes: usize) -> Option<String> {
crate::nesting::deep_guard!(Some(crate::nesting::TOO_DEEP.into()); value);
if json_nesting_exceeds(value, MAX_NESTING) {
return Some(format!("input nests more than {MAX_NESTING} levels"));
}
if approx_size(value, max_bytes) > max_bytes {
return Some(format!("input larger than {max_bytes} bytes"));
}
None
}
pub fn proof_unbound_reason(proof: &Value, issuer: &str) -> Option<&'static str> {
crate::nesting::deep_guard!(Some(crate::nesting::TOO_DEEP); proof);
let p = match proof.as_object() {
Some(p) => p,
None => return Some("proof is not an object"),
};
if p.get("proofPurpose").and_then(|v| v.as_str()) != Some(ASSERTION_METHOD) {
return Some("proofPurpose is not assertionMethod");
}
match p.get("verificationMethod").and_then(|v| v.as_str()) {
Some(vm) if vm.split('#').next() == Some(issuer) => None,
_ => Some("proof verificationMethod is not a key of the issuer"),
}
}
pub fn no_key_source(keys: &Keys<'_>) -> bool {
match keys {
Keys::Embedded | Keys::Pinned(_) => true,
Keys::Map(m) => m.is_empty(),
_ => false,
}
}
pub fn pin_if_keyless<'a>(keys: Keys<'a>, did: Option<&'a str>) -> Keys<'a> {
match did {
Some(d) if !d.is_empty() && no_key_source(&keys) => Keys::Pinned(d),
_ => keys,
}
}
pub fn resolve_issuer_key(issuer: &str, keys: Keys<'_>) -> core::result::Result<Vec<u8>, String> {
resolve_issuer_key_trusted(issuer, keys, None)
}
pub fn resolve_issuer_key_trusted(
issuer: &str,
keys: Keys<'_>,
trusted: Option<&HashSet<String>>,
) -> core::result::Result<Vec<u8>, String> {
let is_did_key = issuer.starts_with("did:key:");
let embedded = if is_did_key {
match crate::keys::did_key_to_ed25519(issuer) {
Ok(k) if k.len() == 32 => Some(k),
_ => return Err("did:key issuer does not carry a usable Ed25519 key".into()),
}
} else {
None
};
let short: String = issuer.chars().take(80).collect();
if no_key_source(&keys) {
let e = embedded.ok_or_else(|| format!("no key supplied for issuer {short}"))?;
let pinned = matches!(keys, Keys::Pinned(d) if d == issuer);
let named = trusted.is_some_and(|t| !t.is_empty() && t.contains(issuer));
if pinned || named {
return Ok(e);
}
return Err(
"no key source: pass keys, a non-empty trusted issuer set, or pin the \
expected issuer; any freshly minted did:key would verify otherwise"
.into(),
);
}
let candidate: Vec<u8> = match keys {
Keys::Embedded | Keys::Pinned(_) => unreachable!("handled above"),
Keys::Bare(k) => {
if embedded.is_none() {
return Err(
"a bare key is accepted only for a did:key issuer; pass {issuer_did: key}"
.into(),
);
}
k.to_vec()
}
Keys::One(did, k) => {
if !did.starts_with("did:") {
return Err("key map must be keyed by DID".into());
}
if did != issuer {
return Err(format!("issuer {short} is not in the key map"));
}
k.to_vec()
}
Keys::Map(m) => {
if m.is_empty() || !m.keys().all(|d| d.starts_with("did:")) {
return Err("key map must be keyed by DID".into());
}
match m.get(issuer) {
Some(k) => k.clone(),
None => return Err(format!("issuer {short} is not in the key map")),
}
}
Keys::Resolver(f) => match f(issuer) {
Some(k) => k,
None => return Err(format!("resolver has no key for issuer {short}")),
},
};
if candidate.len() != 32 {
return Err("unusable public key".into());
}
if let Some(e) = embedded {
if e != candidate {
return Err("key does not match the key inside the did:key issuer".into());
}
}
Ok(candidate)
}
pub fn window_reason(
credential: &Value,
window: Window,
now_ns: i128,
skew_seconds: i64,
) -> Option<String> {
crate::nesting::deep_guard!(Some(crate::nesting::TOO_DEEP.into()); credential);
let obj = credential.as_object()?;
let vf_present = obj.contains_key("validFrom");
let vu_present = obj.contains_key("validUntil");
if window == Window::Required && !(vf_present && vu_present) {
return Some("validFrom and validUntil are required".into());
}
if window == Window::FromRequired && !vf_present {
return Some("validFrom is required".into());
}
let vf = if vf_present {
match time_ns(obj.get("validFrom")) {
Some(t) => Some(t),
None => return Some("validFrom is not a strict protocol time".into()),
}
} else {
None
};
let vu = if vu_present {
match time_ns(obj.get("validUntil")) {
Some(t) => Some(t),
None => return Some("validUntil is not a strict protocol time".into()),
}
} else {
None
};
let skew = match time::check_clock_skew(skew_seconds) {
Ok(s) => s,
Err(_) => return Some("now or clock skew is not acceptable".into()),
};
match time::window_state_ns(now_ns, vf, vu, skew) {
time::WindowState::Ok => None,
s => Some(format!("credential window: {}", s.as_str())),
}
}
#[derive(Clone, Copy)]
pub struct VerifyOptions<'a> {
pub window: Window,
pub clock_skew_seconds: i64,
pub trusted_issuers: Option<&'a HashSet<String>>,
pub max_bytes: usize,
}
impl Default for VerifyOptions<'_> {
fn default() -> Self {
Self {
window: Window::Required,
clock_skew_seconds: 0,
trusted_issuers: None,
max_bytes: MAX_CREDENTIAL_BYTES,
}
}
}
impl VerifyOptions<'_> {
pub fn window(window: Window) -> Self {
Self {
window,
..Self::default()
}
}
}
pub fn verify_robotics_credential(
credential: &Value,
keys: Keys<'_>,
expected_type: Option<&str>,
now_ns: i128,
opts: VerifyOptions<'_>,
) -> core::result::Result<Verified, String> {
crate::nesting::deep_guard!(Err(crate::nesting::TOO_DEEP.into()); credential);
let obj = credential
.as_object()
.ok_or_else(|| "credential is not an object".to_string())?;
if let Some(big) = input_too_large(credential, opts.max_bytes) {
return Err(big);
}
let types: Vec<&str> = match obj.get("type") {
Some(Value::String(s)) => vec![s.as_str()],
Some(Value::Array(a)) if a.iter().all(|t| t.is_string()) => {
a.iter().filter_map(|t| t.as_str()).collect()
}
_ => return Err("type is not a string or list of strings".into()),
};
if let Some(want) = expected_type {
if !types.contains(&want) {
return Err(format!("not a {want}"));
}
}
let subject = match obj.get("credentialSubject") {
Some(s @ Value::Object(_)) => s,
_ => return Err("credentialSubject is not an object".into()),
};
let issuer = match issuer_id(obj.get("issuer")) {
Some(i) if i.starts_with("did:") => i,
_ => return Err("issuer is not a DID".into()),
};
let proof = match obj.get("proof") {
Some(p @ Value::Object(_)) => p,
_ => return Err("no proof".into()),
};
if let Some(why) = proof_unbound_reason(proof, issuer) {
return Err(why.into());
}
if let Keys::Pinned(d) = keys {
if d != issuer {
return Err("issuer is not the expected issuer".into());
}
}
let key = resolve_issuer_key_trusted(issuer, keys, opts.trusted_issuers)?;
match data_integrity::verify_proof(credential, &key) {
Ok(true) => {}
Ok(false) => return Err("proof does not verify".into()),
Err(_) => return Err("malformed proof".into()),
}
if let Some(why) = window_reason(credential, opts.window, now_ns, opts.clock_skew_seconds) {
return Err(why);
}
if let Some(trusted) = opts.trusted_issuers {
if !trusted.contains(issuer) {
return Err("issuer is not trusted".into());
}
}
Ok(Verified {
issuer: issuer.to_string(),
subject: subject.clone(),
})
}
pub fn collect_verified(
credentials: &[Value],
keys: Keys<'_>,
expected_type: &str,
now_ns: i128,
window: Window,
role_field: Option<&str>,
trusted: Option<&HashSet<String>>,
) -> Vec<VerifiedPair> {
let mut out = Vec::new();
if no_key_source(&keys) && !matches!(keys, Keys::Pinned(_)) && trusted.is_none() {
return out;
}
for c in credentials {
if crate::nesting::too_deep_here(c) {
continue;
}
let v = match verify_robotics_credential(
c,
keys,
Some(expected_type),
now_ns,
VerifyOptions {
trusted_issuers: trusted,
..VerifyOptions::window(window)
},
) {
Ok(v) => v,
Err(_) => continue,
};
if let Some(field) = role_field {
if v.subject.get(field).and_then(|x| x.as_str()) != Some(v.issuer.as_str()) {
continue;
}
}
out.push(VerifiedPair {
issuer: v.issuer,
subject: v.subject,
_sealed: (),
});
}
out
}
pub fn iter_pairs(pairs: &[VerifiedPair]) -> impl Iterator<Item = (&str, &Value)> {
pairs
.iter()
.filter(|p| p.issuer.starts_with("did:") && p.subject.is_object())
.map(|p| (p.issuer.as_str(), &p.subject))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::data_integrity::{sign, BuildProofOptions};
use crate::keys::Ed25519KeyPair;
use serde_json::json;
const NOW: &str = "2026-06-01T00:00:00Z";
fn signed(seed: &[u8], issuer: &str, vm: &str) -> Value {
let cred = json!({
"@context": ["https://www.w3.org/ns/credentials/v2"],
"type": ["VerifiableCredential", "X"],
"issuer": issuer,
"validFrom": "2026-01-01T00:00:00Z",
"credentialSubject": {"id": issuer},
});
sign(
&cred,
seed,
&BuildProofOptions::new(vm.to_string(), "2026-01-01T00:00:00Z"),
)
.unwrap()
}
fn now() -> i128 {
require_now(NOW).unwrap()
}
#[test]
fn binds_did_web_issuer_to_its_map_key_only() {
let seed = [3u8; 32];
let pk = Ed25519KeyPair::from_seed(&seed).public_key().to_vec();
let did = "did:web:a.example";
let c = signed(&seed, did, "did:web:a.example#key-1");
let opts = VerifyOptions::window(Window::FromRequired);
assert!(
verify_robotics_credential(&c, Keys::One(did, &pk), Some("X"), now(), opts).is_ok()
);
assert!(verify_robotics_credential(&c, Keys::Bare(&pk), Some("X"), now(), opts).is_err());
assert!(verify_robotics_credential(
&c,
Keys::One("did:web:b", &pk),
Some("X"),
now(),
opts
)
.is_err());
let wrong_vm = signed(&seed, did, "did:web:evil.example#key-1");
assert!(
verify_robotics_credential(&wrong_vm, Keys::One(did, &pk), Some("X"), now(), opts)
.is_err()
);
}
#[test]
fn did_key_issuer_uses_its_own_key() {
let seed = [4u8; 32];
let pk = Ed25519KeyPair::from_seed(&seed).public_key().to_vec();
let did = crate::keys::ed25519_to_did_key(&pk).unwrap();
let c = signed(&seed, &did, &format!("{did}#k"));
let opts = VerifyOptions::window(Window::FromRequired);
assert!(verify_robotics_credential(&c, Keys::Embedded, Some("X"), now(), opts).is_err());
assert!(verify_robotics_credential(&c, Keys::Pinned(&did), Some("X"), now(), opts).is_ok());
assert!(verify_robotics_credential(
&c,
Keys::Pinned("did:key:z6MkOther"),
Some("X"),
now(),
opts
)
.is_err());
let named: HashSet<String> = [did.clone()].into_iter().collect();
let empty: HashSet<String> = HashSet::new();
let with = |t| VerifyOptions {
trusted_issuers: Some(t),
..opts
};
assert!(
verify_robotics_credential(&c, Keys::Embedded, Some("X"), now(), with(&named)).is_ok()
);
assert!(
verify_robotics_credential(&c, Keys::Embedded, Some("X"), now(), with(&empty)).is_err()
);
let empty_map = BTreeMap::new();
assert!(
verify_robotics_credential(&c, Keys::Map(&empty_map), Some("X"), now(), opts).is_err()
);
assert!(verify_robotics_credential(&c, Keys::Bare(&pk), Some("X"), now(), opts).is_ok());
let other = Ed25519KeyPair::from_seed(&[5u8; 32]).public_key().to_vec();
assert!(
verify_robotics_credential(&c, Keys::Bare(&other), Some("X"), now(), opts).is_err()
);
}
#[test]
fn collect_needs_a_key_map_or_a_member_set() {
let seed = [6u8; 32];
let pk = Ed25519KeyPair::from_seed(&seed).public_key().to_vec();
let did = crate::keys::ed25519_to_did_key(&pk).unwrap();
let c = signed(&seed, &did, &format!("{did}#k"));
let creds = vec![c];
let none = collect_verified(
&creds,
Keys::Embedded,
"X",
now(),
Window::IfPresent,
None,
None,
);
assert!(none.is_empty());
let members: HashSet<String> = [did.clone()].into_iter().collect();
let some = collect_verified(
&creds,
Keys::Embedded,
"X",
now(),
Window::IfPresent,
None,
Some(&members),
);
assert_eq!(some.len(), 1);
assert_eq!(some[0].issuer(), did);
}
#[test]
fn strict_ints_stop_at_two_to_the_53_minus_one() {
assert!(is_strict_int(&serde_json::json!(9007199254740991_i64)));
assert!(!is_strict_int(&serde_json::json!(9007199254740992_i64)));
assert!(!is_strict_int(&serde_json::json!(-9007199254740992_i64)));
assert!(!is_strict_int(
&serde_json::from_str::<Value>("5.0").unwrap()
));
assert!(!is_strict_int(&serde_json::json!(true)));
}
#[test]
fn window_modes_and_strict_bounds() {
let mut c = json!({"validFrom": "2026-01-01T00:00:00Z"});
assert!(window_reason(&c, Window::Required, now(), 0).is_some());
assert!(window_reason(&c, Window::FromRequired, now(), 0).is_none());
c["validUntil"] = json!(5);
assert!(window_reason(&c, Window::IfPresent, now(), 0).is_some());
c["validUntil"] = json!("2025-01-01T00:00:00Z");
assert!(window_reason(&c, Window::IfPresent, now(), 0).is_some());
assert!(window_reason(&json!({}), Window::FromRequired, now(), 0).is_some());
assert!(window_reason(&json!({}), Window::IfPresent, now(), 0).is_none());
}
}
#[cfg(test)]
pub(crate) mod test_keys {
use super::*;
pub const TNOW: &str = "2026-01-01T00:30:00Z";
pub fn kd<'a>(credential: &'a Value, key: &'a [u8]) -> Keys<'a> {
match issuer_id(credential.get("issuer")) {
Some(i) => Keys::One(i, key),
None => Keys::Bare(key),
}
}
pub fn any_did(key: &[u8]) -> impl Fn(&str) -> Option<Vec<u8>> + '_ {
move |_| Some(key.to_vec())
}
}