connect.js 17 KB

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