-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
Copy pathclient_side_encryption.prose.test.js
2243 lines (2080 loc) · 89.4 KB
/
client_side_encryption.prose.test.js
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
'use strict';
const BSON = require('bson');
const { expect } = require('chai');
const fs = require('fs');
const path = require('path');
const { dropCollection, APMEventCollector } = require('../shared');
const { EJSON } = BSON;
const { LEGACY_HELLO_COMMAND } = require('../../mongodb');
const { MongoServerError, MongoServerSelectionError, MongoClient } = require('../../mongodb');
const { getEncryptExtraOptions } = require('../../tools/utils');
const { installNodeDNSWorkaroundHooks } = require('../../tools/runner/hooks/configuration');
const { coerce, gte } = require('semver');
const {
externalSchema
} = require('../../spec/client-side-encryption/external/external-schema.json');
/* eslint-disable no-restricted-modules */
const { ClientEncryption } = require('../../../src/client-side-encryption/client_encryption');
const getKmsProviders = (localKey, kmipEndpoint, azureEndpoint, gcpEndpoint) => {
const result = BSON.EJSON.parse(process.env.CSFLE_KMS_PROVIDERS || '{}');
if (localKey) {
result.local = { key: localKey };
}
result.kmip = {
endpoint: kmipEndpoint || 'localhost:5698'
};
if (result.azure && azureEndpoint) {
result.azure.identityPlatformEndpoint = azureEndpoint;
}
if (result.gcp && gcpEndpoint) {
result.gcp.endpoint = gcpEndpoint;
}
return result;
};
const noop = () => {};
const metadata = {
requires: {
clientSideEncryption: true,
mongodb: '>=4.2.0',
topology: '!load-balanced'
}
};
const eeMetadata = {
requires: {
clientSideEncryption: true,
mongodb: '>=7.0.0',
topology: ['replicaset', 'sharded']
}
};
// Tests for the ClientEncryption type are not included as part of the YAML tests.
// In the prose tests LOCAL_MASTERKEY refers to the following base64:
// .. code:: javascript
// Mng0NCt4ZHVUYUJCa1kxNkVyNUR1QURhZ2h2UzR2d2RrZzh0cFBwM3R6NmdWMDFBMUN3YkQ5aXRRMkhGRGdQV09wOGVNYUMxT2k3NjZKelhaQmRCZGJkTXVyZG9uSjFk
describe('Client Side Encryption Prose Tests', metadata, function () {
const dataDbName = 'db';
const dataCollName = 'coll';
const dataNamespace = `${dataDbName}.${dataCollName}`;
const keyVaultDbName = 'keyvault';
const keyVaultCollName = 'datakeys';
const keyVaultNamespace = `${keyVaultDbName}.${keyVaultCollName}`;
const LOCAL_KEY = Buffer.from(
'Mng0NCt4ZHVUYUJCa1kxNkVyNUR1QURhZ2h2UzR2d2RrZzh0cFBwM3R6NmdWMDFBMUN3YkQ5aXRRMkhGRGdQV09wOGVNYUMxT2k3NjZKelhaQmRCZGJkTXVyZG9uSjFk',
'base64'
);
installNodeDNSWorkaroundHooks();
describe('Data key and double encryption', function () {
// Data key and double encryption
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// First, perform the setup.
beforeEach(function () {
// 1. Create a MongoClient without encryption enabled (referred to as ``client``). Enable command monitoring to listen for command_started events.
this.client = this.configuration.newClient({}, { monitorCommands: true });
this.commandStartedEvents = new APMEventCollector(this.client, 'commandStarted', {
exclude: [LEGACY_HELLO_COMMAND]
});
const schemaMap = {
[dataNamespace]: {
bsonType: 'object',
properties: {
encrypted_placeholder: {
encrypt: {
keyId: '/placeholder',
bsonType: 'string',
algorithm: 'AEAD_AES_256_CBC_HMAC_SHA_512-Random'
}
}
}
}
};
return (
Promise.resolve()
.then(() => this.client.connect())
// 2. Using ``client``, drop the collections ``keyvault.datakeys`` and ``db.coll``.
.then(() => dropCollection(this.client.db(dataDbName), dataCollName))
.then(() => dropCollection(this.client.db(keyVaultDbName), keyVaultCollName))
// 3. Create the following:
// - A MongoClient configured with auto encryption (referred to as ``client_encrypted``)
// - A ``ClientEncryption`` object (referred to as ``client_encryption``)
// Configure both objects with ``aws`` and the ``local`` KMS providers as follows:
// .. code:: javascript
// {
// "aws": { <AWS credentials> },
// "local": { "key": <base64 decoding of LOCAL_MASTERKEY> }
// }
// Configure both objects with ``keyVaultNamespace`` set to ``keyvault.datakeys``.
// Configure the ``MongoClient`` with the following ``schema_map``:
// .. code:: javascript
// {
// "db.coll": {
// "bsonType": "object",
// "properties": {
// "encrypted_placeholder": {
// "encrypt": {
// "keyId": "/placeholder",
// "bsonType": "string",
// "algorithm": "AEAD_AES_256_CBC_HMAC_SHA_512-Random"
// }
// }
// }
// }
// }
// Configure ``client_encryption`` with the ``keyVaultClient`` of the previously created ``client``.
.then(() => {
this.clientEncryption = new ClientEncryption(this.client, {
kmsProviders: getKmsProviders(),
keyVaultNamespace,
extraOptions: getEncryptExtraOptions()
});
})
.then(() => {
this.clientEncrypted = this.configuration.newClient(
{},
{
autoEncryption: {
keyVaultNamespace,
kmsProviders: getKmsProviders(),
extraOptions: getEncryptExtraOptions(),
schemaMap
}
}
);
return this.clientEncrypted.connect();
})
);
});
afterEach(function () {
if (this.commandStartedEvents) {
this.commandStartedEvents.teardown();
this.commandStartedEvents = undefined;
}
return Promise.resolve()
.then(() => this.clientEncrypted && this.clientEncrypted.close())
.then(() => this.client && this.client.close());
});
it('should work for local KMS provider', metadata, function () {
let localDatakeyId;
let localEncrypted;
return Promise.resolve()
.then(() => {
// #. Call ``client_encryption.createDataKey()`` with the ``local`` KMS provider and keyAltNames set to ``["local_altname"]``.
// - Expect a BSON binary with subtype 4 to be returned, referred to as ``local_datakey_id``.
// - Use ``client`` to run a ``find`` on ``keyvault.datakeys`` by querying with the ``_id`` set to the ``local_datakey_id``.
// - Expect that exactly one document is returned with the "masterKey.provider" equal to "local".
// - Check that ``client`` captured a command_started event for the ``insert`` command containing a majority writeConcern.
this.commandStartedEvents.clear();
return this.clientEncryption
.createDataKey('local', { keyAltNames: ['local_altname'] })
.then(result => {
localDatakeyId = result;
expect(localDatakeyId).to.have.property('sub_type', 4);
})
.then(() => {
return this.client
.db(keyVaultDbName)
.collection(keyVaultCollName)
.find({ _id: localDatakeyId })
.toArray();
})
.then(results => {
expect(results)
.to.have.a.lengthOf(1)
.and.to.have.nested.property('0.masterKey.provider', 'local');
expect(this.commandStartedEvents.events).to.containSubset([
{ commandName: 'insert', command: { writeConcern: { w: 'majority' } } }
]);
});
})
.then(() => {
// #. Call ``client_encryption.encrypt()`` with the value "hello local", the algorithm ``AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic``, and the ``key_id`` of ``local_datakey_id``.
// - Expect the return value to be a BSON binary subtype 6, referred to as ``local_encrypted``.
// - Use ``client_encrypted`` to insert ``{ _id: "local", "value": <local_encrypted> }`` into ``db.coll``.
// - Use ``client_encrypted`` to run a find querying with ``_id`` of "local" and expect ``value`` to be "hello local".
const coll = this.clientEncrypted.db(dataDbName).collection(dataCollName);
return this.clientEncryption
.encrypt('hello local', {
algorithm: 'AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic',
keyId: localDatakeyId
})
.then(value => {
localEncrypted = value;
expect(localEncrypted).to.have.property('sub_type', 6);
})
.then(() => coll.insertOne({ _id: 'local', value: localEncrypted }))
.then(() => coll.findOne({ _id: 'local' }))
.then(result => {
expect(result).to.have.property('value', 'hello local');
});
})
.then(() => {
// #. Call ``client_encryption.encrypt()`` with the value "hello local", the algorithm ``AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic``, and the ``key_alt_name`` of ``local_altname``.
// - Expect the return value to be a BSON binary subtype 6. Expect the value to exactly match the value of ``local_encrypted``.
return this.clientEncryption
.encrypt('hello local', {
algorithm: 'AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic',
keyId: localDatakeyId
})
.then(encrypted => {
expect(encrypted).to.deep.equal(localEncrypted);
});
});
});
it('should work for aws KMS provider', metadata, function () {
// Then, repeat the above tests with the ``aws`` KMS provider:
let awsDatakeyId;
let awsEncrypted;
return Promise.resolve()
.then(() => {
// #. Call ``client_encryption.createDataKey()`` with the ``aws`` KMS provider, keyAltNames set to ``["aws_altname"]``, and ``masterKey`` as follows:
// .. code:: javascript
// {
// region: "us-east-1",
// key: "arn:aws:kms:us-east-1:579766882180:key/89fcc2c4-08b0-4bd9-9f25-e30687b580d0"
// }
// - Expect a BSON binary with subtype 4 to be returned, referred to as ``aws_datakey_id``.
// - Use ``client`` to run a ``find`` on ``keyvault.datakeys`` by querying with the ``_id`` set to the ``aws_datakey_id``.
// - Expect that exactly one document is returned with the "masterKey.provider" equal to "aws".
// - Check that ``client`` captured a command_started event for the ``insert`` command containing a majority writeConcern.
this.commandStartedEvents.clear();
const masterKey = {
region: 'us-east-1',
key: 'arn:aws:kms:us-east-1:579766882180:key/89fcc2c4-08b0-4bd9-9f25-e30687b580d0'
};
return this.clientEncryption
.createDataKey('aws', { masterKey, keyAltNames: ['aws_altname'] })
.then(result => {
awsDatakeyId = result;
expect(awsDatakeyId).to.have.property('sub_type', 4);
})
.then(() => {
return this.client
.db(keyVaultDbName)
.collection(keyVaultCollName)
.find({ _id: awsDatakeyId })
.toArray();
})
.then(results => {
expect(results)
.to.have.a.lengthOf(1)
.and.to.have.nested.property('0.masterKey.provider', 'aws');
expect(this.commandStartedEvents.events).to.containSubset([
{ commandName: 'insert', command: { writeConcern: { w: 'majority' } } }
]);
});
})
.then(() => {
// #. Call ``client_encryption.encrypt()`` with the value "hello aws", the algorithm ``AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic``, and the ``key_id`` of ``aws_datakey_id``.
// - Expect the return value to be a BSON binary subtype 6, referred to as ``aws_encrypted``.
// - Use ``client_encrypted`` to insert ``{ _id: "aws", "value": <aws_encrypted> }`` into ``db.coll``.
// - Use ``client_encrypted`` to run a find querying with ``_id`` of "aws" and expect ``value`` to be "hello aws".
const coll = this.clientEncrypted.db(dataDbName).collection(dataCollName);
return this.clientEncryption
.encrypt('hello aws', {
algorithm: 'AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic',
keyId: awsDatakeyId
})
.then(value => {
awsEncrypted = value;
expect(awsEncrypted).to.have.property('sub_type', 6);
})
.then(() => coll.insertOne({ _id: 'aws', value: awsEncrypted }))
.then(() => coll.findOne({ _id: 'aws' }))
.then(result => {
expect(result).to.have.property('value', 'hello aws');
});
})
.then(() => {
// #. Call ``client_encryption.encrypt()`` with the value "hello aws", the algorithm ``AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic``, and the ``key_alt_name`` of ``aws_altname``.
// - Expect the return value to be a BSON binary subtype 6. Expect the value to exactly match the value of ``aws_encrypted``.
return this.clientEncryption
.encrypt('hello aws', {
algorithm: 'AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic',
keyId: awsDatakeyId
})
.then(encrypted => {
expect(encrypted).to.deep.equal(awsEncrypted);
});
});
});
it('should error on an attempt to double-encrypt a value', metadata, function () {
// Then, run the following final tests:
// #. Test explicit encrypting an auto encrypted field.
// - Use ``client_encrypted`` to attempt to insert ``{ "encrypted_placeholder": (local_encrypted) }``
// - Expect an exception to be thrown, since this is an attempt to auto encrypt an already encrypted value.
return Promise.resolve()
.then(() => this.clientEncryption.createDataKey('local'))
.then(keyId =>
this.clientEncryption.encrypt('hello double', {
keyId,
algorithm: 'AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic'
})
)
.then(encrypted =>
this.clientEncrypted
.db(dataDbName)
.collection(dataCollName)
.insertOne({ encrypted_placeholder: encrypted })
.then(
() => {
throw new Error('Expected double-encryption to fail, but it has succeeded');
},
err => {
expect(err).to.be.an.instanceOf(Error);
}
)
);
});
});
// TODO(NODE-4000): We cannot implement these tests according to spec b/c the tests require a
// connect-less client. So instead we are implementing the tests via APM,
// and confirming that the externalClient is firing off keyVault requests during
// encrypted operations
describe('External Key Vault Test', function () {
function loadExternal(file) {
return EJSON.parse(
fs.readFileSync(path.resolve(__dirname, '../../spec/client-side-encryption/external', file))
);
}
const externalKey = loadExternal('external-key.json');
const externalSchema = loadExternal('external-schema.json');
beforeEach(function () {
this.client = this.configuration.newClient();
// 1. Create a MongoClient without encryption enabled (referred to as ``client``).
return (
this.client
.connect()
// 2. Using ``client``, drop the collections ``keyvault.datakeys`` and ``db.coll``.
// Insert the document `external/external-key.json <../external/external-key.json>`_ into ``keyvault.datakeys``.
.then(() => dropCollection(this.client.db(dataDbName), dataCollName))
.then(() => dropCollection(this.client.db(keyVaultDbName), keyVaultCollName))
.then(() => {
return this.client
.db(keyVaultDbName)
.collection(keyVaultCollName)
.insertOne(externalKey, { writeConcern: { w: 'majority' } });
})
);
});
afterEach(function () {
if (this.commandStartedEvents) {
this.commandStartedEvents.teardown();
this.commandStartedEvents = undefined;
}
return Promise.resolve()
.then(() => this.externalClient && this.externalClient.close())
.then(() => this.clientEncrypted && this.clientEncrypted.close())
.then(() => this.client && this.client.close());
});
function defineTest(withExternalKeyVault) {
it(
`should work ${withExternalKeyVault ? 'with' : 'without'} external key vault`,
metadata,
function () {
return (
Promise.resolve()
.then(() => {
// If ``withExternalKeyVault == true``, configure both objects with an external key vault client. The external client MUST connect to the same
// MongoDB cluster that is being tested against, except it MUST use the username ``fake-user`` and password ``fake-pwd``.
this.externalClient = this.configuration.newClient(
// this.configuration.url('fake-user', 'fake-pwd'),
// TODO: Do this properly
{},
{ monitorCommands: true }
);
this.commandStartedEvents = new APMEventCollector(
this.externalClient,
'commandStarted',
{
include: ['find']
}
);
return this.externalClient.connect();
})
// 3. Create the following:
// - A MongoClient configured with auto encryption (referred to as ``client_encrypted``)
// - A ``ClientEncryption`` object (referred to as ``client_encryption``)
// Configure both objects with the ``local`` KMS providers as follows:
// .. code:: javascript
// { "local": { "key": <base64 decoding of LOCAL_MASTERKEY> } }
// Configure both objects with ``keyVaultNamespace`` set to ``keyvault.datakeys``.
// Configure ``client_encrypted`` to use the schema `external/external-schema.json <../external/external-schema.json>`_ for ``db.coll`` by setting a schema map like: ``{ "db.coll": <contents of external-schema.json>}``
.then(() => {
const options = {
bson: BSON,
keyVaultNamespace,
kmsProviders: getKmsProviders(LOCAL_KEY),
extraOptions: getEncryptExtraOptions()
};
if (withExternalKeyVault) {
options.keyVaultClient = this.externalClient;
}
this.clientEncryption = new ClientEncryption(
this.client,
Object.assign({}, options)
);
this.clientEncrypted = this.configuration.newClient(
{},
{
autoEncryption: Object.assign({}, options, {
schemaMap: {
'db.coll': externalSchema
}
})
}
);
return this.clientEncrypted.connect();
})
.then(() => {
// 4. Use ``client_encrypted`` to insert the document ``{"encrypted": "test"}`` into ``db.coll``.
// If ``withExternalKeyVault == true``, expect an authentication exception to be thrown. Otherwise, expect the insert to succeed.
this.commandStartedEvents.clear();
return this.clientEncrypted
.db(dataDbName)
.collection(dataCollName)
.insertOne({ encrypted: 'test' })
.then(() => {
if (withExternalKeyVault) {
expect(this.commandStartedEvents.events).to.containSubset([
{
commandName: 'find',
databaseName: keyVaultDbName,
command: { find: keyVaultCollName }
}
]);
} else {
expect(this.commandStartedEvents.events).to.not.containSubset([
{
commandName: 'find',
databaseName: keyVaultDbName,
command: { find: keyVaultCollName }
}
]);
}
});
// TODO: Do this in the spec-compliant way using bad auth credentials
// .then(
// () => {
// if (withExternalKeyVault) {
// throw new Error(
// 'expected insert to fail with authentication error, but it passed'
// );
// }
// },
// err => {
// if (!withExternalKeyVault) {
// throw err;
// }
// expect(err).to.be.an.instanceOf(Error);
// }
// );
})
.then(() => {
// 5. Use ``client_encryption`` to explicitly encrypt the string ``"test"`` with key ID ``LOCALAAAAAAAAAAAAAAAAA==`` and deterministic algorithm.
// If ``withExternalKeyVault == true``, expect an authentication exception to be thrown. Otherwise, expect the insert to succeed.
this.commandStartedEvents.clear();
return this.clientEncryption
.encrypt('test', {
keyId: externalKey._id,
algorithm: 'AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic'
})
.then(() => {
if (withExternalKeyVault) {
expect(this.commandStartedEvents.events).to.containSubset([
{
commandName: 'find',
databaseName: keyVaultDbName,
command: { find: keyVaultCollName }
}
]);
} else {
expect(this.commandStartedEvents.events).to.not.containSubset([
{
commandName: 'find',
databaseName: keyVaultDbName,
command: { find: keyVaultCollName }
}
]);
}
});
// TODO: Do this in the spec-compliant way using bad auth credentials
// .then(
// () => {
// if (withExternalKeyVault) {
// throw new Error(
// 'expected insert to fail with authentication error, but it passed'
// );
// }
// },
// err => {
// if (!withExternalKeyVault) {
// throw err;
// }
// expect(err).to.be.an.instanceOf(Error);
// }
// );
})
);
}
);
}
// Run the following tests twice, parameterized by a boolean ``withExternalKeyVault``.
defineTest(true);
defineTest(false);
});
describe('BSON size limits and batch splitting', function () {
function loadLimits(file) {
return EJSON.parse(
fs.readFileSync(path.resolve(__dirname, '../../spec/client-side-encryption/limits', file))
);
}
const limitsSchema = loadLimits('limits-schema.json');
const limitsKey = loadLimits('limits-key.json');
const limitsDoc = loadLimits('limits-doc.json');
let hasRunFirstTimeSetup = false;
beforeEach(async function () {
if (hasRunFirstTimeSetup) {
// Even though we have to use a beforeEach here
// We still only want the following code to be run *once*
// before all the tests that follow
return;
}
hasRunFirstTimeSetup = true;
// First, perform the setup.
// 1. Create a MongoClient without encryption enabled (referred to as ``client``).
this.client = this.configuration.newClient();
await this.client
.connect()
// 2. Using ``client``, drop and create the collection ``db.coll`` configured with the included JSON schema `limits/limits-schema.json <../limits/limits-schema.json>`_.
.then(() => dropCollection(this.client.db(dataDbName), dataCollName))
.then(() => {
return this.client.db(dataDbName).createCollection(dataCollName, {
validator: { $jsonSchema: limitsSchema }
});
})
// 3. Using ``client``, drop the collection ``keyvault.datakeys``. Insert the document `limits/limits-key.json <../limits/limits-key.json>`_
.then(() => dropCollection(this.client.db(keyVaultDbName), keyVaultCollName))
.then(() => {
return this.client
.db(keyVaultDbName)
.collection(keyVaultCollName)
.insertOne(limitsKey, { writeConcern: { w: 'majority' } });
});
});
beforeEach(function () {
// 4. Create a MongoClient configured with auto encryption (referred to as ``client_encrypted``)
// Configure with the ``local`` KMS provider as follows:
// .. code:: javascript
// { "local": { "key": <base64 decoding of LOCAL_MASTERKEY> } }
// Configure with the ``keyVaultNamespace`` set to ``keyvault.datakeys``.
this.clientEncrypted = this.configuration.newClient(
{},
{
monitorCommands: true,
autoEncryption: {
keyVaultNamespace,
kmsProviders: getKmsProviders(LOCAL_KEY),
extraOptions: getEncryptExtraOptions()
}
}
);
return this.clientEncrypted.connect().then(() => {
this.encryptedColl = this.clientEncrypted.db(dataDbName).collection(dataCollName);
this.commandStartedEvents = new APMEventCollector(this.clientEncrypted, 'commandStarted', {
include: ['insert']
});
});
});
afterEach(function () {
if (this.commandStartedEvents) {
this.commandStartedEvents.teardown();
this.commandStartedEvents = undefined;
}
if (this.clientEncrypted) {
return this.clientEncrypted.close();
}
});
afterEach(function () {
return this.client && this.client.close();
});
// Using ``client_encrypted`` perform the following operations:
function repeatedChar(char, length) {
return Array.from({ length })
.map(() => char)
.join('');
}
const testCases = [
// 1. Insert ``{ "_id": "over_2mib_under_16mib", "unencrypted": <the string "a" repeated 2097152 times> }``.
// Expect this to succeed since this is still under the ``maxBsonObjectSize`` limit.
{
description: 'should succeed for over_2mib_under_16mib',
docs: () => [{ _id: 'over_2mib_under_16mib', unencrypted: repeatedChar('a', 2097152) }],
expectedEvents: [{ commandName: 'insert' }]
},
// 2. Insert the document `limits/limits-doc.json <../limits/limits-doc.json>`_ concatenated with ``{ "_id": "encryption_exceeds_2mib", "unencrypted": < the string "a" repeated (2097152 - 2000) times > }``
// Note: limits-doc.json is a 1005 byte BSON document that encrypts to a ~10,000 byte document.
// Expect this to succeed since after encryption this still is below the normal maximum BSON document size.
// Note, before auto encryption this document is under the 2 MiB limit. After encryption it exceeds the 2 MiB limit, but does NOT exceed the 16 MiB limit.
{
description: 'should succeed for encryption_exceeds_2mib',
docs: () => [
Object.assign({}, limitsDoc, {
_id: 'encryption_exceeds_2mib',
unencrypted: repeatedChar('a', 2097152 - 2000)
})
],
expectedEvents: [{ commandName: 'insert' }]
},
// 3. Bulk insert the following:
// - ``{ "_id": "over_2mib_1", "unencrypted": <the string "a" repeated (2097152) times> }``
// - ``{ "_id": "over_2mib_2", "unencrypted": <the string "a" repeated (2097152) times> }``
// Expect the bulk write to succeed and split after first doc (i.e. two inserts occur). This may be verified using `command monitoring <https://github.com/mongodb/specifications/tree/master/source/command-monitoring/command-monitoring.rst>`_.
{
description: 'should succeed for bulk over_2mib',
docs: () => [
{ _id: 'over_2mib_1', unencrypted: repeatedChar('a', 2097152) },
{ _id: 'over_2mib_2', unencrypted: repeatedChar('a', 2097152) }
],
expectedEvents: [{ commandName: 'insert' }, { commandName: 'insert' }]
},
// 4. Bulk insert the following:
// - The document `limits/limits-doc.json <../limits/limits-doc.json>`_ concatenated with ``{ "_id": "encryption_exceeds_2mib_1", "unencrypted": < the string "a" repeated (2097152 - 2000) times > }``
// - The document `limits/limits-doc.json <../limits/limits-doc.json>`_ concatenated with ``{ "_id": "encryption_exceeds_2mib_2", "unencrypted": < the string "a" repeated (2097152 - 2000) times > }``
// Expect the bulk write to succeed and split after first doc (i.e. two inserts occur). This may be verified using `command monitoring <https://github.com/mongodb/specifications/tree/master/source/command-monitoring/command-monitoring.rst>`_.
{
description: 'should succeed for bulk encryption_exceeds_2mib',
docs: () => [
Object.assign({}, limitsDoc, {
_id: 'encryption_exceeds_2mib_1',
unencrypted: repeatedChar('a', 2097152 - 2000)
}),
Object.assign({}, limitsDoc, {
_id: 'encryption_exceeds_2mib_2',
unencrypted: repeatedChar('a', 2097152 - 2000)
})
],
expectedEvents: [{ commandName: 'insert' }, { commandName: 'insert' }]
},
// 5. Insert ``{ "_id": "under_16mib", "unencrypted": <the string "a" repeated 16777216 - 2000 times>``.
// Expect this to succeed since this is still (just) under the ``maxBsonObjectSize`` limit.
{
description: 'should succeed for under_16mib',
docs: () => [{ _id: 'under_16mib', unencrypted: repeatedChar('a', 16777216 - 2000) }],
expectedEvents: [{ commandName: 'insert' }]
},
// 6. Insert the document `limits/limits-doc.json <../limits/limits-doc.json>`_ concatenated with ``{ "_id": "encryption_exceeds_16mib", "unencrypted": < the string "a" repeated (16777216 - 2000) times > }``
// Expect this to fail since encryption results in a document exceeding the ``maxBsonObjectSize`` limit.
{
description: 'should fail for encryption_exceeds_16mib',
docs: () => [
Object.assign({}, limitsDoc, {
_id: 'encryption_exceeds_16mib',
unencrypted: repeatedChar('a', 16777216 - 2000)
})
],
error: true
}
];
testCases.forEach(testCase => {
it(testCase.description, metadata, function () {
return this.encryptedColl.insertMany(testCase.docs()).then(
() => {
if (testCase.error) {
throw new Error('Expected this insert to fail, but it succeeded');
}
const expectedEvents = Array.from(testCase.expectedEvents);
const actualEvents = pruneEvents(this.commandStartedEvents.events);
expect(actualEvents)
.to.have.a.lengthOf(expectedEvents.length)
.and.to.containSubset(expectedEvents);
},
err => {
if (!testCase.error) {
throw err;
}
}
);
});
});
function pruneEvents(events) {
return events.map(event => {
// We are pruning out the bunch of repeating As, mostly
// b/c an error failure will try to print 2mb of 'a's
// and not have a good time.
event.command = Object.assign({}, event.command);
event.command.documents = event.command.documents.map(doc => {
doc = Object.assign({}, doc);
if (doc.unencrypted) {
doc.unencrypted = "Lots of repeating 'a's";
}
return doc;
});
return event;
});
}
});
describe('Views are prohibited', function () {
beforeEach(function () {
// First, perform the setup.
// 1. Create a MongoClient without encryption enabled (referred to as ``client``).
this.client = this.configuration.newClient();
// 2. Using client, drop and create a view named db.view with an empty pipeline.
// E.g. using the command { "create": "view", "viewOn": "coll" }.
return this.client
.connect()
.then(() => dropCollection(this.client.db(dataDbName), dataCollName))
.then(() => {
return this.client.db(dataDbName).createCollection(dataCollName);
})
.then(() => {
return this.client
.db(dataDbName)
.createCollection('view', { viewOn: dataCollName, pipeline: [] })
.then(noop, noop);
}, noop);
});
afterEach(function () {
return this.client && this.client.close();
});
beforeEach(function () {
// 3. Create a MongoClient configured with auto encryption (referred to as client_encrypted)
// Configure with the local KMS provider
this.clientEncrypted = this.configuration.newClient(
{},
{
autoEncryption: {
keyVaultNamespace,
kmsProviders: getKmsProviders(LOCAL_KEY),
extraOptions: getEncryptExtraOptions()
}
}
);
return this.clientEncrypted.connect();
});
afterEach(function () {
return this.clientEncrypted && this.clientEncrypted.close();
});
// 4. Using client_encrypted, attempt to insert a document into db.view.
// Expect an exception to be thrown containing the message: "cannot auto encrypt a view".
it('should error when inserting into a view with autoEncryption', metadata, function () {
return this.clientEncrypted
.db(dataDbName)
.collection('view')
.insertOne({ a: 1 })
.then(
() => {
throw new Error('Expected insert to fail, but it succeeded');
},
err => {
expect(err)
.to.have.property('message')
.that.matches(/cannot auto encrypt a view/);
}
);
});
});
describe('Corpus Test', function () {
it('runs in a separate suite', () => {
expect(() =>
fs.statSync(path.resolve(__dirname, './client_side_encryption.prose.06.corpus.test.ts'))
).not.to.throw();
});
});
describe('Custom Endpoint Test', function () {
// Data keys created with AWS KMS may specify a custom endpoint to contact (instead of the default endpoint derived from the AWS region).
beforeEach(function () {
// 1. Create a ``ClientEncryption`` object (referred to as ``client_encryption``)
// Configure with ``aws`` KMS providers as follows:
// .. code:: javascript
// {
// "aws": { <AWS credentials> }
// }
// Configure with ``keyVaultNamespace`` set to ``keyvault.datakeys``, and a default MongoClient as the ``keyVaultClient``.
this.client = this.configuration.newClient();
const customKmsProviders = getKmsProviders();
customKmsProviders.azure.identityPlatformEndpoint = 'login.microsoftonline.com:443';
customKmsProviders.gcp.endpoint = 'oauth2.googleapis.com:443';
const invalidKmsProviders = getKmsProviders();
invalidKmsProviders.azure.identityPlatformEndpoint = 'doesnotexist.invalid:443';
invalidKmsProviders.gcp.endpoint = 'doesnotexist.invalid:443';
invalidKmsProviders.kmip.endpoint = 'doesnotexist.local:5698';
return this.client.connect().then(() => {
this.clientEncryption = new ClientEncryption(this.client, {
bson: BSON,
keyVaultNamespace,
kmsProviders: customKmsProviders,
tlsOptions: {
kmip: {
tlsCAFile: process.env.KMIP_TLS_CA_FILE,
tlsCertificateKeyFile: process.env.KMIP_TLS_CERT_FILE
}
},
extraOptions: getEncryptExtraOptions()
});
this.clientEncryptionInvalid = new ClientEncryption(this.client, {
keyVaultNamespace,
kmsProviders: invalidKmsProviders,
tlsOptions: {
kmip: {
tlsCAFile: process.env.KMIP_TLS_CA_FILE,
tlsCertificateKeyFile: process.env.KMIP_TLS_CERT_FILE
}
},
extraOptions: getEncryptExtraOptions()
});
});
});
afterEach(function () {
return this.client && this.client.close();
});
const testCases = [
{
description: '1. aws: no custom endpoint',
provider: 'aws',
masterKey: {
region: 'us-east-1',
key: 'arn:aws:kms:us-east-1:579766882180:key/89fcc2c4-08b0-4bd9-9f25-e30687b580d0'
},
succeed: true
},
{
description: '2. aws: custom endpoint',
provider: 'aws',
masterKey: {
region: 'us-east-1',
key: 'arn:aws:kms:us-east-1:579766882180:key/89fcc2c4-08b0-4bd9-9f25-e30687b580d0',
endpoint: 'kms.us-east-1.amazonaws.com'
},
succeed: true
},
{
description: '3. aws: custom endpoint with port',
provider: 'aws',
masterKey: {
region: 'us-east-1',
key: 'arn:aws:kms:us-east-1:579766882180:key/89fcc2c4-08b0-4bd9-9f25-e30687b580d0',
endpoint: 'kms.us-east-1.amazonaws.com:443'
},
succeed: true
},
{
description: '4. aws: custom endpoint with bad url',
provider: 'aws',
masterKey: {
region: 'us-east-1',
key: 'arn:aws:kms:us-east-1:579766882180:key/89fcc2c4-08b0-4bd9-9f25-e30687b580d0',
endpoint: 'kms.us-east-1.amazonaws.com:12345'
},
succeed: false,
errorValidator: err => {
expect(err)
.to.be.an.instanceOf(Error)
.and.to.have.property('message')
.that.matches(/KMS request failed/);
}
},
{
description: '5. aws: custom endpoint that does not match region',
provider: 'aws',
masterKey: {
region: 'us-east-1',
key: 'arn:aws:kms:us-east-1:579766882180:key/89fcc2c4-08b0-4bd9-9f25-e30687b580d0',
endpoint: 'kms.us-east-2.amazonaws.com'
},
succeed: false,
errorValidator: err => {
expect(err).to.be.an.instanceOf(Error);
}
},
{
description: '6. aws: custom endpoint with parse error',
provider: 'aws',
masterKey: {
region: 'us-east-1',
key: 'arn:aws:kms:us-east-1:579766882180:key/89fcc2c4-08b0-4bd9-9f25-e30687b580d0',
endpoint: 'doesnotexist.invalid'
},
succeed: false,
errorValidator: err => {
// Expect this to fail with a network exception indicating failure to resolve "doesnotexist.invalid".
expect(err)
.to.be.an.instanceOf(Error)
.and.to.have.property('message')
.that.matches(/KMS request failed/);
}
},
{
description: '7. azure: custom endpoint',
provider: 'azure',
masterKey: {
keyVaultEndpoint: 'key-vault-csfle.vault.azure.net',
keyName: 'key-name-csfle'
},
succeed: true,
checkAgainstInvalid: true
},
{
description: '8. gcp: custom endpoint',
provider: 'gcp',
masterKey: {
projectId: 'devprod-drivers',
location: 'global',
keyRing: 'key-ring-csfle',
keyName: 'key-name-csfle',
endpoint: 'cloudkms.googleapis.com:443'
},
succeed: true,
checkAgainstInvalid: true
},
{
description: '9. gcp: invalid custom endpoint',
provider: 'gcp',
masterKey: {
projectId: 'devprod-drivers',
location: 'global',
keyRing: 'key-ring-csfle',
keyName: 'key-name-csfle',
endpoint: 'doesnotexist.invalid:443'
},