Skip to content

chore(deps): update dependency mongoose to v9.11.4 [security] - #1698

Open
renovate[bot] wants to merge 1 commit into
mainfrom
renovate/npm-mongoose-vulnerability
Open

renovate[bot] wants to merge 1 commit into
mainfrom
renovate/npm-mongoose-vulnerability

Conversation

@renovate

@renovate renovate Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

This PR contains the following updates:

Package Change Age Confidence
mongoose (source) 9.9.3 → 9.11.4 age confidence

Mongoose: Connection-level sanitizeFilter not applied

CVE-2026-125119 / GHSA-gg4r-jv3p-qx3c

More information

Details

Summary

sanitizeFilter exists to stop query selector injection: it wraps operator objects such as { $ne: null } in filter values in $eq, so they are matched literally. Set on a connection with mongoose.connect() or createConnection(uri, { sanitizeFilter: true }), the connection reports it as enabled but queries never apply it. An application that relies on the connection-level option and passes an attacker-controlled object into a filter therefore remains open to selector injection, and a password value of { $ne: null } returns the account record without the password.

Details

NativeConnection#createClient() at lib/drivers/node-mongodb-native/connection.js:270-272 moves options.sanitizeFilter into Connection.config and deletes the original option. Query#_castConditions() at lib/query.js:2413-2423 checks Connection.options, the global options, and the per-query options, but never Connection.config. The defense therefore does not run even though Connection#get('sanitizeFilter') returns true. This storage was introduced in Mongoose 6.0.0 and the same mismatch is present in 9.11.2.

Proof of concept
import mongoose from 'mongoose'

const conn = await mongoose.createConnection('<MONGODB_URI>', { sanitizeFilter: true }).asPromise()
const User = conn.model('User', new mongoose.Schema({
  username: String,
  password: String,
  marker: String
}))

await User.create({
  username: 'victim',
  password: 'correct-password',
  marker: 'PROTECTED_RECORD'
})

const filter = { username: 'victim', password: { $ne: null } }
console.log(conn.get('sanitizeFilter'))
console.log((await User.findOne(filter).lean()).marker)

A control query with a literal wrong password returned no document in the same run, confirming the filter is otherwise enforced.

Impact

Connection-level sanitizeFilter option is not respected. Any user that relies on connection-level config and sanitizeFilter to defend against query selector injection is affected. Users that set sanitizeFilter globally using mongoose.set('sanitizeFilter') or on specific queries using Model.find().sanitizeFilter() are not affected.

Severity

  • CVSS Score: 7.5 / 10 (High)
  • Vector String: CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N

References

This data is provided by the GitHub Advisory Database (CC-BY 4.0).


Mongoose: Prototype pollution via Schema.prototype.virtual()

CVE-2026-125118 / GHSA-6972-9mcm-vhwj

More information

Details

Summary

Prototype pollution via Schema.prototype.virtual() — the 2022 fix for CVE-2022-2564 / CVE-2022-24304 protected Schema.path()/add() but never virtual(), so the same class of bug is still exploitable in all maintained release lines.

Details

In lib/schema.js, Schema.prototype.virtual() (defined at line 2643) builds the virtual path via:

virtuals[name] = parts.reduce(function(mem, part, i) {
mem[part] || (mem[part] = (i === parts.length - 1)
? new VirtualType(options, name)
: {});
return mem[part];
}, this.tree); // lines 2755-2759

Unlike path()/add(), virtual() never received the specialProperties check added for CVE-2022-2564/CVE-2022-24304 (lib/schema.js lines 806, 1308, 1331).

A path containing __proto__/constructor/prototype segments resolves through the prototype chain and writes onto Object.prototype / Function.prototype.

Proof of concept
const mongoose = require('mongoose');
const schema = new mongoose.Schema({});

schema.virtual('__proto__.polluted');
console.log(({}).polluted); // VirtualType instance
console.log(Object.prototype.hasOwnProperty('polluted')); // true
console.log(Object.getOwnPropertyDescriptor(
Object.prototype, 'polluted').enumerable); // true

schema.virtual('constructor.prototype.opol');
console.log(({}).opol); // true

schema.virtual('hasOwnProperty.__proto__.fpol');
console.log((function(){}).fpol); // Function.prototype polluted
Impact

Attacker-influenced schema field names (dynamic schemas, CMS form builders, schema-as-code) allow pollution of Object.prototype (own, enumerable keys visible on every object — e.g. ({}).isAdmin checks can be spoofed) and Function.prototype (a known gadget primitive in server-side JS).

Severity

  • CVSS Score: 6.5 / 10 (Medium)
  • Vector String: CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:L/A:L

References

This data is provided by the GitHub Advisory Database (CC-BY 4.0).


Mongoose walks into inherited properties when hydrating, setting, and merging, allowing overwrites of built-in functions (denial of service) and shared schema state

CVE-2026-125117 / GHSA-8332-j7wj-wjw4

More information

Details

Summary

Three Mongoose code paths copy data into objects by property name without checking whether the property is the object's own or inherited from its prototype:

  1. Loading a document from the database (init(), also used by Model.hydrate())
  2. Setting a dotted path on a document ($__set, used by new Model(obj), doc.set() and doc.$set())
  3. Merging update documents (utils.mergeClone, used by findOneAndReplace(), chained update calls and Query.prototype.merge())

When a key names an inherited property, such as toString or valueOf, or a document internal such as $__schema, Mongoose writes into the shared object behind that property. The data comes from the attacker.

  • Denial of service. For example, { "toString": { "call": 1 } } overwrites Object.prototype.toString.call. Mongoose and most other libraries rely on Object.prototype.toString.call(). After the overwrite, every later query in the process throws TypeError: _toString.call is not a function until the process restarts. This includes queries on unrelated models.
  • Changing shared schema state. Through a subdocument with strict: false, a path such as profile.$__schema.paths.email.validators reaches the subdocument's schema, which every document shares. Setting it to [] removes the required validator for every document in the process.

Mongoose already blocked __proto__, constructor and prototype, so these bugs cannot add properties to Object.prototype itself. They can still overwrite methods and properties of shared built-in functions and of Mongoose's internal objects.

Details
1. Loading documents: init()
if (!schemaType && utils.isPOJO(value)) {
  // assume nested object
  if (!doc[i]) { doc[i] = {}; ... }
  init(self, value, doc[i], opts, path + '.');
}

For a stored field named toString, doc[i] is the inherited Object.prototype.toString. It is truthy, so init() recurses into that function and copies the stored subfields onto it.

This runs for every document Mongoose loads: find(), findOne(), cursors, populated documents and Model.hydrate(). It runs whatever the strict setting, and it applies to top-level and nested paths alike. lean() queries are not affected.

A malicious document can get into the collection in several ways:

  • through a model with strict: false, for example new Model(req.body).save();
  • through another application or the raw MongoDB driver;
  • through any update that writes arbitrary keys.
2. Setting dotted paths: $__set

When it walks a dotted path, $__set read obj[parts[i]] and descended into whatever it found. That included inherited functions, such as Object.prototype.toString on a plain object or Document.prototype.toObject on a subdocument. On subdocuments it also included non-function internals that are prototype getters, such as $__schema, schema, $__middleware and $__schemaTypeOptions. Those point at objects that every document of the model shares.

Attacker-controlled input reaches this path through:

  • A Mixed path on a default, strict schema: new Model({ "mixed.toString.call": 1 }), or doc.set({ "mixed.toString.call": 1 }). Nothing needs to be saved.
  • Any root path on a schema with strict: false: for example doc.set('toString.call', 1).
  • A subdocument with strict: false, when the application passes a user-controlled path to doc.set(path, value): for example doc.set('profile.$__schema.paths.email.validators', []).
3. Merging updates: utils.mergeClone
if (typeof to[key] === 'undefined') {
  to[key] = clone(fromObj[key]);
} else if (isObject(val)) {
  mergeClone(to[key], val);   // to[key] may be an inherited built-in
}

to[key] was read without an own-property check, so a key such as toString recursed into Object.prototype.toString. This affects:

  • Model.findOneAndReplace(filter, replacement). It always merges the replacement into the query's update, so a single call with an untrusted replacement is enough.
  • Update calls chained onto a query that already has an update. For example Model.updateOne(filter, { $set: {...} }).updateOne({}, untrustedUpdate), the same pattern with findOneAndUpdate(), or middleware that calls this.updateOne(...).
  • Query.prototype.merge() with a source query whose update came from untrusted input.
Proof of concept
const mongoose = require('mongoose');
const { Schema } = mongoose;

// 2. Setting dotted paths: a Mixed path on a default strict schema, nothing saved
const Item = mongoose.model('Item', new Schema({ name: String, meta: {} }));
new Item(JSON.parse('{"meta.toString.call": 1}'));  // e.g. new Item(req.body)
console.log(typeof Object.prototype.toString.call); // 'number'
// From here on, every query in the process fails:
// TypeError: _toString.call is not a function
// 1. Loading documents: a stored field named after an Object.prototype method
const Loose = mongoose.model('Loose', new Schema({ name: String }, { strict: false }));
await new Loose(JSON.parse('{"name":"evil","toString":{"call":1}}')).save();
await Loose.findOne({ name: 'evil' });              // any later read of this document
await OtherModel.findOne();                         // TypeError: _toString.call is not a function
// 3. Merging updates: a single findOneAndReplace() call with an untrusted replacement
const Doc = mongoose.model('Doc', new Schema({ name: String }));
Doc.findOneAndReplace({}, JSON.parse('{"toString":{"call":1}}'));
console.log(typeof Object.prototype.toString.call); // 'number'
// 2. Setting dotted paths: changing the shared subdocument schema
const User = mongoose.model('User', new Schema({
  profile: new Schema({ email: { type: String, required: true } }, { strict: false })
}));
// e.g. JSON-patch style endpoint: doc.set(req.body.path, req.body.value)
new User({ profile: { email: 'a@b.c' } }).set('profile.$__schema.paths.email.validators', []);
await new User({ profile: {} }).validate();         // resolves: `required` removed for every document
Impact
  • Denial of service (paths 1, 2 and 3). One request overwrites Object.prototype.toString.call. After that, every query in the process fails, and so does much other code, until the process restarts. Ways in:

    • new Model(req.body) on any schema with a Mixed path;
    • findOneAndReplace() with an untrusted replacement;
    • reading one stored document that contains a field such as { "toString": { "call": 1 } }.

    In the stored-document case, the attacker does not need any write path through Mongoose at the moment of the attack. Any later read of that document triggers the overwrite. If the document is read on startup or by a scheduled job, the application can be kept down.

  • Changes to shared state (path 2, strict: false subdocuments). An attacker who controls the path passed to doc.set(path, value) can change a subdocument schema that every document shares. For example, they can remove validators or change schema options for every later document in the process.

  • Properties on built-in functions. More generally, an attacker can attach properties they choose to built-in functions such as Object.prototype.toString, Object.prototype.valueOf and Function.prototype.call. Any other code that reads properties of those functions sees the attacker's values.

Severity

  • CVSS Score: 8.2 / 10 (High)
  • Vector String: CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:L/A:H

References

This data is provided by the GitHub Advisory Database (CC-BY 4.0).


Mongoose: Discriminator key values matching inherited properties (e.g. __t: 'constructor') bypass schema casting and can poison collections

CVE-2026-125116 / GHSA-wr5m-5jph-8m96

More information

Details

Summary

Mongoose chooses which discriminator model or schema to use by looking up the discriminator key value (__t by default) in a plain object of registered discriminators, for example Model.discriminators[doc.__t]. That value comes from user documents and query filters. Because the lookup did not check own properties, a value that names a property inherited from Object.prototype resolves to that inherited value instead of a discriminator. Examples are 'constructor', 'toString' and 'hasOwnProperty'.

  • __t: 'constructor' resolves to the global Object function. Mongoose then calls new Object(doc), which returns the raw user object where a Mongoose document is expected.
  • __t: 'toString' and similar names resolve to built-in functions that throw when used as a constructor or schema.

The most serious effect: through bulkWrite() insertOne with skipValidation: true, the raw user object is stored as-is, without schema casting or strict filtering. After that, every query that returns the stored document throws, until the document is removed from the database.

Details

The registries that hold discriminators are plain objects: Model.discriminators, schema.discriminators, and the embedded discriminator registries on document arrays and single nested subdocuments. Several code paths indexed them directly with a value taken from the document or filter:

Code path Input
Model constructor (new Model(doc)) document
Model.create(), insertMany(), bulkWrite(), bulkSave() documents
Hydrating query results (find(), findOne(), etc.) and Model.hydrate() stored documents
Casting query filters, including flat paths such as 'events.__t' and $elemMatch query filter
Casting updates and array filters update filter, arrayFilters
Document array push() / create(), document array and single nested casting subdocuments
Populate on embedded discriminators stored subdocuments

getDiscriminatorByValue() already iterated the registry's own keys safely. But most callers tried the direct lookup first and only fell back to it afterwards, so a truthy inherited value took precedence.

The lookups only read inherited properties. They do not write to Object.prototype or any other shared object, and they do not change in-memory state that affects other requests. This is NOT a prototype pollution vector.

Proof of concept
const mongoose = require('mongoose');

const Base = mongoose.model('Base', new mongoose.Schema({ name: String, age: Number }));
Base.discriminator('Child', new mongoose.Schema({ extra: String }));

// Type confusion: the "document" is the raw input object
const doc = new Base({ name: 'x', __t: 'constructor' });
console.log(doc instanceof mongoose.Document); // false
// Schema bypass and persistent poison document via bulkWrite + skipValidation
await Base.bulkWrite([{
  insertOne: { document: { name: 'x', age: 'not a number', notInSchema: true, __t: 'constructor' } }
}], { skipValidation: true });
// Stored verbatim: { age: 'not a number', notInSchema: true, __t: 'constructor', ... }

await Base.find(); // throws: Cannot read properties of undefined (reading 'eachPath')
Impact
  • Crashing the request. An attacker who controls the discriminator key of a document or filter can make the request fail. In most code paths that sent the value, this means a TypeError or a non-document object returned to application code. Ways in include Model.create(req.body), new Model(req.body), Model.find(req.query)-style filters, and pushing user input onto embedded discriminator arrays. The effect is limited to the request carrying the value.
  • Schema bypass on bulkWrite({ skipValidation: true }). When an application passes untrusted documents to bulkWrite() insertOne with skipValidation: true, the raw object is stored without casting or strict filtering. Fields the schema would normally strip are persisted, such as an isAdmin that isn't in the schema. Fields with wrong types are also persisted.
  • Persistent denial of service for queries. A stored document with such a discriminator key value makes hydration throw. Every query that returns that document fails, for all users, until the document is deleted directly in the database. Besides the bulkWrite() path above, the document can get into the collection through another application, the raw MongoDB driver, or any other writer that does not go through Mongoose casting.

This issue doesn't let an attacker modify Object.prototype, built-in functions, schemas or other shared in-memory state. The schema bypass requires the application to opt in to skipValidation with untrusted input.

Severity

  • CVSS Score: 4.8 / 10 (Medium)
  • Vector String: CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:N/I:L/A:L

References

This data is provided by the GitHub Advisory Database (CC-BY 4.0).


Release Notes

Automattic/mongoose (mongoose)

v9.11.4

Compare Source

===================

  • fix: avoid walking into inherited properties like toString when hydrating documents, setting dotted paths, and merging updates
  • fix: only use own properties when looking up discriminators by key
  • fix(schema): disallow setting special properties via virtual()
  • fix(query): respect connection-level sanitizeFilter in queries
  • fix(query): disallow special properties like __proto__ as paths in where() and mod()
  • fix(deps): upgrade mquery -> 6.0.1 to avoid prototype pollution with query helpers like gt() and in()

v9.11.3

Compare Source

===================

v9.11.2

Compare Source

===================

v9.11.1

Compare Source

===================

v9.11.0

Compare Source

===================

v9.10.4

Compare Source

===================

  • fix: handle MongoDB server 9.x returning collation: { locale: 'simple' } on all indexes #​16557
  • fix(populate): resolve dotted parent path when collecting deferred sub-populate children #​16538 jfits
  • fix(array): compare dates by value in indexOf() so pull() removes them #​16535 giaBaoJS
  • fix(map): register $set when Map#set() replaces an array #​16540 #​16539 luantaraschi
  • fix(query): cast case and then expressions in $expr $switch branches #​16534 kwy404
  • docs(guide): fix read preference tag set example #​16541 NotAFlightRisk

v9.10.3

Compare Source

===================

v9.10.2

Compare Source

===================

v9.10.1

Compare Source

===================

  • types: relax populate Model generics to allow typed virtuals to be passed to populate in TypeScript 7 with skipLibCheck #​16503

v9.10.0

Compare Source

===================

  • feat: upgrade mongodb driver -> 7.6.0
  • feat(model): add Model.findAndCount() wrapper for limit+skip based pagination with countDocuments #​16460 #​16454
  • feat(schema): add Schema.prototype.queryHelper() to make it easier to define query helpers in TypeScript #​16464 #​16410
  • feat: support middleware skip option for cursors and custom hooks #​16350 #​15883 #​8768 AbdelrahmanHafez
  • fix: apply defaults to undefined array elements #​16542 #​9232
  • types: support for type narrowing when using projection in find and findOne #​16500 #​15545
  • types: make Schema.prototype.static() return type with new static #​16464

v9.9.5

Compare Source

==================

v9.9.4

Compare Source

==================


Configuration

📅 Schedule: (UTC)

  • Branch creation
    • At any time (no schedule defined)
  • Automerge
    • At any time (no schedule defined)

🚦 Automerge: Disabled by config. Please merge this manually once you are satisfied.

♻ Rebasing: Whenever PR is behind base branch, or you tick the rebase/retry checkbox.

🔕 Ignore: Close this PR and you won't be reminded about this update again.


  • If you want to rebase/retry this PR, check this box

This PR was generated by Mend Renovate. View the repository job log.

@renovate
renovate Bot force-pushed the renovate/npm-mongoose-vulnerability branch 2 times, most recently from a4586f8 to 4c864d4 Compare November 11, 2026 00:32
@renovate
renovate Bot force-pushed the renovate/npm-mongoose-vulnerability branch from 4c864d4 to a37e567 Compare November 11, 2026 00:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

0 participants