GuardAPI Logo
GuardAPI

Fix Mass Assignment in Fastify

Mass Assignment occurs when an application takes user-provided data and binds it to internal models without proper filtering. In Fastify, this usually happens when developers blindly spread 'request.body' into a database query or an ORM object. If your model contains sensitive fields like 'role', 'isAdmin', or 'balance', an attacker can overwrite them by simply adding those keys to their JSON payload. To kill this bug, you must enforce strict input schemas or manual property extraction.

The Vulnerable Pattern

fastify.post('/api/profile/update', async (request, reply) => {
  const user = await User.findOne({ id: request.user.id });

// VULNERABILITY: Blindly merging the entire request body into the user object. // An attacker can send { “isAdmin”: true } to escalate privileges. Object.assign(user, request.body);

await user.save(); return { success: true }; });

The Secure Implementation

The fix leverages Fastify's built-in validation powered by Ajv. By setting 'additionalProperties: false' in the JSON schema, Fastify automatically strips or rejects any fields that aren't explicitly defined in the 'properties' object. This creates a strict allowlist. Even if an attacker injects 'role': 'admin' into the POST body, the validation layer will catch it before the controller logic is even executed, ensuring the database model remains untainted.

const updateProfileSchema = {
  body: {
    type: 'object',
    properties: {
      bio: { type: 'string' },
      avatarUrl: { type: 'string' }
    },
    // CRITICAL: Prevent keys not defined in 'properties' from being processed
    additionalProperties: false 
  }
};

fastify.post(‘/api/profile/update’, { schema: updateProfileSchema }, async (request, reply) => { const user = await User.findOne({ id: request.user.id });

// Even if using Object.assign, ‘request.body’ now only contains ‘bio’ and ‘avatarUrl’ Object.assign(user, request.body);

await user.save(); return { success: true }; });

System Alert • ID: 7662
Target: Fastify API
Potential Vulnerability

Your Fastify API might be exposed to Mass Assignment

74% of Fastify apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.

RUN FREE SECURITY DIAGNOSTIC
GuardLabs Engine: ONLINE

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.