Fix NoSQL Injection in AdonisJS
NoSQL Injection in AdonisJS environments—specifically when using Lucid with MongoDB adapters or raw Mongoose integrations—occurs when the application fails to enforce strict type checking on user-supplied data. Attackers leverage JSON object injection to pass operators like $gt, $ne, or $regex, effectively hijacking query logic to bypass authentication or dump the entire database.
The Vulnerable Pattern
async login({ request, response }) { // VULNERABLE: request.all() returns raw objects. // If 'password' is sent as {"$ne": null}, authentication is bypassed. const { email, password } = request.all(); const user = await User.query() .where('email', email) .where('password', password) .first();
if (user) return response.ok(user); return response.unauthorized(); }
The Secure Implementation
The exploit targets the loose typing of JavaScript objects. In the vulnerable snippet, passing a JSON body like {"email": "[email protected]", "password": {"$ne": ""}} causes the underlying driver to query for any user where the password is not an empty string. To remediate, you must sanitize inputs by enforcing string-only types. Using the AdonisJS Validator is the gold standard; it strips unexpected nested objects and ensures the database driver receives a literal string, nullifying operator injection attempts.
import { schema, rules } from '@ioc:Adonis/Core/Validator';async login({ request, response }) { // SECURE: Enforce strict string typing using the Adonis Validator const loginSchema = schema.create({ email: schema.string({ trim: true }, [rules.email()]), password: schema.string(), });
const payload = await request.validate({ schema: loginSchema });
const user = await User.query() .where(‘email’, payload.email) .where(‘password’, payload.password) .first();
if (user) return response.ok(user); return response.unauthorized(); }
Protect your AdonisJS API
Don't rely on manual checks. GuardAPI's Gemini 3 Pro engine detects NoSQL Injection and logic flaws in seconds.
Run Automated AuditVerified 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.