GuardAPI Logo
GuardAPI

Fix NoSQL Injection in Fastify

NoSQL injection in Fastify/Mongoose environments occurs when untrusted input is merged directly into a query object. Attackers exploit this by passing objects instead of strings, injecting operators like '$gt', '$ne', or '$regex' to bypass logic or exfiltrate data. In a Fastify context, failing to leverage JSON schema validation is the primary root cause.

The Vulnerable Pattern

fastify.post('/api/login', async (req, reply) => {
  // VULNERABLE: req.body is used directly. 
  // An attacker can send {"password": {"$ne": ""}} to bypass authentication.
  const { username, password } = req.body;
  const user = await db.collection('users').findOne({ username, password });
  return user || reply.status(401).send({ error: 'Unauthorized' });
});

The Secure Implementation

The vulnerability exists because NoSQL databases like MongoDB treat objects as operators. By default, Fastify parses JSON bodies into objects; if the schema is not defined, 'req.body.password' could be an object. The fix uses Fastify's built-in JSON Schema validation (Ajv) to enforce that 'username' and 'password' are strictly strings. This prevents 'operator injection' because any non-string value causes a validation failure at the framework level, ensuring the database driver only receives literal values.

fastify.post('/api/login', {
  schema: {
    body: {
      type: 'object',
      properties: {
        username: { type: 'string' },
        password: { type: 'string' }
      },
      required: ['username', 'password'],
      additionalProperties: false
    }
  }
}, async (req, reply) => {
  // SECURE: Fastify's Ajv validation ensures username and password are primitives.
  // If an attacker sends an object, the request is rejected with a 400 error before execution.
  const { username, password } = req.body;
  const user = await db.collection('users').findOne({ username, password });
  return user || reply.status(401).send({ error: 'Unauthorized' });
});
System Alert • ID: 4998
Target: Fastify API
Potential Vulnerability

Your Fastify API might be exposed to NoSQL Injection

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.