Prevent Mass Assignment Vulnerabilities

Mass assignment occurs when an API blindly accepts client-provided properties and applies them directly to a database document.

Imagine a user update endpoint that accepts:

{
  "name": "John",
  "role": "admin",
  "isActive": false
}

If the backend directly passes this object into a database update operation, an ordinary user may be able to modify privileged properties.

Prevent this by explicitly selecting the properties that clients are allowed to update.

For profile updates, allow only fields such as name and age.

Role changes should be implemented through a separate administrator-authorized operation.

Never Trust req.body

Do not spread arbitrary request bodies into Mongoose updates. Restrict writable properties using validation schemas and explicit allowlists.

Allowlist Update Properties
export function pickUserUpdateFields(body) {
  const allowedFields = ['name', 'age'];

  return Object.fromEntries(
    Object.entries(body).filter(([key]) =>
      allowedFields.includes(key)
    )
  );
}

Creates an update object containing only explicitly permitted properties.

Key Takeaways
  • Mass assignment can expose privileged fields.

  • Use explicit property allowlists.

  • Protect role and account-status modifications.