diff --git a/lib/bson/parser/serializer.js b/lib/bson/parser/serializer.js index e4ff2bd9..6bb212ed 100644 --- a/lib/bson/parser/serializer.js +++ b/lib/bson/parser/serializer.js @@ -777,6 +777,8 @@ var serializeInto = function serializeInto( index = serializeInt32(buffer, key, value, index, true); } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { index = serializeMinMax(buffer, key, value, index, true); + } else if (typeof value['_bsontype'] !== 'undefined') { + throw new TypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']); } } } else if (object instanceof Map) { @@ -875,6 +877,8 @@ var serializeInto = function serializeInto( index = serializeInt32(buffer, key, value, index); } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { index = serializeMinMax(buffer, key, value, index); + } else if (typeof value['_bsontype'] !== 'undefined') { + throw new TypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']); } } } else { @@ -977,6 +981,8 @@ var serializeInto = function serializeInto( index = serializeInt32(buffer, key, value, index); } else if (value['_bsontype'] === 'MinKey' || value['_bsontype'] === 'MaxKey') { index = serializeMinMax(buffer, key, value, index); + } else if (typeof value['_bsontype'] !== 'undefined') { + throw new TypeError('Unrecognized or invalid _bsontype: ' + value['_bsontype']); } } } diff --git a/test/node/bson_test.js b/test/node/bson_test.js index 5c948df2..6bce9b01 100644 --- a/test/node/bson_test.js +++ b/test/node/bson_test.js @@ -21,6 +21,7 @@ var Buffer = require('buffer').Buffer, vm = require('vm'); var createBSON = require('../utils'); +var M = require('../../lib/bson/map'); // for tests BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; @@ -2400,3 +2401,23 @@ exports['Should serialize _bsontype=ObjectID (capital D) from v4.0.0/4.0.1'] = f test.equal(doc._id.toHexString(), createBSON().deserialize(serialized_data)._id.toHexString()); test.done(); }; + +exports['should throw if invalid BSON types are input to BSON serializer'] = function(test) { + var oid = new ObjectId('111111111111111111111111'); + var badBsonType = new ObjectId('111111111111111111111111'); + badBsonType._bsontype = 'bogus'; + var badDoc = { bad: badBsonType }; + var badArray = [oid, badDoc]; + var badMap = new M([['a', badBsonType], ['b', badDoc], ['c', badArray]]); + var BSON = createBSON(); + test.throws(function() { + BSON.serialize(badDoc); + }); + test.throws(function() { + BSON.serialize(badArray); + }); + test.throws(function() { + BSON.serialize(badMap); + }); + test.done(); +}