Skip to content

Commit cc0fdd9

Browse files
committed
fix: Add test and logic to ignore credentials if authSource is the only auth option
1 parent bda08a8 commit cc0fdd9

File tree

2 files changed

+35
-2
lines changed

2 files changed

+35
-2
lines changed

src/connection_string.ts

+10
Original file line numberDiff line numberDiff line change
@@ -394,6 +394,16 @@ export function parseOptions(
394394
}
395395

396396
mongoOptions.credentials.validate();
397+
398+
// Check if the only auth related option provided was authSource, if so we can remove credentials
399+
if (
400+
mongoOptions.credentials.password === '' &&
401+
mongoOptions.credentials.username === '' &&
402+
mongoOptions.credentials.mechanism === AuthMechanism.MONGODB_DEFAULT &&
403+
Object.keys(mongoOptions.credentials.mechanismProperties).length === 0
404+
) {
405+
delete mongoOptions.credentials;
406+
}
397407
}
398408

399409
if (!mongoOptions.dbName) {

test/unit/connection_string.test.ts

+25-2
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,13 @@ import { promisify } from 'util';
66
import { MongoCredentials } from '../../src/cmap/auth/mongo_credentials';
77
import { AUTH_MECHS_AUTH_SRC_EXTERNAL, AuthMechanism } from '../../src/cmap/auth/providers';
88
import { parseOptions, resolveSRVRecord } from '../../src/connection_string';
9-
import { MongoDriverError, MongoInvalidArgumentError, MongoParseError } from '../../src/error';
10-
import { MongoOptions } from '../../src/mongo_client';
9+
import {
10+
MongoDriverError,
11+
MongoInvalidArgumentError,
12+
MongoParseError,
13+
MongoServerSelectionError
14+
} from '../../src/error';
15+
import { MongoClient, MongoOptions } from '../../src/mongo_client';
1116

1217
describe('Connection String', function () {
1318
it('should not support auth passed with user', function () {
@@ -98,6 +103,24 @@ describe('Connection String', function () {
98103
expect(options).to.have.nested.property('credentials.source', mockAuthSource);
99104
});
100105

106+
it('should omit credentials if the only auth related option is authSource', async () => {
107+
const client = new MongoClient('mongodb://localhost:123/?authSource=someDb', {
108+
serverSelectionTimeoutMS: 500
109+
});
110+
111+
let thrownError: Error;
112+
try {
113+
// relies on us not running a mongod on port 123, fairly likely assumption
114+
await client.connect();
115+
} catch (error) {
116+
thrownError = error;
117+
}
118+
119+
// We should fail to connect, not fail to find an auth provider
120+
expect(thrownError).to.be.instanceOf(MongoServerSelectionError);
121+
expect(client.options).to.not.have.a.property('credentials');
122+
});
123+
101124
it('should parse a numeric authSource with variable width', function () {
102125
const options = parseOptions('mongodb://test@localhost/?authSource=0001');
103126
expect(options.credentials.source).to.equal('0001');

0 commit comments

Comments
 (0)