mongoid 9.0.12 → 9.0.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. checksums.yaml +4 -4
  2. data/lib/config/locales/en.yml +44 -11
  3. data/lib/mongoid/association/embedded/batchable.rb +8 -0
  4. data/lib/mongoid/association/referenced/belongs_to.rb +16 -8
  5. data/lib/mongoid/association/referenced/has_and_belongs_to_many.rb +12 -0
  6. data/lib/mongoid/association/referenced/has_many/proxy.rb +4 -2
  7. data/lib/mongoid/attributes/readonly.rb +19 -1
  8. data/lib/mongoid/changeable.rb +21 -1
  9. data/lib/mongoid/clients/factory.rb +2 -0
  10. data/lib/mongoid/config/encryption.rb +152 -19
  11. data/lib/mongoid/contextual/none.rb +51 -0
  12. data/lib/mongoid/criteria/scopable.rb +7 -1
  13. data/lib/mongoid/criteria.rb +45 -1
  14. data/lib/mongoid/document.rb +10 -0
  15. data/lib/mongoid/encryptable.rb +43 -16
  16. data/lib/mongoid/errors/invalid_encrypted_association.rb +28 -0
  17. data/lib/mongoid/errors/invalid_encryption_schema.rb +27 -0
  18. data/lib/mongoid/errors/no_encryption_schema.rb +5 -3
  19. data/lib/mongoid/errors.rb +2 -0
  20. data/lib/mongoid/fields/encrypted.rb +14 -3
  21. data/lib/mongoid/fields/foreign_key.rb +9 -0
  22. data/lib/mongoid/fields/standard.rb +10 -0
  23. data/lib/mongoid/fields/validators/macro.rb +29 -0
  24. data/lib/mongoid/fields.rb +42 -2
  25. data/lib/mongoid/persistence_context.rb +46 -4
  26. data/lib/mongoid/reloadable.rb +1 -0
  27. data/lib/mongoid/search_indexable.rb +5 -1
  28. data/lib/mongoid/tasks/database.rb +10 -7
  29. data/lib/mongoid/threaded.rb +1 -1
  30. data/lib/mongoid/version.rb +1 -1
  31. data/lib/mongoid/warnings.rb +4 -0
  32. data/spec/integration/atomic/modifiers_spec.rb +57 -0
  33. data/spec/integration/encryption_spec.rb +418 -0
  34. data/spec/mongoid/association/referenced/encrypted_foreign_key_spec.rb +144 -0
  35. data/spec/mongoid/association/referenced/has_and_belongs_to_many/proxy_spec.rb +48 -0
  36. data/spec/mongoid/association/referenced/has_many/proxy_spec.rb +83 -0
  37. data/spec/mongoid/attributes/readonly_dotted_spec.rb +332 -0
  38. data/spec/mongoid/attributes/readonly_spec.rb +389 -0
  39. data/spec/mongoid/changeable_spec.rb +18 -0
  40. data/spec/mongoid/clients/factory_spec.rb +36 -0
  41. data/spec/mongoid/config/encryption_spec.rb +450 -0
  42. data/spec/mongoid/contextual/none_spec.rb +22 -5
  43. data/spec/mongoid/criteria_spec.rb +17 -0
  44. data/spec/mongoid/encryptable_spec.rb +54 -0
  45. data/spec/mongoid/fields_spec.rb +29 -0
  46. data/spec/mongoid/findable_spec.rb +14 -0
  47. data/spec/mongoid/matcher/regexp_budget_spec.rb +6 -0
  48. data/spec/mongoid/scopable_spec.rb +103 -2
  49. data/spec/mongoid/search_indexable_spec.rb +34 -1
  50. data/spec/mongoid/tasks/database_spec.rb +13 -0
  51. data/spec/spec_helper.rb +8 -0
  52. data/spec/support/crypt/models.rb +138 -0
  53. data/spec/support/models/delete_all_account.rb +10 -0
  54. data/spec/support/models/delete_all_item.rb +9 -0
  55. data/spec/support/models/delete_all_scoped_item.rb +11 -0
  56. data/spec/support/models/delete_all_tag.rb +7 -0
  57. data/spec/support/models/modifier_models.rb +32 -0
  58. metadata +1995 -1958
@@ -35,23 +35,33 @@ describe 'Encryption' do
35
35
  Mongoid.default_client[Crypt::Patient.collection_name].drop
36
36
  Mongoid.default_client[Crypt::Car.collection_name].drop
37
37
  Mongoid.default_client[Crypt::Folder.collection_name].drop
38
+ Mongoid.default_client[Crypt::Dossier.collection_name].drop
39
+ Mongoid.default_client[Crypt::Archive.collection_name].drop
38
40
  existing_key_id = Crypt::Patient.encrypt_metadata[:key_id]
39
41
  Crypt::Patient.set_key_id(data_key_id)
40
42
  Crypt::Car.set_key_id(data_key_id)
41
43
  Crypt::Note.set_key_id(data_key_id)
44
+ Crypt::Dossier.set_key_id(data_key_id)
45
+ Crypt::Archive.set_key_id(data_key_id)
42
46
  Mongoid::Config.send(:clients=, config)
43
47
  Mongoid::Clients.with_name(:key_vault)[key_vault_collection].drop
44
48
  Crypt::Patient.store_in(client: :encrypted)
45
49
  Crypt::Car.store_in(client: :encrypted, database: Crypt::Car.storage_options[:database])
46
50
  Crypt::Folder.store_in(client: :encrypted)
51
+ Crypt::Dossier.store_in(client: :encrypted)
52
+ Crypt::Archive.store_in(client: :encrypted)
47
53
 
48
54
  example.run
49
55
 
50
56
  Crypt::Patient.reset_storage_options!
51
57
  Crypt::Folder.reset_storage_options!
58
+ Crypt::Dossier.reset_storage_options!
59
+ Crypt::Archive.reset_storage_options!
52
60
  Crypt::Patient.set_key_id(existing_key_id)
53
61
  Crypt::Car.set_key_id(existing_key_id)
54
62
  Crypt::Note.set_key_id(existing_key_id)
63
+ Crypt::Dossier.set_key_id(existing_key_id)
64
+ Crypt::Archive.set_key_id(existing_key_id)
55
65
  end
56
66
 
57
67
  it 'encrypts and decrypts fields' do
@@ -102,6 +112,27 @@ describe 'Encryption' do
102
112
  end
103
113
  end
104
114
 
115
+ # The document is persisted under the store_as key, not the association
116
+ # name, so the schema has to be keyed by it or the field is stored in the
117
+ # clear.
118
+ it 'stores an embedded field encrypted when the association uses store_as' do
119
+ dossier = Crypt::Dossier.create!(secret: Crypt::DossierSecret.new(token: 'SECRET'))
120
+ unencrypted_client[Crypt::Dossier.collection.name].find(_id: dossier.id).first.tap do |doc|
121
+ expect(doc['s']['token']).to be_a(BSON::Binary)
122
+ expect(doc['s']['token'].type).to eq(:ciphertext)
123
+ end
124
+ expect(Crypt::Dossier.find(dossier.id).secret.token).to eq('SECRET')
125
+ end
126
+
127
+ it 'stores a nested embedded field encrypted when the associations use store_as' do
128
+ archive = Crypt::Archive.create!(entry: Crypt::ArchiveEntry.new(payload: Crypt::ArchivePayload.new(token: 'SECRET')))
129
+ unencrypted_client[Crypt::Archive.collection.name].find(_id: archive.id).first.tap do |doc|
130
+ expect(doc['e']['p']['token']).to be_a(BSON::Binary)
131
+ expect(doc['e']['p']['token'].type).to eq(:ciphertext)
132
+ end
133
+ expect(Crypt::Archive.find(archive.id).entry.payload.token).to eq('SECRET')
134
+ end
135
+
105
136
  it 'stores data encrypted in the non-default database' do
106
137
  car = Crypt::Car.create!(vin: 'VA1234')
107
138
  unencrypted_client
@@ -246,4 +277,391 @@ describe 'Encryption' do
246
277
  end
247
278
  end
248
279
  end
280
+
281
+ # The schema map has one entry per namespace, and it has to cover every model
282
+ # that writes there: models sharing a collection, subclasses, and subclasses
283
+ # of embedded models. Documents are read back through a client without
284
+ # automatic encryption, to see what is actually stored.
285
+ describe 'when more than one model writes to a namespace' do
286
+ let(:root_models) do
287
+ [ Crypt::Badge, Crypt::BadgeScan, Crypt::Member, Crypt::Listing, Crypt::Box, Crypt::Locker ]
288
+ end
289
+
290
+ let(:keyed_models) do
291
+ [ Crypt::Badge, Crypt::BadgeScan, Crypt::Member, Crypt::PrivateListing, Crypt::Box, Crypt::SecretContent ]
292
+ end
293
+
294
+ around do |example|
295
+ original_options = root_models.to_h { |model| [ model, model.storage_options ] }
296
+ existing_key_ids = keyed_models.to_h { |model| [ model, model.encrypt_metadata[:key_id] ] }
297
+ keyed_models.each { |model| model.set_key_id(data_key_id) }
298
+ root_models.each do |model|
299
+ unencrypted_client[model.collection_name.to_s].drop
300
+ model.store_in(client: :encrypted)
301
+ end
302
+ # The schema map is generated when the client is built, so the client has
303
+ # to be built after the key ids above are in place.
304
+ Mongoid::Clients.clear
305
+
306
+ example.run
307
+
308
+ original_options.each { |model, options| model.storage_options = options }
309
+ existing_key_ids.each { |model, key_id| model.set_key_id(key_id) }
310
+ Mongoid::Clients.clear
311
+ end
312
+
313
+ def stored_document(model, id)
314
+ unencrypted_client[model.collection_name.to_s].find(_id: id).first
315
+ end
316
+
317
+ def expect_ciphertext(value)
318
+ expect(value).to be_a(BSON::Binary).and(have_attributes(type: :ciphertext))
319
+ end
320
+
321
+ context 'when two models are stored in one collection' do
322
+ it 'stores the fields of both models encrypted', :aggregate_failures do
323
+ badge = Crypt::Badge.create!(serial: 'SERIAL-1')
324
+ scan = Crypt::BadgeScan.create!(holder: 'HOLDER-1')
325
+
326
+ expect_ciphertext(stored_document(Crypt::Badge, badge.id)['serial'])
327
+ expect_ciphertext(stored_document(Crypt::BadgeScan, scan.id)['holder'])
328
+ end
329
+ end
330
+
331
+ context 'when a subclass adds an encrypted field to an encrypted parent' do
332
+ it 'stores the fields of the parent and of the subclass encrypted', :aggregate_failures do
333
+ employee = Crypt::Employee.create!(ssn: 'SSN-1', salary: 'SALARY-1')
334
+
335
+ stored_document(Crypt::Member, employee.id).tap do |doc|
336
+ expect_ciphertext(doc['ssn'])
337
+ expect_ciphertext(doc['salary'])
338
+ end
339
+ end
340
+
341
+ it 'stores the fields of a sibling subclass encrypted' do
342
+ contractor = Crypt::Contractor.create!(ssn: 'SSN-2', rate: 'RATE-1')
343
+
344
+ expect_ciphertext(stored_document(Crypt::Member, contractor.id)['rate'])
345
+ end
346
+
347
+ it 'reads the fields back' do
348
+ employee = Crypt::Employee.create!(ssn: 'SSN-3', salary: 'SALARY-3')
349
+
350
+ expect(Crypt::Member.find(employee.id).salary).to eq('SALARY-3')
351
+ end
352
+ end
353
+
354
+ context 'when only a subclass has encrypted fields' do
355
+ it 'stores the fields of the subclass encrypted' do
356
+ listing = Crypt::PrivateListing.create!(title: 'TITLE-1', owner_ssn: 'SSN-4')
357
+
358
+ expect_ciphertext(stored_document(Crypt::Listing, listing.id)['owner_ssn'])
359
+ end
360
+ end
361
+
362
+ context 'when a subclass of an embeds_one target adds an encrypted field' do
363
+ it 'stores the fields of the target and of the subclass encrypted', :aggregate_failures do
364
+ box = Crypt::Box.create!(item: Crypt::SealedItem.new(label: 'LABEL-1', seal: 'SEAL-1'))
365
+
366
+ stored_document(Crypt::Box, box.id)['item'].tap do |item|
367
+ expect_ciphertext(item['label'])
368
+ expect_ciphertext(item['seal'])
369
+ end
370
+ end
371
+ end
372
+
373
+ context 'when only a subclass of an embeds_one target has encrypted fields' do
374
+ it 'stores the fields of the subclass encrypted' do
375
+ locker = Crypt::Locker.create!(content: Crypt::SecretContent.new(label: 'LABEL-2', code: 'CODE-1'))
376
+
377
+ expect_ciphertext(stored_document(Crypt::Locker, locker.id)['content']['code'])
378
+ end
379
+ end
380
+
381
+ # An entry for the namespace exists, but it does not cover every encrypted
382
+ # field of the model. The driver encrypts what the entry lists and writes
383
+ # the rest in plaintext.
384
+ context 'when the schema entry for the namespace misses an encrypted field' do
385
+ let(:config) do
386
+ super().merge(
387
+ partial: {
388
+ hosts: SpecConfig.instance.addresses,
389
+ database: database_id,
390
+ options: {
391
+ auto_encryption_options: {
392
+ key_vault_client: :key_vault,
393
+ kms_providers: kms_providers,
394
+ key_vault_namespace: key_vault_namespace,
395
+ extra_options: extra_options,
396
+ schema_map: partial_schema_map
397
+ }
398
+ }
399
+ }
400
+ )
401
+ end
402
+
403
+ let(:partial_schema_map) do
404
+ {
405
+ "#{database_id}.#{Crypt::Member.collection_name}" => {
406
+ 'bsonType' => 'object',
407
+ 'encryptMetadata' => {
408
+ 'keyId' => [ BSON::Binary.new(Base64.decode64(data_key_id), :uuid) ],
409
+ 'algorithm' => 'AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic'
410
+ },
411
+ 'properties' => {
412
+ 'ssn' => { 'encrypt' => { 'bsonType' => 'string' } }
413
+ }
414
+ }
415
+ }
416
+ end
417
+
418
+ it 'does not store the field in plaintext', :aggregate_failures do
419
+ expect do
420
+ Crypt::Employee.with(client: :partial) { |klass| klass.create!(ssn: 'SSN-5', salary: 'PARTIAL-1') }
421
+ end.to raise_error(Mongoid::Errors::NoEncryptionSchema)
422
+
423
+ expect(
424
+ unencrypted_client[Crypt::Member.collection_name.to_s].find(salary: 'PARTIAL-1').to_a
425
+ ).to be_empty
426
+ end
427
+ end
428
+ end
429
+
430
+ describe 'an encrypted belongs_to foreign key' do
431
+ let(:foreign_key_models) { [] }
432
+
433
+ let(:owner_class) do
434
+ klass = stub_const('Crypt::ForeignKeyOwner', Class.new)
435
+ klass.include(Mongoid::Document)
436
+ foreign_key_models << klass
437
+ klass
438
+ end
439
+
440
+ let(:reference_class) do
441
+ owner_class
442
+ klass = stub_const('Crypt::ForeignKeyReference', Class.new)
443
+ klass.include(Mongoid::Document)
444
+ foreign_key_models << klass
445
+ klass.encrypt_with(key_id: data_key_id) if deterministic
446
+ klass.store_in(client: :encrypted)
447
+ association_options = { class_name: 'Crypt::ForeignKeyOwner', inverse_of: nil }
448
+ association_options[:foreign_key] = foreign_key if foreign_key != :owner_id
449
+ encryption_options = { deterministic: deterministic }
450
+ encryption_options[:key_id] = data_key_id unless deterministic
451
+
452
+ klass.field(foreign_key, type: BSON::ObjectId, encrypt: encryption_options)
453
+ klass.belongs_to(:owner, association_options)
454
+
455
+ # The schema map is built when the client is constructed.
456
+ Mongoid::Clients.clear
457
+ klass
458
+ end
459
+
460
+ after do
461
+ foreign_key_models.each { |model| Mongoid.deregister_model(model) }
462
+ Mongoid::Clients.clear
463
+ end
464
+
465
+ foreign_keys = %i[owner_id secret_owner_id]
466
+ [ true, false ].each do |deterministic|
467
+ foreign_keys.each do |foreign_key|
468
+ key_type = (foreign_key == :owner_id) ? 'default' : 'custom'
469
+ context "with #{deterministic ? 'deterministic' : 'random'} encryption and the " \
470
+ "#{key_type} foreign key" do
471
+ let(:deterministic) { deterministic }
472
+ let(:foreign_key) { foreign_key }
473
+
474
+ it 'encrypts the key and preserves association behavior', :aggregate_failures do
475
+ owner = owner_class.create!
476
+ other_owner = owner_class.create!
477
+ reference = reference_class.create!(owner: owner)
478
+ same_owner = reference_class.create!(owner: owner)
479
+ collection = unencrypted_client[reference_class.collection_name.to_s]
480
+
481
+ stored = collection.find(_id: reference.id).first
482
+ expect(stored[foreign_key.to_s]).to be_a(BSON::Binary).and(have_attributes(type: :ciphertext))
483
+ other_ciphertext = collection.find(_id: same_owner.id).first[foreign_key.to_s]
484
+ if deterministic
485
+ expect(stored[foreign_key.to_s]).to eq(other_ciphertext)
486
+ else
487
+ expect(stored[foreign_key.to_s]).not_to eq(other_ciphertext)
488
+ end
489
+
490
+ reference.reload
491
+ expect(reference.public_send(foreign_key)).to eq(owner.id)
492
+ expect(reference.owner.id).to eq(owner.id)
493
+
494
+ # Assigning the foreign key must also invalidate the cached association.
495
+ reference.public_send("#{foreign_key}=", other_owner.id)
496
+ expect(reference.owner.id).to eq(other_owner.id)
497
+ reference.save!
498
+
499
+ stored = collection.find(_id: reference.id).first
500
+ expect(stored[foreign_key.to_s]).to be_a(BSON::Binary).and(have_attributes(type: :ciphertext))
501
+ expect(reference.reload.owner.id).to eq(other_owner.id)
502
+ end
503
+ end
504
+ end
505
+ end
506
+ end
507
+
508
+ # A belongs_to declared on a parent generates the foreign key on the whole
509
+ # hierarchy. An encrypted declaration of that key on a subclass must survive
510
+ # the propagation, or the subclass silently loses its encryption.
511
+ describe 'an encrypted belongs_to foreign key declared on a subclass' do
512
+ let(:models) { [] }
513
+
514
+ let(:owner_class) do
515
+ klass = stub_const('Crypt::InheritedForeignKeyOwner', Class.new)
516
+ klass.include(Mongoid::Document)
517
+ models << klass
518
+ klass
519
+ end
520
+
521
+ let(:parent_class) do
522
+ klass = stub_const('Crypt::InheritedForeignKeyParent', Class.new)
523
+ klass.include(Mongoid::Document)
524
+ models << klass
525
+ klass
526
+ end
527
+
528
+ let(:child_class) do
529
+ parent_class
530
+ klass = stub_const('Crypt::InheritedForeignKeyChild', Class.new(parent_class))
531
+ models << klass
532
+ klass.store_in(client: :encrypted)
533
+ klass.encrypt_with(key_id: data_key_id) if model_key
534
+ klass.field(foreign_key, type: BSON::ObjectId, encrypt: encryption_options)
535
+ klass.belongs_to(:owner, association_options) if child_association
536
+ klass
537
+ end
538
+
539
+ let(:association_options) do
540
+ { class_name: 'Crypt::InheritedForeignKeyOwner', inverse_of: nil }.tap do |options|
541
+ options[:foreign_key] = foreign_key if foreign_key != :owner_id
542
+ end
543
+ end
544
+
545
+ let(:encryption_options) do
546
+ { deterministic: deterministic }.tap do |options|
547
+ options[:key_id] = data_key_id unless model_key
548
+ end
549
+ end
550
+
551
+ let(:algorithm) do
552
+ if deterministic
553
+ 'AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic'
554
+ else
555
+ 'AEAD_AES_256_CBC_HMAC_SHA_512-Random'
556
+ end
557
+ end
558
+
559
+ before do
560
+ child_class
561
+ parent_class.belongs_to(:owner, association_options)
562
+ # The schema map is built when the client is constructed.
563
+ Mongoid::Clients.clear
564
+ end
565
+
566
+ after do
567
+ models.each { |model| Mongoid.deregister_model(model) }
568
+ Mongoid::Clients.clear
569
+ end
570
+
571
+ shared_examples 'an encrypted inherited foreign key' do
572
+ it 'keeps the encryption on the subclass and supports the association', :aggregate_failures do
573
+ field = child_class.fields[foreign_key.to_s]
574
+ expect(field).to be_a(Mongoid::Fields::EncryptedForeignKey)
575
+ expect(field).to be_foreign_key
576
+ expect(field.type).to eq(BSON::ObjectId)
577
+ expect(field.options[:encrypt]).to eq(encryption_options)
578
+ expect(field.deterministic?).to eq(deterministic)
579
+ if model_key
580
+ expect(field.key_id).to be_nil
581
+ else
582
+ expect(field.key_id).to eq(data_key_id)
583
+ end
584
+ expect(child_class.encrypted?).to be true
585
+ expect(parent_class.encrypted?).to be false
586
+
587
+ # The classes share a collection, and only the subclass contributes an
588
+ # entry to the schema map for it.
589
+ expect(child_class.collection_name).to eq(parent_class.collection_name)
590
+ schema = Mongoid.config.encryption_schema_map(
591
+ database_id, [ parent_class, child_class ]
592
+ ).fetch("#{database_id}.#{child_class.collection_name}")
593
+ encryption = schema.dig('properties', foreign_key.to_s, 'encrypt')
594
+ expect(encryption['bsonType']).to eq('objectId')
595
+ expect(encryption['algorithm']).to eq(algorithm)
596
+ if model_key
597
+ expect(encryption).not_to have_key('keyId')
598
+ expect(schema.dig('encryptMetadata', 'keyId')).to be_a(Array)
599
+ else
600
+ expect(encryption['keyId']).to be_a(Array)
601
+ end
602
+
603
+ owner = owner_class.create!
604
+ other_owner = owner_class.create!
605
+ child = child_class.create!(owner: owner)
606
+ same_owner = child_class.create!(owner: owner)
607
+ collection = unencrypted_client[child_class.collection_name.to_s]
608
+
609
+ stored = collection.find(_id: child.id).first
610
+ expect(stored[foreign_key.to_s]).to be_a(BSON::Binary).and(have_attributes(type: :ciphertext))
611
+ other_ciphertext = collection.find(_id: same_owner.id).first[foreign_key.to_s]
612
+ if deterministic
613
+ expect(stored[foreign_key.to_s]).to eq(other_ciphertext)
614
+ else
615
+ expect(stored[foreign_key.to_s]).not_to eq(other_ciphertext)
616
+ end
617
+
618
+ child.reload
619
+ expect(child.public_send(foreign_key)).to eq(owner.id)
620
+ expect(child.owner.id).to eq(owner.id)
621
+
622
+ child.public_send("#{foreign_key}=", other_owner.id)
623
+ expect(child.owner.id).to eq(other_owner.id)
624
+ end
625
+ end
626
+
627
+ context 'when only the subclass declares the field' do
628
+ let(:child_association) { false }
629
+
630
+ context 'with deterministic encryption and the default foreign key' do
631
+ let(:deterministic) { true }
632
+ let(:model_key) { false }
633
+ let(:foreign_key) { :owner_id }
634
+
635
+ it_behaves_like 'an encrypted inherited foreign key'
636
+ end
637
+
638
+ context 'with random encryption, a custom foreign key and a model-level key' do
639
+ let(:deterministic) { false }
640
+ let(:model_key) { true }
641
+ let(:foreign_key) { :secret_owner_id }
642
+
643
+ it_behaves_like 'an encrypted inherited foreign key'
644
+ end
645
+ end
646
+
647
+ context 'when the subclass also declares the association' do
648
+ let(:child_association) { true }
649
+
650
+ context 'with deterministic encryption, a custom foreign key and a model-level key' do
651
+ let(:deterministic) { true }
652
+ let(:model_key) { true }
653
+ let(:foreign_key) { :secret_owner_id }
654
+
655
+ it_behaves_like 'an encrypted inherited foreign key'
656
+ end
657
+
658
+ context 'with random encryption and the default foreign key' do
659
+ let(:deterministic) { false }
660
+ let(:model_key) { false }
661
+ let(:foreign_key) { :owner_id }
662
+
663
+ it_behaves_like 'an encrypted inherited foreign key'
664
+ end
665
+ end
666
+ end
249
667
  end
@@ -0,0 +1,144 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'spec_helper'
4
+
5
+ # rubocop:disable RSpec/MultipleMemoizedHelpers
6
+ describe 'Encrypted has_and_belongs_to_many foreign keys' do
7
+ let(:model) do
8
+ klass = stub_const('ForeignKeyHabtmMember', Class.new)
9
+ klass.include(Mongoid::Document)
10
+ klass
11
+ end
12
+
13
+ after do
14
+ Mongoid.deregister_model(model)
15
+ end
16
+
17
+ [ true, { deterministic: true }, { deterministic: false } ].each do |encryption|
18
+ context "with encrypt: #{encryption.inspect}" do
19
+ it 'rejects the association when its foreign key is already encrypted' do
20
+ model.field(:secret_group_ids, type: Array, encrypt: encryption)
21
+
22
+ expect do
23
+ model.has_and_belongs_to_many(:groups, foreign_key: :secret_group_ids, inverse_of: nil)
24
+ end.to raise_error(Mongoid::Errors::InvalidEncryptedAssociation, /encrypt/i)
25
+ end
26
+
27
+ it 'rejects encryption when the foreign key already belongs to an association' do
28
+ model.has_and_belongs_to_many(:groups, inverse_of: nil)
29
+
30
+ expect do
31
+ model.field(:group_ids, type: Array, encrypt: encryption)
32
+ end.to raise_error(Mongoid::Errors::InvalidEncryptedAssociation, /encrypt/i)
33
+ end
34
+ end
35
+ end
36
+
37
+ it 'allows an unencrypted foreign key' do
38
+ model.field(:group_ids, type: Array)
39
+
40
+ expect do
41
+ model.has_and_belongs_to_many(:groups, inverse_of: nil)
42
+ end.not_to raise_error
43
+ end
44
+
45
+ context 'when the encrypted field is declared on a parent model' do
46
+ let(:parent_model) do
47
+ klass = stub_const('ForeignKeyHabtmParent', Class.new)
48
+ klass.include(Mongoid::Document)
49
+ klass
50
+ end
51
+
52
+ let(:custom_foreign_key) { nil }
53
+
54
+ let(:foreign_key) { custom_foreign_key || :group_ids }
55
+
56
+ let(:association_options) do
57
+ { inverse_of: nil }.tap do |options|
58
+ options[:foreign_key] = custom_foreign_key if custom_foreign_key
59
+ end
60
+ end
61
+
62
+ let(:child_model) do
63
+ parent_model
64
+ klass = stub_const('ForeignKeyHabtmChild', Class.new(parent_model))
65
+ klass.has_and_belongs_to_many(:groups, association_options)
66
+ klass
67
+ end
68
+
69
+ after do
70
+ Mongoid.deregister_model(child_model)
71
+ Mongoid.deregister_model(parent_model)
72
+ end
73
+
74
+ encryption_options = [ { deterministic: true }, { deterministic: false } ]
75
+ custom_foreign_keys = [ nil, :secret_group_ids ]
76
+ encryption_options.each do |encryption|
77
+ custom_foreign_keys.each do |custom_key|
78
+ key_type = custom_key ? 'a custom' : 'the default'
79
+ context "with #{encryption.inspect} and #{key_type} foreign key" do
80
+ let(:custom_foreign_key) { custom_key }
81
+
82
+ it 'rejects the field before changing either model' do
83
+ association = child_model.relations['groups']
84
+ existing_field = child_model.fields[foreign_key.to_s]
85
+
86
+ expect do
87
+ parent_model.field(foreign_key, type: Array, encrypt: encryption)
88
+ end.to raise_error(Mongoid::Errors::InvalidEncryptedAssociation, /encrypt/i)
89
+
90
+ expect(parent_model.fields).not_to have_key(foreign_key.to_s)
91
+ expect(child_model.fields[foreign_key.to_s]).to equal(existing_field)
92
+ expect(child_model.fields[foreign_key.to_s]).not_to be_encrypted
93
+ expect(child_model.relations['groups']).to equal(association)
94
+ end
95
+ end
96
+ end
97
+ end
98
+
99
+ it 'allows an encrypted field that no descendant uses as an association key' do
100
+ child_model
101
+
102
+ expect do
103
+ parent_model.field(:secret, type: String, encrypt: { deterministic: true })
104
+ end.not_to raise_error
105
+
106
+ expect(parent_model.fields['secret']).to be_encrypted
107
+ expect(child_model.fields['secret']).to be_encrypted
108
+ end
109
+ end
110
+
111
+ context 'when the encrypted field is declared on a child model' do
112
+ let(:parent_model) do
113
+ klass = stub_const('ForeignKeyHabtmParentWithChildField', Class.new)
114
+ klass.include(Mongoid::Document)
115
+ klass
116
+ end
117
+
118
+ let(:child_model) do
119
+ parent_model
120
+ klass = stub_const('ForeignKeyHabtmChildWithField', Class.new(parent_model))
121
+ klass.field(:group_ids, type: Array, encrypt: { deterministic: false })
122
+ klass
123
+ end
124
+
125
+ after do
126
+ Mongoid.deregister_model(child_model)
127
+ Mongoid.deregister_model(parent_model)
128
+ end
129
+
130
+ it 'rejects the association before changing either model' do
131
+ existing_field = child_model.fields['group_ids']
132
+
133
+ expect do
134
+ parent_model.has_and_belongs_to_many(:groups, inverse_of: nil)
135
+ end.to raise_error(Mongoid::Errors::InvalidEncryptedAssociation, /encrypt/i)
136
+
137
+ expect(parent_model.fields).not_to have_key('group_ids')
138
+ expect(parent_model.relations).not_to have_key('groups')
139
+ expect(child_model.fields['group_ids']).to equal(existing_field)
140
+ expect(child_model.fields['group_ids']).to be_encrypted
141
+ end
142
+ end
143
+ end
144
+ # rubocop:enable RSpec/MultipleMemoizedHelpers
@@ -3794,4 +3794,52 @@ describe Mongoid::Association::Referenced::HasAndBelongsToMany::Proxy do
3794
3794
  expect(contract.signature_ids).to eq([signature.id])
3795
3795
  end
3796
3796
  end
3797
+
3798
+ # Conditions that share a key with the association selector must be
3799
+ # intersected with it, whatever kind of key the caller used.
3800
+ key_variants = {
3801
+ 'String' => :stringify_keys,
3802
+ 'Symbol' => :symbolize_keys,
3803
+ 'indifferent access' => :with_indifferent_access
3804
+ }.freeze
3805
+
3806
+ %i[ delete_all destroy_all ].each do |method|
3807
+ describe "##{method} with conditions on a key the association selector uses" do
3808
+ key_variants.each do |label, converter|
3809
+ context "when the keys are #{label}" do
3810
+ let(:draft) { DeleteAllTag.create!(state: 'draft') }
3811
+ let(:outside) { DeleteAllTag.create!(state: 'draft') }
3812
+ let(:account) { DeleteAllAccount.create!(tags: [ draft, DeleteAllTag.create!(state: 'open') ]) }
3813
+ let(:proxy) { DeleteAllAccount.find(account.id).tags }
3814
+
3815
+ before { outside }
3816
+
3817
+ context 'with a condition on the primary key' do
3818
+ let(:conditions) { { _id: outside.id }.send(converter) }
3819
+
3820
+ it 'deletes nothing outside the association' do
3821
+ expect(proxy.send(method, conditions)).to eq(0)
3822
+ expect(DeleteAllTag.count).to eq(3)
3823
+ end
3824
+
3825
+ it 'does not modify the conditions' do
3826
+ original = conditions.deep_dup
3827
+ proxy.send(method, conditions)
3828
+ expect(conditions).to eq(original)
3829
+ end
3830
+ end
3831
+
3832
+ context 'with a condition on the primary key inside the association' do
3833
+ let(:conditions) { { _id: draft.id }.send(converter) }
3834
+
3835
+ it 'deletes only the matching document' do
3836
+ expect(proxy.send(method, conditions)).to eq(1)
3837
+ expect(DeleteAllTag.pluck(:_id)).not_to include(draft.id)
3838
+ expect(DeleteAllTag.count).to eq(2)
3839
+ end
3840
+ end
3841
+ end
3842
+ end
3843
+ end
3844
+ end
3797
3845
  end