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
37use 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
46/// The deepest nesting a robotics credential may have.
47pub const MAX_NESTING: usize = 128;
48/// The largest robotics credential accepted, estimated before canonicalization.
49pub const MAX_CREDENTIAL_BYTES: usize = 1024 * 1024;
50/// The only proof purpose a robotics credential may carry.
51pub const ASSERTION_METHOD: &str = "assertionMethod";
52
53/// Which validity bounds a credential must carry. A present bound is always a
54/// strict protocol-time string and is always enforced.
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56pub enum Window {
57    /// Both `validFrom` and `validUntil` must be present.
58    Required,
59    /// `validFrom` must be present; `validUntil` is optional.
60    FromRequired,
61    /// Both bounds are optional.
62    IfPresent,
63}
64
65/// Where an issuer's Ed25519 key comes from.
66#[derive(Clone, Copy)]
67pub enum Keys<'a> {
68    /// No key from the caller. A `did:key` issuer verifies under the key
69    /// inside its DID only when a non-empty trusted-issuer set names it.
70    Embedded,
71    /// No key from the caller, and the caller pins the issuer it expects (a
72    /// self-attestation): a `did:key` issuer equal to this DID verifies under
73    /// the key inside its DID. Any other issuer is refused.
74    Pinned(&'a str),
75    /// A bare 32-byte key. Accepted only for a `did:key` issuer, and only when
76    /// it equals the key inside the DID.
77    Bare(&'a [u8]),
78    /// One `(did, key)` entry: the key is trusted for that DID only.
79    One(&'a str, &'a [u8]),
80    /// A map keyed by issuer DID.
81    Map(&'a BTreeMap<String, Vec<u8>>),
82    /// A resolver from DID to key (`None` means unknown).
83    Resolver(&'a dyn Fn(&str) -> Option<Vec<u8>>),
84}
85
86impl<'a> Keys<'a> {
87    /// The map form of a key list given as `(did, key)` pairs.
88    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/// A credential that passed [`verify_robotics_credential`]: the bound issuer
102/// DID and the credentialSubject.
103#[derive(Debug, Clone)]
104pub struct Verified {
105    pub issuer: String,
106    pub subject: Value,
107}
108
109/// A verified `(issuer, subject)` pair, the input the threshold predicates
110/// count. They count the verified issuer, never a name written in a subject.
111///
112/// Only [`collect_verified`] makes these (the private field keeps callers from
113/// building one), so a hand-built `(did, subject)` pair, which proves nothing
114/// about who signed, can never reach a predicate.
115#[derive(Debug, Clone, PartialEq)]
116pub struct VerifiedPair {
117    issuer: String,
118    subject: Value,
119    _sealed: (),
120}
121
122impl VerifiedPair {
123    /// The verified issuer DID.
124    pub fn issuer(&self) -> &str {
125        &self.issuer
126    }
127    /// The verified credentialSubject.
128    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
141/// Parse the verifier's clock. An empty or malformed `now` is an error.
142pub 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
153/// The issuer DID from an `issuer` field: a non-empty string, or an object
154/// with a non-empty string `id`.
155pub 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
166/// The largest integer every port reads exactly (JavaScript's
167/// `Number.MAX_SAFE_INTEGER`, 2^53 - 1). A larger integer would round in a
168/// port that reads JSON numbers as doubles, so every language refuses it.
169pub const MAX_SAFE_INT: i64 = (1_i64 << 53) - 1;
170
171/// True for a real JSON integer within +-(2^53 - 1). A boolean is refused, and
172/// so is a number written with a fraction or exponent such as `5.0`.
173pub fn is_strict_int(v: &Value) -> bool {
174    strict_int(Some(v)).is_some()
175}
176
177/// The value as an `i64` when it is a real JSON integer within +-(2^53 - 1).
178pub 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
189/// The value as a finite `f64` when it is a JSON number (never a boolean).
190pub 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
195/// A strict protocol time in nanoseconds, or `None`.
196pub 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
201/// A cheap estimate of the JSON size of `value`, stopping once past `limit`.
202/// Iterative, so it is safe on deep input. Mirrors the Python `approx_size`.
203pub 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
229/// A reason when `value` nests too deeply or is too large, else `None`.
230pub 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
240/// Why `proof` is not an assertion by `issuer`, or `None` when it is.
241pub 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
255/// True when `keys` names no key at all: [`Keys::Embedded`], [`Keys::Pinned`]
256/// or an empty map.
257pub 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
265/// `keys`, or, when it names no key and `did` is given, a pin on `did`: the
266/// verifier knows which party must have signed (a self-attestation about a
267/// subject the caller pinned, or a link whose signer a verified earlier link
268/// named), so that party's did:key verifies under its own key.
269pub 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
276/// The Ed25519 key that belongs to `issuer`, or the reason there is none.
277/// With no key source this refuses every issuer; see
278/// [`resolve_issuer_key_trusted`] for the trusted-set rule.
279pub fn resolve_issuer_key(issuer: &str, keys: Keys<'_>) -> std::result::Result<Vec<u8>, String> {
280    resolve_issuer_key_trusted(issuer, keys, None)
281}
282
283/// The Ed25519 key that belongs to `issuer`, or the reason there is none.
284///
285/// With no key source (see [`no_key_source`]), a `did:key` issuer verifies
286/// under the key inside its DID only when [`Keys::Pinned`] names it or it is
287/// in the non-empty `trusted` set.
288pub 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
361/// Why `credential` is outside its window at `now_ns`, or `None`.
362pub 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/// Options for [`verify_robotics_credential`].
404#[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    /// Options with the given window mode and every other value at its default.
425    pub fn window(window: Window) -> Self {
426        Self {
427            window,
428            ..Self::default()
429        }
430    }
431}
432
433/// Verify a robotics credential and bind its proof to its issuer at `now_ns`.
434/// See the module docs for the order of checks. Returns the bound issuer and
435/// subject, or the reason it failed. Never panics.
436pub 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
501/// Verify many credentials and keep the good ones as [`VerifiedPair`]s. With
502/// `role_field`, a subject that names someone other than its issuer in that
503/// field is dropped too.
504///
505/// A threshold counts distinct parties, so the caller must say which parties
506/// exist: a key map (or resolver) in `keys`, or a non-empty member set in
507/// `trusted`. With neither, nothing is collected, because any number of
508/// freshly minted `did:key` identities would otherwise count. With a member
509/// set, every issuer must be in it.
510pub 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
551/// The well-formed pairs (issuer starts with `did:`, subject an object).
552pub 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        // No key source: refused unless the caller names the issuer.
622        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/// Test helpers shared by the robotics test modules.
712#[cfg(test)]
713pub(crate) mod test_keys {
714    use super::*;
715
716    /// A clock inside the windows the robotics tests build credentials with.
717    pub const TNOW: &str = "2026-01-01T00:30:00Z";
718
719    /// Trust `key` for the issuer the credential names (what a caller that
720    /// already knows which party signed does with a `{did: key}` map).
721    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    /// A resolver that returns `key` for any DID (a chain whose links share
729    /// one signer, checked link by link).
730    pub fn any_did(key: &[u8]) -> impl Fn(&str) -> Option<Vec<u8>> + '_ {
731        move |_| Some(key.to_vec())
732    }
733}