#[allow(unused_imports)]
use crate::prelude::*;
use serde_json::Value;
use crate::error::{CoreError, Result};
pub const NO_STD_MAX_NESTING: usize = 32;
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
}
pub const TOO_DEEP: &str = "json: nested more than 32 levels deep, the limit of the no_std build";
pub fn too_deep() -> CoreError {
CoreError::Json(TOO_DEEP.into())
}
#[cfg_attr(feature = "std", allow(dead_code))]
pub(crate) trait Nested {
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))
}
}
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)
}
}
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;
#[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
}
}
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)),
_ => {}
}
}
}
#[allow(dead_code)]
pub(crate) fn drop_flat_all<I: IntoIterator<Item = Value>>(values: I) {
for value in values {
drop_flat(value);
}
}
#[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(())
}
#[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(())
}
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::*;
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",
"wipe_strings",
"secret_json_text",
"py_type_name",
"parse_value_ns",
"check_skew",
];
const UNGUARDED_METHODS: &[&str] = &[
"new",
"reset",
"with_limits",
"with_log",
"head",
"genesis",
"entries",
"count",
"limits",
"now_ns",
"contains",
"issuer",
"subject",
];
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",
];
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 == '_')
})
}
fn guarded_type(ty: &str) -> bool {
GUARDED_TYPES.iter().any(|t| word(ty, t))
}
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");
}
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
}
#[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:#?}"
);
}
#[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());
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}");
}
}