GuardAPI Logo
GuardAPI

Fix Mass Assignment in NestJS

Mass assignment in NestJS occurs when untrusted input is bound directly to internal models or database entities. Attackers exploit this by injecting unauthorized keys—like 'role', 'isAdmin', or 'balance'—into the JSON payload. If the backend spreads the raw request body into a persistence layer, it permits privilege escalation or data corruption.

The Vulnerable Pattern

@Post('profile')
async updateProfile(@Req() req, @Body() body: any) {
  // VULNERABLE: The spread operator passes every key in 'body' to the update method.
  // An attacker sends { "bio": "new bio", "role": "admin" } to escalate privileges.
  return this.userService.update(req.user.id, { ...body });
}

The Secure Implementation

The fix relies on an allow-list approach via DTOs and the NestJS ValidationPipe. By setting 'whitelist: true', the pipe automatically strips any properties from the request body that do not have a corresponding decorator in the DTO. Enabling 'forbidNonWhitelisted: true' takes it further by throwing a 400 Bad Request error if the attacker attempts to pass unauthorized keys, providing immediate feedback that their injection attempt was blocked.

// 1. Configure the Global Validation Pipe in main.ts
app.useGlobalPipes(new ValidationPipe({
  whitelist: true,
  forbidNonWhitelisted: true,
  transform: true,
}));

// 2. Define a strict Data Transfer Object (DTO) export class UpdateUserDto { @IsString() @IsOptional() bio?: string;

@IsString() @IsOptional() avatarUrl?: string; }

// 3. Use the DTO in the Controller @Post(‘profile’) async updateProfile(@Body() updateDto: UpdateUserDto) { // SECURE: Only ‘bio’ and ‘avatarUrl’ will exist in updateDto. // Any other fields like ‘role’ are stripped by the ValidationPipe. return this.userService.update(req.user.id, updateDto); }

System Alert • ID: 9181
Target: NestJS API
Potential Vulnerability

Your NestJS API might be exposed to Mass Assignment

74% of NestJS 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.