Skip to content

Lesson 5 of 14 · 18m

Serde at the Boundary: Parse, Don't Validate

deny_unknown_fields as a mass-assignment defense, try_from newtypes that make invalid states unrepresentable, and why untagged enums re-route payloads silently.

A request hits your Axum handler as Json(payload): Json<SignupForm>. Between the socket and that signature, serde_json allocated a SignupForm and — here's the part nobody thinks about — silently dropped every field it didn't recognize. The client sent "role": "admin" alongside the username and password. Serde ignored it by default. Whether that's a shrug or a mass-assignment bug is a decision you make in the struct definition, not a default you inherit.

Unknown fields are a policy decision, not a parser detail

Serde's default on unknown fields is ignore — forwards compatibility, the argument goes, so a newer client can talk to an older server. That argument is right for config files and federation. For a request that changes state, it's the mass-assignment bug from 2012 all over again — the same year GitHub got owned through Rails' equivalent feature. If a field isn't in your struct, it shouldn't reach your code:

#[derive(serde::Deserialize)]
#[serde(deny_unknown_fields)]
struct SignupForm {
    username: String,
    password: String,
}

Now "role": "admin" in the JSON is a 422, not a silent privilege. deny_unknown_fields doesn't fix handlers that do accept the field — it fixes the ones where a stray key means something went wrong upstream or something malicious went right.

Parse, don't validate

The wrong mental model: deserialize the loose struct, then run validate(). Now every function downstream of the boundary carries an invisible precondition — "the string is a real email," "the slug is DNS-safe," "the quantity isn't negative" — and the type system can't check any of it. The fix is making the boundary parse produce a validated type, so illegal states can't exist past the edge:

use serde::Deserialize;

#[derive(Deserialize)]
#[serde(try_from = "String")]
struct Email(String);

impl TryFrom<String> for Email {
    type Error = &'static str;
    fn try_from(s: String) -> Result<Self, Self::Error> {
        if s.contains('@') && s.len() <= 254 { Ok(Email(s)) } else { Err("invalid email") }
    }
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct SignupForm {
    username: Username,   // another validated newtype
    email: Email,         // if this parses, it IS a valid email
    password: String,
}

From here down, Email is proof — no function ever re-checks. This is "parse, don't validate" (Alexis King coined the name for Haskell, but it's a serde pattern): the boundary does the work once, and every downstream signature gets to assume it. #[serde(try_from = "...")] runs your validator during deserialization, so a bad payload is a clean 422 with the parse error — not a panic three layers deep.

The untagged trap, and serde_json's coercion surprises

#[serde(untagged)] is where type confusion actually lives:

#[derive(Deserialize)]
#[serde(untagged)]
enum Amount {
    Text(String),
    Cents(i64),
}

Serde tries variants in declared order and keeps the first that parses. Rearranged variants change your wire format without a single test noticing — and any variant that accepts a map or serde_json::Value acts as a catch-all that silently swallows payloads meant for the variants after it. An integer is the classic case: 5 parses fine as i64, but if you ever widen it to f64 or add a serde_json::Number arm, 5.0-vs-5 ambiguity is yours to debug. Tagged enums — #[serde(tag = "type")] — make the payload say what it is:

#[derive(Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
enum Amount {
    Cents { cents: i64 },
    Text { text: String },
}

{"kind": "cents", "cents": 5} can't be misread as the other variant. Untagged means the payload guesses; a guess is what makes a "harmless" schema change a breaking change.

Two more serde_json specifics worth knowing by name: serde_path_to_error (which field failed — the difference between invalid type: string "yes", expected u64 and ...at line 4 column 12 with no context) and serde_with for the crates-level transforms (#[serde_as], DisplayFromStr for numbers-that-are-strings in someone else's API).

The bug that ships

The boundary bug that ships is the #[serde(default)] on a field that shouldn't have a default — "notify": false on a security-alert toggle — combined with ignored unknown fields, so the client believes it set a preference the server never saw. Every #[serde(default)] is "what does the absence of this field mean," and the answer "nothing, silently" is usually wrong for anything a security-relevant flow consumes.

Try this

Take a public-facing DTO in a codebase you own. Add deny_unknown_fields and run the test suite — count how many tests were sending fields that never did anything. Then move one String field to a #[serde(try_from)] validated newtype and delete the validate() call downstream. If nothing breaks, the validation was real; if a test panics, you just found a caller that was never validating.

Field notes

  • serde(rename_all = "camelCase") on a struct beats twenty rename attributes — and serde(rename_all_fields) handles enums-of-structs in one shot.
  • axum's Json rejection already wraps serde_json errors; add serde_path_to_error if you want the field path in the 422.
  • validator and nutype do attribute-driven validation if TryFrom gets long — same pattern, less hand-rolled code.

Was this lesson helpful?

Sign in to rate

Keep reading

Related articles from the SudoSecurity blog.