Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

mongodb-client-encryption

Package Overview
Dependencies
Maintainers
1
Versions
63
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

mongodb-client-encryption - npm Package Compare versions

Comparing version 0.3.0 to 0.3.1

86

lib/autoEncrypter.js

@@ -13,2 +13,10 @@ 'use strict';

/**
* @typedef AutoEncrypter~AutoEncryptionExtraOptions
* @prop {string} [mongocryptdURI] overrides the uri used to connect to mongocryptd
* @prop {boolean} [mongocryptdBypassSpawn=false] if true, autoEncryption will not spawn a mongocryptd
* @prop {string} [mongocryptdSpawnPath] the path to the mongocryptd executable
* @prop {string[]} [mongocryptdSpawnArgs] command line arguments to pass to the mongocryptd executable
*/
/**
* An internal class to be used by the driver for auto encryption

@@ -19,11 +27,57 @@ * **NOTE**: Not meant to be instantiated directly, this is for internal use only.

/**
* @name AutoEncrypter~logLevel
* @kind enum
* @description
* The level of severity of the log message
*
* | Value | Level |
* |-------|-------|
* | 0 | Fatal Error |
* | 1 | Error |
* | 2 | Warning |
* | 3 | Info |
* | 4 | Trace |
*/
/**
* @callback AutoEncrypter~logger
* @descritpion A callback that is invoked with logging information from
* the underlying C++ Bindings.
* @param {AutoEncrypter~logLevel} level The level of logging. Valid values are 0 (Fatal Error), 1 (Error), 2 (Warning), 3 (Info), 4 (Trace)
* @param {string} message The message to log
*/
/**
* Create an AutoEncrypter
*
* @param {object} options Optional settings
* @param {MongoClient} options.client The parent client auto encryption is enabled on
* @param {string} options.keyVaultNamespace The namespace of the key vault, used to store encryption keys
* @param {object} options.schemaMap
* @param {object} options.kmsProviders
* @param {function} options.logger
* @param {AutoEncryptionExtraOptions} [options.extraOptions] Extra options related to mongocryptd
* **Note**: Do not instantiate this class directly. Rather, supply the relevant options to a MongoClient
*
* **Note**: Supplying `options.schemaMap` provides more security than relying on JSON Schemas obtained from the server.
* It protects against a malicious server advertising a false JSON Schema, which could trick the client into sending unencrypted data that should be encrypted.
* Schemas supplied in the schemaMap only apply to configuring automatic encryption for client side encryption.
* Other validation rules in the JSON schema will not be enforced by the driver and will result in an error.
*
* @param {MongoClient} client The client autoEncryption is enabled on
* @param {object} [options] Optional settings
* @param {string} [options.keyVaultNamespace='admin.dataKeys'] The namespace of the key vault, used to store encryption keys
* @param {object} [options.schemaMap] A local specification of a JSON schema used for encryption
* @param {KMSProviders} [options.kmsProviders] options for specific KMS providers to use
* @param {function} [options.logger] An optional hook to catch logging messages from the underlying encryption engine
* @param {AutoEncrypter~AutoEncryptionExtraOptions} [options.extraOptions] Extra options related to mongocryptd
*
* @example
* // Enabling autoEncryption via a MongoClient
* const { MongoClient } = require('mongodb');
* const client = new MongoClient(URL, {
* autoEncryption: {
* kmsProviders: {
* aws: {
* accessKeyId: AWS_ACCESS_KEY,
* secretAccessKey: AWS_SECRET_KEY
* }
* }
* }
* });
*
* await client.connect();
* // From here on, the client will be encrypting / decrypting automatically
*/

@@ -60,2 +114,6 @@ constructor(client, options) {

/**
* @ignore
* @param {Function} callback Invoked when the mongocryptd client either successfully connects or errors
*/
init(callback) {

@@ -71,2 +129,6 @@ if (this._mongocryptdManager.bypassSpawn) {

/**
* @ignore
* @param {Function} callback Invoked when the mongocryptd client either successfully disconnects or errors
*/
teardown(force, callback) {

@@ -77,7 +139,8 @@ this._mongocryptdClient.close(force, callback);

/**
* Encrypt a command for a given namespace
* @ignore
* Encrypt a command for a given namespace.
*
* @param {string} ns The namespace for this encryption context
* @param {object} cmd The command to encrypt
* @param {function} callback
* @param {Function} callback
*/

@@ -114,6 +177,7 @@ encrypt(ns, cmd, callback) {

/**
* @ignore
* Decrypt a command response
*
* @param {*} buffer
* @param {*} callback
* @param {Buffer} buffer
* @param {Function} callback
*/

@@ -120,0 +184,0 @@ decrypt(response, callback) {

@@ -37,3 +37,3 @@ 'use strict';

options.keyAltNames = serializedKeyAltNames;
} else if (options.keyAltNAmes == null) {
} else if (options.keyAltNames == null) {
// If keyAltNames is null or undefined, we can assume the intent of

@@ -51,2 +51,12 @@ // the user is to not pass in the value. B/c Nan::Has will still

/**
* @typedef KMSProviders
* @description Configuration options that are used by specific KMS providers during key generation, encryption, and decryption.
* @prop {object} [aws] Configuration options for using 'aws' as your KMS provider
* @prop {string} [aws.accessKeyId] An AWS Access Key
* @prop {string} [aws.secretAccessKey] An AWS Secret Key
* @prop {object} [local] Configuration options for using 'local' as your KMS provider
* @prop {Buffer} [local.key] A 96-byte long Buffer used for local encryption
*/
/**
* The public interface for explicit client side encryption

@@ -61,2 +71,24 @@ */

* @param {string} options.keyVaultNamespace The namespace of the key vault, used to store encryption keys
* @param {KMSProviders} [options.kmsProviders] options for specific KMS providers to use
*
* @example
* new ClientEncryption(mongoClient, {
* keyVaultNamespace: 'client.encryption',
* kmsProviders: {
* local: {
* key: masterKey // The master key used for encryption/decryption. A 96-byte long Buffer
* }
* }
* });
*
* @example
* new ClientEncryption(mongoClient, {
* keyVaultNamespace: 'client.encryption',
* kmsProviders: {
* aws: {
* accessKeyId: AWS_ACCESS_KEY,
* secretAccessKey: AWS_SECRET_KEY
* }
* }
* });
*/

@@ -77,7 +109,55 @@ constructor(client, options) {

/**
* @typedef ClientEncryption~dataKey
* @description A key used for manual encryption / decryption. Is a BSON Binary object.
*/
/**
* @callback ClientEncryption~createDataKeyCallback
* @param {Error} [error] If present, indicates an error that occurred in the creation of the data key
* @param {ClientEncryption~dataKey} [dataKey] If present, returns the new data key
*/
/**
* Creates a data key used for explicit encryption
*
* @param {string} provider The KMS provider used for this data key
* @param {*} options
* @param {function} callback
* @param {string} provider The KMS provider used for this data key. Must be `'aws'` or `'local'`
* @param {object} [options] Options for creating the data key
* @param {object} [options.masterKey] Idenfities a new KMS-specific key used to encrypt the new data key. If the kmsProvider is "aws" it is required.
* @param {string} [options.masterKey.region] The AWS region of the KMS
* @param {string} [options.masterKey.key] The Amazon Resource Name (ARN) to the AWS customer master key (CMK)
* @param {string[]} [options.keyAltNames] An optional list of string alternate names used to reference a key. If a key is created with alternate names, then encryption may refer to the key by the unique alternate name instead of by _id.
* @param {ClientEncryption~createDataKeyCallback} [callback] Optional callback to invoke when key is created
* @returns {Promise|void} If no callback is provided, returns a Promise that either resolves with the created data key, or rejects with an error. If a callback is provided, returns nothing.
* @example
* // Using callbacks to create a local key
* clientEncrypion.createDataKey('local', (err, dataKey) => {
* if (err) {
* // This means creating the key failed.
* } else {
* // key creation succeeded
* }
* });
*
* @example
* // Using async/await to create a local key
* const dataKey = await clientEncryption.createDataKey('local');
*
* @example
* // Using async/await to create an aws key
* const dataKey = await clientEncryption.createDataKey('aws', {
* masterKey: {
* region: 'us-east-1',
* key: 'xxxxxxxxxxxxxx' // CMK ARN here
* }
* });
*
* @example
* // Using async/await to create an aws key with a keyAltName
* const dataKey = await clientEncryption.createDataKey('aws', {
* masterKey: {
* region: 'us-east-1',
* key: 'xxxxxxxxxxxxxx' // CMK ARN here
* },
* keyAltNames: [ 'mySpecialKey' ]
* });
*/

@@ -117,7 +197,43 @@ createDataKey(provider, options, callback) {

/**
* Explicitly encrypt a provided value
* @callback ClientEncryption~encryptCallback
* @param {Error} [err] If present, indicates an error that occurred in the process of encryption
* @param {Buffer} [result] If present, is the encrypted result
*/
/**
* Explicitly encrypt a provided value. Note that either `options.dataKey` or `options.keyAltName` must
* be specified. Specifying both `options.dataKey` and `options.keyAltName` is considered an error.
*
* @param {*} value
* @param {*} options
* @param {*} callback
* @param {*} value The value that you wish to serialize. Must be of a type that can be serialized into BSON
* @param {object} options
* @param {ClientEncryption~dataKey} [options.dataKey] The Binary dataKey to use for encryption
* @param {string} [options.keyAltName] A unique string name corresponding to an already existing {{@link ClientEncryption~dataKey dataKey}}
* @param {} options.algorithm The algorithm to use for encryption. Must be either `'AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic'` or `AEAD_AES_256_CBC_HMAC_SHA_512-Random'`
* @param {ClientEncryption~encryptCallback} [callback] Optional callback to invoke when value is encrypted
* @returns {Promise|void} If no callback is provided, returns a Promise that either resolves with the encrypted value, or rejects with an error. If a callback is provided, returns nothing.
*
* @example
* // Encryption with callback API
* function encryptMyData(value, callback) {
* clientEncryption.createDataKey('local', (err, dataKey) => {
* if (err) {
* return callback(err);
* }
* clientEncryption.encrypt(value, { dataKey, algorithm: 'AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic' }, callback);
* });
* }
*
* @example
* // Encryption with async/await api
* async function encryptMyData(value) {
* const dataKey = await clientEncryption.createDataKey('local');
* return clientEncryption.encrypt(value, { dataKey, algorithm: 'AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic' });
* }
*
* @example
* // Encryption using a keyAltName
* async function encryptMyData(value) {
* await clientEncryption.createDataKey('local', { keyAltNames: 'mySpecialKey' });
* return clientEncryption.encrypt(value, { keyAltName: 'mySpecialKey', algorithm: 'AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic' });
* }
*/

@@ -162,6 +278,25 @@ encrypt(value, options, callback) {

/**
* @callback ClientEncryption~decryptCallback
* @param {Error} [err] If present, indicates an error that occurred in the process of decryption
* @param {object} [result] If present, is the decrypted result
*/
/**
* Explicitly decrypt a provided encrypted value
*
* @param {*} value
* @param {*} callback
* @param {Buffer} value An encrypted value
* @param {ClientEncryption~decryptCallback} callback Optional callback to invoke when value is decrypted
* @returns {Promise|void} If no callback is provided, returns a Promise that either resolves with the decryped value, or rejects with an error. If a callback is provided, returns nothing.
*
* @example
* // Decrypting value with callback API
* function decryptMyValue(value, callback) {
* clientEncryption.decrypt(value, callback);
* }
*
* @example
* // Decrypting value with async/await API
* async function decryptMyValue(value) {
* return clientEncryption.decrypt(value);
* }
*/

@@ -168,0 +303,0 @@ decrypt(value, callback) {

'use strict';
/**
* @ignore
* Helper function for logging. Enabled by setting the environment flag MONGODB_CRYPT_DEBUG.
* @param {*} msg Anything you want to be logged.
*/
function debug(msg) {

@@ -9,6 +14,17 @@ if (process.env.MONGODB_CRYPT_DEBUG) {

/**
* @ignore
* Gets the database portion of a namespace string
* @param {string} ns A string in the format of a namespace (database.collection)
* @returns {string} The database portion of the namespace
*/
function databaseNamespace(ns) {
return ns.split('.')[0];
}
/**
* @ignore
* Gets the colleciton portion of a namespace string
* @param {string} ns A string in the format of a namespace (database.collection)
* @returns {string} The collection portion of the namespace
*/
function collectionNamespace(ns) {

@@ -21,2 +37,6 @@ return ns

/**
* @class
* An error indicating that something went wrong specifically with MongoDB Client Encryption
*/
class MongoCryptError extends Error {

@@ -30,2 +50,12 @@ constructor(message) {

/**
* @ignore
* A helper function. Invokes a function that takes a callback as the final
* parameter. If a callback is supplied, then it is passed to the function.
* If not, a Promise is returned that resolves/rejects with the result of the
* callback
* @param {Function} [callback] an optional callback.
* @param {Function} fn A function that takes a callback
* @returns {Promise|void} Returns nothing if a callback is supplied, else returns a Promise.
*/
function promiseOrCallback(callback, fn) {

@@ -32,0 +62,0 @@ if (typeof callback === 'function') {

@@ -34,5 +34,22 @@ 'use strict';

function randomHook(buffer, count) {
crypto.randomFillSync(buffer, 0, count);
try {
crypto.randomFillSync(buffer, 0, count);
} catch (e) {
return e;
}
return count;
}
function randomHookNode4(buffer, count) {
let result;
try {
result = crypto.randomBytes(count);
} catch (e) {
return e;
}
result.copy(buffer);
return count;
}
function sha256Hook(input, output) {

@@ -73,3 +90,3 @@ let result;

aes256CbcDecryptHook,
randomHook,
randomHook: typeof crypto.randomFillSync === 'function' ? randomHook : randomHookNode4,
hmacSha512Hook: makeHmacHook('sha512'),

@@ -76,0 +93,0 @@ hmacSha256Hook: makeHmacHook('sha256'),

38

lib/mongocryptdManager.js

@@ -6,13 +6,12 @@ 'use strict';

/**
* @typedef AutoEncryptionExtraOptions
* @prop {string} [mongocryptdURI] overrides the uri used to connect to mongocryptd
* @prop {boolean} [mongocryptdBypassSpawn=false] if true, autoEncryption will not spawn a mongocryptd
* @prop {string} [mongocryptdSpawnPath] the path to the mongocryptd executable
* @prop {string[]} [mongocryptdSpawnArgs] command line arguments to pass to the mongocryptd executable
*/
const mongocryptdPidFileName = 'mongocryptd.pid';
const checkIntervalMS = 50;
/**
* @ignore
* A heuristic check to see if a mongocryptd is running. Checks for a mongocryptd.pid
* file that contains valid JSON. If the pid file exists, the mongocryptd is likely
* running.
* @param {} callback Invoked with true if a valid pid file is found, false otherwise
*/
function checkIsUp(callback) {

@@ -38,2 +37,10 @@ readFile(mongocryptdPidFileName, 'utf8', (err, data) => {

/**
* @ignore
* Attempts to wait for a mongocryptd to be up. Will check with checkIsUp
* in 50ms intervals up to tries times.
* @param {number} tries The number of times to check for a mongocryptd
* @param {Function} callback Is called when either the number of tries have been
* attempted, or when we think a mongocryptd is up
*/
function waitForUp(tries, callback) {

@@ -54,3 +61,12 @@ if (tries <= 0) {

/**
* @ignore
* An internal class that handles spawning a mongocryptd.
*/
class MongocryptdManager {
/**
* @ignore
* Creates a new Mongocryptd Manager
* @param {AutoEncrypter~AutoEncryptionExtraOptions} [extraOptions] extra options that determine how/when to spawn a mongocryptd
*/
constructor(extraOptions) {

@@ -81,2 +97,8 @@ extraOptions = extraOptions || {};

/**
* @ignore
* Will check to see if a mongocryptd is up. If it is not up, it will attempt
* to spawn a mongocryptd in a detached process, and then wait for it to be up.
* @param {Function} callback Invoked when we think a mongocryptd is up
*/
spawn(callback) {

@@ -83,0 +105,0 @@ checkIsUp((err, isUp) => {

@@ -23,13 +23,58 @@ 'use strict';

function stateToString(state) {
if (state === MONGOCRYPT_CTX_ERROR) return 'MONGOCRYPT_CTX_ERROR';
if (state === MONGOCRYPT_CTX_NEED_MONGO_COLLINFO) return 'MONGOCRYPT_CTX_NEED_MONGO_COLLINFO';
if (state === MONGOCRYPT_CTX_NEED_MONGO_MARKINGS) return 'MONGOCRYPT_CTX_NEED_MONGO_MARKINGS';
if (state === MONGOCRYPT_CTX_NEED_MONGO_KEYS) return 'MONGOCRYPT_CTX_NEED_MONGO_KEYS';
if (state === MONGOCRYPT_CTX_NEED_KMS) return 'MONGOCRYPT_CTX_NEED_KMS';
if (state === MONGOCRYPT_CTX_READY) return 'MONGOCRYPT_CTX_READY';
if (state === MONGOCRYPT_CTX_DONE) return 'MONGOCRYPT_CTX_DONE';
}
const stateToString = new Map([
[MONGOCRYPT_CTX_ERROR, 'MONGOCRYPT_CTX_ERROR'],
[MONGOCRYPT_CTX_NEED_MONGO_COLLINFO, 'MONGOCRYPT_CTX_NEED_MONGO_COLLINFO'],
[MONGOCRYPT_CTX_NEED_MONGO_MARKINGS, 'MONGOCRYPT_CTX_NEED_MONGO_MARKINGS'],
[MONGOCRYPT_CTX_NEED_MONGO_KEYS, 'MONGOCRYPT_CTX_NEED_MONGO_KEYS'],
[MONGOCRYPT_CTX_NEED_KMS, 'MONGOCRYPT_CTX_NEED_KMS'],
[MONGOCRYPT_CTX_READY, 'MONGOCRYPT_CTX_READY'],
[MONGOCRYPT_CTX_DONE, 'MONGOCRYPT_CTX_DONE']
]);
/**
* @ignore
* @callback StateMachine~executeCallback
* @param {Error} [err] If present, indicates that the execute call failed with the given error
* @param {object} [result] If present, is the result of executing the state machine.
* @returns {void}
*/
/**
* @ignore
* @callback StateMachine~fetchCollectionInfoCallback
* @param {Error} [err] If present, indicates that fetching the collection info failed with the given error
* @param {object} [result] If present, is the fetched collection info for the first collection to match the given filter
* @returns {void}
*/
/**
* @ignore
* @callback StateMachine~markCommandCallback
* @param {Error} [err] If present, indicates that marking the command failed with the given error
* @param {Buffer} [result] If present, is the marked command serialized into bson
* @returns {void}
*/
/**
* @ignore
* @callback StateMachine~fetchKeysCallback
* @param {Error} [err] If present, indicates that fetching the keys failed with the given error
* @param {object[]} [result] If present, is all the keys from the keyVault colleciton that matched the given filter
*/
/**
* @ignore
* An internal class that executes across a MongoCryptContext until either
* a finishing state or an error is reached. Do not instantiate directly.
* @class StateMachine
*/
class StateMachine {
/**
* @ignore
* Executes the state machine according to the specification
* @param {AutoEncrypter|ClientEncryption} autoEncrypter The JS encryption object
* @param {object} context The C++ context object returned from the bindings
* @param {StateMachine~executeCallback} callback Invoked with the result/error of executing the state machine
* @returns {void}
*/
execute(autoEncrypter, context, callback) {

@@ -42,3 +87,3 @@ const bson = autoEncrypter._bson;

debug(`[context#${context.id}] ${stateToString(context.state)}`);
debug(`[context#${context.id}] ${stateToString.get(context.state) || context.state}`);
switch (context.state) {

@@ -162,4 +207,6 @@ case MONGOCRYPT_CTX_NEED_MONGO_COLLINFO: {

/**
*
* @param {*} kmsContext
* @ignore
* Handles the request to the KMS service. Exposed for testing purposes. Do not directly invoke.
* @param {*} kmsContext A C++ KMS context returned from the bindings
* @returns {Promise<void>} A promise that resolves when the KMS reply has be fully parsed
*/

@@ -198,11 +245,12 @@ kmsRequest(request) {

/**
* @ignore
* Fetches collection info for a provided namespace, when libmongocrypt
* enters the `MONGOCRYPT_CTX_NEED_MONGO_COLLINFO` state. The result is
* used to inform libmongocrypt of the schema associated with this
* namespace.
* namespace. Exposed for testing purposes. Do not directly invoke.
*
* @param {MongoClient} client The shared
* @param {MongoClient} client A MongoClient connected to the topology
* @param {string} ns The namespace to list collections from
* @param {object} filter A filter used to select a particular
* @param {function} callback
* @param {object} filter A filter for the listCollections command
* @param {StateMachine~fetchCollectionInfoCallback} callback Invoked with the info of the requested collection, or with an error
*/

@@ -228,3 +276,10 @@ fetchCollectionInfo(client, ns, filter, callback) {

/**
*
* @ignore
* Calls to the mongocryptd to provide markings for a command.
* Exposed for testing purposes. Do not directly invoke.
* @param {MongoClient} client A MongoClient connected to a mongocryptd
* @param {string} ns The namespace (database.collection) the command is being executed on
* @param {object} command The command to execute.
* @param {StateMachine~markCommandCallback} callback Invoked with the serialized and marked bson command, or with an error
* @returns {void}
*/

@@ -247,3 +302,10 @@ markCommand(client, ns, command, callback) {

/**
*
* @ignore
* Requests keys from the keyVault collection on the topology.
* Exposed for testing purposes. Do not directly invoke.
* @param {MongoClient} client A MongoClient connected to the topology
* @param {string} keyVaultNamespace The namespace (database.collection) of the keyVault Collection
* @param {object} filter The filter for the find query against the keyVault Collection
* @param {StateMachine~fetchKeysCallback} callback Invoked with the found keys, or with an error
* @returns {void}
*/

@@ -250,0 +312,0 @@ fetchKeys(client, keyVaultNamespace, filter, callback) {

{
"name": "mongodb-client-encryption",
"version": "0.3.0",
"version": "0.3.1",
"description": "Official client encryption module for the MongoDB Node.js driver",

@@ -17,3 +17,3 @@ "main": "index.js",

"rebuild": "prebuild --compile",
"prebuild": "prebuild --strip --verbose --tag-prefix node-v -t 10.16.0 -t 8.16.0 -t 6.17.1 -t 4.9.1"
"prebuild": "prebuild --strip --verbose --tag-prefix node-v --all"
},

@@ -36,3 +36,3 @@ "author": "Matt Broadstone <mbroadst@mongodb.com>",

"jsdoc-to-markdown": "^5.0.0",
"mocha": "^6.1.4",
"mocha": "^4.0.0",
"mongodb": "^3.2.7",

@@ -39,0 +39,0 @@ "mongodb-extjson": "^3.0.3",

@@ -38,2 +38,5 @@ MongoDB Client Encryption

</dd>
<dt><a href="#MongoCryptError">MongoCryptError</a></dt>
<dd><p>An error indicating that something went wrong specifically with MongoDB Client Encryption</p>
</dd>
</dl>

@@ -44,4 +47,5 @@

<dl>
<dt><a href="#AutoEncryptionExtraOptions">AutoEncryptionExtraOptions</a></dt>
<dd></dd>
<dt><a href="#KMSProviders">KMSProviders</a></dt>
<dd><p>Configuration options that are used by specific KMS providers during key generation, encryption, and decryption.</p>
</dd>
</dl>

@@ -58,48 +62,88 @@

* [new AutoEncrypter(options)](#new_AutoEncrypter_new)
* [new AutoEncrypter(client, [options])](#new_AutoEncrypter_new)
* [.encrypt(ns, cmd, callback)](#AutoEncrypter+encrypt)
* [~logLevel](#AutoEncrypter..logLevel)
* [.decrypt(buffer, callback)](#AutoEncrypter+decrypt)
* [~AutoEncryptionExtraOptions](#AutoEncrypter..AutoEncryptionExtraOptions)
* [~logger](#AutoEncrypter..logger)
<a name="new_AutoEncrypter_new"></a>
### new AutoEncrypter(options)
### new AutoEncrypter(client, [options])
| Param | Type | Description |
| --- | --- | --- |
| options | <code>object</code> | Optional settings |
| options.client | <code>MongoClient</code> | The parent client auto encryption is enabled on |
| options.keyVaultNamespace | <code>string</code> | The namespace of the key vault, used to store encryption keys |
| options.schemaMap | <code>object</code> | |
| options.kmsProviders | <code>object</code> | |
| options.logger | <code>function</code> | |
| [options.extraOptions] | [<code>AutoEncryptionExtraOptions</code>](#AutoEncryptionExtraOptions) | Extra options related to mongocryptd |
| Param | Type | Default | Description |
| --- | --- | --- | --- |
| client | <code>MongoClient</code> | | The client autoEncryption is enabled on |
| [options] | <code>object</code> | | Optional settings |
| [options.keyVaultNamespace] | <code>string</code> | <code>&quot;&#x27;admin.dataKeys&#x27;&quot;</code> | The namespace of the key vault, used to store encryption keys |
| [options.schemaMap] | <code>object</code> | | A local specification of a JSON schema used for encryption |
| [options.kmsProviders] | [<code>KMSProviders</code>](#KMSProviders) | | options for specific KMS providers to use |
| [options.logger] | <code>function</code> | | An optional hook to catch logging messages from the underlying encryption engine |
| [options.extraOptions] | [<code>AutoEncryptionExtraOptions</code>](#AutoEncrypter..AutoEncryptionExtraOptions) | | Extra options related to mongocryptd |
Create an AutoEncrypter
<a name="AutoEncrypter+encrypt"></a>
**Note**: Do not instantiate this class directly. Rather, supply the relevant options to a MongoClient
### *autoEncrypter*.encrypt(ns, cmd, callback)
**Note**: Supplying `options.schemaMap` provides more security than relying on JSON Schemas obtained from the server.
It protects against a malicious server advertising a false JSON Schema, which could trick the client into sending unencrypted data that should be encrypted.
Schemas supplied in the schemaMap only apply to configuring automatic encryption for client side encryption.
Other validation rules in the JSON schema will not be enforced by the driver and will result in an error.
| Param | Type | Description |
| --- | --- | --- |
| ns | <code>string</code> | The namespace for this encryption context |
| cmd | <code>object</code> | The command to encrypt |
| callback | <code>function</code> | |
**Example**
```js
// Enabling autoEncryption via a MongoClient
const { MongoClient } = require('mongodb');
const client = new MongoClient(URL, {
autoEncryption: {
kmsProviders: {
aws: {
accessKeyId: AWS_ACCESS_KEY,
secretAccessKey: AWS_SECRET_KEY
}
}
}
});
Encrypt a command for a given namespace
await client.connect();
// From here on, the client will be encrypting / decrypting automatically
```
<a name="AutoEncrypter..logLevel"></a>
<a name="AutoEncrypter+decrypt"></a>
### *AutoEncrypter*~logLevel
The level of severity of the log message
### *autoEncrypter*.decrypt(buffer, callback)
| Value | Level |
|-------|-------|
| 0 | Fatal Error |
| 1 | Error |
| 2 | Warning |
| 3 | Info |
| 4 | Trace |
| Param | Type |
| --- | --- |
| buffer | <code>\*</code> |
| callback | <code>\*</code> |
<a name="AutoEncrypter..AutoEncryptionExtraOptions"></a>
Decrypt a command response
### *AutoEncrypter*~AutoEncryptionExtraOptions
**Properties**
| Name | Type | Default | Description |
| --- | --- | --- | --- |
| [mongocryptdURI] | <code>string</code> | | overrides the uri used to connect to mongocryptd |
| [mongocryptdBypassSpawn] | <code>boolean</code> | <code>false</code> | if true, autoEncryption will not spawn a mongocryptd |
| [mongocryptdSpawnPath] | <code>string</code> | | the path to the mongocryptd executable |
| [mongocryptdSpawnArgs] | <code>Array.&lt;string&gt;</code> | | command line arguments to pass to the mongocryptd executable |
<a name="AutoEncrypter..logger"></a>
### *AutoEncrypter*~logger
**Descritpion**: A callback that is invoked with logging information from
the underlying C++ Bindings.
| Param | Type | Description |
| --- | --- | --- |
| level | [<code>logLevel</code>](#AutoEncrypter..logLevel) | The level of logging. Valid values are 0 (Fatal Error), 1 (Error), 2 (Warning), 3 (Info), 4 (Trace) |
| message | <code>string</code> | The message to log |
<a name="ClientEncryption"></a>

@@ -115,9 +159,19 @@

* [.createDataKey(provider, options, callback)](#ClientEncryption+createDataKey)
* _instance_
* [.createDataKey(provider, [options], [callback])](#ClientEncryption+createDataKey)
* [.encrypt(value, options, callback)](#ClientEncryption+encrypt)
* [.encrypt(value, options, [callback])](#ClientEncryption+encrypt)
* [.decrypt(value, callback)](#ClientEncryption+decrypt)
* [.decrypt(value, callback)](#ClientEncryption+decrypt)
* _inner_
* [~dataKey](#ClientEncryption..dataKey)
* [~createDataKeyCallback](#ClientEncryption..createDataKeyCallback)
* [~encryptCallback](#ClientEncryption..encryptCallback)
* [~decryptCallback](#ClientEncryption..decryptCallback)
<a name="new_ClientEncryption_new"></a>

@@ -132,29 +186,128 @@

| options.keyVaultNamespace | <code>string</code> | The namespace of the key vault, used to store encryption keys |
| [options.kmsProviders] | [<code>KMSProviders</code>](#KMSProviders) | options for specific KMS providers to use |
Create a new encryption instance
**Example**
```js
new ClientEncryption(mongoClient, {
keyVaultNamespace: 'client.encryption',
kmsProviders: {
local: {
key: masterKey // The master key used for encryption/decryption. A 96-byte long Buffer
}
}
});
```
**Example**
```js
new ClientEncryption(mongoClient, {
keyVaultNamespace: 'client.encryption',
kmsProviders: {
aws: {
accessKeyId: AWS_ACCESS_KEY,
secretAccessKey: AWS_SECRET_KEY
}
}
});
```
<a name="ClientEncryption+createDataKey"></a>
### *clientEncryption*.createDataKey(provider, options, callback)
### *clientEncryption*.createDataKey(provider, [options], [callback])
| Param | Type | Description |
| --- | --- | --- |
| provider | <code>string</code> | The KMS provider used for this data key |
| options | <code>\*</code> | |
| callback | <code>function</code> | |
| provider | <code>string</code> | The KMS provider used for this data key. Must be `'aws'` or `'local'` |
| [options] | <code>object</code> | Options for creating the data key |
| [options.masterKey] | <code>object</code> | Idenfities a new KMS-specific key used to encrypt the new data key. If the kmsProvider is "aws" it is required. |
| [options.masterKey.region] | <code>string</code> | The AWS region of the KMS |
| [options.masterKey.key] | <code>string</code> | The Amazon Resource Name (ARN) to the AWS customer master key (CMK) |
| [options.keyAltNames] | <code>Array.&lt;string&gt;</code> | An optional list of string alternate names used to reference a key. If a key is created with alternate names, then encryption may refer to the key by the unique alternate name instead of by _id. |
| [callback] | [<code>createDataKeyCallback</code>](#ClientEncryption..createDataKeyCallback) | Optional callback to invoke when key is created |
Creates a data key used for explicit encryption
**Returns**: <code>Promise</code> \| <code>void</code> - If no callback is provided, returns a Promise that either resolves with the created data key, or rejects with an error. If a callback is provided, returns nothing.
**Example**
```js
// Using callbacks to create a local key
clientEncrypion.createDataKey('local', (err, dataKey) => {
if (err) {
// This means creating the key failed.
} else {
// key creation succeeded
}
});
```
**Example**
```js
// Using async/await to create a local key
const dataKey = await clientEncryption.createDataKey('local');
```
**Example**
```js
// Using async/await to create an aws key
const dataKey = await clientEncryption.createDataKey('aws', {
masterKey: {
region: 'us-east-1',
key: 'xxxxxxxxxxxxxx' // CMK ARN here
}
});
```
**Example**
```js
// Using async/await to create an aws key with a keyAltName
const dataKey = await clientEncryption.createDataKey('aws', {
masterKey: {
region: 'us-east-1',
key: 'xxxxxxxxxxxxxx' // CMK ARN here
},
keyAltNames: [ 'mySpecialKey' ]
});
```
<a name="ClientEncryption+encrypt"></a>
### *clientEncryption*.encrypt(value, options, callback)
### *clientEncryption*.encrypt(value, options, [callback])
| Param | Type |
| --- | --- |
| value | <code>\*</code> |
| options | <code>\*</code> |
| callback | <code>\*</code> |
| Param | Type | Description |
| --- | --- | --- |
| value | <code>\*</code> | The value that you wish to serialize. Must be of a type that can be serialized into BSON |
| options | <code>object</code> | |
| [options.dataKey] | [<code>dataKey</code>](#ClientEncryption..dataKey) | The Binary dataKey to use for encryption |
| [options.keyAltName] | <code>string</code> | A unique string name corresponding to an already existing {[dataKey](#ClientEncryption..dataKey)} |
| options.algorithm | | The algorithm to use for encryption. Must be either `'AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic'` or `AEAD_AES_256_CBC_HMAC_SHA_512-Random'` |
| [callback] | [<code>encryptCallback</code>](#ClientEncryption..encryptCallback) | Optional callback to invoke when value is encrypted |
Explicitly encrypt a provided value
Explicitly encrypt a provided value. Note that either `options.dataKey` or `options.keyAltName` must
be specified. Specifying both `options.dataKey` and `options.keyAltName` is considered an error.
**Returns**: <code>Promise</code> \| <code>void</code> - If no callback is provided, returns a Promise that either resolves with the encrypted value, or rejects with an error. If a callback is provided, returns nothing.
**Example**
```js
// Encryption with callback API
function encryptMyData(value, callback) {
clientEncryption.createDataKey('local', (err, dataKey) => {
if (err) {
return callback(err);
}
clientEncryption.encrypt(value, { dataKey, algorithm: 'AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic' }, callback);
});
}
```
**Example**
```js
// Encryption with async/await api
async function encryptMyData(value) {
const dataKey = await clientEncryption.createDataKey('local');
return clientEncryption.encrypt(value, { dataKey, algorithm: 'AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic' });
}
```
**Example**
```js
// Encryption using a keyAltName
async function encryptMyData(value) {
await clientEncryption.createDataKey('local', { keyAltNames: 'mySpecialKey' });
return clientEncryption.encrypt(value, { keyAltName: 'mySpecialKey', algorithm: 'AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic' });
}
```
<a name="ClientEncryption+decrypt"></a>

@@ -164,20 +317,75 @@

| Param | Type |
| --- | --- |
| value | <code>\*</code> |
| callback | <code>\*</code> |
| Param | Type | Description |
| --- | --- | --- |
| value | <code>Buffer</code> | An encrypted value |
| callback | [<code>decryptCallback</code>](#ClientEncryption..decryptCallback) | Optional callback to invoke when value is decrypted |
Explicitly decrypt a provided encrypted value
<a name="AutoEncryptionExtraOptions"></a>
**Returns**: <code>Promise</code> \| <code>void</code> - If no callback is provided, returns a Promise that either resolves with the decryped value, or rejects with an error. If a callback is provided, returns nothing.
**Example**
```js
// Decrypting value with callback API
function decryptMyValue(value, callback) {
clientEncryption.decrypt(value, callback);
}
```
**Example**
```js
// Decrypting value with async/await API
async function decryptMyValue(value) {
return clientEncryption.decrypt(value);
}
```
<a name="ClientEncryption..dataKey"></a>
## AutoEncryptionExtraOptions
### *ClientEncryption*~dataKey
A key used for manual encryption / decryption. Is a BSON Binary object.
<a name="ClientEncryption..createDataKeyCallback"></a>
### *ClientEncryption*~createDataKeyCallback
| Param | Type | Description |
| --- | --- | --- |
| [error] | <code>Error</code> | If present, indicates an error that occurred in the creation of the data key |
| [dataKey] | [<code>dataKey</code>](#ClientEncryption..dataKey) | If present, returns the new data key |
<a name="ClientEncryption..encryptCallback"></a>
### *ClientEncryption*~encryptCallback
| Param | Type | Description |
| --- | --- | --- |
| [err] | <code>Error</code> | If present, indicates an error that occurred in the process of encryption |
| [result] | <code>Buffer</code> | If present, is the encrypted result |
<a name="ClientEncryption..decryptCallback"></a>
### *ClientEncryption*~decryptCallback
| Param | Type | Description |
| --- | --- | --- |
| [err] | <code>Error</code> | If present, indicates an error that occurred in the process of decryption |
| [result] | <code>object</code> | If present, is the decrypted result |
<a name="MongoCryptError"></a>
## MongoCryptError
An error indicating that something went wrong specifically with MongoDB Client Encryption
<a name="KMSProviders"></a>
## KMSProviders
**Properties**
| Name | Type | Default | Description |
| --- | --- | --- | --- |
| [mongocryptdURI] | <code>string</code> | | overrides the uri used to connect to mongocryptd |
| [mongocryptdBypassSpawn] | <code>boolean</code> | <code>false</code> | if true, autoEncryption will not spawn a mongocryptd |
| [mongocryptdSpawnPath] | <code>string</code> | | the path to the mongocryptd executable |
| [mongocryptdSpawnArgs] | <code>Array.&lt;string&gt;</code> | | command line arguments to pass to the mongocryptd executable |
| Name | Type | Description |
| --- | --- | --- |
| [aws] | <code>object</code> | Configuration options for using 'aws' as your KMS provider |
| [aws.accessKeyId] | <code>string</code> | An AWS Access Key |
| [aws.secretAccessKey] | <code>string</code> | An AWS Secret Key |
| [local] | <code>object</code> | Configuration options for using 'local' as your KMS provider |
| [local.key] | <code>Buffer</code> | A 96-byte long Buffer used for local encryption |
Configuration options that are used by specific KMS providers during key generation, encryption, and decryption.

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc