-
Notifications
You must be signed in to change notification settings - Fork 3
/
markFieldsAsPII.spec.js
898 lines (788 loc) · 26.9 KB
/
markFieldsAsPII.spec.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
const MongoDBMemoryServer = require('mongodb-memory-server').default
const mongoose = require('mongoose')
describe('markFieldsAsPII plugin', () => {
let connection
let server
beforeAll(async () => {
// DEV NOTE: do NOT resetModules() here, as it'll impact Mongoose’s
// internal driver initialization, leading to weird "Decimal128 of null"
// errors -- this one was tough to hunt down…
jest.dontMock('./util/ciphers')
server = new MongoDBMemoryServer()
const url = await server.getConnectionString()
connection = await mongoose.createConnection(url, {
autoReconnect: true,
connectTimeoutMS: 1000,
reconnectInterval: 100,
reconnectTries: Number.MAX_VALUE,
useNewUrlParser: true,
})
})
afterAll(() => {
connection.close()
server.stop()
})
describe('when checking its options', () => {
const { markFieldsAsPII } = require('./markFieldsAsPII')
it('should mandate either a `fields` or `passwordFields` option', () => {
expect(() => markFieldsAsPII({})).toThrowError(
/at least one of.*fields.*passwordFields/
)
})
it('should mandate a `key` setting when `fields` is provided', () => {
expect(() => markFieldsAsPII({}, { fields: ['email'] })).toThrowError(
/Missing required.*key/
)
})
})
describe('when dealing with PII fields', () => {
let User
let userCollection
beforeAll(() => {
const { markFieldsAsPII } = require('./markFieldsAsPII')
const schema = new mongoose.Schema({
email: String,
firstName: String,
historySize: Number,
lastName: String,
role: String,
})
const key = '126d8cf92d95941e9907b0d9913ce00e'
schema.plugin(markFieldsAsPII, {
fields: ['email', 'firstName', 'lastName'],
key,
})
User = connection.model('PIIUser', schema)
userCollection = new User().collection
})
it('should cipher DB fields on create', async () => {
const user = await User.create({
email: '[email protected]',
firstName: 'John',
historySize: 100,
lastName: 'Smith',
role: 'guest',
})
// Instance fields were deciphered back again
expect(user.email).toEqual('[email protected]')
expect(user.firstName).toEqual('John')
expect(user.lastName).toEqual('Smith')
// DB fields were ciphered
const doc = await rawDocFor(user)
expect(doc.email).toEqual(
'2ZXfUUBPTPaETqXIA33bRwQNnif1/u/axrI84yQShR9Q=='
)
expect(doc.firstName).toEqual(
'QbbQzV3asVB0+Ivxw1bonAIjsLZzhRCjyMoCeHeAE8Lg=='
)
expect(doc.historySize).toEqual(100)
expect(doc.lastName).toEqual(
'L0H0hF8b4HZSxYiKRbMntQsLUZRGr6OpauwAEWsAP4jA=='
)
expect(doc.role).toEqual('guest')
})
it('should cipher DB fields on save', async () => {
const user = new User({
email: '[email protected]',
firstName: 'John',
historySize: 100,
lastName: 'Smith',
role: 'guest',
})
await user.save()
// Instance fields were deciphered back again
expect(user.email).toEqual('[email protected]')
expect(user.firstName).toEqual('John')
expect(user.lastName).toEqual('Smith')
// DB fields were ciphered
const doc = await rawDocFor(user)
expect(doc.email).toEqual(
'2ZXfUUBPTPaETqXIA33bRwQNnif1/u/axrI84yQShR9Q=='
)
expect(doc.firstName).toEqual(
'QbbQzV3asVB0+Ivxw1bonAIjsLZzhRCjyMoCeHeAE8Lg=='
)
expect(doc.historySize).toEqual(100)
expect(doc.lastName).toEqual(
'L0H0hF8b4HZSxYiKRbMntQsLUZRGr6OpauwAEWsAP4jA=='
)
expect(doc.role).toEqual('guest')
})
it('should cipher DB fields on insertMany', async () => {
const data = [
{
email: [
'2ZXfUUBPTPaETqXIA33bRwQNnif1/u/axrI84yQShR9Q==',
],
firstName: ['John', 'QbbQzV3asVB0+Ivxw1bonAIjsLZzhRCjyMoCeHeAE8Lg=='],
lastName: ['Smith', 'L0H0hF8b4HZSxYiKRbMntQsLUZRGr6OpauwAEWsAP4jA=='],
},
{
email: [
'qdxEGhjGiXX8dQvjEFp4yASg5f8rgyBzDF0X9l7T1jbhG+Dbajz5EENQ0TEpaxOlc=',
],
firstName: ['Mark', 'Aj6ic0IkuWp3LV5P31i76Q1+eHIACe7wck3uM0vfBu1Q=='],
lastName: [
'Roberts',
'tmoDgrAWHw60SdZPl4pJLgfGmzIAYRuPiGCuK3JtgxTQ==',
],
},
]
for (const datum of data) {
datum.historySize = [100, 100]
datum.role = ['guest', 'guest']
}
// Insert data descriptors should not use [clearText, ciphered] pairs, but
// just clearText values, so let's derive a proper descriptor array from above.
const insertData = data.map((desc) =>
Object.entries(desc).reduce((obj, [field, [clearText]]) => {
obj[field] = clearText
return obj
}, {})
)
const users = await User.insertMany(insertData)
// And now let's check all the fields across both Mongoose Documents
// and stored raw MongoDB documents.
for (const [index, user] of users.entries()) {
const doc = await rawDocFor(user)
for (const [field, [clearText, ciphered]] of Object.entries(
data[index]
)) {
// It stinks to high Heaven that Jasmine/Jest matchers do not allow
// a custom failure message, like, say, Chai or RSpec would. Unbelievable.
// jest-expect-message is a solution, but putting the message *inside expect*
// instead of as a last arg in the matcher just looks fugly.
expect(user[field]).toEqual(clearText)
expect(doc[field]).toEqual(ciphered)
}
}
})
it('should uncipher fields on finds', async () => {
const { ops: docs } = await userCollection.insertMany([
{
email: '2ZXfUUBPTPaETqXIA33bRwQNnif1/u/axrI84yQShR9Q==',
firstName: 'QbbQzV3asVB0+Ivxw1bonAIjsLZzhRCjyMoCeHeAE8Lg==',
historySize: 100,
lastName: 'L0H0hF8b4HZSxYiKRbMntQsLUZRGr6OpauwAEWsAP4jA==',
role: 'guest',
},
{
email:
'qdxEGhjGiXX8dQvjEFp4yASg5f8rgyBzDF0X9l7T1jbhG+Dbajz5EENQ0TEpaxOlc=',
firstName: 'Aj6ic0IkuWp3LV5P31i76Q1+eHIACe7wck3uM0vfBu1Q==',
historySize: 100,
lastName: 'tmoDgrAWHw60SdZPl4pJLgfGmzIAYRuPiGCuK3JtgxTQ==',
role: 'guest',
},
])
const users = await User.find({ _id: docs.map(({ _id }) => _id) })
expect(users[0]).toMatchObject({
email: '[email protected]',
firstName: 'John',
historySize: 100,
lastName: 'Smith',
role: 'guest',
})
expect(users[1]).toMatchObject({
email: '[email protected]',
firstName: 'Mark',
historySize: 100,
lastName: 'Roberts',
role: 'guest',
})
})
it('should cipher queries for finds', async () => {
const {
ops: [doc],
} = await userCollection.insertOne({
email: '2ZXfUUBPTPaETqXIA33bRwQNnif1/u/axrI84yQShR9Q==',
firstName: 'QbbQzV3asVB0+Ivxw1bonAIjsLZzhRCjyMoCeHeAE8Lg==',
historySize: 100,
lastName: 'L0H0hF8b4HZSxYiKRbMntQsLUZRGr6OpauwAEWsAP4jA==',
role: 'guest',
})
// We serialize this to avoid deletion happening before another find
// completes (due to the parallel execution of `Promise.all`), which
// would cause random failures as we've routinely seen on Travis :-/
const results = [
...(await User.find({
_id: doc._id,
email: '[email protected]',
role: 'guest',
})),
await User.findOne({
_id: doc._id,
email: '[email protected]',
role: 'guest',
}),
await User.findOneAndDelete({
_id: doc._id,
email: '[email protected]',
role: 'guest',
}),
]
for (const user of results) {
expect(user).toMatchObject({
email: '[email protected]',
firstName: 'John',
historySize: 100,
lastName: 'Smith',
role: 'guest',
})
}
})
it('should cipher updates for findOneAndUpdate', async () => {
const {
ops: [doc],
} = await userCollection.insertOne({
email: '2ZXfUUBPTPaETqXIA33bRwQNnif1/u/axrI84yQShR9Q==',
firstName: 'QbbQzV3asVB0+Ivxw1bonAIjsLZzhRCjyMoCeHeAE8Lg==',
historySize: 100,
lastName: 'L0H0hF8b4HZSxYiKRbMntQsLUZRGr6OpauwAEWsAP4jA==',
role: 'guest',
})
const user = await User.findOneAndUpdate(
{ _id: doc._id },
{
email: '[email protected]',
role: 'admin',
},
{ new: true }
)
expect(user).toMatchObject({
email: '[email protected]',
firstName: 'John',
historySize: 100,
lastName: 'Smith',
role: 'admin',
})
const updatedDoc = await userCollection.findOne({ _id: doc._id })
expect(updatedDoc).toMatchObject({
email: 'YQ3zjPwlyq6xP8+Aq4uSrwEmOooRV/uaPioRQog9zoBQ==',
role: 'admin',
})
})
it('should cipher queries for counts', async () => {
const attrs = {
email: '2ZXfUUBPTPaETqXIA33bRwQNnif1/u/axrI84yQShR9Q==',
firstName: 'QbbQzV3asVB0+Ivxw1bonAIjsLZzhRCjyMoCeHeAE8Lg==',
historySize: 150,
lastName: 'L0H0hF8b4HZSxYiKRbMntQsLUZRGr6OpauwAEWsAP4jA==',
role: 'countable',
}
const descriptors = [1, 2, 3].map(() => ({ ...attrs }))
await userCollection.insertMany(descriptors)
expect(
await User.count({ email: '[email protected]', role: 'countable' })
).toEqual(descriptors.length)
expect(
await User.countDocuments({ firstName: 'John', role: 'countable' })
).toEqual(descriptors.length)
})
it('should cipher queries for updates and replaces', async () => {
const attrs = {
email: '2ZXfUUBPTPaETqXIA33bRwQNnif1/u/axrI84yQShR9Q==',
firstName: 'QbbQzV3asVB0+Ivxw1bonAIjsLZzhRCjyMoCeHeAE8Lg==',
historySize: 100,
lastName: 'L0H0hF8b4HZSxYiKRbMntQsLUZRGr6OpauwAEWsAP4jA==',
role: 'updatable',
}
const descriptors = [1, 2, 3, 4, 5].map(() => ({ ...attrs }))
const { ops: docs } = await userCollection.insertMany(descriptors)
const result = await Promise.all([
User.replaceOne(
{ _id: docs[0]._id, email: '[email protected]', role: 'updatable' },
{
...attrs,
role: 'updated',
}
),
User.update(
{ _id: docs[1]._id, email: '[email protected]', role: 'updatable' },
{
$set: { role: 'updated' },
}
),
User.updateOne(
{ _id: docs[2]._id, email: '[email protected]', role: 'updatable' },
{
$set: { role: 'updated' },
}
),
User.updateMany(
{
_id: docs.slice(3).map(({ _id }) => _id),
email: '[email protected]',
role: 'updatable',
},
{
$set: { role: 'updated' },
}
),
])
expect(result).toMatchObject([
{ n: 1, nModified: 1 },
{ n: 1, nModified: 1 },
{ n: 1, nModified: 1 },
{ n: 2, nModified: 2 },
])
})
it('should cipher updates on updates and replaces', async () => {
const attrs = {
email: '2ZXfUUBPTPaETqXIA33bRwQNnif1/u/axrI84yQShR9Q==',
firstName: 'QbbQzV3asVB0+Ivxw1bonAIjsLZzhRCjyMoCeHeAE8Lg==',
historySize: 100,
lastName: 'L0H0hF8b4HZSxYiKRbMntQsLUZRGr6OpauwAEWsAP4jA==',
role: 'updateCipherable',
}
const descriptors = [1, 2, 3, 4, 5].map(() => ({ ...attrs }))
const { ops: docs } = await userCollection.insertMany(descriptors)
await Promise.all([
User.replaceOne(
{ _id: docs[0]._id },
{ ...attrs, email: '[email protected]' }
),
User.update({ _id: docs[1]._id }, { $set: { firstName: 'Mark' } }),
User.updateOne({ _id: docs[2]._id }, { $set: { lastName: 'Roberts' } }),
User.updateMany(
{ _id: docs.slice(3).map(({ _id }) => _id) },
{ $set: { email: '[email protected]' } }
),
])
const updatedDocs = await userCollection
.find({ role: 'updateCipherable' })
.toArray()
expect(updatedDocs).toMatchObject([
{ email: 'YQ3zjPwlyq6xP8+Aq4uSrwEmOooRV/uaPioRQog9zoBQ==' },
{ firstName: 'Aj6ic0IkuWp3LV5P31i76Q1+eHIACe7wck3uM0vfBu1Q==' },
{ lastName: 'tmoDgrAWHw60SdZPl4pJLgfGmzIAYRuPiGCuK3JtgxTQ==' },
{ email: 'YQ3zjPwlyq6xP8+Aq4uSrwEmOooRV/uaPioRQog9zoBQ==' },
{ email: 'YQ3zjPwlyq6xP8+Aq4uSrwEmOooRV/uaPioRQog9zoBQ==' },
])
})
function rawDocFor(modelDoc) {
return modelDoc.collection.findOne({ _id: modelDoc._id })
}
})
describe('when dealing with password fields', () => {
let User
let userCollection
beforeAll(() => {
const { markFieldsAsPII } = require('./markFieldsAsPII')
const schema = new mongoose.Schema({
admin: { password: String, role: String },
a: { b: { secret: String } },
email: String,
password: String,
})
schema.plugin(markFieldsAsPII, {
passwordFields: ['password', 'admin.password', 'a.b.secret'],
})
User = connection.model('PassUser', schema)
userCollection = new User().collection
})
it('should hash on save', async () => {
const user = new User({
email: '[email protected]',
password: 'foobar',
admin: { role: 'manager', password: 'foobar42' },
})
await user.save()
const doc = await userCollection.findOne({ _id: user._id })
expect(user.email).toEqual('[email protected]')
expect(user.admin.role).toEqual('manager')
expect(user.password).toMatch(/^\$2a\$\d{2}\$.{53}$/)
expect(doc.password).toEqual(user.password)
expect(user.admin.password).toMatch(/^\$2a\$\d{2}\$.{53}$/)
expect(doc.admin.password).toEqual(user.admin.password)
})
it('should not double-hash', async () => {
const user = await User.create({ password: 'foobar' })
const pwd = user.password
await user.save()
expect(user.password).toEqual(pwd)
})
it('should hash on insertMany', async () => {
const users = await User.insertMany([
{ email: '[email protected]', password: 'kapoué' },
{ email: '[email protected]', password: 'yolo' },
])
const docs = await User.find({ email: users.map(({ email }) => email) })
for (const [index, user] of users.entries()) {
expect(user.password).toMatch(/^\$2a\$\d{2}\$.{53}$/)
expect(docs[index].password).toEqual(user.password)
}
})
it('should not use stable hashes', async () => {
const descriptors = Array(10)
.fill(true)
.map(() => ({ password: 'foobar' }))
const users = await User.insertMany(descriptors)
const uniqueHashes = new Set(users.map(({ password }) => password))
expect(uniqueHashes.size).toEqual(descriptors.length)
})
it('should provide a static authenticate method for models', () => {
expect(User).toHaveProperty('authenticate')
expect(User.authenticate).toBeInstanceOf(Function)
})
it('should require at least one defined password field', () => {
expect(User.authenticate({ email: '[email protected]' })).rejects.toThrowError(
/No password field.*found/
)
})
it('should authenticate honoring query fields', async () => {
const users = await User.insertMany([
{ email: '[email protected]', password: 'query' },
{ email: '[email protected]', password: 'query' },
])
expect(await User.authenticate({ password: 'query' })).toMatchObject(
users[0].toJSON()
)
expect(
await User.authenticate({ password: 'query' }, { single: false })
).toHaveLength(2)
expect(
await User.authenticate({
email: '[email protected]',
password: 'query',
})
).toMatchObject(users[0].toJSON())
expect(
await User.authenticate({
email: '[email protected]',
password: 'query',
})
).toBeNull()
})
it('should be able to authenticate across multiple password fields', async () => {
const users = await User.insertMany([
{ password: 'toplevel' },
{ password: 'toplevel', a: { b: { secret: 'yo' } } },
])
expect(
await User.authenticate({
password: 'toplevel',
a: { b: { secret: 'yo' } },
})
).toMatchObject(users[1].toJSON())
})
})
describe('when dealing with both PII and password fields', () => {
it('should be able to authenticate with queries that need ciphering', async () => {
const { markFieldsAsPII } = require('./markFieldsAsPII')
const schema = new mongoose.Schema({
email: String,
password: String,
kind: String,
})
schema.plugin(markFieldsAsPII, {
fields: 'email',
key: '126d8cf92d95941e9907b0d9913ce00e',
passwordFields: 'password',
})
const User = connection.model('HardUser', schema)
const user = await User.create({
email: '[email protected]',
kind: 'hard',
password: 'foobar',
})
const users = await User.authenticate({
kind: 'hard',
email: '[email protected]',
password: 'foobar',
})
expect(users).toMatchObject(user.toJSON())
})
})
})
describe('pluginWasUsedOn', () => {
let markFieldsAsPII
let pluginWasUsedOn
beforeAll(() => {
;({ markFieldsAsPII, pluginWasUsedOn } = require('./markFieldsAsPII'))
})
it('should return true on Schemas that use the plugin', () => {
const schema = new mongoose.Schema({ name: String, password: String })
schema.plugin(markFieldsAsPII, { passwordFields: 'password' })
expect(pluginWasUsedOn(schema)).toBeTruthy()
})
it('should return true on Models whose schemas use the plugin', () => {
const schema = new mongoose.Schema({ name: String, password: String })
schema.plugin(markFieldsAsPII, { passwordFields: 'password' })
const Model = mongoose.model('UsingPlugin', schema)
expect(pluginWasUsedOn(Model)).toBeTruthy()
})
it('should return false on Schemas that don’t use the plugin', () => {
const schema = new mongoose.Schema({ name: String })
expect(pluginWasUsedOn(schema)).toBeFalsy()
})
it('should return false on Models whose schemas don’t use the plugin', () => {
const schema = new mongoose.Schema({ name: String })
const Model = mongoose.model('NotUsingPlugin', schema)
expect(pluginWasUsedOn(Model)).toBeFalsy()
})
})
describe('Helper functions', () => {
describe('cipherValue', () => {
const { cipherValue } = require('./markFieldsAsPII').tests
const key = '126d8cf92d95941e9907b0d9913ce00e'
it('should handle Buffer values', () => {
const actual = cipherValue(key, Buffer.from('yowza', 'utf8'))
const expected = 'SaUyLkjzcKSwx9PY2c6A5geG7Ydb0nOAFiwQqJZweE+Q=='
expect(actual).toEqual(expected)
})
it('should handle String values', () => {
const actual = cipherValue(key, 'yowza')
const expected = 'SaUyLkjzcKSwx9PY2c6A5geG7Ydb0nOAFiwQqJZweE+Q=='
expect(actual).toEqual(expected)
})
it('should handle non-Buffer, non-String values', () => {
expect(cipherValue(key, 42)).toEqual(
'Ocp86ezGn2lr99ILsj3RUgDAN6Jv5s8/5L00TeTW6Zmg=='
)
expect(cipherValue(key, /foobar/)).toEqual(
'KS13lM9qZVEPZ9eVFTUisQXbLWlfJ394d0C+WgbYMe3w=='
)
})
it('should be stable across calls for the same value', () => {
const expected = 'SaUyLkjzcKSwx9PY2c6A5geG7Ydb0nOAFiwQqJZweE+Q=='
for (let index = 0; index < 10; ++index) {
const actual = cipherValue(key, 'yowza')
expect(actual).toEqual(expected)
}
})
})
describe('processObject', () => {
const key = '59aad44db330ad2bf34f6730e50c0058'
let processObject
beforeAll(() => {
jest.resetModules()
jest.doMock('./util/ciphers', () => ({
cipher(_, clearText) {
return `CIPHERED:${clearText}`
},
decipher(_, obscured) {
return `DECIPHERED:${obscured}`
},
}))
processObject = require('./markFieldsAsPII').tests.processObject
})
afterAll(() => {
jest.dontMock('./util/ciphers')
})
it('should refuse invalid modes', () => {
expect(() => processObject({}, { mode: 'yolo' })).toThrowError(
'Unknown processObject mode: yolo'
)
})
it('should only cipher specified fields', () => {
const obj = { firstName: 'John', lastName: 'Smith', age: 42 }
const expected = {
firstName: 'CIPHERED:John',
lastName: 'CIPHERED:Smith',
age: 42,
}
processObject(obj, {
fields: ['firstName', 'lastName'],
key,
mode: 'cipher',
})
expect(obj).toEqual(expected)
})
it('should dive into operator descriptors', () => {
const update = { $set: { age: 18, firstName: 'Mark' } }
const expected = {
$set: { age: 18, firstName: 'CIPHERED:Mark' },
}
processObject(update, {
fields: ['firstName', 'lastName'],
key,
mode: 'cipher',
})
expect(update).toEqual(expected)
})
it('should dive into object values', () => {
const obj = {
identity: { firstName: 'John', lastName: 'Smith' },
firstName: 'Mark',
}
const expected = {
identity: {
firstName: 'CIPHERED:John',
lastName: 'CIPHERED:Smith',
},
firstName: 'CIPHERED:Mark',
}
processObject(obj, {
fields: ['firstName', 'lastName'],
key,
mode: 'cipher',
})
expect(obj).toEqual(expected)
})
it('should dive into array values', () => {
const obj = {
aliases: ['Killer', 'Boss', 'Spy'],
firstName: 'John',
lastName: 'Smith',
}
const expected = {
aliases: ['CIPHERED:Killer', 'CIPHERED:Boss', 'CIPHERED:Spy'],
firstName: 'CIPHERED:John',
lastName: 'CIPHERED:Smith',
}
processObject(obj, {
fields: ['aliases', 'firstName', 'lastName'],
key,
mode: 'cipher',
})
expect(obj).toEqual(expected)
})
it('should handle nested field descriptors', () => {
const obj = {
identity: { firstName: 'John', lastName: 'Smith' },
age: 42,
firstName: 'Mark',
}
const expected = {
identity: {
firstName: 'CIPHERED:John',
lastName: 'CIPHERED:Smith',
},
age: 42,
firstName: 'Mark',
}
processObject(obj, {
fields: ['identity.firstName', 'identity.lastName'],
key,
mode: 'cipher',
})
expect(obj).toEqual(expected)
})
it('should work in decipher mode', () => {
const obj = {
identity: {
aliases: ['Killer', 'Boss', 'Spy'],
firstName: 'John',
lastName: 'Smith',
},
firstName: 'Mark',
}
const expected = {
identity: {
aliases: ['DECIPHERED:Killer', 'DECIPHERED:Boss', 'DECIPHERED:Spy'],
firstName: 'DECIPHERED:John',
lastName: 'DECIPHERED:Smith',
},
firstName: 'Mark',
}
processObject(obj, {
fields: ['aliases', 'identity.firstName', 'lastName'],
key,
mode: 'decipher',
})
expect(obj).toEqual(expected)
})
it('should work in document mode', () => {
const obj = {
identity: { aliases: ['Foo', 'Bar'] },
trap: { firstName: 'Mark', lastName: 'Roberts' },
firstName: 'John',
lastName: 'Smith',
}
const expected = {
identity: { aliases: ['CIPHERED:Foo', 'CIPHERED:Bar'] },
trap: { firstName: 'Mark', lastName: 'Roberts' },
firstName: 'CIPHERED:John',
lastName: 'CIPHERED:Smith',
}
processObject(obj, {
fields: ['identity.aliases', 'firstName', 'lastName'],
key,
isDocument: true,
mode: 'cipher',
})
expect(obj).toEqual(expected)
})
})
describe('splitAuthenticationFields', () => {
const { splitAuthenticationFields } = require('./markFieldsAsPII').tests
it('should split toplevel fields', () => {
const fields = { email: '[email protected]', password: 'foobar' }
const passwordFields = ['password']
expect(splitAuthenticationFields({ fields, passwordFields })).toEqual({
query: { email: '[email protected]' },
passwords: { password: 'foobar' },
})
})
it('should split nested fields', () => {
const fields = {
email: '[email protected]',
password: 'foobar',
admin: { role: 'manager', password: 'quuxdoo' },
}
const passwordFields = ['password', 'admin.password']
expect(splitAuthenticationFields({ fields, passwordFields })).toEqual({
query: { email: '[email protected]', admin: { role: 'manager' } },
passwords: { password: 'foobar', admin: { password: 'quuxdoo' } },
})
})
})
describe('updateObject', () => {
const { updateObject } = require('./markFieldsAsPII').tests
it('should work on existing containers', () => {
const obj = { foo: 'bar', xyz: 123 }
updateObject(obj, 'foo', 'baz')
expect(obj).toEqual({ foo: 'baz', xyz: 123 })
obj.nested = { abc: 'def', ghi: 'jkl' }
updateObject(obj, 'nested.ghi', 'JKL')
updateObject(obj, 'nested.mno', 'pqr')
expect(obj.nested).toEqual({ abc: 'def', ghi: 'JKL', mno: 'pqr' })
})
it('should create missing containers on-the-fly', () => {
const obj = { foo: 'bar', xyz: 123, nested: { abc: 'def' } }
updateObject(obj, 'nested.deeper.wow', 'much win')
updateObject(obj, 'parallel.yowza', 'such code')
expect(obj).toEqual({
foo: 'bar',
xyz: 123,
nested: { abc: 'def', deeper: { wow: 'much win' } },
parallel: { yowza: 'such code' },
})
})
})
describe('walkDocumentPasswordFields', () => {
const { walkDocumentPasswordFields } = require('./markFieldsAsPII').tests
it('should produce pairs of cleartext/hash, including nested fields', () => {
const doc = {
password: 'hashedPassword',
admin: { password: 'hashedAdminPassword' },
foo: 'bar',
}
const passwords = {
password: 'password',
admin: { password: 'adminPassword' },
}
expect(walkDocumentPasswordFields(doc, passwords)).toEqual([
['password', 'hashedPassword'],
['adminPassword', 'hashedAdminPassword'],
])
})
it('should default missing hashed values to an empty string', () => {
const doc = {
password: 'hashedPassword',
foo: 'bar',
}
const passwords = {
password: 'password',
admin: { password: 'adminPassword' },
}
expect(walkDocumentPasswordFields(doc, passwords)).toEqual([
['password', 'hashedPassword'],
['adminPassword', ''],
])
})
})
})