Fix Mass Assignment in Hapi
Mass Assignment in Hapi.js occurs when an application takes a user-provided object and passes it directly to a database model or internal state without filtering. In a 'hacker' context, this is an Overposting attack. If your route handler blindly merges `request.payload` into a User object, an attacker can inject fields like `isAdmin: true` or `role: 'root'` to escalate privileges.
The Vulnerable Pattern
server.route({ method: 'POST', path: '/api/profile/update', handler: async (request, h) => { const user = await db.users.findOne({ id: request.auth.credentials.id });// VULNERABLE: Blindly merging the entire payload into the database object. // An attacker can send {"username": "hacker", "isAdmin": true} to escalate. Object.assign(user, request.payload); await user.save(); return { success: true };
} });
The Secure Implementation
The vulnerability is mitigated by using Joi validation at the route level. By setting `stripUnknown: true` within the Joi options, Hapi automatically purges any keys in the payload that are not explicitly defined in the schema. Even if the attacker sends `isAdmin: true`, the handler never sees it. As a secondary defense, always prefer explicit destructuring (e.g., `const { bio } = request.payload`) over `Object.assign` when dealing with ORM models.
const Joi = require('joi');server.route({ method: ‘POST’, path: ‘/api/profile/update’, options: { validate: { // SECURE: Define a strict schema for allowed fields payload: Joi.object({ username: Joi.string().max(30), bio: Joi.string().max(255) }).options({ stripUnknown: true }) // CRITICAL: Drops fields not defined in Joi } }, handler: async (request, h) => { const user = await db.users.findOne({ id: request.auth.credentials.id });
// SAFE: request.payload only contains 'username' and 'bio' now Object.assign(user, request.payload); await user.save(); return { success: true };
} });
Your Hapi API
might be exposed to Mass Assignment
74% of Hapi apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.
Free Tier • No Credit Card • Instant Report
Verified by Ghost Labs Security Team
This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.