Skip to main content

vouch_core/
nesting.rs

1//! How deeply JSON may nest, checked before anything recursive touches it.
2//!
3//! Reading JSON (serde_json) and walking it are recursive, so the stack they
4//! need grows with how deeply the text nests arrays and objects. On a laptop
5//! the stack is large and has a guard page. On a microcontroller it is a few
6//! kilobytes with nothing below it, and running off the end silently
7//! overwrites other memory. So the `no_std` build refuses any JSON text that
8//! nests deeper than [`NO_STD_MAX_NESTING`] levels, with a scan of the raw
9//! bytes that uses no recursion, before the text is parsed. Protocol objects
10//! nest about ten levels deep, so real credentials never come near it.
11//!
12//! The `std` build keeps its existing limits (serde_json's own 128 levels and
13//! the per-input limits elsewhere in the core), so nothing changes there.
14
15#[allow(unused_imports)]
16use crate::prelude::*;
17
18use serde_json::Value;
19
20use crate::error::{CoreError, Result};
21
22/// The deepest JSON nesting the `no_std` build reads: `[[1]]` nests 2 levels.
23pub const NO_STD_MAX_NESTING: usize = 32;
24
25/// Whether JSON text nests objects and lists more than `limit` deep: one scan
26/// of the raw bytes, before parsing. Every `[` or `{` outside a string adds a
27/// level and every `]` or `}` takes one away (escapes inside strings are
28/// honoured, and a string with no closing quote runs to the end), so the
29/// answer does not depend on what else is wrong with the text.
30pub(crate) fn text_too_deep(text: &[u8], limit: usize) -> bool {
31    let mut depth: i64 = 0;
32    let mut i = 0;
33    while i < text.len() {
34        match text[i] {
35            b'"' => {
36                i += 1;
37                while i < text.len() {
38                    match text[i] {
39                        b'"' => {
40                            i += 1;
41                            break;
42                        }
43                        b'\\' if i + 1 < text.len() => i += 2,
44                        b'\\' => break,
45                        _ => i += 1,
46                    }
47                }
48                continue;
49            }
50            b'[' | b'{' => {
51                depth += 1;
52                if depth > limit as i64 {
53                    return true;
54                }
55            }
56            b']' | b'}' => depth -= 1,
57            _ => {}
58        }
59        i += 1;
60    }
61    false
62}
63
64/// The text of the refusal for JSON nested past [`NO_STD_MAX_NESTING`].
65pub const TOO_DEEP: &str = "json: nested more than 32 levels deep, the limit of the no_std build";
66
67/// The refusal for JSON nested past [`NO_STD_MAX_NESTING`].
68pub fn too_deep() -> CoreError {
69    CoreError::Json(TOO_DEEP.into())
70}
71
72/// The JSON a public function takes, as the depth guard sees it.
73#[cfg_attr(feature = "std", allow(dead_code))]
74pub(crate) trait Nested {
75    /// Whether it nests arrays or objects deeper than `limit` (a walk with
76    /// its own stack, no recursion).
77    fn nests_past(&self, limit: usize) -> bool;
78}
79
80impl Nested for Value {
81    fn nests_past(&self, limit: usize) -> bool {
82        crate::attenuation::json_nesting_exceeds(self, limit)
83    }
84}
85
86impl Nested for serde_json::Map<String, Value> {
87    fn nests_past(&self, limit: usize) -> bool {
88        limit == 0 || self.values().any(|v| v.nests_past(limit - 1))
89    }
90}
91
92impl<K, V: Nested> Nested for alloc::collections::BTreeMap<K, V> {
93    fn nests_past(&self, limit: usize) -> bool {
94        limit == 0 || self.values().any(|v| v.nests_past(limit - 1))
95    }
96}
97
98/// [`Nested`] for a struct that carries JSON in the named fields: it nests
99/// too deeply when any of them does.
100macro_rules! nested_fields {
101    ($ty:ty; $($field:ident),+ $(,)?) => {
102        impl $crate::nesting::Nested for $ty {
103            fn nests_past(&self, limit: usize) -> bool {
104                false $(|| $crate::nesting::Nested::nests_past(&self.$field, limit))+
105            }
106        }
107    };
108}
109pub(crate) use nested_fields;
110
111impl<T: Nested> Nested for [T] {
112    fn nests_past(&self, limit: usize) -> bool {
113        self.iter().any(|v| v.nests_past(limit))
114    }
115}
116
117impl<T: Nested> Nested for Vec<T> {
118    fn nests_past(&self, limit: usize) -> bool {
119        self.as_slice().nests_past(limit)
120    }
121}
122
123impl<T: Nested> Nested for Option<T> {
124    fn nests_past(&self, limit: usize) -> bool {
125        self.as_ref().is_some_and(|v| v.nests_past(limit))
126    }
127}
128
129impl<T: Nested + ?Sized> Nested for &T {
130    fn nests_past(&self, limit: usize) -> bool {
131        (**self).nests_past(limit)
132    }
133}
134
135impl<T: Nested + ?Sized> Nested for &mut T {
136    fn nests_past(&self, limit: usize) -> bool {
137        (**self).nests_past(limit)
138    }
139}
140
141/// The first statement of every public function that takes JSON values: in
142/// a `no_std` build, return `$refusal` (that function's fail-closed answer)
143/// when any of the values nests past [`NO_STD_MAX_NESTING`]. Serde_json's
144/// clone, comparison, printing and drop all recurse, so this runs before any
145/// of them. The `std` build compiles it away.
146///
147/// Values the function owns (taken by value) go after `drop`, as in
148/// `deep_guard!(refusal; attributes; drop credential_status)` or
149/// `deep_guard!(refusal; drop credential_status)`. On a refusal they are taken
150/// apart with [`drop_flat`] before the return, so a deep owned value is never
151/// dropped by serde_json's recursive drop.
152macro_rules! deep_guard {
153    ($refusal:expr; drop $($owned:ident),+ $(,)?) => {
154        #[cfg(not(feature = "std"))]
155        if false
156            $(|| $crate::nesting::Nested::nests_past(
157                &$owned,
158                $crate::nesting::NO_STD_MAX_NESTING,
159            ))+
160        {
161            $($crate::nesting::drop_flat_all($owned);)+
162            return $refusal;
163        }
164    };
165    ($refusal:expr; $($value:expr),+ ; drop $($owned:ident),+ $(,)?) => {
166        #[cfg(not(feature = "std"))]
167        if false
168            $(|| $crate::nesting::Nested::nests_past(
169                &$value,
170                $crate::nesting::NO_STD_MAX_NESTING,
171            ))+
172            $(|| $crate::nesting::Nested::nests_past(
173                &$owned,
174                $crate::nesting::NO_STD_MAX_NESTING,
175            ))+
176        {
177            $($crate::nesting::drop_flat_all($owned);)+
178            return $refusal;
179        }
180    };
181    ($refusal:expr; $($value:expr),+ $(,)?) => {
182        #[cfg(not(feature = "std"))]
183        if false
184            $(|| $crate::nesting::Nested::nests_past(
185                &$value,
186                $crate::nesting::NO_STD_MAX_NESTING,
187            ))+
188        {
189            return $refusal;
190        }
191    };
192}
193pub(crate) use deep_guard;
194
195/// Whether `value` nests past [`NO_STD_MAX_NESTING`] in a `no_std` build
196/// (always false with `std`). For functions that take a batch and skip each
197/// deep element on its own instead of refusing the whole batch.
198#[inline]
199pub(crate) fn too_deep_here<T: Nested + ?Sized>(value: &T) -> bool {
200    #[cfg(not(feature = "std"))]
201    {
202        value.nests_past(NO_STD_MAX_NESTING)
203    }
204    #[cfg(feature = "std")]
205    {
206        let _ = value;
207        false
208    }
209}
210
211/// Drop a JSON value without recursion: each array or object hands its
212/// members to a heap stack before it goes, so only flat containers are ever
213/// dropped. For a deep value the core owns and refuses (serde_json's own drop
214/// recurses once per level).
215pub(crate) fn drop_flat(value: Value) {
216    let mut pending = vec![value];
217    while let Some(v) = pending.pop() {
218        match v {
219            Value::Array(items) => pending.extend(items),
220            Value::Object(map) => pending.extend(map.into_iter().map(|(_, v)| v)),
221            _ => {}
222        }
223    }
224}
225
226/// [`drop_flat`] for every value in `values`, such as an `Option<Value>`.
227#[allow(dead_code)]
228pub(crate) fn drop_flat_all<I: IntoIterator<Item = Value>>(values: I) {
229    for value in values {
230        drop_flat(value);
231    }
232}
233
234/// Refuse JSON text that nests past [`NO_STD_MAX_NESTING`] in a `no_std`
235/// build. The `std` build accepts it here and applies its own limits.
236#[inline]
237pub(crate) fn check_text(text: &[u8]) -> Result<()> {
238    #[cfg(not(feature = "std"))]
239    if text_too_deep(text, NO_STD_MAX_NESTING) {
240        return Err(too_deep());
241    }
242    let _ = text;
243    Ok(())
244}
245
246/// Refuse a JSON value that nests past [`NO_STD_MAX_NESTING`] in a `no_std`
247/// build (a walk with its own stack, no recursion). For values the caller
248/// built or parsed itself.
249#[inline]
250pub fn check_value(value: &Value) -> Result<()> {
251    #[cfg(not(feature = "std"))]
252    if value.nests_past(NO_STD_MAX_NESTING) {
253        return Err(too_deep());
254    }
255    let _ = value;
256    Ok(())
257}
258
259/// Parse JSON text into a [`Value`], refusing text nested past
260/// [`NO_STD_MAX_NESTING`] in a `no_std` build before serde_json reads it.
261/// Firmware should read every JSON input it hands to the core with this.
262pub fn parse(text: &str) -> Result<Value> {
263    check_text(text.as_bytes())?;
264    serde_json::from_str(text).map_err(|e| CoreError::Json(format!("json: {e}")))
265}
266
267#[cfg(test)]
268mod tests {
269    use super::*;
270
271    /// Public functions that take JSON but read only scalars out of it, or
272    /// walk it with their own stack (JCS and the digests over it), so deep
273    /// input costs them no stack.
274    const UNGUARDED: &[&str] = &[
275        "as_int",
276        "clock_skew_from_json",
277        "json_nesting_exceeds",
278        "is_strict_int",
279        "strict_int",
280        "finite_number",
281        "time_ns",
282        "issuer_id",
283        "issuer_did",
284        "valid_cap",
285        "parse_window",
286        "parse_windows",
287        "parse_zones",
288        "is_canary_value",
289        "wipe_secrets",
290        "approx_size",
291        "encoded_size",
292        "canonicalize",
293        "canonicalize_to_string",
294        "config_hash",
295        "provenance_attestation_id",
296        "report_digest",
297        "integrity_attestation_hash",
298        "encode_passport",
299        "fork_digest_step",
300        "predecessor_key",
301        "parse",
302        "check_value",
303        "nests_past",
304        // A walk with its own stack (on the heap).
305        "wipe_strings",
306        // Part of the std build only.
307        "secret_json_text",
308        // Read only the type, or one scalar, of the value given.
309        "py_type_name",
310        "parse_value_ns",
311        "check_skew",
312    ];
313
314    /// Methods that store JSON or hand back what is already there (a
315    /// constructor, an accessor) without walking it.
316    const UNGUARDED_METHODS: &[&str] = &[
317        "new",
318        "reset",
319        "with_limits",
320        "with_log",
321        "head",
322        "genesis",
323        "entries",
324        "count",
325        "limits",
326        "now_ns",
327        "contains",
328        "issuer",
329        "subject",
330    ];
331
332    /// Types that carry JSON and that callers can fill in: the guard checks
333    /// them (each has a `Nested` impl).
334    const GUARDED_TYPES: &[&str] = &[
335        "Value",
336        "AuthorityFacts",
337        "BuildConformanceAttestation",
338        "BuildConsentEvidence",
339        "BuildCredentialOptions",
340        "BuildDelegationLease",
341        "BuildHandoff",
342        "BuildHumanHandover",
343        "BuildProvenance",
344        "BuildRobotHeartbeat",
345        "BuildSafetyEvidence",
346        "BuildSafetyRecord",
347        "BuildWearAttestation",
348        "ChainOptions",
349        "CustodyCheck",
350        "DecisionInput",
351        "DelegationLinkInput",
352        "FleetOptions",
353        "FleetResult",
354        "IssueRequest",
355        "MintRobotIdentity",
356        "MotionCollector",
357        "Proofs",
358        "Resolution",
359        "SafetyRecordCheck",
360        "SetMembers",
361        "SignReasonedActionOptions",
362    ];
363
364    /// Types that carry JSON only the core puts there: results it built, the
365    /// sealed `VerifiedPair` (only `collect_verified` makes one, and it skips
366    /// deep credentials), logs it appended to, and the did:webvh log set (read
367    /// by its own reader, which refuses deep lines).
368    const SEALED_TYPES: &[&str] = &[
369        "BlackBoxLog",
370        "ChainWalk",
371        "Decision",
372        "DidWebvhVerifyOutcome",
373        "IdentityChainResult",
374        "LogSet",
375        "PerceptionLog",
376        "RobotIdentityChainResult",
377        "SafetyEventLog",
378        "Verified",
379        "VerifiedPair",
380    ];
381
382    fn word(text: &str, w: &str) -> bool {
383        text.match_indices(w).any(|(i, _)| {
384            let before = text[..i].chars().last();
385            let after = text[i + w.len()..].chars().next();
386            !before.is_some_and(|c| c.is_alphanumeric() || c == '_')
387                && !after.is_some_and(|c| c.is_alphanumeric() || c == '_')
388        })
389    }
390
391    /// Whether a parameter type carries JSON the guard checks.
392    fn guarded_type(ty: &str) -> bool {
393        GUARDED_TYPES.iter().any(|t| word(ty, t))
394    }
395
396    /// The text from `open` (a bracket) to its match, without the brackets.
397    fn bracketed(text: &str, open: usize) -> (&str, usize) {
398        let (o, c) = match &text[open..open + 1] {
399            "(" => ('(', ')'),
400            "{" => ('{', '}'),
401            _ => ('<', '>'),
402        };
403        let mut depth = 0;
404        for (i, ch) in text[open..].char_indices() {
405            if ch == o {
406                depth += 1;
407            } else if ch == c {
408                depth -= 1;
409                if depth == 0 {
410                    return (&text[open + 1..open + i], open + i);
411                }
412            }
413        }
414        panic!("unbalanced brackets");
415    }
416
417    /// Split a parameter list at top-level commas.
418    fn params(list: &str) -> Vec<String> {
419        let (mut out, mut cur, mut depth) = (Vec::new(), String::new(), 0i32);
420        for ch in list.chars() {
421            match ch {
422                '<' | '(' | '[' => depth += 1,
423                '>' | ')' | ']' => depth -= 1,
424                ',' if depth == 0 => {
425                    out.push(core::mem::take(&mut cur));
426                    continue;
427                }
428                _ => {}
429            }
430            cur.push(ch);
431        }
432        out.push(cur);
433        out.into_iter()
434            .map(|p| p.trim().to_string())
435            .filter(|p| !p.is_empty())
436            .collect()
437    }
438
439    fn sources() -> Vec<(String, String)> {
440        let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/src");
441        let std_only = [
442            "recovery.rs",
443            "recovery_json.rs",
444            "threshold.rs",
445            "threshold_json.rs",
446        ];
447        let mut out = Vec::new();
448        for entry in std::fs::read_dir(dir).unwrap() {
449            let path = entry.unwrap().path();
450            let file = path.file_name().unwrap().to_str().unwrap().to_string();
451            if !file.ends_with(".rs") || std_only.contains(&file.as_str()) {
452                continue;
453            }
454            let text = std::fs::read_to_string(&path).unwrap();
455            let end = text.find("\n#[cfg(test)]\nmod ").unwrap_or(text.len());
456            out.push((file, text[..end].to_string()));
457        }
458        out
459    }
460
461    /// Every public type that carries JSON is in one of the two lists, so a
462    /// new one cannot slip past the scan below.
463    #[test]
464    fn every_json_carrying_type_is_listed() {
465        let mut known: Vec<String> = GUARDED_TYPES
466            .iter()
467            .chain(SEALED_TYPES)
468            .map(|t| t.to_string())
469            .collect();
470        let mut unlisted = Vec::new();
471        loop {
472            let mut grew = false;
473            for (file, text) in sources() {
474                for kw in ["\npub struct ", "\npub enum ", "\npub type "] {
475                    for (at, _) in text.match_indices(kw) {
476                        let rest = &text[at + kw.len()..];
477                        let name: String = rest
478                            .chars()
479                            .take_while(|c| c.is_alphanumeric() || *c == '_')
480                            .collect();
481                        let body_end = rest
482                            .find("\n}")
483                            .or_else(|| rest.find(';'))
484                            .unwrap_or(rest.len());
485                        let body = &rest[name.len()..body_end];
486                        let carries = word(body, "Value")
487                            || known.iter().any(|k| k != &name && word(body, k));
488                        if carries && !known.contains(&name) {
489                            unlisted.push(format!("{file}: {name}"));
490                            known.push(name);
491                            grew = true;
492                        }
493                    }
494                }
495            }
496            if !grew {
497                break;
498            }
499        }
500        assert!(
501            unlisted.is_empty(),
502            "add to GUARDED_TYPES or SEALED_TYPES: {unlisted:#?}"
503        );
504    }
505
506    /// Every public function or method that takes JSON the caller can fill in
507    /// starts with the depth guard over all of it (or skips deep elements one
508    /// by one), so the no_std build refuses deep input before serde_json's
509    /// recursive clone, comparison, printing or drop can touch it. Any
510    /// indentation, impl methods (`self` counts when its type carries JSON),
511    /// generics, and parameters whose type is a struct holding JSON.
512    #[test]
513    fn every_public_json_entry_point_is_guarded() {
514        let mut missing = Vec::new();
515        let mut guarded = 0;
516        for (file, text) in sources() {
517            let mut impl_type = String::new();
518            let mut pos = 0;
519            for line in text.split_inclusive('\n') {
520                let start = pos;
521                pos += line.len();
522                if let Some(rest) = line.strip_prefix("impl") {
523                    let head = rest.split('{').next().unwrap_or("");
524                    let head = head.rsplit(" for ").next().unwrap_or(head);
525                    let head = if head.trim_start().starts_with('<') {
526                        let h = head.trim_start();
527                        &h[bracketed(h, 0).1 + 1..]
528                    } else {
529                        head
530                    };
531                    impl_type = head
532                        .trim()
533                        .chars()
534                        .take_while(|c| c.is_alphanumeric() || *c == '_')
535                        .collect();
536                    continue;
537                }
538                if !line.starts_with(|c: char| c.is_whitespace()) && !line.starts_with("pub fn ") {
539                    if !line.trim().is_empty()
540                        && !line.starts_with('}')
541                        && !line.starts_with("//")
542                        && !line.starts_with('#')
543                    {
544                        impl_type.clear();
545                    }
546                }
547                let trimmed = line.trim_start();
548                let Some(after) = trimmed.strip_prefix("pub fn ") else {
549                    continue;
550                };
551                let method = line.starts_with(char::is_whitespace);
552                let name: String = after
553                    .chars()
554                    .take_while(|c| c.is_alphanumeric() || *c == '_')
555                    .collect();
556                let fn_at = start + (line.len() - trimmed.len()) + 7 + name.len();
557                let mut open = fn_at;
558                if text[open..].starts_with('<') {
559                    open = bracketed(&text, open).1 + 1;
560                }
561                let (list, close) = bracketed(&text, open);
562                let mut json_params = Vec::new();
563                for p in params(list) {
564                    let bare = p.trim_start_matches('&').trim_start_matches("'_ ");
565                    if bare == "self"
566                        || bare == "mut self"
567                        || p.ends_with("self") && !p.contains(':')
568                    {
569                        if method && GUARDED_TYPES.contains(&impl_type.as_str()) {
570                            json_params.push("self".to_string());
571                        }
572                        continue;
573                    }
574                    let Some((pname, ty)) = p.split_once(':') else {
575                        continue;
576                    };
577                    let pname = pname.trim().trim_start_matches("mut ").to_string();
578                    let ty = ty.trim();
579                    let map_of_value =
580                        (word(ty, "Map") || word(ty, "BTreeMap") || word(ty, "HashMap"))
581                            && word(ty, "Value");
582                    if guarded_type(ty) || map_of_value {
583                        json_params.push(pname);
584                    }
585                }
586                if json_params.is_empty()
587                    || UNGUARDED.contains(&name.as_str())
588                    || (method && UNGUARDED_METHODS.contains(&name.as_str()))
589                {
590                    continue;
591                }
592                let body_open = close + text[close..].find('{').unwrap();
593                let (body, _) = bracketed(&text, body_open);
594                let first = body.trim_start();
595                let ok = if first.starts_with("crate::nesting::deep_guard!(") {
596                    let (args, _) = bracketed(first, first.find('(').unwrap());
597                    // Every list after the refusal, owned (`drop`) values too.
598                    let covered: Vec<&str> = args
599                        .split(';')
600                        .skip(1)
601                        .flat_map(|list| list.trim().trim_start_matches("drop ").split(','))
602                        .map(str::trim)
603                        .collect();
604                    json_params.iter().all(|p| covered.contains(&p.as_str()))
605                } else {
606                    body.contains("crate::nesting::too_deep_here(")
607                        || body.contains("crate::nesting::Nested::nests_past(")
608                };
609                if ok {
610                    guarded += 1;
611                } else {
612                    missing.push(format!("{file}: {impl_type}::{name} {json_params:?}"));
613                }
614            }
615        }
616        assert!(missing.is_empty(), "no depth guard over: {missing:#?}");
617        assert!(guarded > 300, "only {guarded} guarded entry points found");
618    }
619
620    #[test]
621    fn the_refusal_text_names_the_limit() {
622        assert!(TOO_DEEP.contains(&format!(" {NO_STD_MAX_NESTING} levels")));
623    }
624
625    #[test]
626    fn the_scan_counts_brackets_outside_strings() {
627        let nested = |n: usize| format!("{}{}", "[".repeat(n), "]".repeat(n));
628        assert!(!text_too_deep(nested(32).as_bytes(), 32));
629        assert!(text_too_deep(nested(33).as_bytes(), 32));
630        let quoted = format!("{{\"a\":\"{}\\\"{}\"}}", "[".repeat(100), "{".repeat(100));
631        assert!(!text_too_deep(quoted.as_bytes(), 2));
632    }
633
634    #[test]
635    #[cfg_attr(feature = "std", ignore = "checks the no_std build")]
636    fn no_std_parse_refuses_past_the_cap() {
637        let nested = |n: usize| format!("{}1{}", "[".repeat(n), "]".repeat(n));
638        assert!(parse(&nested(NO_STD_MAX_NESTING)).is_ok());
639        let e = parse(&nested(NO_STD_MAX_NESTING + 1)).unwrap_err();
640        assert!(e.to_string().contains("no_std"), "{e}");
641    }
642}