Press n or j to go to the next uncovered block, b, p or k for the previous block.
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 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 | 131x 131x 131x 131x 131x 131x 131x 131x 131x 131x 131x 131x 131x 131x 131x 131x 131x 131x 131x 131x 262x 1380x 1380x 775x 140x 635x 131x 131x 131x 690x 690x 690x 690x 690x 690x 612x 612x 755x 403x 260x 260x 260x 232x 70x 162x 28x 28x 28x 28x 84x 28x 28x 28x 28x 8x 28x 28x 28x 28x 28x 412521x 412521x 2887151x 192x 412521x 412505x 412489x 412457x 412425x 412393x 412361x 4251541x 37882x 25435x 12153x 294x 5471826x 5471826x 5471782x 44x 5056326x 5056286x 56x 5056230x 206x 4x 202x 202x 302x 302x 8x 294x 1237878x 52547815x 61960540x 2858198x 131x 412901x 232x 232x 412901x 44x 412857x 44x 412813x 412689x 412689x 412689x 412625x 412625x 121850x 121850x 121850x 412625x 153231x 153231x 153231x 153231x 412625x 285516x 285516x 285516x 28x 285488x 28x 285460x 285436x 412569x 867212x 412569x 4x 412565x 412565x 146x 146x 4x 412561x 8x 412553x 412553x 412553x 1427122x 1427122x 1427122x 866752x 1427122x 1427122x 1427122x 412553x 359x 359x 32x 412521x 412329x 45768519x 412329x 34x 34x 34x 412295x 45740569x 45740569x 44314537x 11305540x 1426032x 1426032x 41x 41x 1426032x 411967x 219055x 219055x 219055x 219055x 219055x 16x 219039x 196x 219039x 4x 219035x 218967x 65481x 411879x 290087x 411879x 411843x 9931x 9931x 9890x 411802x 411802x 411802x 770x 770x 770x 12x 758x 758x 758x 520x 411032x 411032x 32x 411758x 8x 411750x 16x 411734x 8x 411726x 1646904x 1646904x 411726x 411726x 411726x 411726x 412167x 104x 8x 96x 8x 88x 8x 80x 12x 412131x 12731572x 12731572x 12731572x 4250747x 4250699x 412003x 411999x 4637020x 4636944x 629268x 629268x 629268x 422154x 422154x 422154x 52x 52x 2380328x 2380328x 2380128x 2380128x 131x 153435x 20x 153415x 548x 4932x 548x 4x 544x 544x 336x 544x 544x 20x 544x 160x 160x 168x 142x 230x 230x 226x 26x 26x 156x 116434x 116434x 1931x 1931x 1931x 8x 1923x 56x 1867x 412203x 412203x 412203x 412203x 4x 412199x 412223x 412207x 16x 412183x 3497x 3497x 3497x 17x 13x 13x 4x 4x 4x 16x 12x 12x 412147x 412143x 4x 412139x 30x 22x 22x 412123x 412123x 112x 112x 315x 412123x 411485x 638x 4x 4x 634x 630x 630x 4x 73x 73x 73x 109x 109x 64x 64x 105x 45x 45x 105x 69x 412067x 8x 412059x 24x 24x 16x 12x 8x 8x 4x 4x 12x 12572x 620x 620x 4x 4x 7125x 7117x 10176x 12x 10164x 12532x 12532x 14528x 51536x 107978x 12x 12520x 131x 14541x 3799x | import * as dns from 'dns'; import ConnectionString from 'mongodb-connection-string-url'; import { URLSearchParams } from 'url'; import type { Document } from './bson'; import { MongoCredentials } from './cmap/auth/mongo_credentials'; import { AUTH_MECHS_AUTH_SRC_EXTERNAL, AuthMechanism } from './cmap/auth/providers'; import { addContainerMetadata, makeClientMetadata } from './cmap/handshake/client_metadata'; import { Compressor, type CompressorName } from './cmap/wire_protocol/compression'; import { Encrypter } from './encrypter'; import { MongoAPIError, MongoInvalidArgumentError, MongoMissingCredentialsError, MongoParseError } from './error'; import { MongoClient, type MongoClientOptions, type MongoOptions, type PkFactory, type ServerApi, ServerApiVersion } from './mongo_client'; import { MongoLoggableComponent, MongoLogger, SeverityLevel } from './mongo_logger'; import { ReadConcern, type ReadConcernLevel } from './read_concern'; import { ReadPreference, type ReadPreferenceMode } from './read_preference'; import { ServerMonitoringMode } from './sdam/monitor'; import type { TagSet } from './sdam/server_description'; import { checkParentDomainMatch, DEFAULT_PK_FACTORY, emitWarning, HostAddress, isRecord, parseInteger, setDifference, squashError } from './utils'; import { type W, WriteConcern } from './write_concern'; const VALID_TXT_RECORDS = ['authSource', 'replicaSet', 'loadBalanced']; const LB_SINGLE_HOST_ERROR = 'loadBalanced option only supported with a single host in the URI'; const LB_REPLICA_SET_ERROR = 'loadBalanced option not supported with a replicaSet option'; const LB_DIRECT_CONNECTION_ERROR = 'loadBalanced option not supported when directConnection is provided'; function retryDNSTimeoutFor(api: 'resolveSrv'): (a: string) => Promise<dns.SrvRecord[]>; function retryDNSTimeoutFor(api: 'resolveTxt'): (a: string) => Promise<string[][]>; function retryDNSTimeoutFor( api: 'resolveSrv' | 'resolveTxt' ): (a: string) => Promise<dns.SrvRecord[] | string[][]> { return async function dnsReqRetryTimeout(lookupAddress: string) { try { return await dns.promises[api](lookupAddress); } catch (firstDNSError) { if (firstDNSError.code === dns.TIMEOUT) { return await dns.promises[api](lookupAddress); } else { throw firstDNSError; } } }; } const resolveSrv = retryDNSTimeoutFor('resolveSrv'); const resolveTxt = retryDNSTimeoutFor('resolveTxt'); /** * Lookup a `mongodb+srv` connection string, combine the parts and reparse it as a normal * connection string. * * @param uri - The connection string to parse * @param options - Optional user provided connection string options */ export async function resolveSRVRecord(options: MongoOptions): Promise<HostAddress[]> { Iif (typeof options.srvHost !== 'string') { throw new MongoAPIError('Option "srvHost" must not be empty'); } // Asynchronously start TXT resolution so that we do not have to wait until // the SRV record is resolved before starting a second DNS query. const lookupAddress = options.srvHost; const txtResolutionPromise = resolveTxt(lookupAddress); txtResolutionPromise.then(undefined, squashError); // rejections will be handled later const hostname = `_${options.srvServiceName}._tcp.${lookupAddress}`; // Resolve the SRV record and use the result as the list of hosts to connect to. const addresses = await resolveSrv(hostname); Iif (addresses.length === 0) { throw new MongoAPIError('No addresses found at host'); } for (const { name } of addresses) { checkParentDomainMatch(name, lookupAddress); } const hostAddresses = addresses.map(r => HostAddress.fromString(`${r.name}:${r.port ?? 27017}`)); validateLoadBalancedOptions(hostAddresses, options, true); // Use the result of resolving the TXT record and add options from there if they exist. let record; try { record = await txtResolutionPromise; } catch (error) { if (error.code !== 'ENODATA' && error.code !== 'ENOTFOUND') { throw error; } return hostAddresses; } Iif (record.length > 1) { throw new MongoParseError('Multiple text records not allowed'); } const txtRecordOptions = new URLSearchParams(record[0].join('')); const txtRecordOptionKeys = [...txtRecordOptions.keys()]; Iif (txtRecordOptionKeys.some(key => !VALID_TXT_RECORDS.includes(key))) { throw new MongoParseError(`Text record may only set any of: ${VALID_TXT_RECORDS.join(', ')}`); } Iif (VALID_TXT_RECORDS.some(option => txtRecordOptions.get(option) === '')) { throw new MongoParseError('Cannot have empty URI params in DNS TXT Record'); } const source = txtRecordOptions.get('authSource') ?? undefined; const replicaSet = txtRecordOptions.get('replicaSet') ?? undefined; const loadBalanced = txtRecordOptions.get('loadBalanced') ?? undefined; if ( !options.userSpecifiedAuthSource && source && options.credentials && !AUTH_MECHS_AUTH_SRC_EXTERNAL.has(options.credentials.mechanism) ) { options.credentials = MongoCredentials.merge(options.credentials, { source }); } Iif (!options.userSpecifiedReplicaSet && replicaSet) { options.replicaSet = replicaSet; } Iif (loadBalanced === 'true') { options.loadBalanced = true; } Iif (options.replicaSet && options.srvMaxHosts > 0) { throw new MongoParseError('Cannot combine replicaSet option with srvMaxHosts'); } validateLoadBalancedOptions(hostAddresses, options, true); return hostAddresses; } /** * Checks if TLS options are valid * * @param allOptions - All options provided by user or included in default options map * @throws MongoAPIError if TLS options are invalid */ function checkTLSOptions(allOptions: CaseInsensitiveMap): void { Iif (!allOptions) return; const check = (a: string, b: string) => { if (allOptions.has(a) && allOptions.has(b)) { throw new MongoAPIError(`The '${a}' option cannot be used with the '${b}' option`); } }; check('tlsInsecure', 'tlsAllowInvalidCertificates'); check('tlsInsecure', 'tlsAllowInvalidHostnames'); check('tlsInsecure', 'tlsDisableCertificateRevocationCheck'); check('tlsInsecure', 'tlsDisableOCSPEndpointCheck'); check('tlsAllowInvalidCertificates', 'tlsDisableCertificateRevocationCheck'); check('tlsAllowInvalidCertificates', 'tlsDisableOCSPEndpointCheck'); check('tlsDisableCertificateRevocationCheck', 'tlsDisableOCSPEndpointCheck'); } function getBoolean(name: string, value: unknown): boolean { if (typeof value === 'boolean') return value; switch (value) { case 'true': return true; case 'false': return false; default: throw new MongoParseError(`${name} must be either "true" or "false"`); } } function getIntFromOptions(name: string, value: unknown): number { const parsedInt = parseInteger(value); if (parsedInt != null) { return parsedInt; } throw new MongoParseError(`Expected ${name} to be stringified int value, got: ${value}`); } function getUIntFromOptions(name: string, value: unknown): number { const parsedValue = getIntFromOptions(name, value); if (parsedValue < 0) { throw new MongoParseError(`${name} can only be a positive int value, got: ${value}`); } return parsedValue; } function* entriesFromString(value: string): Generator<[string, string]> { if (value === '') { return; } const keyValuePairs = value.split(','); for (const keyValue of keyValuePairs) { const [key, value] = keyValue.split(/:(.*)/); if (value == null) { throw new MongoParseError('Cannot have undefined values in key value pairs'); } yield [key, value]; } } class CaseInsensitiveMap<Value = any> extends Map<string, Value> { constructor(entries: Array<[string, any]> = []) { super(entries.map(([k, v]) => [k.toLowerCase(), v])); } override has(k: string) { return super.has(k.toLowerCase()); } override get(k: string) { return super.get(k.toLowerCase()); } override set(k: string, v: any) { return super.set(k.toLowerCase(), v); } override delete(k: string): boolean { return super.delete(k.toLowerCase()); } } export function parseOptions( uri: string, mongoClient: MongoClient | MongoClientOptions | undefined = undefined, options: MongoClientOptions = {} ): MongoOptions { if (mongoClient != null && !(mongoClient instanceof MongoClient)) { options = mongoClient; mongoClient = undefined; } // validate BSONOptions if (options.useBigInt64 && typeof options.promoteLongs === 'boolean' && !options.promoteLongs) { throw new MongoAPIError('Must request either bigint or Long for int64 deserialization'); } if (options.useBigInt64 && typeof options.promoteValues === 'boolean' && !options.promoteValues) { throw new MongoAPIError('Must request either bigint or Long for int64 deserialization'); } const url = new ConnectionString(uri); const { hosts, isSRV } = url; const mongoOptions = Object.create(null); mongoOptions.hosts = isSRV ? [] : hosts.map(HostAddress.fromString); const urlOptions = new CaseInsensitiveMap<unknown[]>(); if (url.pathname !== '/' && url.pathname !== '') { const dbName = decodeURIComponent( url.pathname[0] === '/' ? url.pathname.slice(1) : url.pathname ); Eif (dbName) { urlOptions.set('dbName', [dbName]); } } if (url.username !== '') { const auth: Document = { username: decodeURIComponent(url.username) }; Eif (typeof url.password === 'string') { auth.password = decodeURIComponent(url.password); } urlOptions.set('auth', [auth]); } for (const key of url.searchParams.keys()) { const values = url.searchParams.getAll(key); const isReadPreferenceTags = /readPreferenceTags/i.test(key); if (!isReadPreferenceTags && values.length > 1) { throw new MongoInvalidArgumentError( `URI option "${key}" cannot appear more than once in the connection string` ); } if (!isReadPreferenceTags && values.includes('')) { throw new MongoAPIError(`URI option "${key}" cannot be specified with no value`); } if (!urlOptions.has(key)) { urlOptions.set(key, values); } } const objectOptions = new CaseInsensitiveMap<unknown>( Object.entries(options).filter(([, v]) => v != null) ); // Validate options that can only be provided by one of uri or object if (urlOptions.has('serverApi')) { throw new MongoParseError( 'URI cannot contain `serverApi`, it can only be passed to the client' ); } const uriMechanismProperties = urlOptions.get('authMechanismProperties'); if (uriMechanismProperties) { for (const property of uriMechanismProperties) { if (/(^|,)ALLOWED_HOSTS:/.test(property as string)) { throw new MongoParseError( 'Auth mechanism property ALLOWED_HOSTS is not allowed in the connection string.' ); } } } if (objectOptions.has('loadBalanced')) { throw new MongoParseError('loadBalanced is only a valid option in the URI'); } // All option collection const allProvidedOptions = new CaseInsensitiveMap<unknown[]>(); const allProvidedKeys = new Set<string>([...urlOptions.keys(), ...objectOptions.keys()]); for (const key of allProvidedKeys) { const values = []; const objectOptionValue = objectOptions.get(key); if (objectOptionValue != null) { values.push(objectOptionValue); } const urlValues = urlOptions.get(key) ?? []; values.push(...urlValues); allProvidedOptions.set(key, values); } if (allProvidedOptions.has('tls') || allProvidedOptions.has('ssl')) { const tlsAndSslOpts = (allProvidedOptions.get('tls') || []) .concat(allProvidedOptions.get('ssl') || []) .map(getBoolean.bind(null, 'tls/ssl')); if (new Set(tlsAndSslOpts).size !== 1) { throw new MongoParseError('All values of tls/ssl must be the same.'); } } checkTLSOptions(allProvidedOptions); const unsupportedOptions = setDifference( allProvidedKeys, Array.from(Object.keys(OPTIONS)).map(s => s.toLowerCase()) ); if (unsupportedOptions.size !== 0) { const optionWord = unsupportedOptions.size > 1 ? 'options' : 'option'; const isOrAre = unsupportedOptions.size > 1 ? 'are' : 'is'; throw new MongoParseError( `${optionWord} ${Array.from(unsupportedOptions).join(', ')} ${isOrAre} not supported` ); } // Option parsing and setting for (const [key, descriptor] of Object.entries(OPTIONS)) { const values = allProvidedOptions.get(key); if (!values || values.length === 0) { if (DEFAULT_OPTIONS.has(key)) { setOption(mongoOptions, key, descriptor, [DEFAULT_OPTIONS.get(key)]); } } else { const { deprecated } = descriptor; if (deprecated) { const deprecatedMsg = typeof deprecated === 'string' ? `: ${deprecated}` : ''; emitWarning(`${key} is a deprecated option${deprecatedMsg}`); } setOption(mongoOptions, key, descriptor, values); } } if (mongoOptions.credentials) { const isGssapi = mongoOptions.credentials.mechanism === AuthMechanism.MONGODB_GSSAPI; const isX509 = mongoOptions.credentials.mechanism === AuthMechanism.MONGODB_X509; const isAws = mongoOptions.credentials.mechanism === AuthMechanism.MONGODB_AWS; const isOidc = mongoOptions.credentials.mechanism === AuthMechanism.MONGODB_OIDC; if ( (isGssapi || isX509) && allProvidedOptions.has('authSource') && mongoOptions.credentials.source !== '$external' ) { // If authSource was explicitly given and its incorrect, we error throw new MongoParseError( `authMechanism ${mongoOptions.credentials.mechanism} requires an authSource of '$external'` ); } if ( !(isGssapi || isX509 || isAws || isOidc) && mongoOptions.dbName && !allProvidedOptions.has('authSource') ) { // inherit the dbName unless GSSAPI or X509, then silently ignore dbName // and there was no specific authSource given mongoOptions.credentials = MongoCredentials.merge(mongoOptions.credentials, { source: mongoOptions.dbName }); } if (isAws && mongoOptions.credentials.username && !mongoOptions.credentials.password) { throw new MongoMissingCredentialsError( `When using ${mongoOptions.credentials.mechanism} password must be set when a username is specified` ); } mongoOptions.credentials.validate(); // Check if the only auth related option provided was authSource, if so we can remove credentials if ( mongoOptions.credentials.password === '' && mongoOptions.credentials.username === '' && mongoOptions.credentials.mechanism === AuthMechanism.MONGODB_DEFAULT && Object.keys(mongoOptions.credentials.mechanismProperties).length === 0 ) { delete mongoOptions.credentials; } } if (!mongoOptions.dbName) { // dbName default is applied here because of the credential validation above mongoOptions.dbName = 'test'; } validateLoadBalancedOptions(hosts, mongoOptions, isSRV); if (mongoClient && mongoOptions.autoEncryption) { Encrypter.checkForMongoCrypt(); mongoOptions.encrypter = new Encrypter(mongoClient, uri, options); mongoOptions.autoEncrypter = mongoOptions.encrypter.autoEncrypter; } // Potential SRV Overrides and SRV connection string validations mongoOptions.userSpecifiedAuthSource = objectOptions.has('authSource') || urlOptions.has('authSource'); mongoOptions.userSpecifiedReplicaSet = objectOptions.has('replicaSet') || urlOptions.has('replicaSet'); if (isSRV) { // SRV Record is resolved upon connecting mongoOptions.srvHost = hosts[0]; Iif (mongoOptions.directConnection) { throw new MongoAPIError('SRV URI does not support directConnection'); } if (mongoOptions.srvMaxHosts > 0 && typeof mongoOptions.replicaSet === 'string') { throw new MongoParseError('Cannot use srvMaxHosts option with replicaSet'); } // SRV turns on TLS by default, but users can override and turn it off const noUserSpecifiedTLS = !objectOptions.has('tls') && !urlOptions.has('tls'); const noUserSpecifiedSSL = !objectOptions.has('ssl') && !urlOptions.has('ssl'); if (noUserSpecifiedTLS && noUserSpecifiedSSL) { mongoOptions.tls = true; } } else { const userSpecifiedSrvOptions = urlOptions.has('srvMaxHosts') || objectOptions.has('srvMaxHosts') || urlOptions.has('srvServiceName') || objectOptions.has('srvServiceName'); if (userSpecifiedSrvOptions) { throw new MongoParseError( 'Cannot use srvMaxHosts or srvServiceName with a non-srv connection string' ); } } if (mongoOptions.directConnection && mongoOptions.hosts.length !== 1) { throw new MongoParseError('directConnection option requires exactly one host'); } if ( !mongoOptions.proxyHost && (mongoOptions.proxyPort || mongoOptions.proxyUsername || mongoOptions.proxyPassword) ) { throw new MongoParseError('Must specify proxyHost if other proxy options are passed'); } if ( (mongoOptions.proxyUsername && !mongoOptions.proxyPassword) || (!mongoOptions.proxyUsername && mongoOptions.proxyPassword) ) { throw new MongoParseError('Can only specify both of proxy username/password or neither'); } const proxyOptions = ['proxyHost', 'proxyPort', 'proxyUsername', 'proxyPassword'].map( key => urlOptions.get(key) ?? [] ); Iif (proxyOptions.some(options => options.length > 1)) { throw new MongoParseError( 'Proxy options cannot be specified multiple times in the connection string' ); } mongoOptions.mongoLoggerOptions = MongoLogger.resolveOptions( { MONGODB_LOG_COMMAND: process.env.MONGODB_LOG_COMMAND, MONGODB_LOG_TOPOLOGY: process.env.MONGODB_LOG_TOPOLOGY, MONGODB_LOG_SERVER_SELECTION: process.env.MONGODB_LOG_SERVER_SELECTION, MONGODB_LOG_CONNECTION: process.env.MONGODB_LOG_CONNECTION, MONGODB_LOG_CLIENT: process.env.MONGODB_LOG_CLIENT, MONGODB_LOG_ALL: process.env.MONGODB_LOG_ALL, MONGODB_LOG_MAX_DOCUMENT_LENGTH: process.env.MONGODB_LOG_MAX_DOCUMENT_LENGTH, MONGODB_LOG_PATH: process.env.MONGODB_LOG_PATH }, { mongodbLogPath: mongoOptions.mongodbLogPath, mongodbLogComponentSeverities: mongoOptions.mongodbLogComponentSeverities, mongodbLogMaxDocumentLength: mongoOptions.mongodbLogMaxDocumentLength } ); mongoOptions.metadata = makeClientMetadata(mongoOptions); mongoOptions.extendedMetadata = addContainerMetadata(mongoOptions.metadata).then( undefined, squashError ); // rejections will be handled later return mongoOptions; } /** * #### Throws if LB mode is true: * - hosts contains more than one host * - there is a replicaSet name set * - directConnection is set * - if srvMaxHosts is used when an srv connection string is passed in * * @throws MongoParseError */ function validateLoadBalancedOptions( hosts: HostAddress[] | string[], mongoOptions: MongoOptions, isSrv: boolean ): void { if (mongoOptions.loadBalanced) { if (hosts.length > 1) { throw new MongoParseError(LB_SINGLE_HOST_ERROR); } if (mongoOptions.replicaSet) { throw new MongoParseError(LB_REPLICA_SET_ERROR); } if (mongoOptions.directConnection) { throw new MongoParseError(LB_DIRECT_CONNECTION_ERROR); } if (isSrv && mongoOptions.srvMaxHosts > 0) { throw new MongoParseError('Cannot limit srv hosts with loadBalanced enabled'); } } return; } function setOption( mongoOptions: any, key: string, descriptor: OptionDescriptor, values: unknown[] ) { const { target, type, transform } = descriptor; const name = target ?? key; switch (type) { case 'boolean': mongoOptions[name] = getBoolean(name, values[0]); break; case 'int': mongoOptions[name] = getIntFromOptions(name, values[0]); break; case 'uint': mongoOptions[name] = getUIntFromOptions(name, values[0]); break; case 'string': Iif (values[0] == null) { break; } mongoOptions[name] = String(values[0]); break; case 'record': Iif (!isRecord(values[0])) { throw new MongoParseError(`${name} must be an object`); } mongoOptions[name] = values[0]; break; case 'any': mongoOptions[name] = values[0]; break; default: { Iif (!transform) { throw new MongoParseError('Descriptors missing a type must define a transform'); } const transformValue = transform({ name, options: mongoOptions, values }); mongoOptions[name] = transformValue; break; } } } interface OptionDescriptor { target?: string; type?: 'boolean' | 'int' | 'uint' | 'record' | 'string' | 'any'; default?: any; deprecated?: boolean | string; /** * @param name - the original option name * @param options - the options so far for resolution * @param values - the possible values in precedence order */ transform?: (args: { name: string; options: MongoOptions; values: unknown[] }) => unknown; } export const OPTIONS = { appName: { type: 'string' }, auth: { target: 'credentials', transform({ name, options, values: [value] }): MongoCredentials { if (!isRecord(value, ['username', 'password'] as const)) { throw new MongoParseError( `${name} must be an object with 'username' and 'password' properties` ); } return MongoCredentials.merge(options.credentials, { username: value.username, password: value.password }); } }, authMechanism: { target: 'credentials', transform({ options, values: [value] }): MongoCredentials { const mechanisms = Object.values(AuthMechanism); const [mechanism] = mechanisms.filter(m => m.match(RegExp(String.raw`\b${value}\b`, 'i'))); if (!mechanism) { throw new MongoParseError(`authMechanism one of ${mechanisms}, got ${value}`); } let source = options.credentials?.source; if ( mechanism === AuthMechanism.MONGODB_PLAIN || AUTH_MECHS_AUTH_SRC_EXTERNAL.has(mechanism) ) { // some mechanisms have '$external' as the Auth Source source = '$external'; } let password = options.credentials?.password; if (mechanism === AuthMechanism.MONGODB_X509 && password === '') { password = undefined; } return MongoCredentials.merge(options.credentials, { mechanism, source, password }); } }, // Note that if the authMechanismProperties contain a TOKEN_RESOURCE that has a // comma in it, it MUST be supplied as a MongoClient option instead of in the // connection string. authMechanismProperties: { target: 'credentials', transform({ options, values }): MongoCredentials { // We can have a combination of options passed in the URI and options passed // as an object to the MongoClient. So we must transform the string options // as well as merge them together with a potentially provided object. let mechanismProperties = Object.create(null); for (const optionValue of values) { if (typeof optionValue === 'string') { for (const [key, value] of entriesFromString(optionValue)) { try { mechanismProperties[key] = getBoolean(key, value); } catch { mechanismProperties[key] = value; } } } else { Iif (!isRecord(optionValue)) { throw new MongoParseError('AuthMechanismProperties must be an object'); } mechanismProperties = { ...optionValue }; } } return MongoCredentials.merge(options.credentials, { mechanismProperties }); } }, authSource: { target: 'credentials', transform({ options, values: [value] }): MongoCredentials { const source = String(value); return MongoCredentials.merge(options.credentials, { source }); } }, autoEncryption: { type: 'record' }, autoSelectFamily: { type: 'boolean', default: true }, autoSelectFamilyAttemptTimeout: { type: 'uint' }, bsonRegExp: { type: 'boolean' }, serverApi: { target: 'serverApi', transform({ values: [version] }): ServerApi { const serverApiToValidate = typeof version === 'string' ? ({ version } as ServerApi) : (version as ServerApi); const versionToValidate = serverApiToValidate && serverApiToValidate.version; if (!versionToValidate) { throw new MongoParseError( `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 MongoParseError( `Invalid server API version=${versionToValidate}; must be in the following enum: ["${Object.values( ServerApiVersion ).join('", "')}"]` ); } return serverApiToValidate; } }, checkKeys: { type: 'boolean' }, compressors: { default: 'none', target: 'compressors', transform({ values }) { const compressionList = new Set(); for (const compVal of values as (CompressorName[] | string)[]) { const compValArray = typeof compVal === 'string' ? compVal.split(',') : compVal; if (!Array.isArray(compValArray)) { throw new MongoInvalidArgumentError( 'compressors must be an array or a comma-delimited list of strings' ); } for (const c of compValArray) { if (Object.keys(Compressor).includes(String(c))) { compressionList.add(String(c)); } else { throw new MongoInvalidArgumentError( `${c} is not a valid compression mechanism. Must be one of: ${Object.keys( Compressor )}.` ); } } } return [...compressionList]; } }, connectTimeoutMS: { default: 30000, type: 'uint' }, dbName: { type: 'string' }, directConnection: { default: false, type: 'boolean' }, driverInfo: { default: {}, type: 'record' }, enableUtf8Validation: { type: 'boolean', default: true }, family: { transform({ name, values: [value] }): 4 | 6 { const transformValue = getIntFromOptions(name, value); Eif (transformValue === 4 || transformValue === 6) { return transformValue; } throw new MongoParseError(`Option 'family' must be 4 or 6 got ${transformValue}.`); } }, fieldsAsRaw: { type: 'record' }, forceServerObjectId: { default: false, type: 'boolean' }, fsync: { deprecated: 'Please use journal instead', target: 'writeConcern', transform({ name, options, values: [value] }): WriteConcern { const wc = WriteConcern.fromOptions({ writeConcern: { ...options.writeConcern, fsync: getBoolean(name, value) } }); Iif (!wc) throw new MongoParseError(`Unable to make a writeConcern from fsync=${value}`); return wc; } } as OptionDescriptor, heartbeatFrequencyMS: { default: 10000, type: 'uint' }, ignoreUndefined: { type: 'boolean' }, j: { deprecated: 'Please use journal instead', target: 'writeConcern', transform({ name, options, values: [value] }): WriteConcern { const wc = WriteConcern.fromOptions({ writeConcern: { ...options.writeConcern, journal: getBoolean(name, value) } }); Iif (!wc) throw new MongoParseError(`Unable to make a writeConcern from journal=${value}`); return wc; } } as OptionDescriptor, journal: { target: 'writeConcern', transform({ name, options, values: [value] }): WriteConcern { const wc = WriteConcern.fromOptions({ writeConcern: { ...options.writeConcern, journal: getBoolean(name, value) } }); Iif (!wc) throw new MongoParseError(`Unable to make a writeConcern from journal=${value}`); return wc; } }, loadBalanced: { default: false, type: 'boolean' }, localThresholdMS: { default: 15, type: 'uint' }, maxConnecting: { default: 2, transform({ name, values: [value] }): number { const maxConnecting = getUIntFromOptions(name, value); if (maxConnecting === 0) { throw new MongoInvalidArgumentError('maxConnecting must be > 0 if specified'); } return maxConnecting; } }, maxIdleTimeMS: { default: 0, type: 'uint' }, maxPoolSize: { default: 100, type: 'uint' }, maxStalenessSeconds: { target: 'readPreference', transform({ name, options, values: [value] }) { const maxStalenessSeconds = getUIntFromOptions(name, value); Iif (options.readPreference) { return ReadPreference.fromOptions({ readPreference: { ...options.readPreference, maxStalenessSeconds } }); } else { return new ReadPreference('secondary', undefined, { maxStalenessSeconds }); } } }, minInternalBufferSize: { type: 'uint' }, minPoolSize: { default: 0, type: 'uint' }, minHeartbeatFrequencyMS: { default: 500, type: 'uint' }, monitorCommands: { default: false, type: 'boolean' }, name: { target: 'driverInfo', transform({ values: [value], options }) { return { ...options.driverInfo, name: String(value) }; } } as OptionDescriptor, noDelay: { default: true, type: 'boolean' }, pkFactory: { default: DEFAULT_PK_FACTORY, transform({ values: [value] }): PkFactory { Eif (isRecord(value, ['createPk'] as const) && typeof value.createPk === 'function') { return value as PkFactory; } throw new MongoParseError( `Option pkFactory must be an object with a createPk function, got ${value}` ); } }, promoteBuffers: { type: 'boolean' }, promoteLongs: { type: 'boolean' }, promoteValues: { type: 'boolean' }, useBigInt64: { type: 'boolean' }, proxyHost: { type: 'string' }, proxyPassword: { type: 'string' }, proxyPort: { type: 'uint' }, proxyUsername: { type: 'string' }, raw: { default: false, type: 'boolean' }, readConcern: { transform({ values: [value], options }) { Eif (value instanceof ReadConcern || isRecord(value, ['level'] as const)) { return ReadConcern.fromOptions({ ...options.readConcern, ...value } as any); } throw new MongoParseError(`ReadConcern must be an object, got ${JSON.stringify(value)}`); } }, readConcernLevel: { target: 'readConcern', transform({ values: [level], options }) { return ReadConcern.fromOptions({ ...options.readConcern, level: level as ReadConcernLevel }); } }, readPreference: { default: ReadPreference.primary, transform({ values: [value], options }) { if (value instanceof ReadPreference) { return ReadPreference.fromOptions({ readPreference: { ...options.readPreference, ...value }, ...value } as any); } if (isRecord(value, ['mode'] as const)) { const rp = ReadPreference.fromOptions({ readPreference: { ...options.readPreference, ...value }, ...value } as any); Eif (rp) return rp; else throw new MongoParseError(`Cannot make read preference from ${JSON.stringify(value)}`); } if (typeof value === 'string') { const rpOpts = { hedge: options.readPreference?.hedge, maxStalenessSeconds: options.readPreference?.maxStalenessSeconds }; return new ReadPreference( value as ReadPreferenceMode, options.readPreference?.tags, rpOpts ); } throw new MongoParseError(`Unknown ReadPreference value: ${value}`); } }, readPreferenceTags: { target: 'readPreference', transform({ values, options }: { values: Array<string | Record<string, string>[]>; options: MongoClientOptions; }) { const tags: Array<string | Record<string, string>> = Array.isArray(values[0]) ? values[0] : (values as Array<string>); const readPreferenceTags = []; for (const tag of tags) { const readPreferenceTag: TagSet = Object.create(null); if (typeof tag === 'string') { for (const [k, v] of entriesFromString(tag)) { readPreferenceTag[k] = v; } } if (isRecord(tag)) { for (const [k, v] of Object.entries(tag)) { readPreferenceTag[k] = v; } } readPreferenceTags.push(readPreferenceTag); } return ReadPreference.fromOptions({ readPreference: options.readPreference, readPreferenceTags }); } }, replicaSet: { type: 'string' }, retryReads: { default: true, type: 'boolean' }, retryWrites: { default: true, type: 'boolean' }, serializeFunctions: { type: 'boolean' }, serverMonitoringMode: { default: 'auto', transform({ values: [value] }) { if (!Object.values(ServerMonitoringMode).includes(value as any)) { throw new MongoParseError( 'serverMonitoringMode must be one of `auto`, `poll`, or `stream`' ); } return value; } }, serverSelectionTimeoutMS: { default: 30000, type: 'uint' }, servername: { type: 'string' }, socketTimeoutMS: { // TODO(NODE-6491): deprecated: 'Please use timeoutMS instead', default: 0, type: 'uint' }, srvMaxHosts: { type: 'uint', default: 0 }, srvServiceName: { type: 'string', default: 'mongodb' }, ssl: { target: 'tls', type: 'boolean' }, timeoutMS: { type: 'uint' }, tls: { type: 'boolean' }, tlsAllowInvalidCertificates: { target: 'rejectUnauthorized', transform({ name, values: [value] }) { // allowInvalidCertificates is the inverse of rejectUnauthorized return !getBoolean(name, value); } }, tlsAllowInvalidHostnames: { target: 'checkServerIdentity', transform({ name, values: [value] }) { // tlsAllowInvalidHostnames means setting the checkServerIdentity function to a noop return getBoolean(name, value) ? () => undefined : undefined; } }, tlsCAFile: { type: 'string' }, tlsCRLFile: { type: 'string' }, tlsCertificateKeyFile: { type: 'string' }, tlsCertificateKeyFilePassword: { target: 'passphrase', type: 'any' }, tlsInsecure: { transform({ name, options, values: [value] }) { const tlsInsecure = getBoolean(name, value); if (tlsInsecure) { options.checkServerIdentity = () => undefined; options.rejectUnauthorized = false; } else { options.checkServerIdentity = options.tlsAllowInvalidHostnames ? () => undefined : undefined; options.rejectUnauthorized = options.tlsAllowInvalidCertificates ? false : true; } return tlsInsecure; } }, w: { target: 'writeConcern', transform({ values: [value], options }) { return WriteConcern.fromOptions({ writeConcern: { ...options.writeConcern, w: value as W } }); } }, waitQueueTimeoutMS: { // TODO(NODE-6491): deprecated: 'Please use timeoutMS instead', default: 0, type: 'uint' }, writeConcern: { target: 'writeConcern', transform({ values: [value], options }) { Eif (isRecord(value) || value instanceof WriteConcern) { return WriteConcern.fromOptions({ writeConcern: { ...options.writeConcern, ...value } }); } else if (value === 'majority' || typeof value === 'number') { return WriteConcern.fromOptions({ writeConcern: { ...options.writeConcern, w: value } }); } throw new MongoParseError(`Invalid WriteConcern cannot parse: ${JSON.stringify(value)}`); } }, wtimeout: { deprecated: 'Please use wtimeoutMS instead', target: 'writeConcern', transform({ values: [value], options }) { const wc = WriteConcern.fromOptions({ writeConcern: { ...options.writeConcern, wtimeout: getUIntFromOptions('wtimeout', value) } }); Eif (wc) return wc; throw new MongoParseError(`Cannot make WriteConcern from wtimeout`); } } as OptionDescriptor, wtimeoutMS: { target: 'writeConcern', transform({ values: [value], options }) { const wc = WriteConcern.fromOptions({ writeConcern: { ...options.writeConcern, wtimeoutMS: getUIntFromOptions('wtimeoutMS', value) } }); Eif (wc) return wc; throw new MongoParseError(`Cannot make WriteConcern from wtimeout`); } }, zlibCompressionLevel: { default: 0, type: 'int' }, mongodbLogPath: { transform({ values: [value] }) { if ( !( (typeof value === 'string' && ['stderr', 'stdout'].includes(value)) || (value && typeof value === 'object' && 'write' in value && typeof value.write === 'function') ) ) { throw new MongoAPIError( `Option 'mongodbLogPath' must be of type 'stderr' | 'stdout' | MongoDBLogWritable` ); } return value; } }, mongodbLogComponentSeverities: { transform({ values: [value] }) { Iif (typeof value !== 'object' || !value) { throw new MongoAPIError(`Option 'mongodbLogComponentSeverities' must be a non-null object`); } for (const [k, v] of Object.entries(value)) { Iif (typeof v !== 'string' || typeof k !== 'string') { throw new MongoAPIError( `User input for option 'mongodbLogComponentSeverities' object cannot include a non-string key or value` ); } Iif (!Object.values(MongoLoggableComponent).some(val => val === k) && k !== 'default') { throw new MongoAPIError( `User input for option 'mongodbLogComponentSeverities' contains invalid key: ${k}` ); } if (!Object.values(SeverityLevel).some(val => val === v)) { throw new MongoAPIError( `Option 'mongodbLogComponentSeverities' does not support ${v} as a value for ${k}` ); } } return value; } }, mongodbLogMaxDocumentLength: { type: 'uint' }, // Custom types for modifying core behavior connectionType: { type: 'any' }, srvPoller: { type: 'any' }, // Accepted Node.js Options allowPartialTrustChain: { type: 'any' }, minDHSize: { type: 'any' }, pskCallback: { type: 'any' }, secureContext: { type: 'any' }, enableTrace: { type: 'any' }, requestCert: { type: 'any' }, rejectUnauthorized: { type: 'any' }, checkServerIdentity: { type: 'any' }, ALPNProtocols: { type: 'any' }, SNICallback: { type: 'any' }, session: { type: 'any' }, requestOCSP: { type: 'any' }, localAddress: { type: 'any' }, localPort: { type: 'any' }, hints: { type: 'any' }, lookup: { type: 'any' }, ca: { type: 'any' }, cert: { type: 'any' }, ciphers: { type: 'any' }, crl: { type: 'any' }, ecdhCurve: { type: 'any' }, key: { type: 'any' }, passphrase: { type: 'any' }, pfx: { type: 'any' }, secureProtocol: { type: 'any' }, index: { type: 'any' }, // Legacy options from v3 era useNewUrlParser: { type: 'boolean', deprecated: 'useNewUrlParser has no effect since Node.js Driver version 4.0.0 and will be removed in the next major version' } as OptionDescriptor, useUnifiedTopology: { type: 'boolean', deprecated: 'useUnifiedTopology has no effect since Node.js Driver version 4.0.0 and will be removed in the next major version' } as OptionDescriptor, __skipPingOnConnect: { type: 'boolean' } } as Record<keyof MongoClientOptions, OptionDescriptor>; export const DEFAULT_OPTIONS = new CaseInsensitiveMap( Object.entries(OPTIONS) .filter(([, descriptor]) => descriptor.default != null) .map(([k, d]) => [k, d.default]) ); |