Skip to main content

vouch_core/
robotics_verify.rs

1//! Shared verification for robotics credentials, the port of the Python
2//! reference `vouch/robotics/_verify.py`.
3//!
4//! Every robotics verifier goes through [`verify_robotics_credential`]. It
5//! answers one question: did the party named as `issuer` really sign this
6//! credential, and is the credential usable at `now`? It checks, in order:
7//!
8//! 1. The input is a JSON object no deeper than [`MAX_NESTING`] levels and no
9//!    larger than [`MAX_CREDENTIAL_BYTES`] (both before canonicalization).
10//! 2. `type` is a string or a list of strings and lists the expected type.
11//! 3. `credentialSubject` is an object.
12//! 4. `issuer` is a DID (a string, or an object with a string `id`).
13//! 5. `proof.proofPurpose` is `assertionMethod` and the DID part of
14//!    `proof.verificationMethod` (before the first `#`) is exactly the issuer.
15//! 6. The key belongs to the issuer. A `did:key` issuer's key is the one inside
16//!    the DID; any other key a caller passes for it is refused. Any other DID
17//!    needs its key from a map keyed by DID (or a resolver): a bare key is
18//!    never trusted for it, because nothing ties that key to the DID.
19//! 7. The eddsa-jcs-2022 proof verifies under that key.
20//! 8. The window: a present `validFrom` / `validUntil` must be a strict
21//!    protocol-time string, the [`Window`] mode says which bounds must exist,
22//!    and `now` must fall inside it (an inverted window is refused).
23//! 9. When a trusted-issuer set is given, the bound issuer is in it.
24//!
25//! With no key source at all ([`Keys::Embedded`], or an empty [`Keys::Map`]),
26//! nothing says which party the caller trusts, and a credential signed by any
27//! freshly minted `did:key` would verify. So the key inside a `did:key` issuer
28//! is used only when the caller named that issuer: [`Keys::Pinned`] with the
29//! issuer's DID (a self-attestation whose subject the caller pins), or a
30//! non-empty trusted-issuer set that contains it. Otherwise the credential is
31//! refused.
32//!
33//! Malformed input never panics and never errors: the result is
34//! `Err(reason)`. Only a malformed `now` (the caller's own clock) is a
35//! [`CoreError`], raised by the verifiers before they look at the credential.
36
37#[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
50/// The deepest nesting a robotics credential may have.
51pub const MAX_NESTING: usize = 128;
52/// The largest robotics credential accepted, estimated before canonicalization.
53pub const MAX_CREDENTIAL_BYTES: usize = 1024 * 1024;
54/// The only proof purpose a robotics credential may carry.
55pub const ASSERTION_METHOD: &str = "assertionMethod";
56
57/// Which validity bounds a credential must carry. A present bound is always a
58/// strict protocol-time string and is always enforced.
59#[derive(Debug, Clone, Copy, PartialEq, Eq)]
60pub enum Window {
61    /// Both `validFrom` and `validUntil` must be present.
62    Required,
63    /// `validFrom` must be present; `validUntil` is optional.
64    FromRequired,
65    /// Both bounds are optional.
66    IfPresent,
67}
68
69/// Where an issuer's Ed25519 key comes from.
70#[derive(Clone, Copy)]
71pub enum Keys<'a> {
72    /// No key from the caller. A `did:key` issuer verifies under the key
73    /// inside its DID only when a non-empty trusted-issuer set names it.
74    Embedded,
75    /// No key from the caller, and the caller pins the issuer it expects (a
76    /// self-attestation): a `did:key` issuer equal to this DID verifies under
77    /// the key inside its DID. Any other issuer is refused.
78    Pinned(&'a str),
79    /// A bare 32-byte key. Accepted only for a `did:key` issuer, and only when
80    /// it equals the key inside the DID.
81    Bare(&'a [u8]),
82    /// One `(did, key)` entry: the key is trusted for that DID only.
83    One(&'a str, &'a [u8]),
84    /// A map keyed by issuer DID.
85    Map(&'a BTreeMap<String, Vec<u8>>),
86    /// A resolver from DID to key (`None` means unknown).
87    Resolver(&'a dyn Fn(&str) -> Option<Vec<u8>>),
88}
89
90impl<'a> Keys<'a> {
91    /// The map form of a key list given as `(did, key)` pairs.
92    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/// A credential that passed [`verify_robotics_credential`]: the bound issuer
106/// DID and the credentialSubject.
107#[derive(Debug, Clone)]
108pub struct Verified {
109    pub issuer: String,
110    pub subject: Value,
111}
112
113/// A verified `(issuer, subject)` pair, the input the threshold predicates
114/// count. They count the verified issuer, never a name written in a subject.
115///
116/// Only [`collect_verified`] makes these (the private field keeps callers from
117/// building one), so a hand-built `(did, subject)` pair, which proves nothing
118/// about who signed, can never reach a predicate.
119#[derive(Debug, Clone, PartialEq)]
120pub struct VerifiedPair {
121    issuer: String,
122    subject: Value,
123    _sealed: (),
124}
125
126impl VerifiedPair {
127    /// The verified issuer DID.
128    pub fn issuer(&self) -> &str {
129        &self.issuer
130    }
131    /// The verified credentialSubject.
132    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
145/// Parse the verifier's clock. An empty or malformed `now` is an error.
146pub 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
157/// The issuer DID from an `issuer` field: a non-empty string, or an object
158/// with a non-empty string `id`.
159pub 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
170/// The largest integer every port reads exactly (JavaScript's
171/// `Number.MAX_SAFE_INTEGER`, 2^53 - 1). A larger integer would round in a
172/// port that reads JSON numbers as doubles, so every language refuses it.
173pub const MAX_SAFE_INT: i64 = (1_i64 << 53) - 1;
174
175/// True for a real JSON integer within +-(2^53 - 1). A boolean is refused, and
176/// so is a number written with a fraction or exponent such as `5.0`.
177pub fn is_strict_int(v: &Value) -> bool {
178    strict_int(Some(v)).is_some()
179}
180
181/// The value as an `i64` when it is a real JSON integer within +-(2^53 - 1).
182pub 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
193/// The value as a finite `f64` when it is a JSON number (never a boolean).
194pub 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
199/// A strict protocol time in nanoseconds, or `None`.
200pub 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
205/// A cheap estimate of the JSON size of `value`, stopping once past `limit`.
206/// Iterative, so it is safe on deep input. Mirrors the Python `approx_size`.
207pub 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
233/// A reason when `value` nests too deeply or is too large, else `None`.
234pub 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
245/// Why `proof` is not an assertion by `issuer`, or `None` when it is.
246pub 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
261/// True when `keys` names no key at all: [`Keys::Embedded`], [`Keys::Pinned`]
262/// or an empty map.
263pub 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
271/// `keys`, or, when it names no key and `did` is given, a pin on `did`: the
272/// verifier knows which party must have signed (a self-attestation about a
273/// subject the caller pinned, or a link whose signer a verified earlier link
274/// named), so that party's did:key verifies under its own key.
275pub 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
282/// The Ed25519 key that belongs to `issuer`, or the reason there is none.
283/// With no key source this refuses every issuer; see
284/// [`resolve_issuer_key_trusted`] for the trusted-set rule.
285pub fn resolve_issuer_key(issuer: &str, keys: Keys<'_>) -> core::result::Result<Vec<u8>, String> {
286    resolve_issuer_key_trusted(issuer, keys, None)
287}
288
289/// The Ed25519 key that belongs to `issuer`, or the reason there is none.
290///
291/// With no key source (see [`no_key_source`]), a `did:key` issuer verifies
292/// under the key inside its DID only when [`Keys::Pinned`] names it or it is
293/// in the non-empty `trusted` set.
294pub 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
367/// Why `credential` is outside its window at `now_ns`, or `None`.
368pub 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/// Options for [`verify_robotics_credential`].
411#[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    /// Options with the given window mode and every other value at its default.
432    pub fn window(window: Window) -> Self {
433        Self {
434            window,
435            ..Self::default()
436        }
437    }
438}
439
440/// Verify a robotics credential and bind its proof to its issuer at `now_ns`.
441/// See the module docs for the order of checks. Returns the bound issuer and
442/// subject, or the reason it failed. Never panics.
443pub 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
509/// Verify many credentials and keep the good ones as [`VerifiedPair`]s. With
510/// `role_field`, a subject that names someone other than its issuer in that
511/// field is dropped too.
512///
513/// A threshold counts distinct parties, so the caller must say which parties
514/// exist: a key map (or resolver) in `keys`, or a non-empty member set in
515/// `trusted`. With neither, nothing is collected, because any number of
516/// freshly minted `did:key` identities would otherwise count. With a member
517/// set, every issuer must be in it.
518pub 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        // A credential nested past the no_std limit is skipped on its own,
533        // like any other that does not verify; the rest of the batch counts.
534        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
564/// The well-formed pairs (issuer starts with `did:`, subject an object).
565pub 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        // No key source: refused unless the caller names the issuer.
635        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/// Test helpers shared by the robotics test modules.
725#[cfg(test)]
726pub(crate) mod test_keys {
727    use super::*;
728
729    /// A clock inside the windows the robotics tests build credentials with.
730    pub const TNOW: &str = "2026-01-01T00:30:00Z";
731
732    /// Trust `key` for the issuer the credential names (what a caller that
733    /// already knows which party signed does with a `{did: key}` map).
734    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    /// A resolver that returns `key` for any DID (a chain whose links share
742    /// one signer, checked link by link).
743    pub fn any_did(key: &[u8]) -> impl Fn(&str) -> Option<Vec<u8>> + '_ {
744        move |_| Some(key.to_vec())
745    }
746}