Claude MCP skill NoSQL injection in search and filter parameters — SA-SKL-NOSQL4
MongoDB's query language treats JSON object values as operator expressions — { "$regex": "^admin" } is a valid query operator that runs a full-collection regex scan, not a string to match literally. When Express.js receives a query string like ?q[$regex]=^admin, it automatically parses the nested bracket notation into a JavaScript object: { q: { $regex: '^admin' } }. If this object is passed directly to Mongoose as the query value, MongoDB executes the regex operator the attacker injected. SA-SKL-NOSQL4 covers four NoSQL injection patterns in MCP skill registry search and filter endpoints.
{ name: req.query.q } — attacker sends ?q[$regex]=^a&q[$options]=i; Express parses nested brackets as { $regex: '^a', $options: 'i' }; Mongoose executes full collection regex scan; causes DoS + data enumeration of all skill names starting with any prefix{ status: req.body.status } — attacker sends {"status": {"$ne": "active"}} via JSON body; returns all skills that are NOT active — deleted, suspended, and private skills visible; bypasses the active-only filter entirely$match stage uses user-supplied field name — attacker controls the field name in $match: { [req.query.sortBy]: req.query.value }; sends sortBy=passwordHash&value=partialHash to enumerate users by password hash fragmentsfindById() with user-supplied ID — when ID is a JSON object instead of a 24-char hex string, Mongoose throws a CastError that reveals the model collection name and field types; attacker sends {"id":{"$gt":""}} to trigger detailed schema error responsesNOSQL4-001 — MongoDB $regex injection via Express bracket notation
Express's default query string parser (qs) converts bracket notation in URLs to nested JavaScript objects. The URL /api/skills?q[$regex]=^admin&q[$options]=i becomes req.query.q = { $regex: '^admin', $options: 'i' }. When this object is used directly as a MongoDB query value ({ name: req.query.q }), MongoDB executes the attacker's regex operator. This is a full-collection scan: without an index on name, MongoDB scans every document. The attacker can use unbounded regexes to cause CPU-intensive scans on large collections, and can also use the regex as a data enumeration tool by sending multiple requests with different anchored prefixes.
// VULNERABLE — NOSQL4-001
// Attacker URL: GET /api/skills/search?q[$regex]=^admin&q[$options]=i
// Express parses: req.query.q = { $regex: '^admin', $options: 'i' }
// MongoDB executes: { name: { $regex: '^admin', $options: 'i' } }
// — full collection regex scan, no index used
app.get('/api/skills/search', async (req, res) => {
const { q, category, page = 1 } = req.query;
const filter = {};
// VULNERABLE: q is used directly as MongoDB query value
// If q is an object (from bracket notation), MongoDB treats it as an operator expression
if (q) filter.name = q;
if (category) filter.category = category;
const skills = await Skill.find(filter)
.skip((page - 1) * 20)
.limit(20);
res.json({ skills });
});
// FIXED — NOSQL4-001
// Fix 1: Validate that q is a string, not an object, with typeof check.
// Fix 2: For text search, use MongoDB $text operator with a text index (much faster than $regex).
// Fix 3: If regex search is required, enforce anchored prefix pattern and length limits.
app.get('/api/skills/search', async (req, res) => {
const { q, category, page = 1 } = req.query;
const filter = { status: 'active' };
if (q !== undefined) {
// FIX 1: Reject non-string query values (bracket-notation objects)
if (typeof q !== 'string') {
return res.status(400).json({ error: 'Invalid search query' });
}
// FIX 2: Sanitize length to prevent catastrophic regex
const sanitizedQ = q.slice(0, 100).trim();
if (sanitizedQ.length === 0) {
return res.status(400).json({ error: 'Search query cannot be empty' });
}
// FIX 3: Use $text search (requires a text index on name + description)
// OR use a simple string equality / allowlisted $regex with escaped input:
// FIX option A — text search (preferred):
filter.$text = { $search: sanitizedQ };
// FIX option B — if prefix regex is needed, escape and anchor:
// const escaped = sanitizedQ.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
// filter.name = { $regex: `^${escaped}`, $options: 'i' }; // anchored prefix only
}
if (category !== undefined) {
// FIX: Validate category against an allowlist
const ALLOWED_CATEGORIES = ['security', 'productivity', 'data', 'devtools', 'other'];
if (!ALLOWED_CATEGORIES.includes(category)) {
return res.status(400).json({ error: 'Invalid category' });
}
filter.category = category;
}
const skills = await Skill.find(filter).skip((+page - 1) * 20).limit(20);
res.json({ skills });
});
category is also vulnerable: NOSQL4-001 shows the q parameter, but the same bracket notation attack works on category: ?category[$ne]=security becomes { category: { $ne: 'security' } } which returns all skills that are NOT in the security category — bypassing any category filter. Any query parameter used as a MongoDB field value must be validated as a string.
NOSQL4-002 — MongoDB $ne operator bypasses active-only filter
REST APIs that accept JSON bodies are especially vulnerable to MongoDB operator injection because Content-Type: application/json + express.json() parses the body as a full JavaScript value — including nested objects with operator keys. A filter like { status: req.body.status } is intended to find skills with status === "active", but when the client sends {"status": {"$ne": "active"}}, MongoDB interprets the value as a $ne (not-equal) operator and returns all skills that do NOT have status "active" — including deleted, suspended, flagged, and private skills.
// VULNERABLE — NOSQL4-002
// Attacker body: { "status": { "$ne": "active" } }
// MongoDB query: Skill.find({ status: { $ne: 'active' } })
// Returns: all deleted, suspended, flagged, and private skills
app.get('/api/skills', async (req, res) => {
// Client sends filter params in request body for GET (unusual but common in some APIs)
const { status = 'active', authorId, orgId } = req.body;
// VULNERABLE: status passed directly to MongoDB query
const filter = { status };
if (authorId) filter.authorId = authorId;
if (orgId) filter.orgId = orgId;
const skills = await Skill.find(filter).limit(50);
res.json({ skills });
});
// FIXED — NOSQL4-002
// Fix: Validate status against a strict allowlist before using in query.
// Never pass user-supplied values directly as MongoDB query values without type + value validation.
const ALLOWED_STATUSES = ['active', 'published']; // only public-facing statuses
app.get('/api/skills', async (req, res) => {
const { status, authorId, orgId } = req.body;
// FIX: Validate status against allowlist — reject operator objects
const resolvedStatus = ALLOWED_STATUSES.includes(status) ? status : 'active';
const filter = { status: resolvedStatus };
// FIX: Validate authorId and orgId are strings, not operator objects
if (authorId !== undefined) {
if (typeof authorId !== 'string' || !/^[a-f0-9]{24}$/.test(authorId)) {
return res.status(400).json({ error: 'Invalid authorId' });
}
filter.authorId = authorId;
}
if (orgId !== undefined) {
if (typeof orgId !== 'string' || !/^[a-f0-9]{24}$/.test(orgId)) {
return res.status(400).json({ error: 'Invalid orgId' });
}
filter.orgId = orgId;
}
const skills = await Skill.find(filter).limit(50);
res.json({ skills });
});
NOSQL4-003 — Aggregation $match with user-controlled field name
Some registries expose search endpoints that allow clients to filter by any supported field — using the client-supplied field name directly as the MongoDB aggregation $match key. The developer intended to allow filtering by name, category, or createdAt, but forgot to validate the field name. An attacker sends ?sortBy=passwordHash&value=5e884898da280 — the aggregation executes { $match: { passwordHash: '5e884898...' } }, which returns any user document whose password hash starts with that prefix. Combined with a timing measurement of the response (whether results are returned), the attacker enumerates password hash values across the user collection.
// VULNERABLE — NOSQL4-003
// Attacker: GET /api/skills?sortBy=passwordHash&value=5e884898da28
// Aggregation executes: { $match: { passwordHash: '5e884898da28' } }
// Returns users whose password hash matches — data enumeration via field name injection
app.get('/api/skills/filter', async (req, res) => {
const { sortBy, value, page = 1 } = req.query;
const pipeline = [
{ $match: { status: 'active' } },
];
if (sortBy && value) {
// VULNERABLE: user-controlled field name used as $match key
// Any MongoDB field (including passwordHash, email, tokens) can be targeted
pipeline.push({ $match: { [sortBy]: value } });
}
pipeline.push({ $skip: (page - 1) * 20 }, { $limit: 20 });
const skills = await Skill.aggregate(pipeline);
res.json({ skills });
});
// FIXED — NOSQL4-003
// Fix: Use an explicit allowlist of sortable/filterable field names.
// Never use user-supplied values as MongoDB field name keys.
const ALLOWED_FILTER_FIELDS = new Set(['name', 'category', 'authorId', 'orgId', 'rating']);
app.get('/api/skills/filter', async (req, res) => {
const { sortBy, value, page = 1 } = req.query;
const pipeline = [{ $match: { status: 'active' } }];
if (sortBy !== undefined && value !== undefined) {
// FIX: Validate field name against explicit allowlist
if (!ALLOWED_FILTER_FIELDS.has(sortBy)) {
return res.status(400).json({ error: `Invalid filter field: ${sortBy}` });
}
// FIX: Validate value is a string (not an operator object)
if (typeof value !== 'string') {
return res.status(400).json({ error: 'Filter value must be a string' });
}
pipeline.push({ $match: { [sortBy]: value } });
}
pipeline.push({ $skip: (+(page) - 1) * 20 }, { $limit: 20 });
const skills = await Skill.aggregate(pipeline);
res.json({ skills });
});
NOSQL4-004 — Mongoose findById CastError leaks model schema
Mongoose's findById() method expects a 24-character hex string (MongoDB ObjectId). When an attacker passes a JSON object as the ID parameter, Mongoose tries to cast it to an ObjectId, fails, and throws a CastError. If the error is forwarded to the client unhandled, the error message contains the full model path: Cast to ObjectId failed for value "{\"$gt\":\"\"}" (type Object) at path "_id" for model "Skill". This reveals the model name (Skill), the internal field name (_id), and the expected type (ObjectId). Over multiple probes, an attacker can map the entire schema structure by crafting different invalid input types for different operations.
// VULNERABLE — NOSQL4-004
// Attacker: GET /api/skills/%7B%22%24gt%22%3A%22%22%7D (URL-encoded {"$gt":""})
// Or if Express parses :skillId as a bracket param: GET /api/skills/id[$gt]=
// Mongoose throws: CastError: Cast to ObjectId failed for value "{"$gt":""}"
// Error message reveals: model name "Skill", field "_id", type "ObjectId"
app.get('/api/skills/:skillId', async (req, res) => {
try {
const skill = await Skill.findById(req.params.skillId); // throws CastError for non-ObjectId input
if (!skill) return res.status(404).json({ error: 'Not found' });
res.json({ skill });
} catch (err) {
// VULNERABLE: CastError forwarded to client reveals schema details
res.status(400).json({ error: err.message });
}
});
// FIXED — NOSQL4-004
// Fix 1: Validate the ID parameter matches the expected ObjectId format BEFORE passing to Mongoose.
// Fix 2: Never forward CastError messages to the client — return generic 400/404.
const OBJECT_ID_REGEX = /^[a-f0-9]{24}$/i;
app.get('/api/skills/:skillId', async (req, res) => {
const { skillId } = req.params;
// FIX 1: Validate ObjectId format before database lookup
if (!OBJECT_ID_REGEX.test(skillId)) {
// FIX 2: Return 404 (not 400) so we don't confirm that the format is invalid
// — attacker cannot distinguish "not found" from "invalid ID format"
return res.status(404).json({ error: 'Not found' });
}
const skill = await Skill.findById(skillId);
if (!skill) return res.status(404).json({ error: 'Not found' });
res.json({ skill });
});
Use Mongoose strict mode: Enable strict: true in your Mongoose schema options (it is the default, but explicitly declaring it prevents accidental override in queries). Strict mode causes Mongoose to silently strip fields not defined in the schema before saving — this doesn't prevent injection in find() queries but does prevent an attacker from inserting arbitrary fields via POST bodies.
Summary — SA-SKL-NOSQL4 at a glance
| Pattern | Root cause | Fix | Severity |
|---|---|---|---|
| NOSQL4-001 | Query string bracket notation passed to MongoDB as operator object | typeof check; use $text index; escape and anchor regex | CRITICAL |
| NOSQL4-002 | JSON body $ne operator bypasses status filter | Allowlist validation on all enum field values | HIGH |
| NOSQL4-003 | User-controlled field name used as aggregation $match key | Allowlist of permitted filter field names | HIGH |
| NOSQL4-004 | Mongoose CastError forwarded to client, leaking schema details | Validate ObjectId format before lookup; return generic 404 | MEDIUM |
SkillAudit's NoSQL injection scanner automatically tests search and filter endpoints with bracket-notation payloads, operator injection via JSON body, and user-controlled field names. See also SA-SKL-NOSQL3 (MongoDB query operator injection) and SA-SKL-INJECTION11 (prototype pollution).