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