vouch-core 4.2.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
//! How deeply JSON may nest, checked before anything recursive touches it.
//!
//! Reading JSON (serde_json) and walking it are recursive, so the stack they
//! need grows with how deeply the text nests arrays and objects. On a laptop
//! the stack is large and has a guard page. On a microcontroller it is a few
//! kilobytes with nothing below it, and running off the end silently
//! overwrites other memory. So the `no_std` build refuses any JSON text that
//! nests deeper than [`NO_STD_MAX_NESTING`] levels, with a scan of the raw
//! bytes that uses no recursion, before the text is parsed. Protocol objects
//! nest about ten levels deep, so real credentials never come near it.
//!
//! The `std` build keeps its existing limits (serde_json's own 128 levels and
//! the per-input limits elsewhere in the core), so nothing changes there.

#[allow(unused_imports)]
use crate::prelude::*;

use serde_json::Value;

use crate::error::{CoreError, Result};

/// The deepest JSON nesting the `no_std` build reads: `[[1]]` nests 2 levels.
pub const NO_STD_MAX_NESTING: usize = 32;

/// Whether JSON text nests objects and lists more than `limit` deep: one scan
/// of the raw bytes, before parsing. Every `[` or `{` outside a string adds a
/// level and every `]` or `}` takes one away (escapes inside strings are
/// honoured, and a string with no closing quote runs to the end), so the
/// answer does not depend on what else is wrong with the text.
pub(crate) fn text_too_deep(text: &[u8], limit: usize) -> bool {
    let mut depth: i64 = 0;
    let mut i = 0;
    while i < text.len() {
        match text[i] {
            b'"' => {
                i += 1;
                while i < text.len() {
                    match text[i] {
                        b'"' => {
                            i += 1;
                            break;
                        }
                        b'\\' if i + 1 < text.len() => i += 2,
                        b'\\' => break,
                        _ => i += 1,
                    }
                }
                continue;
            }
            b'[' | b'{' => {
                depth += 1;
                if depth > limit as i64 {
                    return true;
                }
            }
            b']' | b'}' => depth -= 1,
            _ => {}
        }
        i += 1;
    }
    false
}

/// The text of the refusal for JSON nested past [`NO_STD_MAX_NESTING`].
pub const TOO_DEEP: &str = "json: nested more than 32 levels deep, the limit of the no_std build";

/// The refusal for JSON nested past [`NO_STD_MAX_NESTING`].
pub fn too_deep() -> CoreError {
    CoreError::Json(TOO_DEEP.into())
}

/// The JSON a public function takes, as the depth guard sees it.
#[cfg_attr(feature = "std", allow(dead_code))]
pub(crate) trait Nested {
    /// Whether it nests arrays or objects deeper than `limit` (a walk with
    /// its own stack, no recursion).
    fn nests_past(&self, limit: usize) -> bool;
}

impl Nested for Value {
    fn nests_past(&self, limit: usize) -> bool {
        crate::attenuation::json_nesting_exceeds(self, limit)
    }
}

impl Nested for serde_json::Map<String, Value> {
    fn nests_past(&self, limit: usize) -> bool {
        limit == 0 || self.values().any(|v| v.nests_past(limit - 1))
    }
}

impl<K, V: Nested> Nested for alloc::collections::BTreeMap<K, V> {
    fn nests_past(&self, limit: usize) -> bool {
        limit == 0 || self.values().any(|v| v.nests_past(limit - 1))
    }
}

/// [`Nested`] for a struct that carries JSON in the named fields: it nests
/// too deeply when any of them does.
macro_rules! nested_fields {
    ($ty:ty; $($field:ident),+ $(,)?) => {
        impl $crate::nesting::Nested for $ty {
            fn nests_past(&self, limit: usize) -> bool {
                false $(|| $crate::nesting::Nested::nests_past(&self.$field, limit))+
            }
        }
    };
}
pub(crate) use nested_fields;

impl<T: Nested> Nested for [T] {
    fn nests_past(&self, limit: usize) -> bool {
        self.iter().any(|v| v.nests_past(limit))
    }
}

impl<T: Nested> Nested for Vec<T> {
    fn nests_past(&self, limit: usize) -> bool {
        self.as_slice().nests_past(limit)
    }
}

impl<T: Nested> Nested for Option<T> {
    fn nests_past(&self, limit: usize) -> bool {
        self.as_ref().is_some_and(|v| v.nests_past(limit))
    }
}

impl<T: Nested + ?Sized> Nested for &T {
    fn nests_past(&self, limit: usize) -> bool {
        (**self).nests_past(limit)
    }
}

impl<T: Nested + ?Sized> Nested for &mut T {
    fn nests_past(&self, limit: usize) -> bool {
        (**self).nests_past(limit)
    }
}

/// The first statement of every public function that takes JSON values: in
/// a `no_std` build, return `$refusal` (that function's fail-closed answer)
/// when any of the values nests past [`NO_STD_MAX_NESTING`]. Serde_json's
/// clone, comparison, printing and drop all recurse, so this runs before any
/// of them. The `std` build compiles it away.
///
/// Values the function owns (taken by value) go after `drop`, as in
/// `deep_guard!(refusal; attributes; drop credential_status)` or
/// `deep_guard!(refusal; drop credential_status)`. On a refusal they are taken
/// apart with [`drop_flat`] before the return, so a deep owned value is never
/// dropped by serde_json's recursive drop.
macro_rules! deep_guard {
    ($refusal:expr; drop $($owned:ident),+ $(,)?) => {
        #[cfg(not(feature = "std"))]
        if false
            $(|| $crate::nesting::Nested::nests_past(
                &$owned,
                $crate::nesting::NO_STD_MAX_NESTING,
            ))+
        {
            $($crate::nesting::drop_flat_all($owned);)+
            return $refusal;
        }
    };
    ($refusal:expr; $($value:expr),+ ; drop $($owned:ident),+ $(,)?) => {
        #[cfg(not(feature = "std"))]
        if false
            $(|| $crate::nesting::Nested::nests_past(
                &$value,
                $crate::nesting::NO_STD_MAX_NESTING,
            ))+
            $(|| $crate::nesting::Nested::nests_past(
                &$owned,
                $crate::nesting::NO_STD_MAX_NESTING,
            ))+
        {
            $($crate::nesting::drop_flat_all($owned);)+
            return $refusal;
        }
    };
    ($refusal:expr; $($value:expr),+ $(,)?) => {
        #[cfg(not(feature = "std"))]
        if false
            $(|| $crate::nesting::Nested::nests_past(
                &$value,
                $crate::nesting::NO_STD_MAX_NESTING,
            ))+
        {
            return $refusal;
        }
    };
}
pub(crate) use deep_guard;

/// Whether `value` nests past [`NO_STD_MAX_NESTING`] in a `no_std` build
/// (always false with `std`). For functions that take a batch and skip each
/// deep element on its own instead of refusing the whole batch.
#[inline]
pub(crate) fn too_deep_here<T: Nested + ?Sized>(value: &T) -> bool {
    #[cfg(not(feature = "std"))]
    {
        value.nests_past(NO_STD_MAX_NESTING)
    }
    #[cfg(feature = "std")]
    {
        let _ = value;
        false
    }
}

/// Drop a JSON value without recursion: each array or object hands its
/// members to a heap stack before it goes, so only flat containers are ever
/// dropped. For a deep value the core owns and refuses (serde_json's own drop
/// recurses once per level).
pub(crate) fn drop_flat(value: Value) {
    let mut pending = vec![value];
    while let Some(v) = pending.pop() {
        match v {
            Value::Array(items) => pending.extend(items),
            Value::Object(map) => pending.extend(map.into_iter().map(|(_, v)| v)),
            _ => {}
        }
    }
}

/// [`drop_flat`] for every value in `values`, such as an `Option<Value>`.
#[allow(dead_code)]
pub(crate) fn drop_flat_all<I: IntoIterator<Item = Value>>(values: I) {
    for value in values {
        drop_flat(value);
    }
}

/// Refuse JSON text that nests past [`NO_STD_MAX_NESTING`] in a `no_std`
/// build. The `std` build accepts it here and applies its own limits.
#[inline]
pub(crate) fn check_text(text: &[u8]) -> Result<()> {
    #[cfg(not(feature = "std"))]
    if text_too_deep(text, NO_STD_MAX_NESTING) {
        return Err(too_deep());
    }
    let _ = text;
    Ok(())
}

/// Refuse a JSON value that nests past [`NO_STD_MAX_NESTING`] in a `no_std`
/// build (a walk with its own stack, no recursion). For values the caller
/// built or parsed itself.
#[inline]
pub fn check_value(value: &Value) -> Result<()> {
    #[cfg(not(feature = "std"))]
    if value.nests_past(NO_STD_MAX_NESTING) {
        return Err(too_deep());
    }
    let _ = value;
    Ok(())
}

/// Parse JSON text into a [`Value`], refusing text nested past
/// [`NO_STD_MAX_NESTING`] in a `no_std` build before serde_json reads it.
/// Firmware should read every JSON input it hands to the core with this.
pub fn parse(text: &str) -> Result<Value> {
    check_text(text.as_bytes())?;
    serde_json::from_str(text).map_err(|e| CoreError::Json(format!("json: {e}")))
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Public functions that take JSON but read only scalars out of it, or
    /// walk it with their own stack (JCS and the digests over it), so deep
    /// input costs them no stack.
    const UNGUARDED: &[&str] = &[
        "as_int",
        "clock_skew_from_json",
        "json_nesting_exceeds",
        "is_strict_int",
        "strict_int",
        "finite_number",
        "time_ns",
        "issuer_id",
        "issuer_did",
        "valid_cap",
        "parse_window",
        "parse_windows",
        "parse_zones",
        "is_canary_value",
        "wipe_secrets",
        "approx_size",
        "encoded_size",
        "canonicalize",
        "canonicalize_to_string",
        "config_hash",
        "provenance_attestation_id",
        "report_digest",
        "integrity_attestation_hash",
        "encode_passport",
        "fork_digest_step",
        "predecessor_key",
        "parse",
        "check_value",
        "nests_past",
        // A walk with its own stack (on the heap).
        "wipe_strings",
        // Part of the std build only.
        "secret_json_text",
        // Read only the type, or one scalar, of the value given.
        "py_type_name",
        "parse_value_ns",
        "check_skew",
    ];

    /// Methods that store JSON or hand back what is already there (a
    /// constructor, an accessor) without walking it.
    const UNGUARDED_METHODS: &[&str] = &[
        "new",
        "reset",
        "with_limits",
        "with_log",
        "head",
        "genesis",
        "entries",
        "count",
        "limits",
        "now_ns",
        "contains",
        "issuer",
        "subject",
    ];

    /// Types that carry JSON and that callers can fill in: the guard checks
    /// them (each has a `Nested` impl).
    const GUARDED_TYPES: &[&str] = &[
        "Value",
        "AuthorityFacts",
        "BuildConformanceAttestation",
        "BuildConsentEvidence",
        "BuildCredentialOptions",
        "BuildDelegationLease",
        "BuildHandoff",
        "BuildHumanHandover",
        "BuildProvenance",
        "BuildRobotHeartbeat",
        "BuildSafetyEvidence",
        "BuildSafetyRecord",
        "BuildWearAttestation",
        "ChainOptions",
        "DecisionInput",
        "DelegationLinkInput",
        "FleetOptions",
        "FleetResult",
        "IssueRequest",
        "MintRobotIdentity",
        "MotionCollector",
        "Proofs",
        "Resolution",
        "SafetyRecordCheck",
        "SetMembers",
        "SignReasonedActionOptions",
    ];

    /// Types that carry JSON only the core puts there: results it built, the
    /// sealed `VerifiedPair` (only `collect_verified` makes one, and it skips
    /// deep credentials), logs it appended to, and the did:webvh log set (read
    /// by its own reader, which refuses deep lines).
    const SEALED_TYPES: &[&str] = &[
        "BlackBoxLog",
        "ChainWalk",
        "Decision",
        "DidWebvhVerifyOutcome",
        "IdentityChainResult",
        "LogSet",
        "PerceptionLog",
        "RobotIdentityChainResult",
        "SafetyEventLog",
        "Verified",
        "VerifiedPair",
    ];

    fn word(text: &str, w: &str) -> bool {
        text.match_indices(w).any(|(i, _)| {
            let before = text[..i].chars().last();
            let after = text[i + w.len()..].chars().next();
            !before.is_some_and(|c| c.is_alphanumeric() || c == '_')
                && !after.is_some_and(|c| c.is_alphanumeric() || c == '_')
        })
    }

    /// Whether a parameter type carries JSON the guard checks.
    fn guarded_type(ty: &str) -> bool {
        GUARDED_TYPES.iter().any(|t| word(ty, t))
    }

    /// The text from `open` (a bracket) to its match, without the brackets.
    fn bracketed(text: &str, open: usize) -> (&str, usize) {
        let (o, c) = match &text[open..open + 1] {
            "(" => ('(', ')'),
            "{" => ('{', '}'),
            _ => ('<', '>'),
        };
        let mut depth = 0;
        for (i, ch) in text[open..].char_indices() {
            if ch == o {
                depth += 1;
            } else if ch == c {
                depth -= 1;
                if depth == 0 {
                    return (&text[open + 1..open + i], open + i);
                }
            }
        }
        panic!("unbalanced brackets");
    }

    /// Split a parameter list at top-level commas.
    fn params(list: &str) -> Vec<String> {
        let (mut out, mut cur, mut depth) = (Vec::new(), String::new(), 0i32);
        for ch in list.chars() {
            match ch {
                '<' | '(' | '[' => depth += 1,
                '>' | ')' | ']' => depth -= 1,
                ',' if depth == 0 => {
                    out.push(core::mem::take(&mut cur));
                    continue;
                }
                _ => {}
            }
            cur.push(ch);
        }
        out.push(cur);
        out.into_iter()
            .map(|p| p.trim().to_string())
            .filter(|p| !p.is_empty())
            .collect()
    }

    fn sources() -> Vec<(String, String)> {
        let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/src");
        let std_only = [
            "recovery.rs",
            "recovery_json.rs",
            "threshold.rs",
            "threshold_json.rs",
        ];
        let mut out = Vec::new();
        for entry in std::fs::read_dir(dir).unwrap() {
            let path = entry.unwrap().path();
            let file = path.file_name().unwrap().to_str().unwrap().to_string();
            if !file.ends_with(".rs") || std_only.contains(&file.as_str()) {
                continue;
            }
            let text = std::fs::read_to_string(&path).unwrap();
            let end = text.find("\n#[cfg(test)]\nmod ").unwrap_or(text.len());
            out.push((file, text[..end].to_string()));
        }
        out
    }

    /// Every public type that carries JSON is in one of the two lists, so a
    /// new one cannot slip past the scan below.
    #[test]
    fn every_json_carrying_type_is_listed() {
        let mut known: Vec<String> = GUARDED_TYPES
            .iter()
            .chain(SEALED_TYPES)
            .map(|t| t.to_string())
            .collect();
        let mut unlisted = Vec::new();
        loop {
            let mut grew = false;
            for (file, text) in sources() {
                for kw in ["\npub struct ", "\npub enum ", "\npub type "] {
                    for (at, _) in text.match_indices(kw) {
                        let rest = &text[at + kw.len()..];
                        let name: String = rest
                            .chars()
                            .take_while(|c| c.is_alphanumeric() || *c == '_')
                            .collect();
                        let body_end = rest
                            .find("\n}")
                            .or_else(|| rest.find(';'))
                            .unwrap_or(rest.len());
                        let body = &rest[name.len()..body_end];
                        let carries = word(body, "Value")
                            || known.iter().any(|k| k != &name && word(body, k));
                        if carries && !known.contains(&name) {
                            unlisted.push(format!("{file}: {name}"));
                            known.push(name);
                            grew = true;
                        }
                    }
                }
            }
            if !grew {
                break;
            }
        }
        assert!(
            unlisted.is_empty(),
            "add to GUARDED_TYPES or SEALED_TYPES: {unlisted:#?}"
        );
    }

    /// Every public function or method that takes JSON the caller can fill in
    /// starts with the depth guard over all of it (or skips deep elements one
    /// by one), so the no_std build refuses deep input before serde_json's
    /// recursive clone, comparison, printing or drop can touch it. Any
    /// indentation, impl methods (`self` counts when its type carries JSON),
    /// generics, and parameters whose type is a struct holding JSON.
    #[test]
    fn every_public_json_entry_point_is_guarded() {
        let mut missing = Vec::new();
        let mut guarded = 0;
        for (file, text) in sources() {
            let mut impl_type = String::new();
            let mut pos = 0;
            for line in text.split_inclusive('\n') {
                let start = pos;
                pos += line.len();
                if let Some(rest) = line.strip_prefix("impl") {
                    let head = rest.split('{').next().unwrap_or("");
                    let head = head.rsplit(" for ").next().unwrap_or(head);
                    let head = if head.trim_start().starts_with('<') {
                        let h = head.trim_start();
                        &h[bracketed(h, 0).1 + 1..]
                    } else {
                        head
                    };
                    impl_type = head
                        .trim()
                        .chars()
                        .take_while(|c| c.is_alphanumeric() || *c == '_')
                        .collect();
                    continue;
                }
                if !line.starts_with(|c: char| c.is_whitespace()) && !line.starts_with("pub fn ") {
                    if !line.trim().is_empty()
                        && !line.starts_with('}')
                        && !line.starts_with("//")
                        && !line.starts_with('#')
                    {
                        impl_type.clear();
                    }
                }
                let trimmed = line.trim_start();
                let Some(after) = trimmed.strip_prefix("pub fn ") else {
                    continue;
                };
                let method = line.starts_with(char::is_whitespace);
                let name: String = after
                    .chars()
                    .take_while(|c| c.is_alphanumeric() || *c == '_')
                    .collect();
                let fn_at = start + (line.len() - trimmed.len()) + 7 + name.len();
                let mut open = fn_at;
                if text[open..].starts_with('<') {
                    open = bracketed(&text, open).1 + 1;
                }
                let (list, close) = bracketed(&text, open);
                let mut json_params = Vec::new();
                for p in params(list) {
                    let bare = p.trim_start_matches('&').trim_start_matches("'_ ");
                    if bare == "self"
                        || bare == "mut self"
                        || p.ends_with("self") && !p.contains(':')
                    {
                        if method && GUARDED_TYPES.contains(&impl_type.as_str()) {
                            json_params.push("self".to_string());
                        }
                        continue;
                    }
                    let Some((pname, ty)) = p.split_once(':') else {
                        continue;
                    };
                    let pname = pname.trim().trim_start_matches("mut ").to_string();
                    let ty = ty.trim();
                    let map_of_value =
                        (word(ty, "Map") || word(ty, "BTreeMap") || word(ty, "HashMap"))
                            && word(ty, "Value");
                    if guarded_type(ty) || map_of_value {
                        json_params.push(pname);
                    }
                }
                if json_params.is_empty()
                    || UNGUARDED.contains(&name.as_str())
                    || (method && UNGUARDED_METHODS.contains(&name.as_str()))
                {
                    continue;
                }
                let body_open = close + text[close..].find('{').unwrap();
                let (body, _) = bracketed(&text, body_open);
                let first = body.trim_start();
                let ok = if first.starts_with("crate::nesting::deep_guard!(") {
                    let (args, _) = bracketed(first, first.find('(').unwrap());
                    // Every list after the refusal, owned (`drop`) values too.
                    let covered: Vec<&str> = args
                        .split(';')
                        .skip(1)
                        .flat_map(|list| list.trim().trim_start_matches("drop ").split(','))
                        .map(str::trim)
                        .collect();
                    json_params.iter().all(|p| covered.contains(&p.as_str()))
                } else {
                    body.contains("crate::nesting::too_deep_here(")
                        || body.contains("crate::nesting::Nested::nests_past(")
                };
                if ok {
                    guarded += 1;
                } else {
                    missing.push(format!("{file}: {impl_type}::{name} {json_params:?}"));
                }
            }
        }
        assert!(missing.is_empty(), "no depth guard over: {missing:#?}");
        assert!(guarded > 300, "only {guarded} guarded entry points found");
    }

    #[test]
    fn the_refusal_text_names_the_limit() {
        assert!(TOO_DEEP.contains(&format!(" {NO_STD_MAX_NESTING} levels")));
    }

    #[test]
    fn the_scan_counts_brackets_outside_strings() {
        let nested = |n: usize| format!("{}{}", "[".repeat(n), "]".repeat(n));
        assert!(!text_too_deep(nested(32).as_bytes(), 32));
        assert!(text_too_deep(nested(33).as_bytes(), 32));
        let quoted = format!("{{\"a\":\"{}\\\"{}\"}}", "[".repeat(100), "{".repeat(100));
        assert!(!text_too_deep(quoted.as_bytes(), 2));
    }

    #[test]
    #[cfg_attr(feature = "std", ignore = "checks the no_std build")]
    fn no_std_parse_refuses_past_the_cap() {
        let nested = |n: usize| format!("{}1{}", "[".repeat(n), "]".repeat(n));
        assert!(parse(&nested(NO_STD_MAX_NESTING)).is_ok());
        let e = parse(&nested(NO_STD_MAX_NESTING + 1)).unwrap_err();
        assert!(e.to_string().contains("no_std"), "{e}");
    }
}