Skip to content

Commit

Permalink
fix(dbref): only upgrade objects with allowed $keys to DBRefs
Browse files Browse the repository at this point in the history
  • Loading branch information
kmahar authored and mbroadst committed Feb 26, 2018
1 parent b4e4ac5 commit 98eb9e2
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 8 deletions.
22 changes: 18 additions & 4 deletions lib/bson/parser/deserializer.js
Original file line number Diff line number Diff line change
Expand Up @@ -404,6 +404,7 @@ var deserializeObject = function(buffer, index, options, isArray) {
(buffer[index++] << 8) |
(buffer[index++] << 16) |
(buffer[index++] << 24);

object[name] = new Timestamp(lowBits, highBits);
} else if (elementType === BSON.BSON_DATA_MIN_KEY) {
object[name] = new MinKey();
Expand Down Expand Up @@ -570,10 +571,23 @@ var deserializeObject = function(buffer, index, options, isArray) {
throw new Error('corrupt object bson');
}

// Check if we have a db ref object
// this breaks one of the spec tests. should only become a dbref if it's explicitly
// wrapped, like a {dbref: {$ref: ...}}
// if (object['$id'] != null) object = new DBRef(object['$ref'], object['$id'], object['$db']);
// check if object's $ keys are those of a DBRef
var dollarKeys = Object.keys(object).filter(k => k.startsWith('$'));
var valid = true;
dollarKeys.forEach(k => {
if (['$ref', '$id', '$db'].indexOf(k) === -1) valid = false;
});

// if a $key not in "$ref", "$id", "$db", don't make a DBRef
if (!valid) return object;

if (object['$id'] != null && object['$ref'] != null) {
let copy = Object.assign({}, object);
delete copy.$ref;
delete copy.$id;
delete copy.$db;
return new DBRef(object.$ref, object.$id, object.$db || null, copy);
}

return object;
};
Expand Down
8 changes: 4 additions & 4 deletions test/node/bson_test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1111,8 +1111,8 @@ describe('BSON', function() {
expect(serialized_data).to.deep.equal(serialized_data2);

var doc2 = b.deserialize(serialized_data);
expect('namespace').to.equal(doc2.dbref.$ref);
expect(doc2.dbref.$id.toHexString()).to.deep.equal(oid.toHexString());
expect(doc).to.deep.equal(doc2);
expect(doc2.dbref.oid.toHexString()).to.deep.equal(oid.toHexString());
done();
});

Expand All @@ -1131,8 +1131,8 @@ describe('BSON', function() {

var doc2 = b.deserialize(serialized_data);
expect('something').to.equal(doc2.name);
expect('username').to.equal(doc2.user.$ref);
expect(id.toString()).to.equal(doc2.user.$id.toString());
expect('username').to.equal(doc2.user.collection);
expect(id.toString()).to.equal(doc2.user.oid.toString());
done();
});

Expand Down

0 comments on commit 98eb9e2

Please sign in to comment.