From 6a197316564742c0422309e1b5fecfa4faec126e Mon Sep 17 00:00:00 2001 From: Valeri Karpov Date: Mon, 18 Jul 2022 22:21:57 -0400 Subject: [PATCH 1/2] fix(schema): disallow setting __proto__ when creating schema with dotted properties Fix #12085 --- lib/schema.js | 7 +++++++ test/schema.test.js | 10 ++++++++++ 2 files changed, 17 insertions(+) diff --git a/lib/schema.js b/lib/schema.js index c740902d2fd..895e452a36c 100644 --- a/lib/schema.js +++ b/lib/schema.js @@ -478,6 +478,10 @@ Schema.prototype.add = function add(obj, prefix) { const keys = Object.keys(obj); for (const key of keys) { + if (utils.specialProperties.has(key)) { + continue; + } + const fullPath = prefix + key; if (obj[key] == null) { @@ -663,6 +667,9 @@ Schema.prototype.path = function(path, obj) { let fullPath = ''; for (const sub of subpaths) { + if (utils.specialProperties.has(sub)) { + throw new Error('Cannot set special property `' + sub + '` on a schema'); + } fullPath = fullPath += (fullPath.length > 0 ? '.' : '') + sub; if (!branch[sub]) { this.nested[fullPath] = true; diff --git a/test/schema.test.js b/test/schema.test.js index f5adc214066..711054abccd 100644 --- a/test/schema.test.js +++ b/test/schema.test.js @@ -2682,4 +2682,14 @@ describe('schema', function() { assert.equal(TestSchema.path('testprop.$*').instance, 'Number'); assert.equal(TestSchema.path('testprop.$*').options.ref, 'OtherModel'); }); + + it('disallows setting special properties with `add()` or constructor (gh-12085)', async function() { + const maliciousPayload = '{"__proto__.toString": "Number"}'; + + assert.throws(() => { + mongoose.Schema(JSON.parse(maliciousPayload)); + }, /__proto__/); + + assert.ok({}.toString()); + }); }); From 5eb11dd5d434ba24ea10d19e5eb2054a276bb22e Mon Sep 17 00:00:00 2001 From: Shubanker Chourasia Date: Fri, 19 Aug 2022 13:48:46 +0530 Subject: [PATCH 2/2] made function non async --- test/schema.test.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/schema.test.js b/test/schema.test.js index 711054abccd..d2bff3ce34e 100644 --- a/test/schema.test.js +++ b/test/schema.test.js @@ -2682,8 +2682,8 @@ describe('schema', function() { assert.equal(TestSchema.path('testprop.$*').instance, 'Number'); assert.equal(TestSchema.path('testprop.$*').options.ref, 'OtherModel'); }); - - it('disallows setting special properties with `add()` or constructor (gh-12085)', async function() { + + it('disallows setting special properties with `add()` or constructor (gh-12085)', function() { const maliciousPayload = '{"__proto__.toString": "Number"}'; assert.throws(() => {