auto_encrypter.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. "use strict";
  2. var _a;
  3. Object.defineProperty(exports, "__esModule", { value: true });
  4. exports.AutoEncrypter = exports.AutoEncryptionLoggerLevel = void 0;
  5. const net = require("net");
  6. const bson_1 = require("../bson");
  7. const constants_1 = require("../constants");
  8. const deps_1 = require("../deps");
  9. const error_1 = require("../error");
  10. const mongo_client_1 = require("../mongo_client");
  11. const utils_1 = require("../utils");
  12. const client_encryption_1 = require("./client_encryption");
  13. const cryptoCallbacks = require("./crypto_callbacks");
  14. const errors_1 = require("./errors");
  15. const mongocryptd_manager_1 = require("./mongocryptd_manager");
  16. const providers_1 = require("./providers");
  17. const state_machine_1 = require("./state_machine");
  18. /** @public */
  19. exports.AutoEncryptionLoggerLevel = Object.freeze({
  20. FatalError: 0,
  21. Error: 1,
  22. Warning: 2,
  23. Info: 3,
  24. Trace: 4
  25. });
  26. /**
  27. * @internal An internal class to be used by the driver for auto encryption
  28. * **NOTE**: Not meant to be instantiated directly, this is for internal use only.
  29. */
  30. class AutoEncrypter {
  31. /** @internal */
  32. static getMongoCrypt() {
  33. const encryption = (0, deps_1.getMongoDBClientEncryption)();
  34. if ('kModuleError' in encryption) {
  35. throw encryption.kModuleError;
  36. }
  37. return encryption.MongoCrypt;
  38. }
  39. /**
  40. * Create an AutoEncrypter
  41. *
  42. * **Note**: Do not instantiate this class directly. Rather, supply the relevant options to a MongoClient
  43. *
  44. * **Note**: Supplying `options.schemaMap` provides more security than relying on JSON Schemas obtained from the server.
  45. * It protects against a malicious server advertising a false JSON Schema, which could trick the client into sending unencrypted data that should be encrypted.
  46. * Schemas supplied in the schemaMap only apply to configuring automatic encryption for Client-Side Field Level Encryption.
  47. * Other validation rules in the JSON schema will not be enforced by the driver and will result in an error.
  48. *
  49. * @example <caption>Create an AutoEncrypter that makes use of mongocryptd</caption>
  50. * ```ts
  51. * // Enabling autoEncryption via a MongoClient using mongocryptd
  52. * const { MongoClient } = require('mongodb');
  53. * const client = new MongoClient(URL, {
  54. * autoEncryption: {
  55. * kmsProviders: {
  56. * aws: {
  57. * accessKeyId: AWS_ACCESS_KEY,
  58. * secretAccessKey: AWS_SECRET_KEY
  59. * }
  60. * }
  61. * }
  62. * });
  63. * ```
  64. *
  65. * await client.connect();
  66. * // From here on, the client will be encrypting / decrypting automatically
  67. * @example <caption>Create an AutoEncrypter that makes use of libmongocrypt's CSFLE shared library</caption>
  68. * ```ts
  69. * // Enabling autoEncryption via a MongoClient using CSFLE shared library
  70. * const { MongoClient } = require('mongodb');
  71. * const client = new MongoClient(URL, {
  72. * autoEncryption: {
  73. * kmsProviders: {
  74. * aws: {}
  75. * },
  76. * extraOptions: {
  77. * cryptSharedLibPath: '/path/to/local/crypt/shared/lib',
  78. * cryptSharedLibRequired: true
  79. * }
  80. * }
  81. * });
  82. * ```
  83. *
  84. * await client.connect();
  85. * // From here on, the client will be encrypting / decrypting automatically
  86. */
  87. constructor(client, options) {
  88. /**
  89. * Used by devtools to enable decorating decryption results.
  90. *
  91. * When set and enabled, `decrypt` will automatically recursively
  92. * traverse a decrypted document and if a field has been decrypted,
  93. * it will mark it as decrypted. Compass uses this to determine which
  94. * fields were decrypted.
  95. */
  96. this[_a] = false;
  97. this._client = client;
  98. this._bypassEncryption = options.bypassAutoEncryption === true;
  99. this._keyVaultNamespace = options.keyVaultNamespace || 'admin.datakeys';
  100. this._keyVaultClient = options.keyVaultClient || client;
  101. this._metaDataClient = options.metadataClient || client;
  102. this._proxyOptions = options.proxyOptions || {};
  103. this._tlsOptions = options.tlsOptions || {};
  104. this._kmsProviders = options.kmsProviders || {};
  105. this._credentialProviders = options.credentialProviders;
  106. if (options.credentialProviders?.aws && !(0, providers_1.isEmptyCredentials)('aws', this._kmsProviders)) {
  107. throw new errors_1.MongoCryptInvalidArgumentError('Can only provide a custom AWS credential provider when the state machine is configured for automatic AWS credential fetching');
  108. }
  109. const mongoCryptOptions = {
  110. enableMultipleCollinfo: true,
  111. cryptoCallbacks
  112. };
  113. if (options.schemaMap) {
  114. mongoCryptOptions.schemaMap = Buffer.isBuffer(options.schemaMap)
  115. ? options.schemaMap
  116. : (0, bson_1.serialize)(options.schemaMap);
  117. }
  118. if (options.encryptedFieldsMap) {
  119. mongoCryptOptions.encryptedFieldsMap = Buffer.isBuffer(options.encryptedFieldsMap)
  120. ? options.encryptedFieldsMap
  121. : (0, bson_1.serialize)(options.encryptedFieldsMap);
  122. }
  123. mongoCryptOptions.kmsProviders = !Buffer.isBuffer(this._kmsProviders)
  124. ? (0, bson_1.serialize)(this._kmsProviders)
  125. : this._kmsProviders;
  126. if (options.options?.logger) {
  127. mongoCryptOptions.logger = options.options.logger;
  128. }
  129. if (options.extraOptions && options.extraOptions.cryptSharedLibPath) {
  130. mongoCryptOptions.cryptSharedLibPath = options.extraOptions.cryptSharedLibPath;
  131. }
  132. if (options.bypassQueryAnalysis) {
  133. mongoCryptOptions.bypassQueryAnalysis = options.bypassQueryAnalysis;
  134. }
  135. if (options.keyExpirationMS != null) {
  136. mongoCryptOptions.keyExpirationMS = options.keyExpirationMS;
  137. }
  138. this._bypassMongocryptdAndCryptShared = this._bypassEncryption || !!options.bypassQueryAnalysis;
  139. if (options.extraOptions && options.extraOptions.cryptSharedLibSearchPaths) {
  140. // Only for driver testing
  141. mongoCryptOptions.cryptSharedLibSearchPaths = options.extraOptions.cryptSharedLibSearchPaths;
  142. }
  143. else if (!this._bypassMongocryptdAndCryptShared) {
  144. mongoCryptOptions.cryptSharedLibSearchPaths = ['$SYSTEM'];
  145. }
  146. const MongoCrypt = AutoEncrypter.getMongoCrypt();
  147. this._mongocrypt = new MongoCrypt(mongoCryptOptions);
  148. this._contextCounter = 0;
  149. if (options.extraOptions &&
  150. options.extraOptions.cryptSharedLibRequired &&
  151. !this.cryptSharedLibVersionInfo) {
  152. throw new errors_1.MongoCryptInvalidArgumentError('`cryptSharedLibRequired` set but no crypt_shared library loaded');
  153. }
  154. // Only instantiate mongocryptd manager/client once we know for sure
  155. // that we are not using the CSFLE shared library.
  156. if (!this._bypassMongocryptdAndCryptShared && !this.cryptSharedLibVersionInfo) {
  157. this._mongocryptdManager = new mongocryptd_manager_1.MongocryptdManager(options.extraOptions);
  158. const clientOptions = {
  159. serverSelectionTimeoutMS: 10000
  160. };
  161. if ((options.extraOptions == null || typeof options.extraOptions.mongocryptdURI !== 'string') &&
  162. !net.getDefaultAutoSelectFamily) {
  163. // Only set family if autoSelectFamily options are not supported.
  164. clientOptions.family = 4;
  165. }
  166. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  167. // @ts-ignore: TS complains as this always returns true on versions where it is present.
  168. if (net.getDefaultAutoSelectFamily) {
  169. // AutoEncrypter is made inside of MongoClient constructor while options are being parsed,
  170. // we do not have access to the options that are in progress.
  171. // TODO(NODE-6449): AutoEncrypter does not use client options for autoSelectFamily
  172. Object.assign(clientOptions, (0, client_encryption_1.autoSelectSocketOptions)(this._client.s?.options ?? {}));
  173. }
  174. this._mongocryptdClient = new mongo_client_1.MongoClient(this._mongocryptdManager.uri, clientOptions);
  175. }
  176. }
  177. /**
  178. * Initializes the auto encrypter by spawning a mongocryptd and connecting to it.
  179. *
  180. * This function is a no-op when bypassSpawn is set or the crypt shared library is used.
  181. */
  182. async init() {
  183. if (this._bypassMongocryptdAndCryptShared || this.cryptSharedLibVersionInfo) {
  184. return;
  185. }
  186. if (!this._mongocryptdManager) {
  187. throw new error_1.MongoRuntimeError('Reached impossible state: mongocryptdManager is undefined when neither bypassSpawn nor the shared lib are specified.');
  188. }
  189. if (!this._mongocryptdClient) {
  190. throw new error_1.MongoRuntimeError('Reached impossible state: mongocryptdClient is undefined when neither bypassSpawn nor the shared lib are specified.');
  191. }
  192. if (!this._mongocryptdManager.bypassSpawn) {
  193. await this._mongocryptdManager.spawn();
  194. }
  195. try {
  196. const client = await this._mongocryptdClient.connect();
  197. return client;
  198. }
  199. catch (error) {
  200. throw new error_1.MongoRuntimeError('Unable to connect to `mongocryptd`, please make sure it is running or in your PATH for auto-spawn', { cause: error });
  201. }
  202. }
  203. /**
  204. * Cleans up the `_mongocryptdClient`, if present.
  205. */
  206. async close() {
  207. await this._mongocryptdClient?.close();
  208. }
  209. /**
  210. * Encrypt a command for a given namespace.
  211. */
  212. async encrypt(ns, cmd, options = {}) {
  213. options.signal?.throwIfAborted();
  214. if (this._bypassEncryption) {
  215. // If `bypassAutoEncryption` has been specified, don't encrypt
  216. return cmd;
  217. }
  218. const commandBuffer = Buffer.isBuffer(cmd) ? cmd : (0, bson_1.serialize)(cmd, options);
  219. const context = this._mongocrypt.makeEncryptionContext(utils_1.MongoDBCollectionNamespace.fromString(ns).db, commandBuffer);
  220. context.id = this._contextCounter++;
  221. context.ns = ns;
  222. context.document = cmd;
  223. const stateMachine = new state_machine_1.StateMachine({
  224. promoteValues: false,
  225. promoteLongs: false,
  226. proxyOptions: this._proxyOptions,
  227. tlsOptions: this._tlsOptions,
  228. socketOptions: (0, client_encryption_1.autoSelectSocketOptions)(this._client.s.options)
  229. });
  230. return (0, bson_1.deserialize)(await stateMachine.execute(this, context, options), {
  231. promoteValues: false,
  232. promoteLongs: false
  233. });
  234. }
  235. /**
  236. * Decrypt a command response
  237. */
  238. async decrypt(response, options = {}) {
  239. options.signal?.throwIfAborted();
  240. const context = this._mongocrypt.makeDecryptionContext(response);
  241. context.id = this._contextCounter++;
  242. const stateMachine = new state_machine_1.StateMachine({
  243. ...options,
  244. proxyOptions: this._proxyOptions,
  245. tlsOptions: this._tlsOptions,
  246. socketOptions: (0, client_encryption_1.autoSelectSocketOptions)(this._client.s.options)
  247. });
  248. return await stateMachine.execute(this, context, options);
  249. }
  250. /**
  251. * Ask the user for KMS credentials.
  252. *
  253. * This returns anything that looks like the kmsProviders original input
  254. * option. It can be empty, and any provider specified here will override
  255. * the original ones.
  256. */
  257. async askForKMSCredentials() {
  258. return await (0, providers_1.refreshKMSCredentials)(this._kmsProviders, this._credentialProviders);
  259. }
  260. /**
  261. * Return the current libmongocrypt's CSFLE shared library version
  262. * as `{ version: bigint, versionStr: string }`, or `null` if no CSFLE
  263. * shared library was loaded.
  264. */
  265. get cryptSharedLibVersionInfo() {
  266. return this._mongocrypt.cryptSharedLibVersionInfo;
  267. }
  268. static get libmongocryptVersion() {
  269. return AutoEncrypter.getMongoCrypt().libmongocryptVersion;
  270. }
  271. }
  272. exports.AutoEncrypter = AutoEncrypter;
  273. _a = constants_1.kDecorateResult;
  274. //# sourceMappingURL=auto_encrypter.js.map