Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(NODE-3290): versioned api validation and tests #2869

Merged
merged 6 commits into from
Jul 14, 2021
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions lib/core/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ try {
} catch (err) {} // eslint-disable-line

module.exports = {
// Versioned API
ServerApiVersion: Object.freeze({
nbbeeken marked this conversation as resolved.
Show resolved Hide resolved
v1: '1'
}),
// Errors
MongoError: require('./error').MongoError,
MongoNetworkError: require('./error').MongoNetworkError,
Expand Down
27 changes: 25 additions & 2 deletions lib/mongo_client.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const Db = require('./db');
const EventEmitter = require('events').EventEmitter;
const inherits = require('util').inherits;
const MongoError = require('./core').MongoError;
const ServerApiVersion = require('./core').ServerApiVersion;
const deprecate = require('util').deprecate;
const WriteConcern = require('./write_concern');
const MongoDBNamespace = require('./utils').MongoDBNamespace;
Expand Down Expand Up @@ -191,16 +192,38 @@ const validOptions = require('./operations/connect').validOptions;
* @param {MongoClientOptions} [options] Optional settings
*/
function MongoClient(url, options) {
options = options || {};
if (!(this instanceof MongoClient)) return new MongoClient(url, options);
// Set up event emitter
EventEmitter.call(this);

if (options && options.autoEncryption) require('./encrypter'); // Does CSFLE lib check
nbbeeken marked this conversation as resolved.
Show resolved Hide resolved

if (options.serverApi) {
const serverApiToValidate =
typeof options.serverApi === 'string' ? { version: options.serverApi } : options.serverApi;
const versionToValidate = serverApiToValidate && serverApiToValidate.version;
if (!versionToValidate) {
throw new MongoError(
`Invalid \`serverApi\` property; must specify a version from the following enum: ["${Object.values(
ServerApiVersion
).join('", "')}"]`
);
}
if (!Object.values(ServerApiVersion).some(v => v === versionToValidate)) {
throw new MongoError(
`Invalid server API version=${versionToValidate}; must be in the following enum: ["${Object.values(
ServerApiVersion
).join('", "')}"]`
);
}
options.serverApi = serverApiToValidate;
}

// The internal state
this.s = {
url: url,
options: options || {},
url,
options,
promiseLibrary: (options && options.promiseLibrary) || Promise,
dbCache: new Map(),
sessions: new Set(),
Expand Down
71 changes: 67 additions & 4 deletions test/functional/versioned-api.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,80 @@
const expect = require('chai').expect;
const loadSpecTests = require('../spec/index').loadSpecTests;
const runUnifiedTest = require('./unified-spec-runner/runner').runUnifiedTest;
const ServerApiVersion = require('../../lib/core').ServerApiVersion;

describe('Versioned API', function() {
it('should throw an error if serverApi version is provided via the uri with new parser', {
metadata: { topology: 'single' },
test: function(done) {
describe('client option validation', function() {
it('is supported as a client option when it is a valid ServerApiVersion string', function() {
const validVersions = Object.values(ServerApiVersion);
expect(validVersions.length).to.be.at.least(1);
for (const version of validVersions) {
const client = this.configuration.newClient('mongodb://localhost/', {
serverApi: version
});
expect(client.s.options)
.to.have.property('serverApi')
.deep.equal({ version });
}
});

it('is supported as a client option when it is an object with a valid version property', function() {
const validVersions = Object.values(ServerApiVersion);
expect(validVersions.length).to.be.at.least(1);
for (const version of validVersions) {
const client = this.configuration.newClient('mongodb://localhost/', {
serverApi: { version }
});
expect(client.s.options)
.to.have.property('serverApi')
.deep.equal({ version });
}
});

it('is not supported as a client option when it is an invalid string', function() {
expect(() =>
this.configuration.newClient('mongodb://localhost/', {
serverApi: 'bad'
})
).to.throw(/^Invalid server API version=bad;/);
});

it('is not supported as a client option when it is a number', function() {
expect(() =>
this.configuration.newClient('mongodb://localhost/', {
serverApi: 1
})
).to.throw(/^Invalid `serverApi` property;/);
});

it('is not supported as a client option when it is an object without a specified version', function() {
expect(() =>
this.configuration.newClient('mongodb://localhost/', {
serverApi: {}
})
).to.throw(/^Invalid `serverApi` property;/);
});

it('is not supported as a client option when it is an object with an invalid specified version', function() {
expect(() =>
this.configuration.newClient('mongodb://localhost/', {
serverApi: { version: 1 }
})
).to.throw(/^Invalid server API version=1;/);
expect(() =>
this.configuration.newClient('mongodb://localhost/', {
serverApi: { version: 'bad' }
})
).to.throw(/^Invalid server API version=bad;/);
});

it('is not supported as a URI option even when it is a valid ServerApiVersion string', function(done) {
const client = this.configuration.newClient({ serverApi: '1' }, { useNewUrlParser: true });
client.connect(err => {
expect(err).to.match(/URI cannot contain `serverApi`, it can only be passed to the client/);
client.close(done);
});
}
});
});

for (const versionedApiTest of loadSpecTests('versioned-api')) {
Expand Down
24 changes: 19 additions & 5 deletions test/tools/cluster_setup.sh
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,31 @@

if [ "$#" -ne 1 ]; then
echo "usage: cluster_setup <server|replica_set|sharded_cluster>"
echo "override <DATA_DIR | SINGLE_DIR | REPLICASET_DIR | SHARDED_DIR> env variables to change dbPath"
exit
fi

DATA_DIR=${DATA_DIR:-data}
SINGLE_DIR=${SINGLE_DIR:-$DATA_DIR/server}
REPLICASET_DIR=${REPLICASET_DIR:-$DATA_DIR/replica_set}
SHARDED_DIR=${SHARDED_DIR:-$DATA_DIR/sharded_cluster}

if [[ ! -z "$MONGODB_API_VERSION" ]]; then
echo "Requiring versioned API $MONGODB_API_VERSION"
REQUIRE_API="--setParameter requireApiVersion=$MONGODB_API_VERSION"
fi

if [[ $1 == "replica_set" ]]; then
mlaunch init --replicaset --nodes 3 --arbiter --name rs --port 31000 --enableMajorityReadConcern --setParameter enableTestCommands=1
echo "mongodb://localhost:31000/?replicaSet=rs"
mkdir -p $REPLICASET_DIR
mlaunch init --dir $REPLICASET_DIR --replicaset --nodes 3 --arbiter --name rs --port 31000 --enableMajorityReadConcern --setParameter enableTestCommands=1
echo "mongodb://localhost:31000,localhost:31001,localhost:31002/?replicaSet=rs"
elif [[ $1 == "sharded_cluster" ]]; then
mlaunch init --replicaset --nodes 3 --arbiter --name rs --port 51000 --enableMajorityReadConcern --setParameter enableTestCommands=1 --sharded 1 --mongos 2
echo "mongodb://localhost:51000,localhost:51001/"
mkdir -p $SHARDED_DIR
mlaunch init --dir $SHARDED_DIR --replicaset --nodes 3 --arbiter --name rs --port 51000 --enableMajorityReadConcern --setParameter enableTestCommands=1 --sharded 1 --mongos 2
echo "mongodb://localhost:51000,localhost:51001"
elif [[ $1 == "server" ]]; then
mlaunch init --single --setParameter enableTestCommands=1
mkdir -p $SINGLE_DIR
mlaunch init --dir $SINGLE_DIR --single --setParameter enableTestCommands=1 $REQUIRE_API
echo "mongodb://localhost:27017"
else
echo "unsupported topology: $1"
Expand Down