Fix NoSQL Injection in LoopBack
LoopBack's abstraction layer often masks the underlying NoSQL query construction. When developers pass raw, unvalidated request objects directly into repository methods like 'find' or 'findOne', they open the door for NoSQL injection. Attackers can inject MongoDB operators such as $gt, $ne, or $where to bypass authentication, leak the entire database, or cause Denial of Service.
The Vulnerable Pattern
import {get, param, Filter} from '@loopback/rest'; import {User} from '../models';
export class UserController { @get(‘/users’) async find(@param.query.object(‘filter’) filter?: Filter) { // VULNERABLE: The filter object is taken directly from the URL query string. // An attacker can send: /users?filter={“where”:{“password”:{“$gt”:""}}} return this.userRepository.find(filter); } }
The Secure Implementation
The vulnerability occurs because the LoopBack MongoDB connector maps JSON objects directly to MongoDB queries. If an attacker provides an object where a string is expected, they can use operators like '$ne' (not equal) to return all records except one, effectively dumping the database. To fix this, you must: 1. Avoid accepting complex 'Filter' objects directly from users. 2. Enforce strict type validation using OpenAPI decorators (e.g., @param.query.string). 3. Sanitize inputs to strip any key starting with '$' if you must accept objects. 4. Use LoopBack's built-in validation at the Model level to ensure properties match expected primitive types.
import {get, param} from '@loopback/rest';
export class UserController { @get(‘/users’) async find(@param.query.string(‘username’) username: string) { // SECURE: Force a primitive type (string) and manually construct the filter. // This prevents the injection of MongoDB operator objects. return this.userRepository.find({ where: { username: username }, limit: 10 }); } }
Your LoopBack API
might be exposed to NoSQL Injection
74% of LoopBack 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.