TExcelTAD

Mass Assignment

Frameworks save developers a lot of typing by binding request data straight onto objects: user.update(**request.json), Object.assign(user, req.body), Rails' User.update(params[:user]) without strong parameters, Spring binding a form onto an entity. The developer thinks of the three fields the profile form has: name, e-mail, bio. The object has more: role, is_verified, credit, tenant_id. If the binding copies every field the client sends, the client can set those too, just by adding them to the JSON. This is mass assignment (also auto-binding or object injection), part of API3 Broken Object Property Level Authorization in the OWASP API Security Top 10 2023. Its mirror image, returning more properties than the client should see ("excessive data exposure"), is in the same category, and both are fixed the same way: say explicitly which properties go in and which come out.

Definitions

  • Mass assignment: binding client input to an object (or ORM model) without an allow-list of writable fields.
  • Object property level authorization: per-property rules, e.g. "the user may write bio; only an admin may write role; nobody writes created_at".
  • DTO / input schema: a separate type that lists exactly the fields a request may carry (Pydantic model, a serializer, a form class, a C# record), mapped explicitly onto the domain object.
  • Excessive data exposure: responses that serialise whole objects (password_hash, internal_notes, other users' e-mails) and rely on the front end to hide them.

The bug, and two fixes

The handler updates a user profile from JSON. The vulnerable version copies every key. The first fix uses an allow-list per role; the second uses a schema that also checks types and refuses unknown keys, which turns probing into a visible 400 instead of silently ignoring it.

python · try it yourself
import json
from dataclasses import dataclass, asdict, fields

def new_user():
    return {"id": 7, "name": "Ana", "email": "ana@lab.test", "bio": "",
            "role": "user", "email_verified": False, "credit": 0, "tenant_id": 3}

def update_vulnerable(user, body):
    user.update(json.loads(body))                       # every key the client sends
    return user

WRITABLE = {"user": {"name", "bio"}, "admin": {"name", "bio", "role", "email_verified"}}

def update_allowlist(user, body, caller_role="user"):
    data = json.loads(body)
    for key in data.keys() & WRITABLE[caller_role]:
        user[key] = data[key]
    return user

@dataclass
class ProfileUpdate:                                    # the input schema
    name: str | None = None
    bio: str | None = None

def update_schema(user, body):
    data = json.loads(body)
    allowed = {f.name for f in fields(ProfileUpdate)}
    unknown = sorted(data.keys() - allowed)
    if unknown:
        return f"422 unknown fields: {unknown}"
    dto = ProfileUpdate(**data)
    if dto.name is not None and (not isinstance(dto.name, str) or not 1 <= len(dto.name) <= 50):
        return "422 name must be 1-50 characters"
    if dto.bio is not None and (not isinstance(dto.bio, str) or len(dto.bio) > 300):
        return "422 bio too long"
    user.update({k: v for k, v in asdict(dto).items() if v is not None})
    return user

PUBLIC = ("id", "name", "bio")                          # what responses may contain
body = '{"bio": "tea lover", "role": "admin", "email_verified": true, "credit": 500, "tenant_id": 1}'
print("vulnerable:", update_vulnerable(new_user(), body))
print("allow-list:", update_allowlist(new_user(), body))
print("schema:    ", update_schema(new_user(), body))
print("schema ok: ", {k: v for k, v in update_schema(new_user(), '{"bio": "tea lover"}').items() if k in PUBLIC})
print("admin may set role:", update_allowlist(new_user(), '{"role": "support"}', caller_role="admin")["role"])
vulnerable: {'id': 7, 'name': 'Ana', 'email': 'ana@lab.test', 'bio': 'tea lover', 'role': 'admin', 'email_verified': True, 'credit': 500, 'tenant_id': 1}
allow-list: {'id': 7, 'name': 'Ana', 'email': 'ana@lab.test', 'bio': 'tea lover', 'role': 'user', 'email_verified': False, 'credit': 0, 'tenant_id': 3}
schema:     422 unknown fields: ['credit', 'email_verified', 'role', 'tenant_id']
schema ok:  {'id': 7, 'name': 'Ana', 'bio': 'tea lover'}
admin may set role: support

One request made Ana an administrator with a verified e-mail, 500 units of credit, in another tenant. The allow-list version applied only bio and ignored the rest. The schema version refused the whole request and named the unexpected fields, which is better for detection: a legitimate client never sends role to the profile endpoint, so a 422 for it is worth an alert. The response is built from an explicit list of public fields, never by serialising the whole object.

Where to look for writable properties

Attackers (and testers) learn the hidden properties from the application itself:

  • GET responses: if GET /api/users/me returns role and credit, try sending them back in PUT/PATCH.
  • Registration and sign-up endpoints: "role": "admin" or "is_staff": true at creation is the most damaging variant.
  • Front-end code and API documentation: field names in the JavaScript bundle, OpenAPI schemas, GraphQL input types.
  • Nested objects: {"profile": {"bio": "x"}, "account": {"plan": "enterprise"}}, or ORMs that save related objects.

How mass assignment is detected

  • Testing: for each write endpoint, add properties seen in responses or guessed (role, admin, is_admin, verified, balance, owner_id, tenant_id, created_at), with both plausible and wrong types, then read the object back. Any change is a finding.
  • Code review: update(**data), Object.assign(model, req.body), Model.create(req.body), params.permit! in Rails, ModelForm with fields = "__all__" in Django, entity classes bound directly in Spring MVC or ASP.NET without [Bind]/DTOs.
  • Logs: requests with property names the UI never sends (schema validation errors are an easy signal), changes to privileged fields made through self-service endpoints (audit logs on role, plan, tenant_id).

How it is fixed

  1. Explicit input schemas per endpoint (Pydantic with extra="forbid", marshmallow, Joi/Zod with strict mode, Rails strong parameters, DTO classes in Java and .NET). Reject unknown fields.
  2. Property-level authorization: privileged fields are written only by dedicated endpoints with their own checks (POST /api/admin/users/7/role).
  3. Explicit output schemas: serialise only public fields; never return ORM objects directly.
  4. Server-owned fields (id, owner_id, tenant_id, timestamps, balances) are set by the server from the session and business logic, never from input.

Pitfalls

  • Block-lists (data.pop("role")) miss the next field someone adds to the model.
  • Allow-lists that differ between create and update without anyone noticing: sign-up often has the weaker one.
  • Front-end validation only: the form has no role field, but the API accepts it.

Practice

1. GET /api/me returns {"name": …, "plan": "free", "plan_expires": null}. Which test do you run?

PATCH /api/me with {"plan": "enterprise", "plan_expires": "2099-01-01"}, then GET /api/me again. Also try the sign-up endpoint with the same fields.

2. Why is a 422 for unknown fields better than silently ignoring them?

Silent ignoring is safe for the data but hides probing; a 422 makes attacker behaviour visible in logs and breaks clients that send wrong data early, during development, instead of letting typos pass unnoticed.

Test yourself

What is mass assignment?

  1. Assigning many users to a role
  2. Binding all client-supplied properties onto an object, including ones the client must not set
  3. A SQL bulk insert
  4. A CSRF variant

Which OWASP API Security 2023 category covers mass assignment and excessive data exposure?

  1. API1 BOLA
  2. API3 Broken Object Property Level Authorization
  3. API7 SSRF
  4. API9 Improper Inventory Management

What is the most robust fix?

  1. Remove dangerous keys with pop()
  2. An explicit input schema per endpoint that rejects unknown fields, plus explicit output schemas
  3. Hide fields in the UI
  4. Rename fields