Skip to content

Broken property-level authorization (mass assignment and overexposure)

When is it relevant

A new or changed entry point that creates or updates a record from request body fields, or returns records, where some fields must not be set or seen by that caller. Examples: role, owner, tenant, price, status, verification flags, secrets.

Attack

The attacker adds fields the UI never sends, such as "role": "admin", "companyId": "…" or "isVerified": true. The server spreads the body into the database. Or the response serializes the whole record, exposing password hashes, tokens or internal flags.

Mitigation

  • Validate the body against a schema that allowlists writable fields for this caller and rejects unknown keys.
  • Set ownership, tenant and privileged fields on the server, never from the body.
  • Build responses from an explicit list of fields.

Test

  • Point-in-time: send create and update requests with extra fields (role, ownerId, tenantId, status, price) and check none is stored. Check responses for fields the caller shouldn't see.
  • Continuous: a unit test on the schema or DTO that rejects or ignores unknown keys, and a response snapshot test that fails when a new field appears.

Examples

Mitigation options

Option When it fits Docs
Allowlist the fields you accept Default choice; the shape is explicit in the handler Express routing
Schema validation with unknown keys rejected Bigger payloads, shared between routes Zod
Mongoose strict + explicit select Mongoose already models the document Mongoose schemas

Vulnerable — write side (mass assignment)

router.patch('/me', requireAuth, async (req, res) => {
  const user = await User.findByIdAndUpdate(req.user.id, req.body, { new: true })
  res.json(user)                    // {"role":"admin"} or {"credits":9999} lands here
})

Vulnerable — read side (overexposure)

router.get('/users/:id', requireAuth, async (req, res) => {
  res.json(await User.findById(req.params.id))   // passwordHash, resetToken, email
})

Mitigated — allowlist

const EDITABLE = ['displayName', 'bio', 'avatarUrl']

router.patch('/me', requireAuth, async (req, res) => {
  const update = {}
  for (const key of EDITABLE) {
    if (key in req.body) update[key] = req.body[key]
  }
  const user = await User.findByIdAndUpdate(req.user.id, update, { new: true })
  res.json({ id: user.id, displayName: user.displayName, bio: user.bio })
})

The response is built field by field too, so a column added to the model later is not published by accident.

Docs: Mongoose queries

Mitigated — schema validation

const ProfileUpdate = z.object({
  displayName: z.string().min(1).max(80),
  bio: z.string().max(500).optional(),
}).strict()                          // unknown keys are an error, not ignored

const parsed = ProfileUpdate.safeParse(req.body)
if (!parsed.success) return res.status(400).json({ error: 'Invalid body' })
await User.findByIdAndUpdate(req.user.id, parsed.data)

Docs: Zod objects and .strict()

Mitigated — Mongoose schema

const userSchema = new mongoose.Schema({
  displayName: String,
  role: { type: String, default: 'user', immutable: true },
  passwordHash: { type: String, select: false },   // never loaded unless asked
}, { strict: 'throw' })                            // unknown paths throw

Docs: Mongoose schemas

Bypasses to check

  • Privileged field allowed through a second path. The profile route allowlists fields, but registration (new User(req.body)), an import job, or an admin route reuses the raw body.
  • { strict: true } silently drops unknown keys rather than rejecting them, so a review can't tell from the response whether a field was honoured; dotted keys ("profile.role") and $set payloads can still reach nested paths.
  • Zod without .strict() (or .passthrough()) keeps unknown keys.
  • Prototype pollution through __proto__ or constructor.prototype when the body is merged with Object.assign, spread, or a deep-merge helper.
  • Check then change: the body is validated, then re-read from the original req.body instead of from the validated result.
  • Read side: select('-passwordHash') on one query but not on populate(), aggregation, or the list endpoint; a toJSON transform that a .lean() query bypasses.
  • Errors that echo the whole document back in a message or log.

What to grep for

  • req.body passed whole: findByIdAndUpdate(, updateOne(, new User(, Object.assign(, { ...req.body }
  • strict, .strict(), passthrough(, select(, lean(, toJSON

Mitigation options

Option When it fits Docs
Request and response DTOs (Java records) Default choice; the shape is explicit per endpoint Jackson databind
Bean Validation on the DTO, unknown fields rejected Bigger payloads; reject rather than ignore extras Spring validation
@InitBinder allowed fields Server-rendered forms bound with @ModelAttribute @InitBinder
Jackson annotations on the entity (@JsonIgnore, READ_ONLY) Last resort when the entity is the API model Jackson annotations

Vulnerable — write side: the entity is the request body

@PutMapping("/api/me")
public User update(@RequestBody User body, @AuthenticationPrincipal AppUser me) {
    body.setId(me.getId());
    return users.save(body);        // {"role":"ADMIN"}, {"credits":9999}, {"tenantId":…} all land
}

Vulnerable — write side: a map straight into the update

@PutMapping("/api/projects/{projectId}/tasks/{taskId}")
public Task update(@PathVariable String projectId, @PathVariable String taskId,
                   @RequestBody Map<String, Object> body) {
    service.requireTaskInProject(projectId, taskId);
    Update update = new Update();
    body.forEach(update::set);      // {"projectId":"<other>"} moves the task to another project
    mongo.updateFirst(byId(taskId), update, Task.class);
    return tasks.findById(taskId);
}

Any key the client sends becomes a field write, including projectId, createdBy and dotted paths like "members.0.role".

Vulnerable — server-rendered form bound to the entity

@PostMapping("/profile")
public String save(@ModelAttribute User user) {   // a hidden <input name="role"> is enough
    users.save(user);
    return "redirect:/profile";
}

Vulnerable — read side: the entity is the response

@GetMapping("/api/users/{id}")
public User get(@PathVariable Long id) {
    return users.findById(id).orElseThrow();      // passwordHash, resetToken, mfaSecret, email
}

Mitigated — request and response records

public record ProfileUpdate(
        @NotBlank @Size(max = 80) String displayName,
        @Size(max = 500) String bio) { }

public record ProfileView(Long id, String displayName, String bio) {
    static ProfileView of(User u) { return new ProfileView(u.getId(), u.getDisplayName(), u.getBio()); }
}

@PutMapping("/api/me")
public ProfileView update(@Valid @RequestBody ProfileUpdate body, @AuthenticationPrincipal AppUser me) {
    User user = users.findById(me.getId()).orElseThrow();
    user.setDisplayName(body.displayName());
    user.setBio(body.bio());
    return ProfileView.of(users.save(user));
}

The record has no role field, so there is nothing to bind it to. The response is built field by field, so a column added to the entity later isn't published by accident.

Docs: Bean Validation in Spring MVC · @AuthenticationPrincipal

Mitigated — reject unknown fields

spring.jackson.deserialization.fail-on-unknown-properties=true

Spring Boot sets this to false, so by default an extra "role" is silently dropped on a DTO. That's safe, but a reviewer or tester can't tell from the response whether the field was honoured. Failing loudly makes it visible.

Docs: Customize the Jackson ObjectMapper

Mitigated — allowlist the map keys

private static final Set<String> EDITABLE = Set.of("title", "description", "status", "assignedTo");

Map<String, Object> changes = new HashMap<>();
for (String key : EDITABLE) {
    if (body.containsKey(key)) changes.put(key, validate(key, body.get(key)));
}
Update update = new Update();
changes.forEach(update::set);

Iterate over the allowlist, not over the request, so an unexpected key can never reach the update.

Docs: Spring Data MongoDB Update

Mitigated — form binding

@InitBinder("user")
void allowedFields(WebDataBinder binder) {
    binder.setAllowedFields("displayName", "bio");
}

Better still, bind forms to a DTO too. setAllowedFields is an allowlist; setDisallowedFields is a blocklist and misses fields added later.

Docs: @InitBinder

Bypasses to check

  • Privileged field allowed through a second path. The profile endpoint uses a DTO, but registration, an admin import, or the form controller binds the entity.
  • @JsonIgnore on a field that also has a public setter annotated @JsonProperty, or Lombok @Data regenerating setters that the annotation was meant to hide. @JsonProperty(access = READ_ONLY) is the clearer intent.
  • ObjectMapper.updateValue(entity, body), BeanUtils.copyProperties(body, entity) and MapStruct mappers with no ignore = true for privileged targets: these copy every matching property.
  • Map<String, Object> bodies passed to Update.set, Criteria, or a JPA @Modifying query builder.
  • Nested objects: a DTO that includes List<Member> or another entity type, so {"members":[{"role":"owner"}]} binds into it.
  • Read side: the entity returned from one endpoint but a DTO from another; @JsonIgnore on passwordHash but not on resetToken; error responses and logs that serialize the entity.
  • Check then change: the DTO is validated, then the raw Map or HttpServletRequest parameters are read again for the write.

What to grep for

  • @RequestBody or @ModelAttribute followed by an @Entity / @Document type
  • @RequestBody Map<String, Object>, Update().set, forEach(update::set)
  • BeanUtils.copyProperties(, updateValue(, convertValue(
  • @JsonIgnore, READ_ONLY, fail-on-unknown-properties, FAIL_ON_UNKNOWN_PROPERTIES
  • @InitBinder, setAllowedFields, setDisallowedFields

Mitigation options

Option When it fits Docs
Read named fields from request.form / request.json Small forms; the simplest allowlist flask.Request
A schema (pydantic, marshmallow) for input and output APIs; validates types and drops unknown fields pydantic, marshmallow
An explicit response serializer Every JSON response marshmallow dump

Vulnerable — the whole body becomes the update

@app.put('/api/users/me')
@require_token
def update_me():
    db.users.update_one({'_id': ObjectId(g.user['id'])}, {'$set': request.json})   # {"role": "admin"}
    return jsonify(ok=True)

Vulnerable — the whole document goes back

return jsonify(serialize(db.users.find_one({'_id': oid})))    # includes password_hash, reset tokens

Mitigated — named fields in, named fields out

@app.put('/api/repos/<rid>')
@require_token
def update_repo(rid):
    data = request.get_json(silent=True) or {}
    fields = {}
    if 'description' in data:
        if not isinstance(data['description'], str):
            return jsonify(error='Invalid description'), 400
        fields['description'] = data['description'].strip()[:280]
    if 'visibility' in data:
        if data['visibility'] not in ('public', 'private'):
            return jsonify(error='Invalid visibility'), 400
        fields['visibility'] = data['visibility']
    repos.update(rid, fields)                     # owner_id, members, stars can't be set here
    return jsonify(repo_json(repos.find_by_id(rid)))

def repo_json(r):
    return {'id': r['id'], 'name': r['name'], 'description': r.get('description', ''), 'visibility': r['visibility']}

Docs: Request.get_json

Mitigated — a schema that forbids extra fields

class ProfileIn(BaseModel):
    model_config = ConfigDict(extra='forbid')
    full_name: constr(max_length=64) = ''
    bio: constr(max_length=280) = ''

data = ProfileIn.model_validate(request.get_json(silent=True) or {})

Docs: pydantic extra='forbid'

Bypasses to check

  • **request.json or **request.form passed to a model constructor or to $set.
  • Dotted keys in MongoDB updates ({"profile.role": "admin"}) and operators ({"$set": …}) that come from the client.
  • Projections that exclude only password_hash, leaving new sensitive fields exposed as the schema grows.
  • Admin-only fields accepted on a sibling route, for example a create route that takes role while the update route ignores it.

What to grep for

  • request.json, request.get_json(, request.form.to_dict(, **request.
  • $set, update_one(, insert_one(, jsonify(, serialize(, password_hash

Resources