← Blog

Claude MCP skill NoSQL injection via MongoDB query operator injection in skill search and filter endpoints — SA-SKL-NOSQL3

MongoDB's query language accepts JavaScript-style operator objects as field values: {"name": {"$regex": ".*"}} matches all documents, {"password": {"$gt": ""}} matches any non-empty string. When a Node.js MCP skill API parses a JSON request body and passes fields directly into a MongoDB find() query without validating that those fields are plain strings rather than operator objects, an attacker can inject MongoDB query operators through the JSON body. The root cause is a category difference between what the developer assumed (a string field value) and what MongoDB actually accepts (an operator object). Unlike SQL injection, there is no escaping step that makes this safe — the fix is structural: validate that every user-supplied field is a plain scalar type before it touches the query. SA-SKL-NOSQL3 covers four MongoDB operator injection patterns in MCP skill search and filter endpoints.

By SkillAudit  |  9 Nov 2026
SA-SKL-NOSQL3 findings at a glance
HIGHNOSQL3-001 — db.skills.find({ name: req.body.name }) — attacker sends JSON body with name: {"$regex": ".*"}; MongoDB accepts the operator object as the field value and matches every document in the collection; full skill database dumped with a single request
CRITICALNOSQL3-002 — db.users.findOne({ email: req.body.email, password: req.body.password }) — attacker sends password: {"$gt": ""}; MongoDB matches any user whose password field is greater than the empty string — effectively any user; authentication bypass for any account with just the email address
CRITICALNOSQL3-003 — MongoDB aggregation pipeline uses $where with a string from user input — $where: "this.rating > " + req.query.minRating; $where executes JavaScript inside the MongoDB engine; attacker injects 0; sleep(5000); return true for DoS or uses this.password references to extract data via Boolean timing
HIGHNOSQL3-004 — Query parameters spread into find() filter via db.skills.find({ ...req.query }); attacker adds ?isAdmin=true or ?internal=true to the query string; MongoDB matches only documents where those fields are truthy — bypassing the intended category/tag filter to access admin-only skill records

NOSQL3-001 — $regex operator injected through skill name search field

MCP skill search endpoints typically filter by skill name using a MongoDB find() query with the name field from the request body. When Express's express.json() middleware parses the request body, it deserializes the JSON faithfully — if the body contains {"name": {"$regex": ".*"}}, the parsed req.body.name is an object {"$regex": ".*"}, not a string. MongoDB's Node.js driver accepts this as a valid query operator. The $regex: ".*" pattern matches every document, so the query returns the full skills collection. The attacker has effectively bypassed the name filter and dumped all skill records with a single crafted request.

// VULNERABLE — NOSQL3-001
// db.skills.find() with req.body.name used directly — operator object injection.
// Attacker sends: POST /api/skills/search with body { "name": { "$regex": ".*" } }
// MongoDB executes: db.skills.find({ name: { $regex: ".*" } }) — returns ALL skills.

import { MongoClient } from 'mongodb';

app.post('/api/skills/search', async (req, res) => {
  const { name, category } = req.body;

  // VULNERABLE: name from request body passed directly to MongoDB query
  // If name is an object like { "$regex": ".*" }, MongoDB treats it as a query operator
  const skills = await db.collection('skills').find({
    name:     name,     // VULNERABLE: should be validated as string
    category: category, // also vulnerable to operator injection
  }).limit(50).toArray();

  res.json({ skills });
});
// FIXED — NOSQL3-001
// Fix 1: Validate that name is a string before using it in the query.
// Fix 2: If regex search is needed, construct the $regex explicitly on the server side.
// Fix 3: Use zod or joi schema validation at the endpoint boundary.

import { z } from 'zod';

const SearchSchema = z.object({
  name:     z.string().max(100).optional(),
  category: z.string().max(50).optional(),
  page:     z.number().int().min(1).max(1000).optional(),
});

app.post('/api/skills/search', async (req, res) => {
  const result = SearchSchema.safeParse(req.body);
  if (!result.success) {
    return res.status(400).json({ error: 'Invalid search parameters' });
  }

  const { name, category, page = 1 } = result.data;

  // FIX 1: name is guaranteed to be a string by schema validation
  // FIX 2: If partial match needed, construct $regex server-side, never accept it from input
  const filter = {};
  if (name)     filter.name     = { $regex: escapeRegex(name), $options: 'i' };  // server-constructed regex
  if (category) filter.category = category;  // string guaranteed by schema

  const skills = await db.collection('skills')
    .find(filter)
    .skip((page - 1) * 20)
    .limit(20)
    .toArray();

  res.json({ skills });
});

function escapeRegex(str) {
  return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}

Detection: SkillAudit scans for MongoDB find(), findOne(), updateOne(), and aggregate() calls where query filter fields trace back to req.body, req.query, or req.params without an intervening type validation step that guarantees the value is a plain scalar.

NOSQL3-002 — $gt operator injection bypasses password authentication

Authentication endpoints that look up a user by email and password in a single findOne() call are vulnerable to operator injection in the password field. MongoDB evaluates {"password": {"$gt": ""}} as "find any document where the password field is greater than the empty string" — which matches any non-empty password string, regardless of its value. An attacker who knows a valid email address sends a login request with the email as a string and the password as the $gt: "" operator object. MongoDB returns the matching user document, the authentication check passes, and the attacker gains access to any account with just the email address. This is the most critical NoSQL injection pattern because it completely bypasses authentication without any brute-forcing.

// VULNERABLE — NOSQL3-002
// Login query uses req.body.password directly — $gt operator injection bypasses auth.
// Attacker sends: POST /auth/login with body { "email": "victim@example.com", "password": { "$gt": "" } }
// MongoDB matches any user with that email whose password field is non-empty — authentication bypassed.

app.post('/auth/login', express.json(), async (req, res) => {
  const { email, password } = req.body;

  // VULNERABLE: password from request body used directly in MongoDB query
  // Operator object { "$gt": "" } passes the query — any non-empty password matches
  const user = await db.collection('users').findOne({ email, password });

  if (!user) {
    return res.status(401).json({ error: 'Invalid credentials' });
  }

  const token = generateJwt(user);
  res.json({ token });
});
// FIXED — NOSQL3-002
// Fix 1: Never store or query plain-text passwords — use bcrypt hashes.
// Fix 2: Look up user by email only; then compare password with bcrypt.compare().
// Fix 3: Type-validate that email and password are strings before any DB query.

import bcrypt from 'bcrypt';
import { z } from 'zod';

const LoginSchema = z.object({
  email:    z.string().email().max(254),
  password: z.string().min(1).max(1024),  // FIX 3: guaranteed string, not object
});

app.post('/auth/login', express.json(), async (req, res) => {
  const result = LoginSchema.safeParse(req.body);
  if (!result.success) {
    return res.status(400).json({ error: 'Invalid credentials format' });
  }

  const { email, password } = result.data;

  // FIX 2: Look up user by email only — no password in the MongoDB query
  const user = await db.collection('users').findOne({ email });

  if (!user) {
    // FIX: Constant-time response — don't reveal whether email exists
    await bcrypt.compare(password, '$2b$12$invalidhashfortimingnormalization');
    return res.status(401).json({ error: 'Invalid credentials' });
  }

  // FIX 1: Password comparison via bcrypt — no MongoDB query operator involved
  const passwordValid = await bcrypt.compare(password, user.passwordHash);
  if (!passwordValid) {
    return res.status(401).json({ error: 'Invalid credentials' });
  }

  const token = generateJwt(user);
  res.json({ token });
});

NOSQL3-003 — MongoDB $where executes JavaScript from user input

MongoDB's $where operator allows JavaScript expressions to be evaluated inside the MongoDB engine for each document in a collection. This feature predates the more capable aggregation pipeline operators and is deprecated in MongoDB 4.4+ for performance and security reasons. When a MCP skill search endpoint constructs a $where expression by concatenating a user-supplied value — such as a minimum rating filter — the user can inject arbitrary JavaScript. The injection runs with access to this (the current document), enabling Boolean-based data extraction (this.password[0] == 'a'), tautology bypasses (return true), or denial-of-service via intentional long-running JavaScript (sleep(5000)). The fix is to never use $where with any user input, and to replace it with structured aggregation pipeline operators.

// VULNERABLE — NOSQL3-003
// MongoDB $where with user-supplied string — executes JavaScript inside MongoDB.
// Attacker sends: GET /api/skills?minRating=0;sleep(5000);return true
// MongoDB executes: $where: "this.rating > 0;sleep(5000);return true" — 5s DoS per request.
// Or: ?minRating=0||this.apiKey.length>0 — extracts data via Boolean timing.

app.get('/api/skills', async (req, res) => {
  const { minRating } = req.query;

  // VULNERABLE: $where with string concatenation — user input executed as MongoDB JavaScript
  const filter = minRating
    ? { $where: `this.rating > ${minRating}` }  // VULNERABLE: minRating injected into JS
    : {};

  const skills = await db.collection('skills').find(filter).toArray();
  res.json({ skills });
});
// FIXED — NOSQL3-003
// Fix 1: Never use $where with any user input — use $expr with $gt/$lt operators instead.
// Fix 2: Validate minRating as a number before using in any query.
// Fix 3: Use aggregation pipeline $match stage with $expr for complex comparisons.

import { z } from 'zod';

const FilterSchema = z.object({
  minRating: z.coerce.number().min(0).max(5).optional(),
  maxRating: z.coerce.number().min(0).max(5).optional(),
  category:  z.string().max(50).optional(),
});

app.get('/api/skills', async (req, res) => {
  const result = FilterSchema.safeParse(req.query);
  if (!result.success) {
    return res.status(400).json({ error: 'Invalid filter parameters' });
  }

  const { minRating, maxRating, category } = result.data;

  // FIX 1 + 2: Use structured MongoDB operators — no JavaScript execution, no $where
  const filter = {};
  if (minRating != null || maxRating != null) {
    filter.rating = {};
    if (minRating != null) filter.rating.$gte = minRating;  // FIX 1: $gte, not $where
    if (maxRating != null) filter.rating.$lte = maxRating;
  }
  if (category) filter.category = category;

  const skills = await db.collection('skills').find(filter).limit(50).toArray();
  res.json({ skills });
});

Detection: SkillAudit scans for $where in MongoDB query objects where the value is a template literal or string concatenation involving request data. It also flags deprecated $where usage even without user input, as the operator is a security risk in any context. It recommends replacing with $expr and aggregation operators.

NOSQL3-004 — req.query spread into MongoDB find() filter

REST API endpoints sometimes accept multiple optional filter parameters via query strings and spread the entire query object into a MongoDB find() call for convenience: db.skills.find({ ...req.query }). This pattern passes all query string parameters as MongoDB filter fields, including any field not intended to be filterable. An attacker who knows the internal MongoDB document schema (observable from API responses, error messages, or public GitHub history) adds query parameters like ?isAdmin=true, ?internal=true, or ?deleted=true to bypass filters and access records that should be hidden — admin-only skills, soft-deleted records, or internal beta features. Unlike the operator injection patterns, this requires no special operator knowledge — just adding a boolean query parameter.

// VULNERABLE — NOSQL3-004
// req.query spread directly into MongoDB find() filter — any query param becomes a filter field.
// Attacker sends: GET /api/skills?category=security&isAdmin=true
// MongoDB executes: db.skills.find({ category: "security", isAdmin: true }) — returns admin skills.
// Or: GET /api/skills?deleted=true — returns soft-deleted skills.
// Or: GET /api/skills?internal=true — returns internal draft skills not meant to be public.

app.get('/api/skills', async (req, res) => {
  // VULNERABLE: entire req.query spread into find filter — attacker controls all filter fields
  const skills = await db.collection('skills').find({
    ...req.query,
    published: true,  // intended gate: only show published skills
    // VULNERABLE: attacker can override or add any MongoDB field as a filter
  }).toArray();

  res.json({ skills });
});
// FIXED — NOSQL3-004
// Fix 1: Allowlist permitted filter fields — construct filter object explicitly from known fields only.
// Fix 2: Type-validate each permitted field — no operator objects, correct scalar types.
// Fix 3: Always include non-overridable security filters (published:true) AFTER building the filter.

import { z } from 'zod';

const SkillFilterSchema = z.object({
  category: z.string().max(50).optional(),
  tags:     z.string().max(100).optional(),   // comma-separated tags
  author:   z.string().max(50).optional(),
  page:     z.coerce.number().int().min(1).optional(),
  limit:    z.coerce.number().int().min(1).max(50).optional(),
});

app.get('/api/skills', async (req, res) => {
  const result = SkillFilterSchema.safeParse(req.query);
  if (!result.success) {
    return res.status(400).json({ error: 'Invalid filter' });
  }

  const { category, tags, author, page = 1, limit = 20 } = result.data;

  // FIX 1 + 2: Build filter explicitly from allowlisted, type-validated fields only
  const filter = {};
  if (category) filter.category = category;  // string, not spread from req.query
  if (author)   filter.author   = author;
  if (tags)     filter.tags     = { $in: tags.split(',').map(t => t.trim()).slice(0, 10) };

  // FIX 3: Non-overridable security gates applied AFTER building filter — attacker cannot override
  filter.published = true;
  filter.isAdmin   = { $ne: true };  // explicitly exclude admin skills
  filter.deleted   = { $ne: true };  // explicitly exclude soft-deleted skills

  const skills = await db.collection('skills')
    .find(filter)
    .skip((page - 1) * limit)
    .limit(limit)
    .toArray();

  res.json({ skills });
});

Summary — SA-SKL-NOSQL3 at a glance

PatternRoot causeFixSeverity
NOSQL3-001find({ name: req.body.name }) — name can be an operator object like {"$regex":".*"}; MongoDB accepts operator as field value; full collection dumped in one requestSchema validate name as z.string(); construct $regex server-side from validated string; never pass raw body fields to find()High
NOSQL3-002findOne({ email, password: req.body.password }) — password can be {"$gt":""}; MongoDB matches any user; complete authentication bypass with just email addressLook up user by email only; compare password with bcrypt.compare(); never query by plaintext or user-supplied password valueCritical
NOSQL3-003$where: "this.rating > " + req.query.minRating — executes JavaScript inside MongoDB engine; attacker injects sleep() DoS or Boolean data extraction via timingNever use $where with user input; replace with $expr + $gte/$lte pipeline operators; validate minRating as a numberCritical
NOSQL3-004find({ ...req.query }) — attacker adds ?isAdmin=true or ?deleted=true; intended security gates (published:true) can be bypassed; admin/internal/deleted records exposedAllowlist permitted filter fields; construct filter object explicitly; apply security gates (published:true, isAdmin:{$ne:true}) after building user-controlled filterHigh
SkillAudit

Does your MCP skill's MongoDB query code protect against NoSQL operator injection?

SkillAudit scans for MongoDB find() and findOne() calls where request body fields are used directly as query values without type validation, login queries that include password in the MongoDB filter, $where with concatenated user input, and req.query spread into find() filters — before an attacker injects an operator and dumps your skill database or bypasses authentication.

Audit your MCP skill →