-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
Copy pathconnection_string.test.ts
791 lines (695 loc) · 30.2 KB
/
connection_string.test.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
import { expect } from 'chai';
import * as dns from 'dns';
import * as sinon from 'sinon';
import {
AUTH_MECHS_AUTH_SRC_EXTERNAL,
AuthMechanism,
DEFAULT_ALLOWED_HOSTS,
FEATURE_FLAGS,
MongoAPIError,
MongoClient,
MongoCredentials,
MongoDriverError,
MongoInvalidArgumentError,
type MongoOptions,
MongoParseError,
MongoRuntimeError,
parseOptions,
resolveSRVRecord
} from '../mongodb';
describe('Connection String', function () {
it('should not support auth passed with user', function () {
const optionsWithUser = {
authMechanism: 'SCRAM-SHA-1',
auth: { user: 'testing', password: 'llamas' }
};
expect(() => parseOptions('mongodb://localhost', optionsWithUser as any)).to.throw(
MongoParseError
);
});
it('should support auth passed with username', function () {
const optionsWithUsername = {
authMechanism: 'SCRAM-SHA-1',
auth: { username: 'testing', password: 'llamas' }
};
const options = parseOptions('mongodb://localhost', optionsWithUsername as any);
expect(options.credentials).to.containSubset({
source: 'admin',
username: 'testing',
password: 'llamas'
});
});
it('throws an error related to the option that was given an empty value', function () {
expect(() => parseOptions('mongodb://localhost?tls=', {})).to.throw(
MongoAPIError,
/tls" cannot/i
);
});
it('should provide a default port if one is not provided', function () {
const options = parseOptions('mongodb://hostname');
expect(options.hosts[0].socketPath).to.be.undefined;
expect(options.hosts[0].host).to.be.a('string');
expect(options.hosts[0].port).to.equal(27017);
});
describe('ca option', () => {
context('when set in the options object', () => {
it('should parse a string', () => {
const options = parseOptions('mongodb://localhost', {
ca: 'hello'
});
expect(options).to.have.property('ca').to.equal('hello');
});
it('should parse a NodeJS buffer', () => {
const options = parseOptions('mongodb://localhost', {
ca: Buffer.from([1, 2, 3, 4])
});
expect(options)
.to.have.property('ca')
.to.deep.equal(Buffer.from([1, 2, 3, 4]));
});
it('should parse arrays with a single element', () => {
const options = parseOptions('mongodb://localhost', {
ca: ['hello']
});
expect(options).to.have.property('ca').to.deep.equal(['hello']);
});
it('should parse an empty array', () => {
const options = parseOptions('mongodb://localhost', {
ca: []
});
expect(options).to.have.property('ca').to.deep.equal([]);
});
it('should parse arrays with multiple elements', () => {
const options = parseOptions('mongodb://localhost', {
ca: ['hello', 'world']
});
expect(options).to.have.property('ca').to.deep.equal(['hello', 'world']);
});
});
// TODO(NODE-4172): align uri behavior with object options behavior
context('when set in the uri', () => {
it('should parse a string value', () => {
const options = parseOptions('mongodb://localhost?ca=hello', {});
expect(options).to.have.property('ca').to.equal('hello');
});
it('should throw an error with a buffer value', () => {
const buffer = Buffer.from([1, 2, 3, 4]);
expect(() => {
parseOptions(`mongodb://localhost?ca=${buffer.toString()}`, {});
}).to.throw(MongoAPIError);
});
it('should not parse multiple string values (array of options)', () => {
const options = parseOptions('mongodb://localhost?ca=hello,world', {});
expect(options).to.have.property('ca').to.equal('hello,world');
});
});
it('should prioritize options set in the object over those set in the URI', () => {
const options = parseOptions('mongodb://localhost?ca=hello', {
ca: ['world']
});
expect(options).to.have.property('ca').to.deep.equal(['world']);
});
});
describe('readPreferenceTags option', function () {
context('when the option is passed in the uri', () => {
it('should parse a single read preference tag', () => {
const options = parseOptions('mongodb://hostname?readPreferenceTags=bar:foo');
expect(options.readPreference.tags).to.deep.equal([{ bar: 'foo' }]);
});
it('should parse multiple readPreferenceTags', () => {
const options = parseOptions(
'mongodb://hostname?readPreferenceTags=bar:foo&readPreferenceTags=baz:bar'
);
expect(options.readPreference.tags).to.deep.equal([{ bar: 'foo' }, { baz: 'bar' }]);
});
it('should parse multiple readPreferenceTags for the same key', () => {
const options = parseOptions(
'mongodb://hostname?readPreferenceTags=bar:foo&readPreferenceTags=bar:banana&readPreferenceTags=baz:bar'
);
expect(options.readPreference.tags).to.deep.equal([
{ bar: 'foo' },
{ bar: 'banana' },
{ baz: 'bar' }
]);
});
it('should parse multiple and empty readPreferenceTags', () => {
const options = parseOptions(
'mongodb://hostname?readPreferenceTags=bar:foo&readPreferenceTags=baz:bar&readPreferenceTags='
);
expect(options.readPreference.tags).to.deep.equal([{ bar: 'foo' }, { baz: 'bar' }, {}]);
});
it('will set "__proto__" as own property on readPreferenceTag', () => {
const options = parseOptions('mongodb://hostname?readPreferenceTags=__proto__:foo');
expect(options.readPreference.tags?.[0]).to.have.own.property('__proto__', 'foo');
expect(Object.getPrototypeOf(options.readPreference.tags?.[0])).to.be.null;
});
});
context('when the option is passed in the options object', () => {
it('should not parse an empty readPreferenceTags object', () => {
const options = parseOptions('mongodb://hostname?', {
readPreferenceTags: []
});
expect(options.readPreference.tags).to.deep.equal([]);
});
it('should parse a single readPreferenceTags object', () => {
const options = parseOptions('mongodb://hostname?', {
readPreferenceTags: [{ bar: 'foo' }]
});
expect(options.readPreference.tags).to.deep.equal([{ bar: 'foo' }]);
});
it('should parse multiple readPreferenceTags', () => {
const options = parseOptions('mongodb://hostname?', {
readPreferenceTags: [{ bar: 'foo' }, { baz: 'bar' }]
});
expect(options.readPreference.tags).to.deep.equal([{ bar: 'foo' }, { baz: 'bar' }]);
});
it('should parse multiple readPreferenceTags for the same key', () => {
const options = parseOptions('mongodb://hostname?', {
readPreferenceTags: [{ bar: 'foo' }, { bar: 'banana' }, { baz: 'bar' }]
});
expect(options.readPreference.tags).to.deep.equal([
{ bar: 'foo' },
{ bar: 'banana' },
{ baz: 'bar' }
]);
});
});
it('should prioritize options from the options object over the uri options', () => {
const options = parseOptions('mongodb://hostname?readPreferenceTags=a:b', {
readPreferenceTags: [{ bar: 'foo' }, { baz: 'bar' }]
});
expect(options.readPreference.tags).to.deep.equal([{ bar: 'foo' }, { baz: 'bar' }]);
});
});
context('boolean options', function () {
const valuesExpectations: { value: string; expectation: 'error' | boolean }[] = [
{ value: 'true', expectation: true },
{ value: 'false', expectation: false },
{ value: '-1', expectation: 'error' },
{ value: '1', expectation: 'error' },
{ value: '0', expectation: 'error' },
{ value: 't', expectation: 'error' },
{ value: 'f', expectation: 'error' },
{ value: 'n', expectation: 'error' },
{ value: 'y', expectation: 'error' },
{ value: 'yes', expectation: 'error' },
{ value: 'no', expectation: 'error' },
{ value: 'unknown', expectation: 'error' }
];
for (const { value, expectation } of valuesExpectations) {
const connString = `mongodb://hostname?retryWrites=${value}`;
context(`when provided '${value}'`, function () {
switch (expectation) {
case 'error':
it('throws MongoParseError', function () {
expect(() => {
parseOptions(connString);
}).to.throw(MongoParseError);
});
break;
default:
it(`parses as ${expectation}`, function () {
const options = parseOptions(connString);
expect(options).to.have.property('retryWrites', expectation);
});
}
});
}
});
it('should parse compression options', function () {
const options = parseOptions('mongodb://localhost/?compressors=zlib&zlibCompressionLevel=4');
expect(options).to.have.property('compressors');
expect(options.compressors).to.include('zlib');
expect(options.zlibCompressionLevel).to.equal(4);
});
it('should parse `readConcernLevel`', function () {
const options = parseOptions('mongodb://localhost/?readConcernLevel=local');
expect(options).to.have.property('readConcern');
expect(options.readConcern.level).to.equal('local');
});
context('when auth mechanism is MONGODB-OIDC', function () {
context('when ALLOWED_HOSTS is in the URI', function () {
it('raises an error', function () {
expect(() => {
parseOptions(
'mongodb://localhost/?authMechanismProperties=PROVIDER_NAME:aws,ALLOWED_HOSTS:[localhost]&authMechanism=MONGODB-OIDC'
);
}).to.throw(
MongoParseError,
'Auth mechanism property ALLOWED_HOSTS is not allowed in the connection string.'
);
});
});
context('when ALLOWED_HOSTS is in the options', function () {
context('when it is an array of strings', function () {
const hosts = ['*.example.com'];
it('sets the allowed hosts property', function () {
const options = parseOptions(
'mongodb://localhost/?authMechanism=MONGODB-OIDC&authMechanismProperties=PROVIDER_NAME:aws',
{
authMechanismProperties: {
ALLOWED_HOSTS: hosts
}
}
);
expect(options.credentials.mechanismProperties).to.deep.equal({
PROVIDER_NAME: 'aws',
ALLOWED_HOSTS: hosts
});
});
});
context('when it is not an array of strings', function () {
it('raises an error', function () {
expect(() => {
parseOptions(
'mongodb://localhost/?authMechanism=MONGODB-OIDC&authMechanismProperties=PROVIDER_NAME:aws',
{
authMechanismProperties: {
ALLOWED_HOSTS: [1, 2, 3]
}
}
);
}).to.throw(
MongoInvalidArgumentError,
'Auth mechanism property ALLOWED_HOSTS must be an array of strings.'
);
});
});
});
context('when ALLOWED_HOSTS is not in the options', function () {
it('sets the default value', function () {
const options = parseOptions(
'mongodb://localhost/?authMechanism=MONGODB-OIDC&authMechanismProperties=PROVIDER_NAME:aws'
);
expect(options.credentials.mechanismProperties).to.deep.equal({
PROVIDER_NAME: 'aws',
ALLOWED_HOSTS: DEFAULT_ALLOWED_HOSTS
});
});
});
context('when TOKEN_AUDIENCE is in the properties', function () {
context('when it is a uri', function () {
const options = parseOptions(
'mongodb://localhost/?authMechanism=MONGODB-OIDC&authMechanismProperties=PROVIDER_NAME:azure,TOKEN_AUDIENCE:api%3A%2F%2Ftest'
);
it('parses the uri', function () {
expect(options.credentials.mechanismProperties).to.deep.equal({
PROVIDER_NAME: 'azure',
TOKEN_AUDIENCE: 'api://test',
ALLOWED_HOSTS: DEFAULT_ALLOWED_HOSTS
});
});
});
});
});
it('should parse `authMechanismProperties`', function () {
const options = parseOptions(
'mongodb://user%40EXAMPLE.COM:secret@localhost/?authMechanismProperties=SERVICE_NAME:other,SERVICE_REALM:blah,CANONICALIZE_HOST_NAME:true,SERVICE_HOST:example.com&authMechanism=GSSAPI'
);
expect(options.credentials.mechanismProperties).to.deep.include({
SERVICE_HOST: 'example.com',
SERVICE_NAME: 'other',
SERVICE_REALM: 'blah',
CANONICALIZE_HOST_NAME: true
});
expect(options.credentials.mechanism).to.equal(AuthMechanism.MONGODB_GSSAPI);
});
it('should provide default authSource when valid AuthMechanism provided', function () {
const options = parseOptions(
'mongodb+srv://jira-sync.pw0q4.mongodb.net/testDB?authMechanism=MONGODB-AWS&retryWrites=true&w=majority'
);
expect(options.credentials.source).to.equal('$external');
});
it('should omit credentials option when the only authSource is provided', function () {
let options = parseOptions(`mongodb://a/?authSource=someDb`);
expect(options).to.not.have.property('credentials');
options = parseOptions(`mongodb+srv://a/?authSource=someDb`);
expect(options).to.not.have.property('credentials');
});
for (const mechanism of ['GSSAPI', 'MONGODB-X509']) {
context(`when the authMechanism is ${mechanism} and authSource is NOT $external`, function () {
it('throws a MongoParseError', function () {
expect(() =>
parseOptions(`mongodb+srv://hostname/?authMechanism=${mechanism}&authSource=invalid`)
)
.to.throw(MongoParseError)
.to.match(/requires an authSource of '\$external'/);
});
});
}
it('should omit credentials and not throw a MongoAPIError if the only auth related option is authSource', async () => {
// The error we're looking to **not** see is
// `new MongoInvalidArgumentError('No AuthProvider for ${credentials.mechanism} defined.')`
// in `prepareHandshakeDocument` and/or `performInitialHandshake`.
// Neither function is exported currently but if I did export them because of the inlined callbacks
// I think I would need to mock quite a bit of internals to get down to that layer.
// My thinking is I can lean on server selection failing for th unit tests to assert we at least don't get an error related to auth.
const client = new MongoClient('mongodb://localhost:123/?authSource=someDb', {
serverSelectionTimeoutMS: 500
});
let thrownError: Error;
try {
// relies on us not running a mongod on port 123, fairly likely assumption
await client.connect();
} catch (error) {
thrownError = error;
}
// We should fail to connect, not fail to find an auth provider thus we should not find a MongoAPIError
expect(thrownError).to.not.be.instanceOf(MongoAPIError);
expect(client.options).to.not.have.a.property('credentials');
});
it('should parse a numeric authSource with variable width', function () {
const options = parseOptions('mongodb://test@localhost/?authSource=0001');
expect(options.credentials.source).to.equal('0001');
});
it('should not remove dbName from the options if authSource is provided', function () {
const dbName = 'my-db-name';
const authSource = 'admin';
const options = parseOptions(
`mongodb://myName:myPassword@localhost:27017/${dbName}?authSource=${authSource}`
);
expect(options).has.property('dbName', dbName);
expect(options.credentials).to.have.property('source', authSource);
});
it('should parse a replicaSet with a leading number', function () {
const options = parseOptions('mongodb://localhost/?replicaSet=123abc');
expect(options).to.have.property('replicaSet');
expect(options.replicaSet).to.equal('123abc');
});
context('when directionConnection is set', () => {
it('sets directConnection successfully when there is one host', () => {
const options = parseOptions('mongodb://localhost:27027/?directConnection=true');
expect(options.directConnection).to.be.true;
});
it('throws when directConnection is true and there is more than one host', () => {
expect(() =>
parseOptions('mongodb://localhost:27027,localhost:27018/?directConnection=true')
).to.throw(MongoParseError, 'directConnection option requires exactly one host');
});
});
context('when both tls and ssl options are provided', function () {
context('when the options are provided in the URI', function () {
context('when the options are equal', function () {
context('when both options are true', function () {
it('sets the tls option', function () {
const options = parseOptions('mongodb://localhost/?tls=true&ssl=true');
expect(options.tls).to.be.true;
});
it('does not set the ssl option', function () {
const options = parseOptions('mongodb://localhost/?tls=true&ssl=true');
expect(options).to.not.have.property('ssl');
});
});
context('when both options are false', function () {
it('sets the tls option', function () {
const options = parseOptions('mongodb://localhost/?tls=false&ssl=false');
expect(options.tls).to.be.false;
});
it('does not set the ssl option', function () {
const options = parseOptions('mongodb://localhost/?tls=false&ssl=false');
expect(options).to.not.have.property('ssl');
});
});
});
context('when the options are not equal', function () {
it('raises an error', function () {
expect(() => {
parseOptions('mongodb://localhost/?tls=true&ssl=false');
}).to.throw(MongoParseError, 'All values of tls/ssl must be the same.');
});
});
});
context('when the options are provided in the options', function () {
context('when the options are equal', function () {
context('when both options are true', function () {
it('sets the tls option', function () {
const options = parseOptions('mongodb://localhost/', { tls: true, ssl: true });
expect(options.tls).to.be.true;
});
it('does not set the ssl option', function () {
const options = parseOptions('mongodb://localhost/', { tls: true, ssl: true });
expect(options).to.not.have.property('ssl');
});
});
context('when both options are false', function () {
context('when the URI is an SRV URI', function () {
it('overrides the tls option', function () {
const options = parseOptions('mongodb+srv://localhost/', { tls: false, ssl: false });
expect(options.tls).to.be.false;
});
it('does not set the ssl option', function () {
const options = parseOptions('mongodb+srv://localhost/', { tls: false, ssl: false });
expect(options).to.not.have.property('ssl');
});
});
context('when the URI is not SRV', function () {
it('sets the tls option', function () {
const options = parseOptions('mongodb://localhost/', { tls: false, ssl: false });
expect(options.tls).to.be.false;
});
it('does not set the ssl option', function () {
const options = parseOptions('mongodb://localhost/', { tls: false, ssl: false });
expect(options).to.not.have.property('ssl');
});
});
});
});
context('when the options are not equal', function () {
it('raises an error', function () {
expect(() => {
parseOptions('mongodb://localhost/', { tls: true, ssl: false });
}).to.throw(MongoParseError, 'All values of tls/ssl must be the same.');
});
});
});
});
describe('validation', function () {
it('should validate compressors options', function () {
let thrownError;
try {
parseOptions('mongodb://localhost/?compressors=bunnies');
} catch (error) {
thrownError = error;
}
expect(thrownError).to.be.instanceOf(MongoInvalidArgumentError);
expect(thrownError.message).to.equal(
'bunnies is not a valid compression mechanism. Must be one of: none,snappy,zlib,zstd.'
);
});
it('throws an error for repeated options that can only appear once', function () {
// At the time of writing, readPreferenceTags is the only options that can be repeated
expect(() => parseOptions('mongodb://localhost/?compressors=zstd&compressors=zstd')).to.throw(
MongoInvalidArgumentError,
/cannot appear more than once/
);
expect(() => parseOptions('mongodb://localhost/?tls=true&tls=true')).to.throw(
MongoInvalidArgumentError,
/cannot appear more than once/
);
});
it('should validate authMechanism', function () {
expect(() => parseOptions('mongodb://localhost/?authMechanism=DOGS')).to.throw(
MongoParseError,
'authMechanism one of MONGODB-AWS,MONGODB-CR,DEFAULT,GSSAPI,PLAIN,SCRAM-SHA-1,SCRAM-SHA-256,MONGODB-X509,MONGODB-OIDC, got DOGS'
);
});
it('should validate readPreference', function () {
expect(() => parseOptions('mongodb://localhost/?readPreference=llamasPreferred')).to.throw(
MongoDriverError, // not parse Error b/c thrown from ReadPreference construction
'Invalid read preference mode "llamasPreferred"'
);
});
});
describe('mongodb+srv', function () {
it('should parse a default database', function () {
const options = parseOptions('mongodb+srv://test1.test.build.10gen.cc/somedb');
expect(options.dbName).to.equal('somedb');
expect(options.srvHost).to.equal('test1.test.build.10gen.cc');
});
});
describe('resolveSRVRecord()', () => {
afterEach(() => {
sinon.restore();
});
function makeStub(txtRecord: string) {
const mockAddress = [
{
name: 'localhost.test.mock.test.build.10gen.cc',
port: 2017,
weight: 0,
priority: 0
}
];
const mockRecord: string[][] = [[txtRecord]];
// first call is for stubbing resolveSrv
// second call is for stubbing resolveTxt
sinon.stub(dns.promises, 'resolveSrv').callsFake(async () => {
return mockAddress;
});
sinon.stub(dns.promises, 'resolveTxt').callsFake(async () => {
return mockRecord;
});
}
for (const mechanism of AUTH_MECHS_AUTH_SRC_EXTERNAL) {
it(`should set authSource to $external for ${mechanism} external mechanism`, async function () {
makeStub('authSource=thisShouldNotBeAuthSource');
const mechanismProperties = {};
if (mechanism === AuthMechanism.MONGODB_OIDC) {
mechanismProperties.PROVIDER_NAME = 'aws';
}
const credentials = new MongoCredentials({
source: '$external',
mechanism,
username: mechanism === AuthMechanism.MONGODB_OIDC ? undefined : 'username',
password: mechanism === AuthMechanism.MONGODB_X509 ? undefined : 'password',
mechanismProperties: mechanismProperties
});
credentials.validate();
const options = {
credentials,
srvHost: 'test.mock.test.build.10gen.cc',
srvServiceName: 'mongodb',
userSpecifiedAuthSource: false
} as MongoOptions;
await resolveSRVRecord(options);
// check MongoCredentials instance (i.e. whether or not merge on options.credentials was called)
expect(options).property('credentials').to.equal(credentials);
expect(options).to.have.nested.property('credentials.source', '$external');
});
}
it('should set a default authSource for non-external mechanisms with no user-specified source', async function () {
makeStub('authSource=thisShouldBeAuthSource');
const credentials = new MongoCredentials({
source: 'admin',
mechanism: AuthMechanism.MONGODB_SCRAM_SHA256,
username: 'username',
password: 'password',
mechanismProperties: {}
});
credentials.validate();
const options = {
credentials,
srvHost: 'test.mock.test.build.10gen.cc',
srvServiceName: 'mongodb',
userSpecifiedAuthSource: false
} as MongoOptions;
await resolveSRVRecord(options);
// check MongoCredentials instance (i.e. whether or not merge on options.credentials was called)
expect(options).property('credentials').to.not.equal(credentials);
expect(options).to.have.nested.property('credentials.source', 'thisShouldBeAuthSource');
});
it('should retain credentials for any mechanism with no user-sepcificed source and no source in DNS', async function () {
makeStub('');
const credentials = new MongoCredentials({
source: 'admin',
mechanism: AuthMechanism.MONGODB_SCRAM_SHA256,
username: 'username',
password: 'password',
mechanismProperties: {}
});
credentials.validate();
const options = {
credentials,
srvHost: 'test.mock.test.build.10gen.cc',
srvServiceName: 'mongodb',
userSpecifiedAuthSource: false
} as MongoOptions;
await resolveSRVRecord(options as any);
// check MongoCredentials instance (i.e. whether or not merge on options.credentials was called)
expect(options).property('credentials').to.equal(credentials);
expect(options).to.have.nested.property('credentials.source', 'admin');
});
it('should retain specified authSource with no provided credentials', async function () {
makeStub('authSource=thisShouldBeAuthSource');
const credentials = {};
const options = {
credentials,
srvHost: 'test.mock.test.build.10gen.cc',
srvServiceName: 'mongodb',
userSpecifiedAuthSource: false
} as MongoOptions;
await resolveSRVRecord(options as any);
expect(options).to.have.nested.property('credentials.username', '');
expect(options).to.have.nested.property('credentials.mechanism', 'DEFAULT');
expect(options).to.have.nested.property('credentials.source', 'thisShouldBeAuthSource');
});
});
describe('feature flags', () => {
it('should be stored in the FEATURE_FLAGS Set', () => {
expect(FEATURE_FLAGS.size).to.equal(3);
expect(FEATURE_FLAGS.has(Symbol.for('@@mdb.skipPingOnConnect'))).to.be.true;
expect(FEATURE_FLAGS.has(Symbol.for('@@mdb.enableMongoLogger'))).to.be.true;
expect(FEATURE_FLAGS.has(Symbol.for('@@mdb.internalLoggerConfig'))).to.be.true;
// Add more flags here
});
it('should should ignore unknown symbols', () => {
const randomFlag = Symbol();
const client = new MongoClient('mongodb://iLoveJavaScript', { [randomFlag]: 23n });
expect(client.s.options).to.not.have.property(randomFlag);
});
it('should be prefixed with @@mdb.', () => {
for (const flag of FEATURE_FLAGS) {
expect(flag).to.be.a('symbol');
expect(flag).to.have.property('description');
expect(flag.description).to.match(/@@mdb\..+/);
}
});
it('should only exist if specified on options', () => {
const flag = Array.from(FEATURE_FLAGS)[0]; // grab a random supported flag
const client = new MongoClient('mongodb://iLoveJavaScript', { [flag]: true });
expect(client.s.options).to.have.property(flag, true);
expect(client.options).to.have.property(flag, true);
});
it('should support nullish values', () => {
const flag = Array.from(FEATURE_FLAGS.keys())[0]; // grab a random supported flag
const client = new MongoClient('mongodb://iLoveJavaScript', { [flag]: null });
expect(client.s.options).to.have.property(flag, null);
});
});
describe('IPv6 host addresses', () => {
it('should not allow multiple unbracketed portless localhost IPv6 addresses', () => {
// Note there is no "port-full" version of this test, there's no way to distinguish when a port begins without brackets
expect(() => new MongoClient('mongodb://::1,::1,::1/test')).to.throw(
/invalid connection string/i
);
});
it('should not allow multiple unbracketed portless remote IPv6 addresses', () => {
expect(
() =>
new MongoClient(
'mongodb://ABCD:f::abcd:abcd:abcd:abcd,ABCD:f::abcd:abcd:abcd:abcd,ABCD:f::abcd:abcd:abcd:abcd/test'
)
).to.throw(MongoRuntimeError);
});
it('should allow multiple bracketed portless localhost IPv6 addresses', () => {
const client = new MongoClient('mongodb://[::1],[::1],[::1]/test');
expect(client.options.hosts).to.deep.equal([
{ host: '::1', port: 27017, isIPv6: true, socketPath: undefined },
{ host: '::1', port: 27017, isIPv6: true, socketPath: undefined },
{ host: '::1', port: 27017, isIPv6: true, socketPath: undefined }
]);
});
it('should allow multiple bracketed portless remote IPv6 addresses', () => {
const client = new MongoClient(
'mongodb://[ABCD:f::abcd:abcd:abcd:abcd],[ABCD:f::abcd:abcd:abcd:abcd],[ABCD:f::abcd:abcd:abcd:abcd]/test'
);
expect(client.options.hosts).to.deep.equal([
{ host: 'abcd:f::abcd:abcd:abcd:abcd', port: 27017, isIPv6: true, socketPath: undefined },
{ host: 'abcd:f::abcd:abcd:abcd:abcd', port: 27017, isIPv6: true, socketPath: undefined },
{ host: 'abcd:f::abcd:abcd:abcd:abcd', port: 27017, isIPv6: true, socketPath: undefined }
]);
});
it('should allow multiple bracketed IPv6 addresses with specified ports', () => {
const client = new MongoClient('mongodb://[::1]:27018,[::1]:27019,[::1]:27020/test');
expect(client.options.hosts).to.deep.equal([
{ host: '::1', port: 27018, isIPv6: true, socketPath: undefined },
{ host: '::1', port: 27019, isIPv6: true, socketPath: undefined },
{ host: '::1', port: 27020, isIPv6: true, socketPath: undefined }
]);
});
});
it('rejects a connection string with an unsupported scheme', () => {
expect(() => new MongoClient('mango://localhost:23')).to.throw(/Invalid scheme/i);
expect(() => new MongoClient('mango+srv://localhost:23')).to.throw(/Invalid scheme/i);
});
});