Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add recursion limit for 1.0.1 #65

Merged
merged 2 commits into from
Jan 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ license = "MIT OR Apache-2.0"
name = "serde-json-wasm"
readme = "README.md"
repository = "https://github.com/CosmWasm/serde-json-wasm"
version = "1.0.0"
version = "1.0.1"
exclude = [
".cargo/",
".github/",
Expand Down
4 changes: 4 additions & 0 deletions src/de/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,9 @@ pub enum Error {
/// JSON has a comma after the last value in an array or map.
TrailingComma,

/// JSON is nested too deeply, exceeded the recursion limit.
RecursionLimitExceeded,

/// Custom error message from serde
Custom(String),
}
Expand Down Expand Up @@ -128,6 +131,7 @@ impl core::fmt::Display for Error {
value."
}
Error::TrailingComma => "JSON has a comma after the last value in an array or map.",
Error::RecursionLimitExceeded => "JSON is nested too deeply, exceeded the recursion limit.",
Error::Custom(msg) => msg,
}
)
Expand Down
59 changes: 47 additions & 12 deletions src/de/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ use self::seq::SeqAccess;
pub struct Deserializer<'b> {
slice: &'b [u8],
index: usize,

/// Remaining depth until we hit the recursion limit
remaining_depth: u8,
}

enum StringLike<'a> {
Expand All @@ -30,7 +33,11 @@ enum StringLike<'a> {

impl<'a> Deserializer<'a> {
fn new(slice: &'a [u8]) -> Deserializer<'_> {
Deserializer { slice, index: 0 }
Deserializer {
slice,
index: 0,
remaining_depth: 128,
}
}

fn eat_char(&mut self) {
Expand Down Expand Up @@ -287,16 +294,22 @@ impl<'a, 'de> de::Deserializer<'de> for &'a mut Deserializer<'de> {
}
}
b'[' => {
self.eat_char();
let ret = visitor.visit_seq(SeqAccess::new(self))?;
check_recursion! {
self.eat_char();
let ret = visitor.visit_seq(SeqAccess::new(self));
}
let ret = ret?;

self.end_seq()?;

Ok(ret)
}
b'{' => {
self.eat_char();
let ret = visitor.visit_map(MapAccess::new(self))?;
check_recursion! {
self.eat_char();
let ret = visitor.visit_map(MapAccess::new(self));
}
let ret = ret?;

self.end_map()?;

Expand Down Expand Up @@ -513,8 +526,11 @@ impl<'a, 'de> de::Deserializer<'de> for &'a mut Deserializer<'de> {
{
match self.parse_whitespace().ok_or(Error::EofWhileParsingValue)? {
b'[' => {
self.eat_char();
let ret = visitor.visit_seq(SeqAccess::new(self))?;
check_recursion! {
self.eat_char();
let ret = visitor.visit_seq(SeqAccess::new(self));
}
let ret = ret?;

self.end_seq()?;

Expand Down Expand Up @@ -550,9 +566,11 @@ impl<'a, 'de> de::Deserializer<'de> for &'a mut Deserializer<'de> {
let peek = self.parse_whitespace().ok_or(Error::EofWhileParsingValue)?;

if peek == b'{' {
self.eat_char();

let ret = visitor.visit_map(MapAccess::new(self))?;
check_recursion! {
self.eat_char();
let ret = visitor.visit_map(MapAccess::new(self));
}
let ret = ret?;

self.end_map()?;

Expand Down Expand Up @@ -588,8 +606,11 @@ impl<'a, 'de> de::Deserializer<'de> for &'a mut Deserializer<'de> {
b'"' => visitor.visit_enum(UnitVariantAccess::new(self)),
// if it is a struct enum
b'{' => {
self.eat_char();
visitor.visit_enum(StructVariantAccess::new(self))
check_recursion! {
self.eat_char();
let value = visitor.visit_enum(StructVariantAccess::new(self));
}
value
}
_ => Err(Error::ExpectedSomeIdent),
}
Expand Down Expand Up @@ -649,6 +670,20 @@ where
from_slice(s.as_bytes())
}

macro_rules! check_recursion {
($this:ident $($body:tt)*) => {
$this.remaining_depth -= 1;
if $this.remaining_depth == 0 {
return Err($crate::de::Error::RecursionLimitExceeded);
}

$this $($body)*

$this.remaining_depth += 1;
};
}
pub(crate) use check_recursion;

#[cfg(test)]
mod tests {
use super::from_str;
Expand Down
25 changes: 25 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -227,4 +227,29 @@ mod test {
item
);
}

#[test]
fn no_stack_overflow() {
const AMOUNT: usize = 2000;
let mut json = String::from(r#"{"":"#);

#[derive(Debug, Deserialize, Serialize)]
pub struct Person {
name: String,
age: u8,
phones: Vec<String>,
}

for _ in 0..AMOUNT {
json.push('[');
}
for _ in 0..AMOUNT {
json.push(']');
}

json.push_str(r#"] }[[[[[[[[[[[[[[[[[[[[[ ""","age":35,"phones":["#);

let err = from_str::<Person>(&json).unwrap_err();
assert_eq!(err, crate::de::Error::RecursionLimitExceeded);
}
}
Loading