Skip to content

Commit 98eb9e2

Browse files
kmaharmbroadst
authored andcommitted
fix(dbref): only upgrade objects with allowed $keys to DBRefs
1 parent b4e4ac5 commit 98eb9e2

File tree

2 files changed

+22
-8
lines changed

2 files changed

+22
-8
lines changed

Diff for: lib/bson/parser/deserializer.js

+18-4
Original file line numberDiff line numberDiff line change
@@ -404,6 +404,7 @@ var deserializeObject = function(buffer, index, options, isArray) {
404404
(buffer[index++] << 8) |
405405
(buffer[index++] << 16) |
406406
(buffer[index++] << 24);
407+
407408
object[name] = new Timestamp(lowBits, highBits);
408409
} else if (elementType === BSON.BSON_DATA_MIN_KEY) {
409410
object[name] = new MinKey();
@@ -570,10 +571,23 @@ var deserializeObject = function(buffer, index, options, isArray) {
570571
throw new Error('corrupt object bson');
571572
}
572573

573-
// Check if we have a db ref object
574-
// this breaks one of the spec tests. should only become a dbref if it's explicitly
575-
// wrapped, like a {dbref: {$ref: ...}}
576-
// if (object['$id'] != null) object = new DBRef(object['$ref'], object['$id'], object['$db']);
574+
// check if object's $ keys are those of a DBRef
575+
var dollarKeys = Object.keys(object).filter(k => k.startsWith('$'));
576+
var valid = true;
577+
dollarKeys.forEach(k => {
578+
if (['$ref', '$id', '$db'].indexOf(k) === -1) valid = false;
579+
});
580+
581+
// if a $key not in "$ref", "$id", "$db", don't make a DBRef
582+
if (!valid) return object;
583+
584+
if (object['$id'] != null && object['$ref'] != null) {
585+
let copy = Object.assign({}, object);
586+
delete copy.$ref;
587+
delete copy.$id;
588+
delete copy.$db;
589+
return new DBRef(object.$ref, object.$id, object.$db || null, copy);
590+
}
577591

578592
return object;
579593
};

Diff for: test/node/bson_test.js

+4-4
Original file line numberDiff line numberDiff line change
@@ -1111,8 +1111,8 @@ describe('BSON', function() {
11111111
expect(serialized_data).to.deep.equal(serialized_data2);
11121112

11131113
var doc2 = b.deserialize(serialized_data);
1114-
expect('namespace').to.equal(doc2.dbref.$ref);
1115-
expect(doc2.dbref.$id.toHexString()).to.deep.equal(oid.toHexString());
1114+
expect(doc).to.deep.equal(doc2);
1115+
expect(doc2.dbref.oid.toHexString()).to.deep.equal(oid.toHexString());
11161116
done();
11171117
});
11181118

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

11321132
var doc2 = b.deserialize(serialized_data);
11331133
expect('something').to.equal(doc2.name);
1134-
expect('username').to.equal(doc2.user.$ref);
1135-
expect(id.toString()).to.equal(doc2.user.$id.toString());
1134+
expect('username').to.equal(doc2.user.collection);
1135+
expect(id.toString()).to.equal(doc2.user.oid.toString());
11361136
done();
11371137
});
11381138

0 commit comments

Comments
 (0)