vouch-core 4.1.0

Vouch Protocol canonical core: JCS canonicalization, Ed25519 + ML-DSA proofs, did:key/multikey, Data Integrity (eddsa-jcs-2022), credentials, delegation, revocation. One byte-exact implementation shared by every language SDK via WASM and UniFFI/C-FFI.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
//! Shared verification for robotics credentials, the port of the Python
//! reference `vouch/robotics/_verify.py`.
//!
//! Every robotics verifier goes through [`verify_robotics_credential`]. It
//! answers one question: did the party named as `issuer` really sign this
//! credential, and is the credential usable at `now`? It checks, in order:
//!
//! 1. The input is a JSON object no deeper than [`MAX_NESTING`] levels and no
//!    larger than [`MAX_CREDENTIAL_BYTES`] (both before canonicalization).
//! 2. `type` is a string or a list of strings and lists the expected type.
//! 3. `credentialSubject` is an object.
//! 4. `issuer` is a DID (a string, or an object with a string `id`).
//! 5. `proof.proofPurpose` is `assertionMethod` and the DID part of
//!    `proof.verificationMethod` (before the first `#`) is exactly the issuer.
//! 6. The key belongs to the issuer. A `did:key` issuer's key is the one inside
//!    the DID; any other key a caller passes for it is refused. Any other DID
//!    needs its key from a map keyed by DID (or a resolver): a bare key is
//!    never trusted for it, because nothing ties that key to the DID.
//! 7. The eddsa-jcs-2022 proof verifies under that key.
//! 8. The window: a present `validFrom` / `validUntil` must be a strict
//!    protocol-time string, the [`Window`] mode says which bounds must exist,
//!    and `now` must fall inside it (an inverted window is refused).
//! 9. When a trusted-issuer set is given, the bound issuer is in it.
//!
//! With no key source at all ([`Keys::Embedded`], or an empty [`Keys::Map`]),
//! nothing says which party the caller trusts, and a credential signed by any
//! freshly minted `did:key` would verify. So the key inside a `did:key` issuer
//! is used only when the caller named that issuer: [`Keys::Pinned`] with the
//! issuer's DID (a self-attestation whose subject the caller pins), or a
//! non-empty trusted-issuer set that contains it. Otherwise the credential is
//! refused.
//!
//! Malformed input never panics and never errors: the result is
//! `Err(reason)`. Only a malformed `now` (the caller's own clock) is a
//! [`CoreError`], raised by the verifiers before they look at the credential.

use std::collections::{BTreeMap, HashSet};

use serde_json::Value;

use crate::attenuation::json_nesting_exceeds;
use crate::data_integrity;
use crate::error::{CoreError, Result};
use crate::time;

/// The deepest nesting a robotics credential may have.
pub const MAX_NESTING: usize = 128;
/// The largest robotics credential accepted, estimated before canonicalization.
pub const MAX_CREDENTIAL_BYTES: usize = 1024 * 1024;
/// The only proof purpose a robotics credential may carry.
pub const ASSERTION_METHOD: &str = "assertionMethod";

/// Which validity bounds a credential must carry. A present bound is always a
/// strict protocol-time string and is always enforced.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Window {
    /// Both `validFrom` and `validUntil` must be present.
    Required,
    /// `validFrom` must be present; `validUntil` is optional.
    FromRequired,
    /// Both bounds are optional.
    IfPresent,
}

/// Where an issuer's Ed25519 key comes from.
#[derive(Clone, Copy)]
pub enum Keys<'a> {
    /// No key from the caller. A `did:key` issuer verifies under the key
    /// inside its DID only when a non-empty trusted-issuer set names it.
    Embedded,
    /// No key from the caller, and the caller pins the issuer it expects (a
    /// self-attestation): a `did:key` issuer equal to this DID verifies under
    /// the key inside its DID. Any other issuer is refused.
    Pinned(&'a str),
    /// A bare 32-byte key. Accepted only for a `did:key` issuer, and only when
    /// it equals the key inside the DID.
    Bare(&'a [u8]),
    /// One `(did, key)` entry: the key is trusted for that DID only.
    One(&'a str, &'a [u8]),
    /// A map keyed by issuer DID.
    Map(&'a BTreeMap<String, Vec<u8>>),
    /// A resolver from DID to key (`None` means unknown).
    Resolver(&'a dyn Fn(&str) -> Option<Vec<u8>>),
}

impl<'a> Keys<'a> {
    /// The map form of a key list given as `(did, key)` pairs.
    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()
    }
}

/// A credential that passed [`verify_robotics_credential`]: the bound issuer
/// DID and the credentialSubject.
#[derive(Debug, Clone)]
pub struct Verified {
    pub issuer: String,
    pub subject: Value,
}

/// A verified `(issuer, subject)` pair, the input the threshold predicates
/// count. They count the verified issuer, never a name written in a subject.
///
/// Only [`collect_verified`] makes these (the private field keeps callers from
/// building one), so a hand-built `(did, subject)` pair, which proves nothing
/// about who signed, can never reach a predicate.
#[derive(Debug, Clone, PartialEq)]
pub struct VerifiedPair {
    issuer: String,
    subject: Value,
    _sealed: (),
}

impl VerifiedPair {
    /// The verified issuer DID.
    pub fn issuer(&self) -> &str {
        &self.issuer
    }
    /// The verified credentialSubject.
    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: (),
        }
    }
}

/// Parse the verifier's clock. An empty or malformed `now` is an error.
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())
    })
}

/// The issuer DID from an `issuer` field: a non-empty string, or an object
/// with a non-empty string `id`.
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,
    }
}

/// The largest integer every port reads exactly (JavaScript's
/// `Number.MAX_SAFE_INTEGER`, 2^53 - 1). A larger integer would round in a
/// port that reads JSON numbers as doubles, so every language refuses it.
pub const MAX_SAFE_INT: i64 = (1_i64 << 53) - 1;

/// True for a real JSON integer within +-(2^53 - 1). A boolean is refused, and
/// so is a number written with a fraction or exponent such as `5.0`.
pub fn is_strict_int(v: &Value) -> bool {
    strict_int(Some(v)).is_some()
}

/// The value as an `i64` when it is a real JSON integer within +-(2^53 - 1).
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))
}

/// The value as a finite `f64` when it is a JSON number (never a boolean).
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())
}

/// A strict protocol time in nanoseconds, or `None`.
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())
}

/// A cheap estimate of the JSON size of `value`, stopping once past `limit`.
/// Iterative, so it is safe on deep input. Mirrors the Python `approx_size`.
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
}

/// A reason when `value` nests too deeply or is too large, else `None`.
pub fn input_too_large(value: &Value, max_bytes: usize) -> Option<String> {
    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
}

/// Why `proof` is not an assertion by `issuer`, or `None` when it is.
pub fn proof_unbound_reason(proof: &Value, issuer: &str) -> Option<&'static str> {
    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"),
    }
}

/// True when `keys` names no key at all: [`Keys::Embedded`], [`Keys::Pinned`]
/// or an empty map.
pub fn no_key_source(keys: &Keys<'_>) -> bool {
    match keys {
        Keys::Embedded | Keys::Pinned(_) => true,
        Keys::Map(m) => m.is_empty(),
        _ => false,
    }
}

/// `keys`, or, when it names no key and `did` is given, a pin on `did`: the
/// verifier knows which party must have signed (a self-attestation about a
/// subject the caller pinned, or a link whose signer a verified earlier link
/// named), so that party's did:key verifies under its own key.
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,
    }
}

/// The Ed25519 key that belongs to `issuer`, or the reason there is none.
/// With no key source this refuses every issuer; see
/// [`resolve_issuer_key_trusted`] for the trusted-set rule.
pub fn resolve_issuer_key(issuer: &str, keys: Keys<'_>) -> std::result::Result<Vec<u8>, String> {
    resolve_issuer_key_trusted(issuer, keys, None)
}

/// The Ed25519 key that belongs to `issuer`, or the reason there is none.
///
/// With no key source (see [`no_key_source`]), a `did:key` issuer verifies
/// under the key inside its DID only when [`Keys::Pinned`] names it or it is
/// in the non-empty `trusted` set.
pub fn resolve_issuer_key_trusted(
    issuer: &str,
    keys: Keys<'_>,
    trusted: Option<&HashSet<String>>,
) -> std::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)
}

/// Why `credential` is outside its window at `now_ns`, or `None`.
pub fn window_reason(
    credential: &Value,
    window: Window,
    now_ns: i128,
    skew_seconds: i64,
) -> Option<String> {
    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())),
    }
}

/// Options for [`verify_robotics_credential`].
#[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<'_> {
    /// Options with the given window mode and every other value at its default.
    pub fn window(window: Window) -> Self {
        Self {
            window,
            ..Self::default()
        }
    }
}

/// Verify a robotics credential and bind its proof to its issuer at `now_ns`.
/// See the module docs for the order of checks. Returns the bound issuer and
/// subject, or the reason it failed. Never panics.
pub fn verify_robotics_credential(
    credential: &Value,
    keys: Keys<'_>,
    expected_type: Option<&str>,
    now_ns: i128,
    opts: VerifyOptions<'_>,
) -> std::result::Result<Verified, String> {
    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(),
    })
}

/// Verify many credentials and keep the good ones as [`VerifiedPair`]s. With
/// `role_field`, a subject that names someone other than its issuer in that
/// field is dropped too.
///
/// A threshold counts distinct parties, so the caller must say which parties
/// exist: a key map (or resolver) in `keys`, or a non-empty member set in
/// `trusted`. With neither, nothing is collected, because any number of
/// freshly minted `did:key` identities would otherwise count. With a member
/// set, every issuer must be in it.
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 {
        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
}

/// The well-formed pairs (issuer starts with `did:`, subject an object).
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);
        // No key source: refused unless the caller names the issuer.
        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());
    }
}

/// Test helpers shared by the robotics test modules.
#[cfg(test)]
pub(crate) mod test_keys {
    use super::*;

    /// A clock inside the windows the robotics tests build credentials with.
    pub const TNOW: &str = "2026-01-01T00:30:00Z";

    /// Trust `key` for the issuer the credential names (what a caller that
    /// already knows which party signed does with a `{did: key}` map).
    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),
        }
    }

    /// A resolver that returns `key` for any DID (a chain whose links share
    /// one signer, checked link by link).
    pub fn any_did(key: &[u8]) -> impl Fn(&str) -> Option<Vec<u8>> + '_ {
        move |_| Some(key.to_vec())
    }
}