-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
Copy pathclient_encryption.ts
1096 lines (998 loc) · 33.3 KB
/
client_encryption.ts
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
import type {
ExplicitEncryptionContextOptions,
MongoCrypt,
MongoCryptConstructor,
MongoCryptOptions
} from 'mongodb-client-encryption';
import {
type Binary,
deserialize,
type Document,
type Int32,
type Long,
serialize,
type UUID
} from '../bson';
import { type AnyBulkWriteOperation, type BulkWriteResult } from '../bulk/common';
import { type ProxyOptions } from '../cmap/connection';
import { type Collection } from '../collection';
import { type FindCursor } from '../cursor/find_cursor';
import { type Db } from '../db';
import { getMongoDBClientEncryption } from '../deps';
import { type MongoClient, type MongoClientOptions } from '../mongo_client';
import { type Filter, type WithId } from '../mongo_types';
import { type CreateCollectionOptions } from '../operations/create_collection';
import { type DeleteResult } from '../operations/delete';
import { type CSOTTimeoutContext, TimeoutContext } from '../timeout';
import { MongoDBCollectionNamespace, resolveTimeoutOptions } from '../utils';
import * as cryptoCallbacks from './crypto_callbacks';
import {
MongoCryptCreateDataKeyError,
MongoCryptCreateEncryptedCollectionError,
MongoCryptInvalidArgumentError
} from './errors';
import {
type ClientEncryptionDataKeyProvider,
type KMSProviders,
refreshKMSCredentials
} from './providers/index';
import {
type ClientEncryptionSocketOptions,
type CSFLEKMSTlsOptions,
StateMachine
} from './state_machine';
/**
* @public
* The schema for a DataKey in the key vault collection.
*/
export interface DataKey {
_id: UUID;
version?: number;
keyAltNames?: string[];
keyMaterial: Binary;
creationDate: Date;
updateDate: Date;
status: number;
masterKey: Document;
}
/**
* @public
* The public interface for explicit in-use encryption
*/
export class ClientEncryption {
/** @internal */
_client: MongoClient;
/** @internal */
_keyVaultNamespace: string;
/** @internal */
_keyVaultClient: MongoClient;
/** @internal */
_proxyOptions: ProxyOptions;
/** @internal */
_tlsOptions: CSFLEKMSTlsOptions;
/** @internal */
_kmsProviders: KMSProviders;
/** @internal */
_timeoutMS?: number;
/** @internal */
_mongoCrypt: MongoCrypt;
/** @internal */
static getMongoCrypt(): MongoCryptConstructor {
const encryption = getMongoDBClientEncryption();
if ('kModuleError' in encryption) {
throw encryption.kModuleError;
}
return encryption.MongoCrypt;
}
/**
* Create a new encryption instance
*
* @example
* ```ts
* new ClientEncryption(mongoClient, {
* keyVaultNamespace: 'client.encryption',
* kmsProviders: {
* local: {
* key: masterKey // The master key used for encryption/decryption. A 96-byte long Buffer
* }
* }
* });
* ```
*
* @example
* ```ts
* new ClientEncryption(mongoClient, {
* keyVaultNamespace: 'client.encryption',
* kmsProviders: {
* aws: {
* accessKeyId: AWS_ACCESS_KEY,
* secretAccessKey: AWS_SECRET_KEY
* }
* }
* });
* ```
*/
constructor(client: MongoClient, options: ClientEncryptionOptions) {
this._client = client;
this._proxyOptions = options.proxyOptions ?? {};
this._tlsOptions = options.tlsOptions ?? {};
this._kmsProviders = options.kmsProviders || {};
const { timeoutMS } = resolveTimeoutOptions(client, options);
this._timeoutMS = timeoutMS;
if (options.keyVaultNamespace == null) {
throw new MongoCryptInvalidArgumentError('Missing required option `keyVaultNamespace`');
}
const mongoCryptOptions: MongoCryptOptions = {
...options,
cryptoCallbacks,
kmsProviders: !Buffer.isBuffer(this._kmsProviders)
? (serialize(this._kmsProviders) as Buffer)
: this._kmsProviders
};
this._keyVaultNamespace = options.keyVaultNamespace;
this._keyVaultClient = options.keyVaultClient || client;
const MongoCrypt = ClientEncryption.getMongoCrypt();
this._mongoCrypt = new MongoCrypt(mongoCryptOptions);
}
/**
* Creates a data key used for explicit encryption and inserts it into the key vault namespace
*
* @example
* ```ts
* // Using async/await to create a local key
* const dataKeyId = await clientEncryption.createDataKey('local');
* ```
*
* @example
* ```ts
* // Using async/await to create an aws key
* const dataKeyId = await clientEncryption.createDataKey('aws', {
* masterKey: {
* region: 'us-east-1',
* key: 'xxxxxxxxxxxxxx' // CMK ARN here
* }
* });
* ```
*
* @example
* ```ts
* // Using async/await to create an aws key with a keyAltName
* const dataKeyId = await clientEncryption.createDataKey('aws', {
* masterKey: {
* region: 'us-east-1',
* key: 'xxxxxxxxxxxxxx' // CMK ARN here
* },
* keyAltNames: [ 'mySpecialKey' ]
* });
* ```
*/
async createDataKey(
provider: ClientEncryptionDataKeyProvider,
options: ClientEncryptionCreateDataKeyProviderOptions = {}
): Promise<UUID> {
if (options.keyAltNames && !Array.isArray(options.keyAltNames)) {
throw new MongoCryptInvalidArgumentError(
`Option "keyAltNames" must be an array of strings, but was of type ${typeof options.keyAltNames}.`
);
}
let keyAltNames = undefined;
if (options.keyAltNames && options.keyAltNames.length > 0) {
keyAltNames = options.keyAltNames.map((keyAltName, i) => {
if (typeof keyAltName !== 'string') {
throw new MongoCryptInvalidArgumentError(
`Option "keyAltNames" must be an array of strings, but item at index ${i} was of type ${typeof keyAltName}`
);
}
return serialize({ keyAltName });
});
}
let keyMaterial = undefined;
if (options.keyMaterial) {
keyMaterial = serialize({ keyMaterial: options.keyMaterial });
}
const dataKeyBson = serialize({
provider,
...options.masterKey
});
const context = this._mongoCrypt.makeDataKeyContext(dataKeyBson, {
keyAltNames,
keyMaterial
});
const stateMachine = new StateMachine(
{
proxyOptions: this._proxyOptions,
tlsOptions: this._tlsOptions,
socketOptions: autoSelectSocketOptions(this._client.s.options)
},
undefined,
this._client.closeSignal
);
const timeoutContext =
options?.timeoutContext ??
TimeoutContext.create(resolveTimeoutOptions(this._client, { timeoutMS: this._timeoutMS }));
const dataKey = deserialize(
await stateMachine.execute(this, context, { timeoutContext })
) as DataKey;
const { db: dbName, collection: collectionName } = MongoDBCollectionNamespace.fromString(
this._keyVaultNamespace
);
const { insertedId } = await this._keyVaultClient
.db(dbName)
.collection<DataKey>(collectionName)
.insertOne(dataKey, {
writeConcern: { w: 'majority' },
timeoutMS: timeoutContext?.csotEnabled()
? timeoutContext?.getRemainingTimeMSOrThrow()
: undefined
});
return insertedId;
}
/**
* Searches the keyvault for any data keys matching the provided filter. If there are matches, rewrapManyDataKey then attempts to re-wrap the data keys using the provided options.
*
* If no matches are found, then no bulk write is performed.
*
* @example
* ```ts
* // rewrapping all data data keys (using a filter that matches all documents)
* const filter = {};
*
* const result = await clientEncryption.rewrapManyDataKey(filter);
* if (result.bulkWriteResult != null) {
* // keys were re-wrapped, results will be available in the bulkWrite object.
* }
* ```
*
* @example
* ```ts
* // attempting to rewrap all data keys with no matches
* const filter = { _id: new Binary() } // assume _id matches no documents in the database
* const result = await clientEncryption.rewrapManyDataKey(filter);
*
* if (result.bulkWriteResult == null) {
* // no keys matched, `bulkWriteResult` does not exist on the result object
* }
* ```
*/
async rewrapManyDataKey(
filter: Filter<DataKey>,
options: ClientEncryptionRewrapManyDataKeyProviderOptions
): Promise<{ bulkWriteResult?: BulkWriteResult }> {
let keyEncryptionKeyBson = undefined;
if (options) {
const keyEncryptionKey = Object.assign({ provider: options.provider }, options.masterKey);
keyEncryptionKeyBson = serialize(keyEncryptionKey);
}
const filterBson = serialize(filter);
const context = this._mongoCrypt.makeRewrapManyDataKeyContext(filterBson, keyEncryptionKeyBson);
const stateMachine = new StateMachine(
{
proxyOptions: this._proxyOptions,
tlsOptions: this._tlsOptions,
socketOptions: autoSelectSocketOptions(this._client.s.options)
},
undefined,
this._client.closeSignal
);
const timeoutContext = TimeoutContext.create(
resolveTimeoutOptions(this._client, { timeoutMS: this._timeoutMS })
);
const { v: dataKeys } = deserialize(
await stateMachine.execute(this, context, { timeoutContext })
);
if (dataKeys.length === 0) {
return {};
}
const { db: dbName, collection: collectionName } = MongoDBCollectionNamespace.fromString(
this._keyVaultNamespace
);
const replacements = dataKeys.map(
(key: DataKey): AnyBulkWriteOperation<DataKey> => ({
updateOne: {
filter: { _id: key._id },
update: {
$set: {
masterKey: key.masterKey,
keyMaterial: key.keyMaterial
},
$currentDate: {
updateDate: true
}
}
}
})
);
const result = await this._keyVaultClient
.db(dbName)
.collection<DataKey>(collectionName)
.bulkWrite(replacements, {
writeConcern: { w: 'majority' },
timeoutMS: timeoutContext.csotEnabled() ? timeoutContext?.remainingTimeMS : undefined
});
return { bulkWriteResult: result };
}
/**
* Deletes the key with the provided id from the keyvault, if it exists.
*
* @example
* ```ts
* // delete a key by _id
* const id = new Binary(); // id is a bson binary subtype 4 object
* const { deletedCount } = await clientEncryption.deleteKey(id);
*
* if (deletedCount != null && deletedCount > 0) {
* // successful deletion
* }
* ```
*
*/
async deleteKey(_id: Binary): Promise<DeleteResult> {
const { db: dbName, collection: collectionName } = MongoDBCollectionNamespace.fromString(
this._keyVaultNamespace
);
return await this._keyVaultClient
.db(dbName)
.collection<DataKey>(collectionName)
.deleteOne({ _id }, { writeConcern: { w: 'majority' }, timeoutMS: this._timeoutMS });
}
/**
* Finds all the keys currently stored in the keyvault.
*
* This method will not throw.
*
* @returns a FindCursor over all keys in the keyvault.
* @example
* ```ts
* // fetching all keys
* const keys = await clientEncryption.getKeys().toArray();
* ```
*/
getKeys(): FindCursor<DataKey> {
const { db: dbName, collection: collectionName } = MongoDBCollectionNamespace.fromString(
this._keyVaultNamespace
);
return this._keyVaultClient
.db(dbName)
.collection<DataKey>(collectionName)
.find({}, { readConcern: { level: 'majority' }, timeoutMS: this._timeoutMS });
}
/**
* Finds a key in the keyvault with the specified _id.
*
* Returns a promise that either resolves to a {@link DataKey} if a document matches the key or null if no documents
* match the id. The promise rejects with an error if an error is thrown.
* @example
* ```ts
* // getting a key by id
* const id = new Binary(); // id is a bson binary subtype 4 object
* const key = await clientEncryption.getKey(id);
* if (!key) {
* // key is null if there was no matching key
* }
* ```
*/
async getKey(_id: Binary): Promise<DataKey | null> {
const { db: dbName, collection: collectionName } = MongoDBCollectionNamespace.fromString(
this._keyVaultNamespace
);
return await this._keyVaultClient
.db(dbName)
.collection<DataKey>(collectionName)
.findOne({ _id }, { readConcern: { level: 'majority' }, timeoutMS: this._timeoutMS });
}
/**
* Finds a key in the keyvault which has the specified keyAltName.
*
* @param keyAltName - a keyAltName to search for a key
* @returns Returns a promise that either resolves to a {@link DataKey} if a document matches the key or null if no documents
* match the keyAltName. The promise rejects with an error if an error is thrown.
* @example
* ```ts
* // get a key by alt name
* const keyAltName = 'keyAltName';
* const key = await clientEncryption.getKeyByAltName(keyAltName);
* if (!key) {
* // key is null if there is no matching key
* }
* ```
*/
async getKeyByAltName(keyAltName: string): Promise<WithId<DataKey> | null> {
const { db: dbName, collection: collectionName } = MongoDBCollectionNamespace.fromString(
this._keyVaultNamespace
);
return await this._keyVaultClient
.db(dbName)
.collection<DataKey>(collectionName)
.findOne(
{ keyAltNames: keyAltName },
{ readConcern: { level: 'majority' }, timeoutMS: this._timeoutMS }
);
}
/**
* Adds a keyAltName to a key identified by the provided _id.
*
* This method resolves to/returns the *old* key value (prior to adding the new altKeyName).
*
* @param _id - The id of the document to update.
* @param keyAltName - a keyAltName to search for a key
* @returns Returns a promise that either resolves to a {@link DataKey} if a document matches the key or null if no documents
* match the id. The promise rejects with an error if an error is thrown.
* @example
* ```ts
* // adding an keyAltName to a data key
* const id = new Binary(); // id is a bson binary subtype 4 object
* const keyAltName = 'keyAltName';
* const oldKey = await clientEncryption.addKeyAltName(id, keyAltName);
* if (!oldKey) {
* // null is returned if there is no matching document with an id matching the supplied id
* }
* ```
*/
async addKeyAltName(_id: Binary, keyAltName: string): Promise<WithId<DataKey> | null> {
const { db: dbName, collection: collectionName } = MongoDBCollectionNamespace.fromString(
this._keyVaultNamespace
);
const value = await this._keyVaultClient
.db(dbName)
.collection<DataKey>(collectionName)
.findOneAndUpdate(
{ _id },
{ $addToSet: { keyAltNames: keyAltName } },
{ writeConcern: { w: 'majority' }, returnDocument: 'before', timeoutMS: this._timeoutMS }
);
return value;
}
/**
* Adds a keyAltName to a key identified by the provided _id.
*
* This method resolves to/returns the *old* key value (prior to removing the new altKeyName).
*
* If the removed keyAltName is the last keyAltName for that key, the `altKeyNames` property is unset from the document.
*
* @param _id - The id of the document to update.
* @param keyAltName - a keyAltName to search for a key
* @returns Returns a promise that either resolves to a {@link DataKey} if a document matches the key or null if no documents
* match the id. The promise rejects with an error if an error is thrown.
* @example
* ```ts
* // removing a key alt name from a data key
* const id = new Binary(); // id is a bson binary subtype 4 object
* const keyAltName = 'keyAltName';
* const oldKey = await clientEncryption.removeKeyAltName(id, keyAltName);
*
* if (!oldKey) {
* // null is returned if there is no matching document with an id matching the supplied id
* }
* ```
*/
async removeKeyAltName(_id: Binary, keyAltName: string): Promise<WithId<DataKey> | null> {
const { db: dbName, collection: collectionName } = MongoDBCollectionNamespace.fromString(
this._keyVaultNamespace
);
const pipeline = [
{
$set: {
keyAltNames: {
$cond: [
{
$eq: ['$keyAltNames', [keyAltName]]
},
'$$REMOVE',
{
$filter: {
input: '$keyAltNames',
cond: {
$ne: ['$$this', keyAltName]
}
}
}
]
}
}
}
];
const value = await this._keyVaultClient
.db(dbName)
.collection<DataKey>(collectionName)
.findOneAndUpdate({ _id }, pipeline, {
writeConcern: { w: 'majority' },
returnDocument: 'before',
timeoutMS: this._timeoutMS
});
return value;
}
/**
* A convenience method for creating an encrypted collection.
* This method will create data keys for any encryptedFields that do not have a `keyId` defined
* and then create a new collection with the full set of encryptedFields.
*
* @param db - A Node.js driver Db object with which to create the collection
* @param name - The name of the collection to be created
* @param options - Options for createDataKey and for createCollection
* @returns created collection and generated encryptedFields
* @throws MongoCryptCreateDataKeyError - If part way through the process a createDataKey invocation fails, an error will be rejected that has the partial `encryptedFields` that were created.
* @throws MongoCryptCreateEncryptedCollectionError - If creating the collection fails, an error will be rejected that has the entire `encryptedFields` that were created.
*/
async createEncryptedCollection<TSchema extends Document = Document>(
db: Db,
name: string,
options: {
provider: ClientEncryptionDataKeyProvider;
createCollectionOptions: Omit<CreateCollectionOptions, 'encryptedFields'> & {
encryptedFields: Document;
};
masterKey?: AWSEncryptionKeyOptions | AzureEncryptionKeyOptions | GCPEncryptionKeyOptions;
}
): Promise<{ collection: Collection<TSchema>; encryptedFields: Document }> {
const {
provider,
masterKey,
createCollectionOptions: {
encryptedFields: { ...encryptedFields },
...createCollectionOptions
}
} = options;
const timeoutContext =
this._timeoutMS != null
? TimeoutContext.create(resolveTimeoutOptions(this._client, { timeoutMS: this._timeoutMS }))
: undefined;
if (Array.isArray(encryptedFields.fields)) {
const createDataKeyPromises = encryptedFields.fields.map(async field =>
field == null || typeof field !== 'object' || field.keyId != null
? field
: {
...field,
keyId: await this.createDataKey(provider, {
masterKey,
// clone the timeoutContext
// in order to avoid sharing the same timeout for server selection and connection checkout across different concurrent operations
timeoutContext: timeoutContext?.csotEnabled() ? timeoutContext?.clone() : undefined
})
}
);
const createDataKeyResolutions = await Promise.allSettled(createDataKeyPromises);
encryptedFields.fields = createDataKeyResolutions.map((resolution, index) =>
resolution.status === 'fulfilled' ? resolution.value : encryptedFields.fields[index]
);
const rejection = createDataKeyResolutions.find(
(result): result is PromiseRejectedResult => result.status === 'rejected'
);
if (rejection != null) {
throw new MongoCryptCreateDataKeyError(encryptedFields, { cause: rejection.reason });
}
}
try {
const collection = await db.createCollection<TSchema>(name, {
...createCollectionOptions,
encryptedFields,
timeoutMS: timeoutContext?.csotEnabled()
? timeoutContext?.getRemainingTimeMSOrThrow()
: undefined
});
return { collection, encryptedFields };
} catch (cause) {
throw new MongoCryptCreateEncryptedCollectionError(encryptedFields, { cause });
}
}
/**
* Explicitly encrypt a provided value. Note that either `options.keyId` or `options.keyAltName` must
* be specified. Specifying both `options.keyId` and `options.keyAltName` is considered an error.
*
* @param value - The value that you wish to serialize. Must be of a type that can be serialized into BSON
* @param options -
* @returns a Promise that either resolves with the encrypted value, or rejects with an error.
*
* @example
* ```ts
* // Encryption with async/await api
* async function encryptMyData(value) {
* const keyId = await clientEncryption.createDataKey('local');
* return clientEncryption.encrypt(value, { keyId, algorithm: 'AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic' });
* }
* ```
*
* @example
* ```ts
* // 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' });
* }
* ```
*/
async encrypt(value: unknown, options: ClientEncryptionEncryptOptions): Promise<Binary> {
return await this._encrypt(value, false, options);
}
/**
* Encrypts a Match Expression or Aggregate Expression to query a range index.
*
* Only supported when queryType is "range" and algorithm is "Range".
*
* @param expression - a BSON document of one of the following forms:
* 1. A Match Expression of this form:
* `{$and: [{<field>: {$gt: <value1>}}, {<field>: {$lt: <value2> }}]}`
* 2. An Aggregate Expression of this form:
* `{$and: [{$gt: [<fieldpath>, <value1>]}, {$lt: [<fieldpath>, <value2>]}]}`
*
* `$gt` may also be `$gte`. `$lt` may also be `$lte`.
*
* @param options -
* @returns Returns a Promise that either resolves with the encrypted value or rejects with an error.
*/
async encryptExpression(
expression: Document,
options: ClientEncryptionEncryptOptions
): Promise<Binary> {
return await this._encrypt(expression, true, options);
}
/**
* Explicitly decrypt a provided encrypted value
*
* @param value - An encrypted value
* @returns a Promise that either resolves with the decrypted value, or rejects with an error
*
* @example
* ```ts
* // Decrypting value with async/await API
* async function decryptMyValue(value) {
* return clientEncryption.decrypt(value);
* }
* ```
*/
async decrypt<T = any>(value: Binary): Promise<T> {
const valueBuffer = serialize({ v: value });
const context = this._mongoCrypt.makeExplicitDecryptionContext(valueBuffer);
const stateMachine = new StateMachine(
{
proxyOptions: this._proxyOptions,
tlsOptions: this._tlsOptions,
socketOptions: autoSelectSocketOptions(this._client.s.options)
},
undefined,
this._client.closeSignal
);
const timeoutContext =
this._timeoutMS != null
? TimeoutContext.create(resolveTimeoutOptions(this._client, { timeoutMS: this._timeoutMS }))
: undefined;
const { v } = deserialize(await stateMachine.execute(this, context, { timeoutContext }));
return v;
}
/**
* @internal
* Ask the user for KMS credentials.
*
* This returns anything that looks like the kmsProviders original input
* option. It can be empty, and any provider specified here will override
* the original ones.
*/
async askForKMSCredentials(): Promise<KMSProviders> {
return await refreshKMSCredentials(this._kmsProviders, this._client.closeSignal);
}
static get libmongocryptVersion() {
return ClientEncryption.getMongoCrypt().libmongocryptVersion;
}
/**
* @internal
* A helper that perform explicit encryption of values and expressions.
* Explicitly encrypt a provided value. Note that either `options.keyId` or `options.keyAltName` must
* be specified. Specifying both `options.keyId` and `options.keyAltName` is considered an error.
*
* @param value - The value that you wish to encrypt. Must be of a type that can be serialized into BSON
* @param expressionMode - a boolean that indicates whether or not to encrypt the value as an expression
* @param options - options to pass to encrypt
* @returns the raw result of the call to stateMachine.execute(). When expressionMode is set to true, the return
* value will be a bson document. When false, the value will be a BSON Binary.
*
*/
private async _encrypt(
value: unknown,
expressionMode: boolean,
options: ClientEncryptionEncryptOptions
): Promise<Binary> {
const { algorithm, keyId, keyAltName, contentionFactor, queryType, rangeOptions } = options;
const contextOptions: ExplicitEncryptionContextOptions = {
expressionMode,
algorithm
};
if (keyId) {
contextOptions.keyId = keyId.buffer;
}
if (keyAltName) {
if (keyId) {
throw new MongoCryptInvalidArgumentError(
`"options" cannot contain both "keyId" and "keyAltName"`
);
}
if (typeof keyAltName !== 'string') {
throw new MongoCryptInvalidArgumentError(
`"options.keyAltName" must be of type string, but was of type ${typeof keyAltName}`
);
}
contextOptions.keyAltName = serialize({ keyAltName });
}
if (typeof contentionFactor === 'number' || typeof contentionFactor === 'bigint') {
contextOptions.contentionFactor = contentionFactor;
}
if (typeof queryType === 'string') {
contextOptions.queryType = queryType;
}
if (typeof rangeOptions === 'object') {
contextOptions.rangeOptions = serialize(rangeOptions);
}
const valueBuffer = serialize({ v: value });
const stateMachine = new StateMachine(
{
proxyOptions: this._proxyOptions,
tlsOptions: this._tlsOptions,
socketOptions: autoSelectSocketOptions(this._client.s.options)
},
undefined,
this._client.closeSignal
);
const context = this._mongoCrypt.makeExplicitEncryptionContext(valueBuffer, contextOptions);
const timeoutContext =
this._timeoutMS != null
? TimeoutContext.create(resolveTimeoutOptions(this._client, { timeoutMS: this._timeoutMS }))
: undefined;
const { v } = deserialize(await stateMachine.execute(this, context, { timeoutContext }));
return v;
}
}
/**
* @public
* Options to provide when encrypting data.
*/
export interface ClientEncryptionEncryptOptions {
/**
* The algorithm to use for encryption.
*/
algorithm:
| 'AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic'
| 'AEAD_AES_256_CBC_HMAC_SHA_512-Random'
| 'Indexed'
| 'Unindexed'
| 'Range';
/**
* The id of the Binary dataKey to use for encryption
*/
keyId?: Binary;
/**
* A unique string name corresponding to an already existing dataKey.
*/
keyAltName?: string;
/** The contention factor. */
contentionFactor?: bigint | number;
/**
* The query type.
*/
queryType?: 'equality' | 'range';
/** The index options for a Queryable Encryption field supporting "range" queries.*/
rangeOptions?: RangeOptions;
}
/**
* @public
* @experimental
*/
export interface ClientEncryptionRewrapManyDataKeyProviderOptions {
provider: ClientEncryptionDataKeyProvider;
masterKey?:
| AWSEncryptionKeyOptions
| AzureEncryptionKeyOptions
| GCPEncryptionKeyOptions
| KMIPEncryptionKeyOptions
| undefined;
}
/**
* @public
* Additional settings to provide when creating a new `ClientEncryption` instance.
*/
export interface ClientEncryptionOptions {
/**
* The namespace of the key vault, used to store encryption keys
*/
keyVaultNamespace: string;
/**
* A MongoClient used to fetch keys from a key vault. Defaults to client.
*/
keyVaultClient?: MongoClient | undefined;
/**
* Options for specific KMS providers to use
*/
kmsProviders?: KMSProviders;
/**
* Options for specifying a Socks5 proxy to use for connecting to the KMS.
*/
proxyOptions?: ProxyOptions;
/**
* TLS options for kms providers to use.
*/
tlsOptions?: CSFLEKMSTlsOptions;
/**
* @experimental
*
* The timeout setting to be used for all the operations on ClientEncryption.
*
* When provided, `timeoutMS` is used as the timeout for each operation executed on
* the ClientEncryption object. For example:
*
* ```typescript
* const clientEncryption = new ClientEncryption(client, {
* timeoutMS: 1_000
* kmsProviders: { local: { key: '<KEY>' } }
* });
*
* // `1_000` is used as the timeout for createDataKey call
* await clientEncryption.createDataKey('local');
* ```
*
* If `timeoutMS` is configured on the provided client, the client's `timeoutMS` value
* will be used unless `timeoutMS` is also provided as a client encryption option.
*
* ```typescript
* const client = new MongoClient('<uri>', { timeoutMS: 2_000 });
*
* // timeoutMS is set to 1_000 on clientEncryption
* const clientEncryption = new ClientEncryption(client, {
* timeoutMS: 1_000
* kmsProviders: { local: { key: '<KEY>' } }
* });
* ```
*/
timeoutMS?: number;
}
/**
* @public
* Configuration options for making an AWS encryption key
*/
export interface AWSEncryptionKeyOptions {
/**
* The AWS region of the KMS
*/
region: string;
/**
* The Amazon Resource Name (ARN) to the AWS customer master key (CMK)
*/
key: string;
/**
* An alternate host to send KMS requests to. May include port number.
*/
endpoint?: string | undefined;
}
/**
* @public
* Configuration options for making an AWS encryption key
*/
export interface GCPEncryptionKeyOptions {
/**
* GCP project ID
*/
projectId: string;
/**
* Location name (e.g. "global")
*/
location: string;
/**
* Key ring name
*/
keyRing: string;
/**
* Key name
*/
keyName: string;
/**
* Key version
*/
keyVersion?: string | undefined;
/**
* KMS URL, defaults to `https://www.googleapis.com/auth/cloudkms`
*/
endpoint?: string | undefined;
}
/**
* @public
* Configuration options for making an Azure encryption key
*/
export interface AzureEncryptionKeyOptions {
/**
* Key name
*/
keyName: string;
/**
* Key vault URL, typically `<name>.vault.azure.net`
*/
keyVaultEndpoint: string;
/**
* Key version
*/
keyVersion?: string | undefined;
}
/**
* @public