Skip to content

Bug: PUT /users/preferences accepts arbitrary fields — no input validation #73

Description

@vipul674

Bug Description

The PUT /api/users/preferences endpoint spreads the entire req.body into user.preferences without field validation:

user.preferences = { ...user.preferences, ...req.body }

This allows clients to inject arbitrary fields beyond the allowed theme and emailNotifications preferences. While Mongoose schema validation may strip unknown fields on save, the intermediate spread pollutes the document object and could lead to unexpected behavior if the schema is modified or if middleware reads the unsaved object.

Steps to Reproduce

curl -X PUT http://localhost:3000/api/users/preferences   -H "Content-Type: application/json"   -H "Authorization: Bearer <token>"   -d '{"theme": "dark", "admin": true, "role": "admin", "reputation": 9999}'

Expected Behavior

Only allowed preference fields (theme, emailNotifications) should be accepted. Any extra fields should be ignored or rejected.

Actual Behavior

The entire request body is merged into user preferences without validation.

Suggested Fix

const { theme, emailNotifications } = req.body
const allowedPrefs = {}
if (theme !== undefined) allowedPrefs.theme = theme
if (emailNotifications !== undefined) allowedPrefs.emailNotifications = emailNotifications
user.preferences = { ...user.preferences, ...allowedPrefs }

Environment

  • Node.js + Express + MongoDB (Mongoose)
  • Reproducible on latest main

Labels

bug, good first issue

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions