FAQ - Help and questions

How do I parse JSON from untrusted clients safely with serde?

#security#serde#jsonpublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Deserialize into a concrete struct instead of a free-form value, add deny_unknown_fields so extra fields are errors, use narrow integer types, and limit the body size first. serde_json also refuses deeply nested input by default, so a hostile document cannot overflow the stack.

Checked with rustc 1.93.0, serde 1.0.229, serde_json 1.0.154, Windows 11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

Parsing JSON in Rust is memory safe; the risks are about what the data means and how much it costs. A typed struct gives you the first for free (a missing field or a wrong type is an error), and a few attributes and limits cover the rest.

Cargo.tomltoml
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"
src/main.rsrust
use serde::Deserialize;

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)] // a misspelt or smuggled field is an error, not silently ignored
struct Signup {
    name: String,
    age: u8,
}

fn main() {
    let ok: Signup = serde_json::from_str(r#"{"name":"Ada","age":36}"#).unwrap();
    println!("{} is {}", ok.name, ok.age);
    println!("{:?}", serde_json::from_str::<Signup>(r#"{"name":"Ada","age":300}"#).map_err(|e| e.to_string()));
    println!("{:?}", serde_json::from_str::<Signup>(r#"{"name":"Ada","age":36,"admin":true}"#).map_err(|e| e.to_string()));

    // Very deep nesting is refused by serde_json's default recursion limit instead of exhausting the stack.
    let deep = "[".repeat(200) + &"]".repeat(200);
    println!("{:?}", serde_json::from_str::<serde_json::Value>(&deep).map_err(|e| e.to_string()));
}
text
Ada is 36
Err("invalid value: integer `300`, expected u8 at line 1 column 23")
Err("unknown field `admin`, expected `name` or `age` at line 1 column 30")
Err("recursion limit exceeded at line 1 column 128")

What the output shows: a number that does not fit u8 is an error, an unexpected field is an error, and a document nested 200 levels deep is refused by serde_json's recursion limit instead of crashing the program.

How to do it#

  1. Limit the body size before parsing (see the thread on limiting input size).
  2. Deserialize into a struct, not into serde_json::Value, wherever you know the shape.
  3. Add #[serde(deny_unknown_fields)] to request structs. Do not use it on structs that must accept fields added by newer clients.
  4. Choose narrow types (u8, enums) so impossible values are rejected by the type.
  5. Check business rules after parsing (ranges, lengths), preferably inside a checked newtype.
  6. Mark fields the client must not control with #[serde(skip_deserializing)] (see the thread on sensitive fields).

Common mistakes#

  • Turning the recursion limit off (disable_recursion_limit) on untrusted input.
  • Deserializing into a map or Value and then reading keys by hand, which loses the type checks.
  • Returning the parser's error text to the client in a way that reveals internal structure. A short generic message is enough; log the detail.

Does the same hold for other formats (TOML, YAML, XML)?#

The principles do: typed targets, size limits, and care with features that expand data. Check each parser's documentation for its limits and defaults.

Should I use serde_json::Value at all?#

For data whose shape you really do not know, such as pass-through documents. Check size and depth first, and convert to typed structs as soon as you can.

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet