Practical technical guides / Core IT: security (mass assignment)

Binding Request JSON Onto a Model Lets Clients Set Fields You Never Offered: Mass Assignment and Explicit Input Models

Copying request JSON onto a record let 8 of 10 hostile bodies change protected fields; a denylist still let 5 through. An explicit input model let none.

By Sandeep Belgavi · Published 2026-11-19

Copying request JSON onto a record let 8 of 10 hostile bodies change protected fields; a denylist still let 5 through. An explicit input model let none.

A profile form with three fields

The account page at Belgavi's Book Store lets a customer change three things: display name, email address and whether they want marketing email. The endpoint behind it, PATCH /customers/me, was written in a few lines. It loads the customer record, copies the JSON body onto it and saves it. The form only ever sends the three fields, and the tests only ever send the form's payload.

The customer record has more fields than the form shows: an identifier, a role that is customer for shoppers and staff for Geetha's team, a store-credit balance, a loyalty object with a tier and points, the shop that owns the account, and a creation date. Anyone who opens the browser's developer tools can send a body with any of those keys. The endpoint will copy them too.

This is mass assignment, also called autobinding or object injection. OWASP lists it in the Mass Assignment Cheat Sheet and, since the 2023 API Security Top 10, as part of API3: Broken Object Property Level Authorization. It needs no injection, no broken cryptography and no unusual input. The server simply accepts properties the client was never meant to set.

Eleven requests against three handlers

The companion example sends eleven request bodies to three versions of the handler and reports which protected fields each request changed. A00 is the legitimate form payload. The rest are what someone curious would try: a role field, the same field as Role, store credit in lower and upper case, a nested loyalty tier, the owning shop, the record identifier, a backdated creation date, an unknown key is_verified that a later release might read, and the string "yes" where a boolean is expected.

HandlerProtected fields changed byUnknown key storedRejected
Copy every keyA01 to A08A09none
Copy every key except a denylistA02, A04, A05, A06, A08A09none
Explicit input modelnonenoneA01 to A10

All three accepted A00 and applied it correctly.

Copying every key let eight of the ten hostile requests change a protected field. The binder matched field names case-insensitively and walked nested objects, as several framework binders do, so Role reached role and {"loyalty": {"tier": "gold"}} changed only the tier, leaving the points intact and the change hard to spot. It also stored is_verified on the record and turned marketing_opt_in into the string "yes".

The denylist blocked role, customer_id and credit_balance, the three fields its author thought of. It missed five requests. Two used a different case, which the binder accepted but the denylist did not check. Two used loyalty and owner_shop, fields added to the record after the denylist was written. One used created_at, which nobody thought an attacker would want. A denylist must be updated every time the record grows, by someone who remembers it exists. It fails open.

The explicit input model changed nothing protected and stored nothing unknown. It rejected each hostile body with a precise reason, such as role: extra_forbidden or marketing_opt_in: bool_type.

The input model

The fix is to stop treating the storage record as the request schema. Each operation gets its own input type listing exactly the fields that operation may change, and the handler copies only those.

from pydantic import BaseModel, ConfigDict, Field, StrictBool, ValidationError

class UpdateProfileInput(BaseModel):
    model_config = ConfigDict(extra="forbid", strict=True)
    display_name: str | None = Field(default=None, min_length=1, max_length=60)
    email: str | None = Field(default=None, max_length=254)
    marketing_opt_in: StrictBool | None = None

def update_profile(record, body):
    try:
        data = UpdateProfileInput.model_validate(body)
    except ValidationError as exc:
        return None, [f"{'.'.join(map(str, e['loc']))}: {e['type']}" for e in exc.errors()]
    for field, value in data.model_dump(exclude_unset=True).items():
        record[field] = value
    return record, None

Three details carry the weight.

  • extra="forbid" turns any unexpected key into a validation error. Pydantic's default is to ignore extra keys, which is also safe for this purpose, because ignored keys are never copied. Forbidding them is better for an API: the client learns its request was wrong, and probing shows up in logs as errors instead of silent success.
  • strict=True stops coercion. Without it, "yes" or 1 may be accepted as a boolean in some modes. Strictness makes the contract match the documentation.
  • exclude_unset=True copies only fields the client actually sent, so a PATCH that changes the display name does not reset the email to null.

Server-owned fields are set in code by the operations that own them: a staff tool changes roles, the refund service changes store credit, the loyalty service changes tiers. None of those operations reads them from a customer's request body.

The same idea in other stacks

Every major framework has a version of this. Rails has strong parameters with permit. ASP.NET Core recommends binding to a view model or DTO rather than the entity. Spring applications use separate request classes, or @InitBinder with allowed fields when binding to a domain object. Java and Kotlin JSON mappers can be configured to fail on unknown properties. The specifics differ; the principle is an allowlist per operation, declared in code that reviewers can read.

The OWASP cheat sheet lists the same choices: allowlist bindable fields, denylist when you must, and prefer data transfer objects. Of those, only the allowlist survives the record growing.

Responses leak the other way

API3 covers both directions. An endpoint that binds too much on input often also returns too much on output: the whole record, including the role, the credit balance and internal flags. Define response models per operation too. An agent or front end reading role from a profile response is one refactor away from sending it back.

Agents make this more likely, not less

When a language model fills tool arguments, it fills them from the schema it is shown and from whatever text it read. If a tool's schema is the storage record, the model sees role and credit_balance as legitimate parameters, and a prompt injection in a customer email only has to ask for them. Give agent tools the same narrow input models as public endpoints, and treat the agent as an untrusted client of your API.

Migrating an endpoint that already binds everything

Switching a live endpoint to a strict input model can break clients that send extra fields harmlessly, such as an old mobile app that echoes the whole profile back. A staged change avoids both the outage and the window of continued exposure.

  1. Add the input model in report-only mode: validate every request, log the keys that would be rejected with the client version, and still apply only the allowed fields. Applying only allowed fields closes the hole on the first day.
  2. Read a week of logs. Keys sent by real clients that the operation does not need are client bugs to fix; protected keys sent by anyone are worth a security review.
  3. Switch to rejecting extra keys once legitimate clients are clean, and return a clear 400 or 422 response naming the field.
  4. Add the record-versus-model test described below so the next new column cannot slip back in.

Failure modes to test

  • Every field of the storage record, in the request body of every update endpoint, in original case, upper case and mixed case. Expect a rejection for each.
  • Nested objects for every object-valued field, including partial updates of a single nested key.
  • A new column added to the record. Add a test that fails if a column exists that is neither in an input model nor in an explicit list of server-owned fields; that catches the denylist problem at review time.
  • Type confusion: strings for booleans and numbers, arrays for objects, nulls for required fields.
  • Alternative content types. Some stacks bind form-encoded and JSON bodies through different paths; send both.

Verification

python example.py in the companion prints every case for every handler, and python -m unittest -v test_example.py asserts the table above, the acceptance of the legitimate change and the rejection of a request that combines an allowed field with a forbidden one. To check your own service, take fixtures/corpus.json, replace the field names with your record's fields, and replay it against each update endpoint in a test environment, comparing the stored record before and after each request.

Primary references and authorship

Original explanation and synthetic examples by Sandeep Belgavi. Companion code: Sandeep-BA/agent-decision-lab/examples/python/mass_assignment_input_models. Views are my own and do not represent any employer, past or present.