Skip to content

Commit

Permalink
fix(NODE-4381): handle __proto__ well in EJSON (#506)
Browse files Browse the repository at this point in the history
  • Loading branch information
addaleax committed Jul 5, 2022
1 parent a2a81bc commit 4bda57d
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 2 deletions.
12 changes: 11 additions & 1 deletion src/extended_json.ts
Expand Up @@ -285,7 +285,17 @@ function serializeDocument(doc: any, options: EJSONSerializeOptions) {
for (const name in doc) {
options.seenObjects.push({ propertyName: name, obj: null });
try {
_doc[name] = serializeValue(doc[name], options);
const value = serializeValue(doc[name], options);
if (name === '__proto__') {
Object.defineProperty(_doc, name, {
value,
writable: true,
enumerable: true,
configurable: true
});
} else {
_doc[name] = value;
}
} finally {
options.seenObjects.pop();
}
Expand Down
7 changes: 6 additions & 1 deletion test/node/bson_test.js
Expand Up @@ -1776,7 +1776,12 @@ describe('BSON', function () {
assertBuffersEqual(done, serialized_data, serialized_data2, 0);

var doc1 = BSON.deserialize(serialized_data);
expect(Object.getOwnPropertyDescriptor(doc1, '__proto__').enumerable).to.equal(true);
expect(doc1).to.have.deep.ownPropertyDescriptor('__proto__', {
configurable: true,
enumerable: true,
writable: true,
value: { a: 42 }
});
expect(doc1.__proto__.a).to.equal(42);
done();
});
Expand Down
14 changes: 14 additions & 0 deletions test/node/extended_json_tests.js
Expand Up @@ -509,6 +509,20 @@ describe('Extended JSON', function () {
// expect(() => EJSON.serialize(badMap)).to.throw(); // uncomment when EJSON supports ES6 Map
});

it('should correctly deserialize objects containing __proto__ keys', function () {
const original = { ['__proto__']: { a: 42 } };
const serialized = EJSON.stringify(original);
expect(serialized).to.equal('{"__proto__":{"a":42}}');
const deserialized = EJSON.parse(serialized);
expect(deserialized).to.have.deep.ownPropertyDescriptor('__proto__', {
configurable: true,
enumerable: true,
writable: true,
value: { a: 42 }
});
expect(deserialized.__proto__.a).to.equal(42);
});

context('circular references', () => {
it('should throw a helpful error message for input with circular references', function () {
const obj = {
Expand Down

0 comments on commit 4bda57d

Please sign in to comment.