← Blog

Claude MCP skill NoSQL injection via MongoDB operator injection in data queries — SA-SKL-NOSQL2

MongoDB operator injection attacks exploit the fact that MongoDB query filters are JavaScript objects — not query strings — which means that when user-supplied data is passed directly into a query filter, an attacker who sends an object instead of a string can inject MongoDB query operators. Sending {"$ne": null} as a username bypasses equality checks; sending {"$where": "this.plan == 'admin'"} executes arbitrary JavaScript in the MongoDB engine. Four SA-SKL-NOSQL2 patterns cover the most common injection points in MCP skill data queries: unvalidated body fields in findOne, operator injection via Mongoose query builders, aggregation pipeline field name injection, and prototype pollution via strict:false schema spread.

By SkillAudit  |  9 Nov 2026
SA-SKL-NOSQL2 findings at a glance
CRITICALNOSQL2-001 — req.body.username passed directly to db.collection.findOne({username: body.username}); body sends {"$ne": null}; query matches any user; authentication bypassed without knowing any credentials
CRITICALNOSQL2-002 — $where operator injected via req.query.filter passed to Mongoose query builder; $where: "this.plan == 'admin'" executes JavaScript in MongoDB engine bypassing field-level access controls
HIGHNOSQL2-003 — Aggregation pipeline $lookup stage uses user-supplied field name without allowlist; arbitrary field name reads any field from the joined collection including password hashes and API keys
HIGHNOSQL2-004 — Mongoose schema strict: false combined with request body spread (new Model(req.body)); attacker adds __proto__ or constructor fields; prototype pollution corrupts application-wide object behavior

NOSQL2-001 — $ne:null authentication bypass

When an MCP skill accepts a JSON request body and uses a body field directly as a MongoDB query value, sending an object instead of a string causes MongoDB to treat the value as a query operator. A body of {"username": {"$ne": null}, "password": {"$ne": null}} causes the query db.users.findOne({username: {"$ne": null}, password: {"$ne": null}}) to match the first user in the collection whose username and password fields are not null — which is typically the admin or first registered user. Authentication is completely bypassed: the attacker needs no credentials.

// VULNERABLE — NOSQL2-001 (CRITICAL)
// req.body.username passed directly to MongoDB query.
// Attacker sends {"username": {"$ne": null}, "password": {"$ne": null}}
// MongoDB matches the first user where both fields are non-null.
import { MongoClient } from 'mongodb';

export async function login(req: express.Request, res: express.Response) {
  const { username, password } = req.body;

  // VULNERABLE: username and password may be objects with MongoDB operators
  const user = await db.collection('users').findOne({
    username: username,   // { "$ne": null } — matches ALL users
    password: password,   // { "$ne": null } — no password check
  });

  if (user) {
    req.session.userId = user._id;
    return res.json({ success: true });
  }
  res.status(401).json({ error: 'Invalid credentials' });
}
// FIXED — NOSQL2-001
// Validate type is string before using in query. Use bcrypt for passwords — never query by hash.
export async function login(req: express.Request, res: express.Response) {
  const { username, password } = req.body;

  // FIX 1: Validate type — reject non-string input at the boundary
  if (typeof username !== 'string' || typeof password !== 'string') {
    return res.status(400).json({ error: 'Invalid input' });
  }

  // FIX 2: Look up by username only, then check password with bcrypt
  // Never query by password directly — hash comparison must happen in JS
  const user = await db.collection('users').findOne({ username: username });
  if (!user || !await bcrypt.compare(password, user.passwordHash)) {
    return res.status(401).json({ error: 'Invalid credentials' });
  }

  req.session.userId = user._id;
  res.json({ success: true });
}

NOSQL2-002 — $where operator injection via query builder

The $where MongoDB operator accepts a JavaScript function or string that is evaluated in the MongoDB server's JavaScript engine. Any user-supplied filter value that reaches a Mongoose query builder without stripping operator-prefixed keys ($-prefixed fields) can inject a $where clause. This is particularly severe because $where executes JavaScript — not just a comparison — in the database engine. An attacker who injects {"$where": "sleep(10000)"} causes a DoS; {"$where": "this.plan == 'admin'"} bypasses plan-level access controls; {"$where": "Object.keys(this).join(',') == 'x'"} can be used to enumerate field names through timing side-channels.

// VULNERABLE — NOSQL2-002 (CRITICAL)
// User-supplied req.query.filter passed to Mongoose query without stripping operators.
// Attacker sends filter={"$where":"this.plan=='admin'"} to execute JS in MongoDB.
router.get('/api/audits', authenticate, async (req, res) => {
  let filter: object = { userId: req.user.id };

  if (req.query.filter) {
    try {
      const userFilter = JSON.parse(req.query.filter as string);
      // VULNERABLE: merges user-supplied object directly into MongoDB query
      // Attacker sends {"$where": "this.plan == 'admin'"} — executes in DB
      filter = { ...filter, ...userFilter };
    } catch (e) {}
  }

  const audits = await Audit.find(filter);
  res.json(audits);
});
// FIXED — NOSQL2-002
// Strip all operator-prefixed keys before merging. Never allow $where.
function stripMongoOperators(obj: Record<string, unknown>): Record<string, unknown> {
  const safe: Record<string, unknown> = {};
  for (const [key, value] of Object.entries(obj)) {
    // Reject any key starting with $ (MongoDB operators)
    if (key.startsWith('$')) continue;
    // Recursively strip nested objects
    if (value !== null && typeof value === 'object' && !Array.isArray(value)) {
      safe[key] = stripMongoOperators(value as Record<string, unknown>);
    } else {
      safe[key] = value;
    }
  }
  return safe;
}

router.get('/api/audits', authenticate, async (req, res) => {
  let filter: object = { userId: req.user.id };

  if (req.query.filter) {
    try {
      const userFilter = JSON.parse(req.query.filter as string);
      if (typeof userFilter === 'object' && !Array.isArray(userFilter)) {
        // FIX: strip all $ operator keys before merging into query
        filter = { ...filter, ...stripMongoOperators(userFilter) };
      }
    } catch (e) {}
  }

  const audits = await Audit.find(filter);
  res.json(audits);
});

NOSQL2-003 — Aggregation pipeline $lookup with user-supplied field name

MongoDB aggregation pipelines are powerful but accept field names as strings, making them vulnerable to injection when field names come from user input. A $lookup stage that uses a user-supplied localField or foreignField name without an allowlist allows the attacker to join on any field — including fields that contain sensitive data like password hashes, API keys, or internal token fields. The attacker does not get to control the pipeline logic, but they can redirect the join to expose columns that the developer never intended to include in the response.

// VULNERABLE — NOSQL2-003 (HIGH)
// $lookup localField comes from user query parameter — no allowlist.
// Attacker sets fieldName=passwordHash to include password hashes in join result.
router.get('/api/reports', authenticate, async (req, res) => {
  const fieldName = req.query.groupBy as string || 'userId';

  const result = await Audit.aggregate([
    { $match: { userId: req.user.id } },
    {
      $lookup: {
        from: 'users',
        localField: fieldName,  // VULNERABLE: user controls which field to join on
        foreignField: '_id',
        as: 'userDetails',
      },
    },
  ]);
  res.json(result);
});
// FIXED — NOSQL2-003
// Allowlist field names. Never pass user input directly into pipeline stage definitions.
const ALLOWED_GROUP_FIELDS = new Set(['userId', 'status', 'createdAt', 'skillId']);

router.get('/api/reports', authenticate, async (req, res) => {
  const rawField = req.query.groupBy as string;
  // FIX: validate against allowlist; default to safe value
  const fieldName = ALLOWED_GROUP_FIELDS.has(rawField) ? rawField : 'userId';

  const result = await Audit.aggregate([
    { $match: { userId: req.user.id } },
    {
      $lookup: {
        from: 'users',
        localField: fieldName,  // safe: allowlisted string only
        foreignField: '_id',
        as: 'userDetails',
      },
    },
    // Also project out sensitive fields from the joined document
    { $project: { 'userDetails.passwordHash': 0, 'userDetails.apiKey': 0 } },
  ]);
  res.json(result);
});

NOSQL2-004 — Mongoose strict:false with request body spread

Mongoose schemas have a strict option that defaults to true, which silently drops fields in a document that are not defined in the schema. Setting strict: false allows arbitrary fields to be stored. When combined with spreading the request body directly into a Mongoose model constructor or update call, an attacker who includes __proto__ or constructor fields in the JSON body can cause prototype pollution — corrupting the prototype chain of plain objects throughout the application. Additionally, MongoDB-specific fields like $set, $unset injected into an update spread can modify arbitrary document fields.

// VULNERABLE — NOSQL2-004 (HIGH)
// Mongoose strict: false combined with body spread into model constructor.
// Attacker adds __proto__ fields in body causing prototype pollution.
const auditSchema = new mongoose.Schema({
  userId: String,
  skillUrl: String,
  score: Number,
}, { strict: false });  // VULNERABLE: allows arbitrary fields to be stored

router.post('/api/audits', authenticate, async (req, res) => {
  // VULNERABLE: req.body spread into new Audit() with strict: false
  // Attacker body: {"__proto__": {"isAdmin": true}, "skillUrl": "..."}
  // Pollutes Object.prototype for all subsequent plain objects
  const audit = new Audit({ userId: req.user.id, ...req.body });
  await audit.save();
  res.json(audit);
});
// FIXED — NOSQL2-004
// Use strict: true (default). Explicitly extract only expected fields from body.
// Never spread req.body into a model constructor.
const auditSchema = new mongoose.Schema({
  userId: String,
  skillUrl: String,
  score: Number,
  // strict: true is the default — unknown fields are silently dropped
});

router.post('/api/audits', authenticate, async (req, res) => {
  // FIX: explicitly extract only the fields you expect — never spread body
  const { skillUrl } = req.body;

  if (typeof skillUrl !== 'string' || !skillUrl.startsWith('https://')) {
    return res.status(400).json({ error: 'Invalid skillUrl' });
  }

  const audit = new Audit({
    userId: req.user.id,
    skillUrl,            // safe: extracted individually, type-checked
    score: null,         // set by audit engine, not user input
  });
  await audit.save();
  res.json(audit);
});

SkillAudit detection: SA-SKL-NOSQL2 flags findOne/find calls that pass req.body fields directly as query values without a typeof string check, Mongoose query builders that accept user-supplied filter objects without $ key stripping, aggregation stage definitions with user-controlled field name strings, and Mongoose schemas with strict: false that also appear in routes spreading req.body. Run a free audit at skillaudit.dev.

PatternCVSSImpactFix
NOSQL2-001 $ne:null auth bypass9.8 CriticalAuthentication bypass without credentialsValidate typeof username === 'string'; check password with bcrypt
NOSQL2-002 $where JS injection9.8 CriticalArbitrary JavaScript in MongoDB engineStrip all $-prefixed keys from user-supplied filter objects
NOSQL2-003 $lookup field name7.5 HighArbitrary field read via join redirectAllowlist valid field names; never use user input as pipeline stage field
NOSQL2-004 strict:false body spread7.3 HighPrototype pollution; arbitrary field writesstrict: true (default); extract fields individually from body