connect.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.LEGAL_TCP_SOCKET_OPTIONS = exports.LEGAL_TLS_SOCKET_OPTIONS = exports.connect = void 0;
  4. const net = require("net");
  5. const socks_1 = require("socks");
  6. const tls = require("tls");
  7. const bson_1 = require("../bson");
  8. const constants_1 = require("../constants");
  9. const error_1 = require("../error");
  10. const utils_1 = require("../utils");
  11. const auth_provider_1 = require("./auth/auth_provider");
  12. const gssapi_1 = require("./auth/gssapi");
  13. const mongocr_1 = require("./auth/mongocr");
  14. const mongodb_aws_1 = require("./auth/mongodb_aws");
  15. const plain_1 = require("./auth/plain");
  16. const providers_1 = require("./auth/providers");
  17. const scram_1 = require("./auth/scram");
  18. const x509_1 = require("./auth/x509");
  19. const connection_1 = require("./connection");
  20. const constants_2 = require("./wire_protocol/constants");
  21. const AUTH_PROVIDERS = new Map([
  22. [providers_1.AuthMechanism.MONGODB_AWS, new mongodb_aws_1.MongoDBAWS()],
  23. [providers_1.AuthMechanism.MONGODB_CR, new mongocr_1.MongoCR()],
  24. [providers_1.AuthMechanism.MONGODB_GSSAPI, new gssapi_1.GSSAPI()],
  25. [providers_1.AuthMechanism.MONGODB_PLAIN, new plain_1.Plain()],
  26. [providers_1.AuthMechanism.MONGODB_SCRAM_SHA1, new scram_1.ScramSHA1()],
  27. [providers_1.AuthMechanism.MONGODB_SCRAM_SHA256, new scram_1.ScramSHA256()],
  28. [providers_1.AuthMechanism.MONGODB_X509, new x509_1.X509()]
  29. ]);
  30. function connect(options, callback) {
  31. makeConnection({ ...options, existingSocket: undefined }, (err, socket) => {
  32. var _a;
  33. if (err || !socket) {
  34. return callback(err);
  35. }
  36. let ConnectionType = (_a = options.connectionType) !== null && _a !== void 0 ? _a : connection_1.Connection;
  37. if (options.autoEncrypter) {
  38. ConnectionType = connection_1.CryptoConnection;
  39. }
  40. performInitialHandshake(new ConnectionType(socket, options), options, callback);
  41. });
  42. }
  43. exports.connect = connect;
  44. function checkSupportedServer(hello, options) {
  45. var _a;
  46. const serverVersionHighEnough = hello &&
  47. (typeof hello.maxWireVersion === 'number' || hello.maxWireVersion instanceof bson_1.Int32) &&
  48. hello.maxWireVersion >= constants_2.MIN_SUPPORTED_WIRE_VERSION;
  49. const serverVersionLowEnough = hello &&
  50. (typeof hello.minWireVersion === 'number' || hello.minWireVersion instanceof bson_1.Int32) &&
  51. hello.minWireVersion <= constants_2.MAX_SUPPORTED_WIRE_VERSION;
  52. if (serverVersionHighEnough) {
  53. if (serverVersionLowEnough) {
  54. return null;
  55. }
  56. const message = `Server at ${options.hostAddress} reports minimum wire version ${JSON.stringify(hello.minWireVersion)}, but this version of the Node.js Driver requires at most ${constants_2.MAX_SUPPORTED_WIRE_VERSION} (MongoDB ${constants_2.MAX_SUPPORTED_SERVER_VERSION})`;
  57. return new error_1.MongoCompatibilityError(message);
  58. }
  59. const message = `Server at ${options.hostAddress} reports maximum wire version ${(_a = JSON.stringify(hello.maxWireVersion)) !== null && _a !== void 0 ? _a : 0}, but this version of the Node.js Driver requires at least ${constants_2.MIN_SUPPORTED_WIRE_VERSION} (MongoDB ${constants_2.MIN_SUPPORTED_SERVER_VERSION})`;
  60. return new error_1.MongoCompatibilityError(message);
  61. }
  62. function performInitialHandshake(conn, options, _callback) {
  63. const callback = function (err, ret) {
  64. if (err && conn) {
  65. conn.destroy();
  66. }
  67. _callback(err, ret);
  68. };
  69. const credentials = options.credentials;
  70. if (credentials) {
  71. if (!(credentials.mechanism === providers_1.AuthMechanism.MONGODB_DEFAULT) &&
  72. !AUTH_PROVIDERS.get(credentials.mechanism)) {
  73. callback(new error_1.MongoInvalidArgumentError(`AuthMechanism '${credentials.mechanism}' not supported`));
  74. return;
  75. }
  76. }
  77. const authContext = new auth_provider_1.AuthContext(conn, credentials, options);
  78. prepareHandshakeDocument(authContext, (err, handshakeDoc) => {
  79. if (err || !handshakeDoc) {
  80. return callback(err);
  81. }
  82. const handshakeOptions = Object.assign({}, options);
  83. if (typeof options.connectTimeoutMS === 'number') {
  84. // The handshake technically is a monitoring check, so its socket timeout should be connectTimeoutMS
  85. handshakeOptions.socketTimeoutMS = options.connectTimeoutMS;
  86. }
  87. const start = new Date().getTime();
  88. conn.command((0, utils_1.ns)('admin.$cmd'), handshakeDoc, handshakeOptions, (err, response) => {
  89. if (err) {
  90. callback(err);
  91. return;
  92. }
  93. if ((response === null || response === void 0 ? void 0 : response.ok) === 0) {
  94. callback(new error_1.MongoServerError(response));
  95. return;
  96. }
  97. if (!('isWritablePrimary' in response)) {
  98. // Provide hello-style response document.
  99. response.isWritablePrimary = response[constants_1.LEGACY_HELLO_COMMAND];
  100. }
  101. if (response.helloOk) {
  102. conn.helloOk = true;
  103. }
  104. const supportedServerErr = checkSupportedServer(response, options);
  105. if (supportedServerErr) {
  106. callback(supportedServerErr);
  107. return;
  108. }
  109. if (options.loadBalanced) {
  110. if (!response.serviceId) {
  111. return callback(new error_1.MongoCompatibilityError('Driver attempted to initialize in load balancing mode, ' +
  112. 'but the server does not support this mode.'));
  113. }
  114. }
  115. // NOTE: This is metadata attached to the connection while porting away from
  116. // handshake being done in the `Server` class. Likely, it should be
  117. // relocated, or at very least restructured.
  118. conn.hello = response;
  119. conn.lastHelloMS = new Date().getTime() - start;
  120. if (!response.arbiterOnly && credentials) {
  121. // store the response on auth context
  122. authContext.response = response;
  123. const resolvedCredentials = credentials.resolveAuthMechanism(response);
  124. const provider = AUTH_PROVIDERS.get(resolvedCredentials.mechanism);
  125. if (!provider) {
  126. return callback(new error_1.MongoInvalidArgumentError(`No AuthProvider for ${resolvedCredentials.mechanism} defined.`));
  127. }
  128. provider.auth(authContext, err => {
  129. if (err) {
  130. if (err instanceof error_1.MongoError) {
  131. err.addErrorLabel(error_1.MongoErrorLabel.HandshakeError);
  132. if ((0, error_1.needsRetryableWriteLabel)(err, response.maxWireVersion)) {
  133. err.addErrorLabel(error_1.MongoErrorLabel.RetryableWriteError);
  134. }
  135. }
  136. return callback(err);
  137. }
  138. callback(undefined, conn);
  139. });
  140. return;
  141. }
  142. callback(undefined, conn);
  143. });
  144. });
  145. }
  146. function prepareHandshakeDocument(authContext, callback) {
  147. const options = authContext.options;
  148. const compressors = options.compressors ? options.compressors : [];
  149. const { serverApi } = authContext.connection;
  150. const handshakeDoc = {
  151. [(serverApi === null || serverApi === void 0 ? void 0 : serverApi.version) ? 'hello' : constants_1.LEGACY_HELLO_COMMAND]: true,
  152. helloOk: true,
  153. client: options.metadata || (0, utils_1.makeClientMetadata)(options),
  154. compression: compressors,
  155. loadBalanced: options.loadBalanced
  156. };
  157. const credentials = authContext.credentials;
  158. if (credentials) {
  159. if (credentials.mechanism === providers_1.AuthMechanism.MONGODB_DEFAULT && credentials.username) {
  160. handshakeDoc.saslSupportedMechs = `${credentials.source}.${credentials.username}`;
  161. const provider = AUTH_PROVIDERS.get(providers_1.AuthMechanism.MONGODB_SCRAM_SHA256);
  162. if (!provider) {
  163. // This auth mechanism is always present.
  164. return callback(new error_1.MongoInvalidArgumentError(`No AuthProvider for ${providers_1.AuthMechanism.MONGODB_SCRAM_SHA256} defined.`));
  165. }
  166. return provider.prepare(handshakeDoc, authContext, callback);
  167. }
  168. const provider = AUTH_PROVIDERS.get(credentials.mechanism);
  169. if (!provider) {
  170. return callback(new error_1.MongoInvalidArgumentError(`No AuthProvider for ${credentials.mechanism} defined.`));
  171. }
  172. return provider.prepare(handshakeDoc, authContext, callback);
  173. }
  174. callback(undefined, handshakeDoc);
  175. }
  176. /** @public */
  177. exports.LEGAL_TLS_SOCKET_OPTIONS = [
  178. 'ALPNProtocols',
  179. 'ca',
  180. 'cert',
  181. 'checkServerIdentity',
  182. 'ciphers',
  183. 'crl',
  184. 'ecdhCurve',
  185. 'key',
  186. 'minDHSize',
  187. 'passphrase',
  188. 'pfx',
  189. 'rejectUnauthorized',
  190. 'secureContext',
  191. 'secureProtocol',
  192. 'servername',
  193. 'session'
  194. ];
  195. /** @public */
  196. exports.LEGAL_TCP_SOCKET_OPTIONS = [
  197. 'family',
  198. 'hints',
  199. 'localAddress',
  200. 'localPort',
  201. 'lookup'
  202. ];
  203. function parseConnectOptions(options) {
  204. const hostAddress = options.hostAddress;
  205. if (!hostAddress)
  206. throw new error_1.MongoInvalidArgumentError('Option "hostAddress" is required');
  207. const result = {};
  208. for (const name of exports.LEGAL_TCP_SOCKET_OPTIONS) {
  209. if (options[name] != null) {
  210. result[name] = options[name];
  211. }
  212. }
  213. if (typeof hostAddress.socketPath === 'string') {
  214. result.path = hostAddress.socketPath;
  215. return result;
  216. }
  217. else if (typeof hostAddress.host === 'string') {
  218. result.host = hostAddress.host;
  219. result.port = hostAddress.port;
  220. return result;
  221. }
  222. else {
  223. // This should never happen since we set up HostAddresses
  224. // But if we don't throw here the socket could hang until timeout
  225. // TODO(NODE-3483)
  226. throw new error_1.MongoRuntimeError(`Unexpected HostAddress ${JSON.stringify(hostAddress)}`);
  227. }
  228. }
  229. function parseSslOptions(options) {
  230. const result = parseConnectOptions(options);
  231. // Merge in valid SSL options
  232. for (const name of exports.LEGAL_TLS_SOCKET_OPTIONS) {
  233. if (options[name] != null) {
  234. result[name] = options[name];
  235. }
  236. }
  237. if (options.existingSocket) {
  238. result.socket = options.existingSocket;
  239. }
  240. // Set default sni servername to be the same as host
  241. if (result.servername == null && result.host && !net.isIP(result.host)) {
  242. result.servername = result.host;
  243. }
  244. return result;
  245. }
  246. const SOCKET_ERROR_EVENT_LIST = ['error', 'close', 'timeout', 'parseError'];
  247. const SOCKET_ERROR_EVENTS = new Set(SOCKET_ERROR_EVENT_LIST);
  248. function makeConnection(options, _callback) {
  249. var _a, _b, _c, _d, _e, _f, _g, _h, _j;
  250. const useTLS = (_a = options.tls) !== null && _a !== void 0 ? _a : false;
  251. const keepAlive = (_b = options.keepAlive) !== null && _b !== void 0 ? _b : true;
  252. const socketTimeoutMS = (_d = (_c = options.socketTimeoutMS) !== null && _c !== void 0 ? _c : Reflect.get(options, 'socketTimeout')) !== null && _d !== void 0 ? _d : 0;
  253. const noDelay = (_e = options.noDelay) !== null && _e !== void 0 ? _e : true;
  254. const connectTimeoutMS = (_f = options.connectTimeoutMS) !== null && _f !== void 0 ? _f : 30000;
  255. const rejectUnauthorized = (_g = options.rejectUnauthorized) !== null && _g !== void 0 ? _g : true;
  256. const keepAliveInitialDelay = (_j = (((_h = options.keepAliveInitialDelay) !== null && _h !== void 0 ? _h : 120000) > socketTimeoutMS
  257. ? Math.round(socketTimeoutMS / 2)
  258. : options.keepAliveInitialDelay)) !== null && _j !== void 0 ? _j : 120000;
  259. const existingSocket = options.existingSocket;
  260. let socket;
  261. const callback = function (err, ret) {
  262. if (err && socket) {
  263. socket.destroy();
  264. }
  265. _callback(err, ret);
  266. };
  267. if (options.proxyHost != null) {
  268. // Currently, only Socks5 is supported.
  269. return makeSocks5Connection({
  270. ...options,
  271. connectTimeoutMS // Should always be present for Socks5
  272. }, callback);
  273. }
  274. if (useTLS) {
  275. const tlsSocket = tls.connect(parseSslOptions(options));
  276. if (typeof tlsSocket.disableRenegotiation === 'function') {
  277. tlsSocket.disableRenegotiation();
  278. }
  279. socket = tlsSocket;
  280. }
  281. else if (existingSocket) {
  282. // In the TLS case, parseSslOptions() sets options.socket to existingSocket,
  283. // so we only need to handle the non-TLS case here (where existingSocket
  284. // gives us all we need out of the box).
  285. socket = existingSocket;
  286. }
  287. else {
  288. socket = net.createConnection(parseConnectOptions(options));
  289. }
  290. socket.setKeepAlive(keepAlive, keepAliveInitialDelay);
  291. socket.setTimeout(connectTimeoutMS);
  292. socket.setNoDelay(noDelay);
  293. const connectEvent = useTLS ? 'secureConnect' : 'connect';
  294. let cancellationHandler;
  295. function errorHandler(eventName) {
  296. return (err) => {
  297. SOCKET_ERROR_EVENTS.forEach(event => socket.removeAllListeners(event));
  298. if (cancellationHandler && options.cancellationToken) {
  299. options.cancellationToken.removeListener('cancel', cancellationHandler);
  300. }
  301. socket.removeListener(connectEvent, connectHandler);
  302. callback(connectionFailureError(eventName, err));
  303. };
  304. }
  305. function connectHandler() {
  306. SOCKET_ERROR_EVENTS.forEach(event => socket.removeAllListeners(event));
  307. if (cancellationHandler && options.cancellationToken) {
  308. options.cancellationToken.removeListener('cancel', cancellationHandler);
  309. }
  310. if ('authorizationError' in socket) {
  311. if (socket.authorizationError && rejectUnauthorized) {
  312. return callback(socket.authorizationError);
  313. }
  314. }
  315. socket.setTimeout(socketTimeoutMS);
  316. callback(undefined, socket);
  317. }
  318. SOCKET_ERROR_EVENTS.forEach(event => socket.once(event, errorHandler(event)));
  319. if (options.cancellationToken) {
  320. cancellationHandler = errorHandler('cancel');
  321. options.cancellationToken.once('cancel', cancellationHandler);
  322. }
  323. if (existingSocket) {
  324. process.nextTick(connectHandler);
  325. }
  326. else {
  327. socket.once(connectEvent, connectHandler);
  328. }
  329. }
  330. function makeSocks5Connection(options, callback) {
  331. var _a, _b;
  332. const hostAddress = utils_1.HostAddress.fromHostPort((_a = options.proxyHost) !== null && _a !== void 0 ? _a : '', // proxyHost is guaranteed to set here
  333. (_b = options.proxyPort) !== null && _b !== void 0 ? _b : 1080);
  334. // First, connect to the proxy server itself:
  335. makeConnection({
  336. ...options,
  337. hostAddress,
  338. tls: false,
  339. proxyHost: undefined
  340. }, (err, rawSocket) => {
  341. if (err) {
  342. return callback(err);
  343. }
  344. const destination = parseConnectOptions(options);
  345. if (typeof destination.host !== 'string' || typeof destination.port !== 'number') {
  346. return callback(new error_1.MongoInvalidArgumentError('Can only make Socks5 connections to TCP hosts'));
  347. }
  348. // Then, establish the Socks5 proxy connection:
  349. socks_1.SocksClient.createConnection({
  350. existing_socket: rawSocket,
  351. timeout: options.connectTimeoutMS,
  352. command: 'connect',
  353. destination: {
  354. host: destination.host,
  355. port: destination.port
  356. },
  357. proxy: {
  358. // host and port are ignored because we pass existing_socket
  359. host: 'iLoveJavaScript',
  360. port: 0,
  361. type: 5,
  362. userId: options.proxyUsername || undefined,
  363. password: options.proxyPassword || undefined
  364. }
  365. }, (err, info) => {
  366. if (err) {
  367. return callback(connectionFailureError('error', err));
  368. }
  369. // Finally, now treat the resulting duplex stream as the
  370. // socket over which we send and receive wire protocol messages:
  371. makeConnection({
  372. ...options,
  373. existingSocket: info.socket,
  374. proxyHost: undefined
  375. }, callback);
  376. });
  377. });
  378. }
  379. function connectionFailureError(type, err) {
  380. switch (type) {
  381. case 'error':
  382. return new error_1.MongoNetworkError(err);
  383. case 'timeout':
  384. return new error_1.MongoNetworkTimeoutError('connection timed out');
  385. case 'close':
  386. return new error_1.MongoNetworkError('connection closed');
  387. case 'cancel':
  388. return new error_1.MongoNetworkError('connection establishment was cancelled');
  389. default:
  390. return new error_1.MongoNetworkError('unknown network error');
  391. }
  392. }
  393. //# sourceMappingURL=connect.js.map