1#[allow(unused_imports)]
16use crate::prelude::*;
17
18use serde_json::Value;
19
20use crate::error::{CoreError, Result};
21
22pub const NO_STD_MAX_NESTING: usize = 32;
24
25pub(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
64pub const TOO_DEEP: &str = "json: nested more than 32 levels deep, the limit of the no_std build";
66
67pub fn too_deep() -> CoreError {
69 CoreError::Json(TOO_DEEP.into())
70}
71
72#[cfg_attr(feature = "std", allow(dead_code))]
74pub(crate) trait Nested {
75 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
98macro_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
141macro_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#[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
211pub(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#[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#[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#[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
259pub 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 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 "wipe_strings",
306 "secret_json_text",
308 "py_type_name",
310 "parse_value_ns",
311 "check_skew",
312 ];
313
314 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 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 "DecisionInput",
350 "DelegationLinkInput",
351 "FleetOptions",
352 "FleetResult",
353 "IssueRequest",
354 "MintRobotIdentity",
355 "MotionCollector",
356 "Proofs",
357 "Resolution",
358 "SafetyRecordCheck",
359 "SetMembers",
360 "SignReasonedActionOptions",
361 ];
362
363 const SEALED_TYPES: &[&str] = &[
368 "BlackBoxLog",
369 "ChainWalk",
370 "Decision",
371 "DidWebvhVerifyOutcome",
372 "IdentityChainResult",
373 "LogSet",
374 "PerceptionLog",
375 "RobotIdentityChainResult",
376 "SafetyEventLog",
377 "Verified",
378 "VerifiedPair",
379 ];
380
381 fn word(text: &str, w: &str) -> bool {
382 text.match_indices(w).any(|(i, _)| {
383 let before = text[..i].chars().last();
384 let after = text[i + w.len()..].chars().next();
385 !before.is_some_and(|c| c.is_alphanumeric() || c == '_')
386 && !after.is_some_and(|c| c.is_alphanumeric() || c == '_')
387 })
388 }
389
390 fn guarded_type(ty: &str) -> bool {
392 GUARDED_TYPES.iter().any(|t| word(ty, t))
393 }
394
395 fn bracketed(text: &str, open: usize) -> (&str, usize) {
397 let (o, c) = match &text[open..open + 1] {
398 "(" => ('(', ')'),
399 "{" => ('{', '}'),
400 _ => ('<', '>'),
401 };
402 let mut depth = 0;
403 for (i, ch) in text[open..].char_indices() {
404 if ch == o {
405 depth += 1;
406 } else if ch == c {
407 depth -= 1;
408 if depth == 0 {
409 return (&text[open + 1..open + i], open + i);
410 }
411 }
412 }
413 panic!("unbalanced brackets");
414 }
415
416 fn params(list: &str) -> Vec<String> {
418 let (mut out, mut cur, mut depth) = (Vec::new(), String::new(), 0i32);
419 for ch in list.chars() {
420 match ch {
421 '<' | '(' | '[' => depth += 1,
422 '>' | ')' | ']' => depth -= 1,
423 ',' if depth == 0 => {
424 out.push(core::mem::take(&mut cur));
425 continue;
426 }
427 _ => {}
428 }
429 cur.push(ch);
430 }
431 out.push(cur);
432 out.into_iter()
433 .map(|p| p.trim().to_string())
434 .filter(|p| !p.is_empty())
435 .collect()
436 }
437
438 fn sources() -> Vec<(String, String)> {
439 let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/src");
440 let std_only = [
441 "recovery.rs",
442 "recovery_json.rs",
443 "threshold.rs",
444 "threshold_json.rs",
445 ];
446 let mut out = Vec::new();
447 for entry in std::fs::read_dir(dir).unwrap() {
448 let path = entry.unwrap().path();
449 let file = path.file_name().unwrap().to_str().unwrap().to_string();
450 if !file.ends_with(".rs") || std_only.contains(&file.as_str()) {
451 continue;
452 }
453 let text = std::fs::read_to_string(&path).unwrap();
454 let end = text.find("\n#[cfg(test)]\nmod ").unwrap_or(text.len());
455 out.push((file, text[..end].to_string()));
456 }
457 out
458 }
459
460 #[test]
463 fn every_json_carrying_type_is_listed() {
464 let mut known: Vec<String> = GUARDED_TYPES
465 .iter()
466 .chain(SEALED_TYPES)
467 .map(|t| t.to_string())
468 .collect();
469 let mut unlisted = Vec::new();
470 loop {
471 let mut grew = false;
472 for (file, text) in sources() {
473 for kw in ["\npub struct ", "\npub enum ", "\npub type "] {
474 for (at, _) in text.match_indices(kw) {
475 let rest = &text[at + kw.len()..];
476 let name: String = rest
477 .chars()
478 .take_while(|c| c.is_alphanumeric() || *c == '_')
479 .collect();
480 let body_end = rest
481 .find("\n}")
482 .or_else(|| rest.find(';'))
483 .unwrap_or(rest.len());
484 let body = &rest[name.len()..body_end];
485 let carries = word(body, "Value")
486 || known.iter().any(|k| k != &name && word(body, k));
487 if carries && !known.contains(&name) {
488 unlisted.push(format!("{file}: {name}"));
489 known.push(name);
490 grew = true;
491 }
492 }
493 }
494 }
495 if !grew {
496 break;
497 }
498 }
499 assert!(
500 unlisted.is_empty(),
501 "add to GUARDED_TYPES or SEALED_TYPES: {unlisted:#?}"
502 );
503 }
504
505 #[test]
512 fn every_public_json_entry_point_is_guarded() {
513 let mut missing = Vec::new();
514 let mut guarded = 0;
515 for (file, text) in sources() {
516 let mut impl_type = String::new();
517 let mut pos = 0;
518 for line in text.split_inclusive('\n') {
519 let start = pos;
520 pos += line.len();
521 if let Some(rest) = line.strip_prefix("impl") {
522 let head = rest.split('{').next().unwrap_or("");
523 let head = head.rsplit(" for ").next().unwrap_or(head);
524 let head = if head.trim_start().starts_with('<') {
525 let h = head.trim_start();
526 &h[bracketed(h, 0).1 + 1..]
527 } else {
528 head
529 };
530 impl_type = head
531 .trim()
532 .chars()
533 .take_while(|c| c.is_alphanumeric() || *c == '_')
534 .collect();
535 continue;
536 }
537 if !line.starts_with(|c: char| c.is_whitespace()) && !line.starts_with("pub fn ") {
538 if !line.trim().is_empty()
539 && !line.starts_with('}')
540 && !line.starts_with("//")
541 && !line.starts_with('#')
542 {
543 impl_type.clear();
544 }
545 }
546 let trimmed = line.trim_start();
547 let Some(after) = trimmed.strip_prefix("pub fn ") else {
548 continue;
549 };
550 let method = line.starts_with(char::is_whitespace);
551 let name: String = after
552 .chars()
553 .take_while(|c| c.is_alphanumeric() || *c == '_')
554 .collect();
555 let fn_at = start + (line.len() - trimmed.len()) + 7 + name.len();
556 let mut open = fn_at;
557 if text[open..].starts_with('<') {
558 open = bracketed(&text, open).1 + 1;
559 }
560 let (list, close) = bracketed(&text, open);
561 let mut json_params = Vec::new();
562 for p in params(list) {
563 let bare = p.trim_start_matches('&').trim_start_matches("'_ ");
564 if bare == "self"
565 || bare == "mut self"
566 || p.ends_with("self") && !p.contains(':')
567 {
568 if method && GUARDED_TYPES.contains(&impl_type.as_str()) {
569 json_params.push("self".to_string());
570 }
571 continue;
572 }
573 let Some((pname, ty)) = p.split_once(':') else {
574 continue;
575 };
576 let pname = pname.trim().trim_start_matches("mut ").to_string();
577 let ty = ty.trim();
578 let map_of_value =
579 (word(ty, "Map") || word(ty, "BTreeMap") || word(ty, "HashMap"))
580 && word(ty, "Value");
581 if guarded_type(ty) || map_of_value {
582 json_params.push(pname);
583 }
584 }
585 if json_params.is_empty()
586 || UNGUARDED.contains(&name.as_str())
587 || (method && UNGUARDED_METHODS.contains(&name.as_str()))
588 {
589 continue;
590 }
591 let body_open = close + text[close..].find('{').unwrap();
592 let (body, _) = bracketed(&text, body_open);
593 let first = body.trim_start();
594 let ok = if first.starts_with("crate::nesting::deep_guard!(") {
595 let (args, _) = bracketed(first, first.find('(').unwrap());
596 let covered: Vec<&str> = args
598 .split(';')
599 .skip(1)
600 .flat_map(|list| list.trim().trim_start_matches("drop ").split(','))
601 .map(str::trim)
602 .collect();
603 json_params.iter().all(|p| covered.contains(&p.as_str()))
604 } else {
605 body.contains("crate::nesting::too_deep_here(")
606 || body.contains("crate::nesting::Nested::nests_past(")
607 };
608 if ok {
609 guarded += 1;
610 } else {
611 missing.push(format!("{file}: {impl_type}::{name} {json_params:?}"));
612 }
613 }
614 }
615 assert!(missing.is_empty(), "no depth guard over: {missing:#?}");
616 assert!(guarded > 300, "only {guarded} guarded entry points found");
617 }
618
619 #[test]
620 fn the_refusal_text_names_the_limit() {
621 assert!(TOO_DEEP.contains(&format!(" {NO_STD_MAX_NESTING} levels")));
622 }
623
624 #[test]
625 fn the_scan_counts_brackets_outside_strings() {
626 let nested = |n: usize| format!("{}{}", "[".repeat(n), "]".repeat(n));
627 assert!(!text_too_deep(nested(32).as_bytes(), 32));
628 assert!(text_too_deep(nested(33).as_bytes(), 32));
629 let quoted = format!("{{\"a\":\"{}\\\"{}\"}}", "[".repeat(100), "{".repeat(100));
630 assert!(!text_too_deep(quoted.as_bytes(), 2));
631 }
632
633 #[test]
634 #[cfg_attr(feature = "std", ignore = "checks the no_std build")]
635 fn no_std_parse_refuses_past_the_cap() {
636 let nested = |n: usize| format!("{}1{}", "[".repeat(n), "]".repeat(n));
637 assert!(parse(&nested(NO_STD_MAX_NESTING)).is_ok());
638 let e = parse(&nested(NO_STD_MAX_NESTING + 1)).unwrap_err();
639 assert!(e.to_string().contains("no_std"), "{e}");
640 }
641}