Skip to content

Commit 02699fa

Browse files
committed
Merge branch 'vkarpov15/avoid-prototype-pollution'
2 parents 2188458 + cc722a1 commit 02699fa

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

lib/document.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -741,6 +741,10 @@ function init(self, obj, doc, opts, prefix) {
741741

742742
function _init(index) {
743743
i = keys[index];
744+
// avoid prototype pollution
745+
if (i === '__proto__' || i === 'constructor') {
746+
return;
747+
}
744748
path = prefix + i;
745749
schemaType = docSchema.path(path);
746750

test/document.test.js

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12233,6 +12233,36 @@ describe('document', function() {
1223312233
assert.deepStrictEqual(doc.elements[0].modifiedPaths(), []);
1223412234
assert.deepStrictEqual(doc.elements[1].modifiedPaths(), []);
1223512235
});
12236+
12237+
it('avoids prototype pollution on init', async function() {
12238+
const Example = db.model('Example', new Schema({ hello: String }));
12239+
12240+
const example = await new Example({ hello: 'world!' }).save();
12241+
await Example.findByIdAndUpdate(example._id, {
12242+
$rename: {
12243+
hello: '__proto__.polluted'
12244+
}
12245+
});
12246+
12247+
// this is what causes the pollution
12248+
await Example.find();
12249+
12250+
const test = {};
12251+
assert.strictEqual(test.polluted, undefined);
12252+
assert.strictEqual(Object.prototype.polluted, undefined);
12253+
12254+
const example2 = await new Example({ hello: 'world!' }).save();
12255+
await Example.findByIdAndUpdate(example2._id, {
12256+
$rename: {
12257+
hello: 'constructor.polluted'
12258+
}
12259+
});
12260+
12261+
await Example.find();
12262+
const test2 = {};
12263+
assert.strictEqual(test2.constructor.polluted, undefined);
12264+
assert.strictEqual(Object.polluted, undefined);
12265+
});
1223612266
});
1223712267

1223812268
describe('Check if instance function that is supplied in schema option is availabe', function() {

0 commit comments

Comments
 (0)