From 06bbef22db00f19e049b3c0031227eb37fab2421 Mon Sep 17 00:00:00 2001 From: Katherine Walker Date: Thu, 16 May 2019 13:42:32 -0400 Subject: [PATCH] fix(ReadPreference): only allow valid ReadPreference modes Fixes NODE-1425 --- lib/core/topologies/read_preference.js | 10 +++++++--- test/functional/readpreference_tests.js | 15 +++++++++++++++ 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/lib/core/topologies/read_preference.js b/lib/core/topologies/read_preference.js index 16ca30ab3d..57208519c1 100644 --- a/lib/core/topologies/read_preference.js +++ b/lib/core/topologies/read_preference.js @@ -12,6 +12,10 @@ * @return {ReadPreference} */ const ReadPreference = function(mode, tags, options) { + if (!ReadPreference.isValid(mode)) { + throw new TypeError(`provided mode ${mode} is an invalid ReadPreference mode`); + } + // TODO(major): tags MUST be an array of tagsets if (tags && !Array.isArray(tags)) { console.warn( @@ -43,7 +47,7 @@ const ReadPreference = function(mode, tags, options) { this.minWireVersion = 5; } - if (this.mode === ReadPreference.PRIMARY || this.mode === true) { + if (this.mode === ReadPreference.PRIMARY) { if (this.tags && Array.isArray(this.tags) && this.tags.length > 0) { throw new TypeError('Primary read preference cannot be combined with tags'); } @@ -77,8 +81,8 @@ const VALID_MODES = [ ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST, - true, - false, + // true, + // false, null ]; diff --git a/test/functional/readpreference_tests.js b/test/functional/readpreference_tests.js index a495e66d2c..caaea50cd5 100644 --- a/test/functional/readpreference_tests.js +++ b/test/functional/readpreference_tests.js @@ -1,6 +1,7 @@ 'use strict'; var test = require('./shared').assert; var setupDatabase = require('./shared').setupDatabase; +const expect = require('chai').expect; describe('ReadPreference', function() { before(function() { @@ -546,4 +547,18 @@ describe('ReadPreference', function() { }); } }); + + it('Should throw an error on an invalid readPreference', function(done) { + const configuration = this.configuration; + + const client = configuration.newClient(); + client.connect((err, client) => { + const db = client.db(configuration.db); + expect(db.collection.bind(db, 'test', { readPreference: 'invalid' })).to.throw( + 'provided mode invalid is an invalid ReadPreference mode' + ); + client.close(); + done(); + }); + }); });