guides · 2026-11-14
NoSQL Injection: How a MongoDB Login Falls to a Single $ne Operator
Published 2026-11-14 · Reviewed 2026-11-14 · By the Ingenious AI team
The short answer
If your login passes request JSON straight into a MongoDB query, an attacker who sends {"password": {"$ne": null}} is not guessing your password — they are asking the database for 'any user whose password is not null', and it answers. The fix is type discipline: cast credentials to strings before querying, reject objects in scalar fields, and never let req.body become a query or a document unchanged.
Check your own app free: paste your code or enter your site URL on the Vibe-Code Audit homepage — the free scan checks for exposed secrets, injection flaws, XSS patterns, missing headers and exposed .env/.git paths, with a copy-paste fix for every finding. No credit card.
The bypass, line by line
The vulnerable shape is beloved by generators because it is three lines long: const user = await User.findOne({ email: req.body.email, password: req.body.password }). With a normal form post, both fields are strings and it works. But a JSON content-type lets the caller send objects: {"email": "[email protected]", "password": {"$ne": null}}. MongoDB reads the password condition as an operator — not equal to null — which is true for every real account, so findOne returns the admin. No password was guessed; the query was rewritten by its own input.
Variations multiply: $gt: "" matches any non-empty string, $regex enables probing passwords character by character through timing and error differences, and $where (in older configurations) executes JavaScript server-side. Vibe-Code Audit carries dedicated detectors for both the $where shape and operators receiving raw request data — this class is common enough in AI-generated Node code to deserve its own patterns.
Why TypeScript and schemas did not save you
Teams protest that their types declare password: string. Types are compile-time fiction; the wire sends what it sends, and a JSON parser happily produces an object where the type promised a string. Unless runtime validation actually runs — a schema check, an explicit typeof test, a casting helper — the database receives the object untouched. The same gap bites Python apps using PyMongo with request JSON, and any stack where 'the framework validates it' is assumed rather than configured.
The second false comfort is hashing: 'we store bcrypt hashes, so $ne cannot match.' The operator attack does not need the stored value's shape — $ne: null is true for a hash too. Hashing protects passwords at rest; it does nothing about query logic.
What is NoSQL injection (operator injection)?
a flaw specific to document databases: because queries are themselves JSON-like objects, attacker-supplied JSON can smuggle query operators ($ne, $gt, $regex, $where) into a query, changing its logic. It is SQL injection's sibling, born from passing parsed request bodies directly into find() calls.
The fix: cast, validate, constrain
At the boundary, force scalars to be scalars: const email = String(req.body.email ?? ''); then reject the request if the original value was not a string at all — silent casting of an object produces '[object Object]', which fails closed, but explicit rejection is clearer and loggable. Use a validation library (zod, joi, pydantic) with strict schemas on every auth and query-adjacent endpoint, configured to strip or reject unknown operators. For queries you must build dynamically, allow-list the fields and operators your feature needs instead of forwarding the client's object.
Defence in depth: run the database user for the app with least privilege, keep $where disabled, and add the bypass payloads to your test suite — the $ne login attempt should return 401 forever, including after future refactors.
Where else operators hide
Login is the famous case, not the only one. Search endpoints that forward filters, 'advanced query' features, webhook handlers that look up records by posted JSON, and update endpoints doing findOneAndUpdate(filterFromBody) all share the shape. The audit sweep is a grep for find/findOne/update calls whose arguments trace back to request data without an intervening schema — the same taint question a scanner asks when it flags operator-with-user-input patterns. Fix the pattern at a shared validation helper and the whole class closes at once, instead of endpoint by endpoint.
Worked example: Petal & Post, a florist marketplace
Petal & Post (fictional), a marketplace with 3,100 accounts, had its login generated by an AI assistant in the three-line style. During a scan the NoSQL operator detector fired on the auth route; the owner reproduced the bypass in staging with {"$ne": null} and was logged in as the marketplace admin in under a minute. The fix took an afternoon: zod schemas on the four auth-adjacent endpoints, explicit string checks in the login handler, and operator allow-listing on the seller search. They added the $ne and $gt payloads as permanent API tests. No evidence of prior abuse was found in 90 days of logs — the scan caught what the logs would eventually have shown.
Five things to do before you ship
- Send {"$ne": null} and {"$gt": ""} as the password to your own staging login; a successful login is a critical finding.
- Add runtime validation (zod, joi, pydantic) to every endpoint that feeds request data into a query — types alone do not run at runtime.
- Cast credential and lookup fields to strings explicitly and reject non-string input with a 400.
- Grep for find, findOne and update calls built from request bodies; route them all through one validated helper.
- Save the operator payloads as regression tests so a future refactor cannot quietly reopen the bypass.
Sources
- CWE-89: Improper Neutralization of Special Elements used in an SQL Command, MITRE's weakness entry for SQL injection and its mitigations: cwe.mitre.org, 2026
- PortSwigger Web Security Academy — SQL injection, the reference tutorial on how SQL injection works and how parameterized queries prevent it: portswigger.net, 2026
- OWASP Top 10, the OWASP Foundation's standard awareness list of the most critical web application security risks: owasp.org, 2021
Frequently asked questions
Does this affect SQL databases too?
Not in this shape — SQL drivers receive strings, not operator objects. The JSON-operator trick is specific to document stores (MongoDB and friends) where the query language is itself JSON-like.
We hash passwords. Are we safe?
No. The attack changes the comparison, not the value: 'hash is not null' is true regardless of hashing. Hashing is essential for storage and irrelevant to operator injection.
Is String(req.body.password) a complete fix?
It closes the login case, because an object becomes a harmless literal string. The complete fix is validation everywhere request data meets a query — search filters and update endpoints have the same disease.
How do I find every vulnerable endpoint?
Search the codebase for query calls whose arguments derive from request objects without a schema step, and scan: the operator-with-user-input detector exists for exactly this sweep.
Related guides
- SSRF in AI-Generated Code: When Your App Fetches Any URL a User Gives It
- Server-Side Template Injection in Flask Apps Built With AI
- Why pickle.loads and yaml.load Turn User Data Into Code Execution
- JWT alg=none and Key Confusion: How Attackers Forge Any User's Token
- How to Fix CORS Errors Without Opening Your API to Every Website
- Debug Mode in Production: What One Stack Trace Hands an Attacker
- 7 Security Mistakes AI Coders Keep Making
- Supply-Chain Attacks in the AI-Coding Era
- Secret Hygiene: Stop API Key Leaks
- What Code Scanners Can't Find
- Scan Your Lovable Code Before Deploying
- LLM Threats in AI-Generated Apps
Browse the full library on the guides index, run the checks in the launch audit, or compare plans on pricing.
Informational explainer, not a security guarantee. Scan your code free before every deploy.