API Security NoSQL Injection

NoSQL databases such as MongoDB, CouchDB, and Redis store information as documents, key-value pairs, or graphs instead of rows and columns. These systems skip the SQL language, yet attackers still twist queries when an API trusts user input. NoSQL injection happens when crafted data changes the meaning of a database query.

Layman's Explanation

Picture a hotel receptionist who finds guest files by name. A visitor walks up and says, "Show me every guest whose name is not blank." The receptionist follows the sentence literally and hands over the whole filing cabinet. The visitor never needed a real name. A NoSQL injection tricks the database in the same way, because the database obeys the shape of the question it receives.

How the Attack Works

Most NoSQL queries use JSON objects. Special keys that start with a dollar sign act as operators. The operator $ne means "not equal", $gt means "greater than", and $regex means "matches a pattern". An API that passes the request body straight into a query lets the caller supply those operators.

Normal Login Versus Manipulated Login

 NORMAL REQUEST                     MANIPULATED REQUEST
 {                                  {
   "user": "ana",                     "user": "ana",
   "pass": "abc123"                   "pass": { "$ne": "" }
 }                                  }
        |                                   |
        v                                   v
 find( user = ana,                  find( user = ana,
       pass = abc123 )                    pass is anything non-empty )
        |                                   |
        v                                   v
 Matches only if the            Matches any account named ana,
 password is correct            with no password knowledge

Common Forms of NoSQL Injection

Operator Injection

The caller replaces a plain value with an object that holds an operator. Login forms, search filters, and password reset endpoints suffer most often.

JavaScript Injection

Some databases run JavaScript on the server through features like $where. Unchecked input inside those expressions lets a caller run logic inside the database engine.

Blind Data Extraction

An attacker uses pattern operators and watches response differences. A response that returns data means the guess matched. Repeated guesses reveal values one character at a time.

Real-World Impact

  • Login bypass and account takeover
  • Exposure of customer records
  • Slow queries that exhaust database resources
  • Data deletion or modification through unsafe update filters

Defense Methods

Enforce Data Types

Declare that a password field must be a string. Reject any request where the field arrives as an object or array. Type enforcement alone stops the most common attack.

Validate With a Schema

Libraries such as JSON Schema, Joi, Zod, and Pydantic describe the exact shape of each request. The API rejects anything outside that shape before the data touches a query.

Block Operator Keys

Strip or refuse keys that begin with a dollar sign or contain a dot in user-supplied objects. Many frameworks offer sanitize middleware for this job.

Compare Secrets in Code

Fetch the user record by username only. Compare the stored password hash with the submitted password inside the application. The database never evaluates the password as part of a filter.

Disable Server-Side JavaScript

Turn off features that run scripts inside the database when the application does not need them.

Apply Least Privilege

Give the API account the smallest set of rights. A read-only endpoint uses a read-only database user.

Quick Comparison

Risky HabitSafer Habit
Passing the request body directly into a queryPicking named fields and checking each type
Searching by username and password togetherSearching by username, then verifying the hash
Leaving server-side scripting onDisabling scripting features
Showing raw database errorsReturning short, generic error messages

Testing Your Own API

Send unexpected data types to every endpoint that reads JSON. Replace strings with objects and arrays. Watch for responses that return data instead of a clean validation error. Automated scanners and unit tests that submit wrong types catch these gaps early, and a failing test blocks a release before users ever see the flaw.