Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
fix: avoid mutating user-provided query selectors using where()
Fix #14567
  • Loading branch information
vkarpov15 committed May 8, 2024
commit a20eaa8e6753ea318cb7aeaedaa5390f67ebd129
7 changes: 6 additions & 1 deletion lib/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ const isObject = require('./helpers/isObject');
const isMongooseArray = require('./types/array/isMongooseArray');
const isMongooseDocumentArray = require('./types/documentArray/isMongooseDocumentArray');
const isBsonType = require('./helpers/isBsonType');
const isPOJO = require('./helpers/isPOJO');
const getFunctionName = require('./helpers/getFunctionName');
const isMongooseObject = require('./helpers/isMongooseObject');
const promiseOrCallback = require('./helpers/promiseOrCallback');
Expand Down Expand Up @@ -264,7 +265,11 @@ exports.merge = function merge(to, from, options, path) {
continue;
}
if (to[key] == null) {
to[key] = from[key];
if (isPOJO(from[key])) {
to[key] = { ...from[key] };
} else {
to[key] = from[key];

Check warning

Code scanning / CodeQL

Prototype-polluting function

Properties are copied from [from](1) to [to](2) without guarding against prototype pollution.
}
} else if (exports.isObject(from[key])) {
if (!exports.isObject(to[key])) {
to[key] = {};
Expand Down
18 changes: 18 additions & 0 deletions test/query.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -4255,4 +4255,22 @@ describe('Query', function() {
q.sort({}, { override: true });
assert.deepStrictEqual(q.getOptions().sort, {});
});

it('avoids mutating user-provided query selectors (gh-14567)', async function() {
const TestModel = db.model(
'Test',
Schema({ name: String, age: Number, active: Boolean })
);

await TestModel.create({ name: 'John', age: 21 });
await TestModel.create({ name: 'Bob', age: 35 });

const adultQuery = { age: { $gte: 18 } };

const docs = await TestModel.find(adultQuery).where('age').lte(25);
assert.equal(docs.length, 1);
assert.equal(docs[0].name, 'John');

assert.deepStrictEqual(adultQuery, { age: { $gte: 18 } });
});
});