mongoid 9.1.2 → 9.1.3

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 (53) hide show
  1. checksums.yaml +4 -4
  2. data/lib/config/locales/en.yml +13 -0
  3. data/lib/mongoid/association/accessors.rb +4 -1
  4. data/lib/mongoid/association/referenced/belongs_to/buildable.rb +19 -15
  5. data/lib/mongoid/association/referenced/belongs_to.rb +11 -3
  6. data/lib/mongoid/association/referenced/has_and_belongs_to_many/buildable.rb +21 -7
  7. data/lib/mongoid/association/referenced/has_and_belongs_to_many.rb +12 -0
  8. data/lib/mongoid/association/referenced/has_many/buildable.rb +17 -7
  9. data/lib/mongoid/association/referenced/has_many/proxy.rb +4 -2
  10. data/lib/mongoid/association/referenced/has_one/buildable.rb +20 -6
  11. data/lib/mongoid/association.rb +15 -0
  12. data/lib/mongoid/attributes/readonly.rb +19 -1
  13. data/lib/mongoid/changeable.rb +19 -1
  14. data/lib/mongoid/config/encryption.rb +5 -3
  15. data/lib/mongoid/contextual/none.rb +51 -0
  16. data/lib/mongoid/criteria/scopable.rb +5 -0
  17. data/lib/mongoid/criteria.rb +45 -1
  18. data/lib/mongoid/document.rb +10 -0
  19. data/lib/mongoid/encryptable.rb +1 -1
  20. data/lib/mongoid/errors/invalid_encrypted_association.rb +28 -0
  21. data/lib/mongoid/errors.rb +1 -0
  22. data/lib/mongoid/factory.rb +1 -1
  23. data/lib/mongoid/fields/encrypted.rb +14 -3
  24. data/lib/mongoid/fields/foreign_key.rb +9 -0
  25. data/lib/mongoid/fields/standard.rb +10 -0
  26. data/lib/mongoid/fields/validators/macro.rb +29 -0
  27. data/lib/mongoid/fields.rb +42 -2
  28. data/lib/mongoid/reloadable.rb +1 -0
  29. data/lib/mongoid/version.rb +1 -1
  30. data/spec/integration/encryption_spec.rb +269 -0
  31. data/spec/mongoid/association/referenced/belongs_to/buildable_spec.rb +35 -6
  32. data/spec/mongoid/association/referenced/encrypted_foreign_key_spec.rb +142 -0
  33. data/spec/mongoid/association/referenced/has_and_belongs_to_many/buildable_spec.rb +25 -5
  34. data/spec/mongoid/association/referenced/has_and_belongs_to_many/proxy_spec.rb +48 -0
  35. data/spec/mongoid/association/referenced/has_many/buildable_spec.rb +24 -6
  36. data/spec/mongoid/association/referenced/has_many/proxy_spec.rb +81 -0
  37. data/spec/mongoid/association/referenced/has_one/buildable_spec.rb +18 -3
  38. data/spec/mongoid/attributes/readonly_dotted_spec.rb +334 -0
  39. data/spec/mongoid/attributes/readonly_spec.rb +389 -0
  40. data/spec/mongoid/changeable_spec.rb +18 -0
  41. data/spec/mongoid/config/encryption_spec.rb +227 -0
  42. data/spec/mongoid/contextual/none_spec.rb +18 -0
  43. data/spec/mongoid/criteria_spec.rb +17 -0
  44. data/spec/mongoid/factory_spec.rb +8 -0
  45. data/spec/mongoid/fields_spec.rb +29 -0
  46. data/spec/mongoid/findable_spec.rb +14 -0
  47. data/spec/mongoid/scopable_spec.rb +102 -0
  48. data/spec/support/crypt/models.rb +42 -0
  49. data/spec/support/models/delete_all_account.rb +10 -0
  50. data/spec/support/models/delete_all_item.rb +9 -0
  51. data/spec/support/models/delete_all_scoped_item.rb +11 -0
  52. data/spec/support/models/delete_all_tag.rb +7 -0
  53. metadata +2045 -2011
@@ -2,8 +2,8 @@
2
2
 
3
3
  module Mongoid
4
4
  module Fields
5
- # Represents a field that should be encrypted.
6
- class Encrypted < Standard
5
+ # Behavior shared by the field types whose value is encrypted.
6
+ module EncryptionOptions
7
7
  def initialize(name, options = {})
8
8
  @encryption_options = if options[:encrypt].is_a?(Hash)
9
9
  options[:encrypt]
@@ -13,6 +13,11 @@ module Mongoid
13
13
  super
14
14
  end
15
15
 
16
+ # @return [ true ] Always true: this field is encrypted.
17
+ def encrypted?
18
+ true
19
+ end
20
+
16
21
  # @return [ true | false | nil ] Whether the field should be encrypted using a
17
22
  # deterministic encryption algorithm; if not specified, nil is returned.
18
23
  def deterministic?
@@ -26,7 +31,8 @@ module Mongoid
26
31
  end
27
32
 
28
33
  # @return [ String | nil ] The name of the field that contains the
29
- # key alt name to use for encryption; if not specified, nil is returned.
34
+ # key alt name to use for encryption; if not specified, nil is
35
+ # returned.
30
36
  def key_name_field
31
37
  @encryption_options[:key_name_field]
32
38
  end
@@ -43,5 +49,10 @@ module Mongoid
43
49
  @encryption_options[:key_id] = key_id
44
50
  end
45
51
  end
52
+
53
+ # Represents a field that should be encrypted.
54
+ class Encrypted < Standard
55
+ include EncryptionOptions
56
+ end
46
57
  end
47
58
  end
@@ -187,5 +187,14 @@ module Mongoid
187
187
  object
188
188
  end
189
189
  end
190
+
191
+ # Represents a foreign key field whose value is encrypted.
192
+ #
193
+ # A belongs_to association stores its key in a single value, so it can be
194
+ # encrypted like any other field. The encryption options of the field
195
+ # declared before the association are preserved here.
196
+ class EncryptedForeignKey < ForeignKey
197
+ include EncryptionOptions
198
+ end
190
199
  end
191
200
  end
@@ -56,6 +56,16 @@ module Mongoid
56
56
  false
57
57
  end
58
58
 
59
+ # Is this field encrypted?
60
+ #
61
+ # @example Is the field encrypted?
62
+ # field.encrypted?
63
+ #
64
+ # @return [ true | false ] If the field is encrypted.
65
+ def encrypted?
66
+ false
67
+ end
68
+
59
69
  # Create the new field with a name and optional additional options.
60
70
  #
61
71
  # @example Create the new field.
@@ -34,6 +34,7 @@ module Mongoid
34
34
  validate_field_name(klass, name)
35
35
  validate_name_uniqueness(klass, name, options)
36
36
  validate_options(klass, name, options)
37
+ validate_encrypted_association(klass, name, options)
37
38
  end
38
39
 
39
40
  # Validate the association definition.
@@ -109,6 +110,34 @@ module Mongoid
109
110
  Mongoid::Warnings.warn_symbol_type_deprecated if option == :type && options[option] == Symbol
110
111
  end
111
112
  end
113
+
114
+ # Determine if an encrypted field is the foreign key of a
115
+ # has_and_belongs_to_many association. Defining the field after the
116
+ # association has to be rejected, and so does defining it on a parent
117
+ # of the class that declares the association: the field is propagated
118
+ # to the descendants and would replace their association key.
119
+ #
120
+ # @api private
121
+ #
122
+ # @param [ Class ] klass The model class.
123
+ # @param [ Symbol | String ] name The field name.
124
+ # @param [ Hash ] options The provided options.
125
+ #
126
+ # @raise [ Errors::InvalidEncryptedAssociation ] If the field is the
127
+ # foreign key of a has_and_belongs_to_many association.
128
+ def validate_encrypted_association(klass, name, options)
129
+ return unless options[:encrypt]
130
+
131
+ ([ klass ] + klass.descendants).each do |candidate|
132
+ field = candidate.fields[name.to_s]
133
+ next unless field&.foreign_key?
134
+
135
+ association = field.association
136
+ next unless association.is_a?(Association::Referenced::HasAndBelongsToMany)
137
+
138
+ raise Errors::InvalidEncryptedAssociation.new(candidate, association.name, name)
139
+ end
140
+ end
112
141
  end
113
142
  end
114
143
  end
@@ -586,7 +586,7 @@ module Mongoid
586
586
  Validators::Macro.validate(self, name, options)
587
587
  added = add_field(named, options)
588
588
  descendants.each do |subclass|
589
- subclass.add_field(named, options)
589
+ subclass.add_field(named, descendant_field_options(subclass, named, options))
590
590
  end
591
591
  added
592
592
  end
@@ -681,6 +681,41 @@ module Mongoid
681
681
  field
682
682
  end
683
683
 
684
+ # Build the options to apply to a descendant when a belongs_to
685
+ # association declared on an ancestor generates its foreign key. A
686
+ # descendant may declare the field as encrypted before the association
687
+ # is declared on the parent. The encryption options and the declared
688
+ # type belong to the descendant and must survive the propagation, as
689
+ # must the foreign key behavior.
690
+ #
691
+ # When the descendant's encryption options differ from the ancestor's,
692
+ # the difference is preserved: the schema generation reports it instead
693
+ # of one declaration silently overriding the other.
694
+ #
695
+ # A field declared without an association is not covered: the ancestor's
696
+ # declaration keeps replacing the descendant's field as before.
697
+ #
698
+ # @api private
699
+ #
700
+ # @param [ Class ] subclass The descendant the field is propagated to.
701
+ # @param [ String ] name The field name.
702
+ # @param [ Hash ] options The options of the ancestor's declaration.
703
+ #
704
+ # @return [ Hash ] The options to apply to the descendant.
705
+ def descendant_field_options(subclass, name, options)
706
+ return options unless options[:identity]
707
+ return options unless options[:association].is_a?(Association::Referenced::BelongsTo)
708
+
709
+ existing = subclass.fields[name]
710
+ return options unless existing&.encrypted?
711
+
712
+ preserved = options.merge(type: existing.type, encrypt: existing.options[:encrypt])
713
+ if existing.foreign_key? && existing.association
714
+ preserved[:association] = existing.association
715
+ end
716
+ preserved
717
+ end
718
+
684
719
  # Run through all custom options stored in Mongoid::Fields.options and
685
720
  # execute the handler if the option is provided.
686
721
  #
@@ -901,7 +936,12 @@ module Mongoid
901
936
  opts = options.merge(klass: self)
902
937
  opts[:type] = retrieve_and_validate_type(name, options[:type])
903
938
  return Fields::Localized.new(name, opts) if options[:localize]
904
- return Fields::ForeignKey.new(name, opts) if options[:identity]
939
+
940
+ if options[:identity]
941
+ return Fields::EncryptedForeignKey.new(name, opts) if options[:encrypt]
942
+
943
+ return Fields::ForeignKey.new(name, opts)
944
+ end
905
945
  return Fields::Encrypted.new(name, opts) if options[:encrypt]
906
946
 
907
947
  Fields::Standard.new(name, opts)
@@ -42,6 +42,7 @@ module Mongoid
42
42
  @attributes = attributes
43
43
  @attributes_before_type_cast = @attributes.dup
44
44
  @changed_attributes = {}
45
+ @pre_create_changed_attributes = nil
45
46
  @previous_changes = {}
46
47
  @previous_attributes = {}
47
48
  @previously_new_record = false
@@ -5,5 +5,5 @@ module Mongoid
5
5
  #
6
6
  # Note that this file is automatically updated via `rake candidate:create`.
7
7
  # Manual changes to this file will be overwritten by that rake task.
8
- VERSION = '9.1.2'
8
+ VERSION = '9.1.3'
9
9
  end
@@ -34,23 +34,33 @@ describe 'Encryption' do
34
34
  Mongoid.default_client[Crypt::Patient.collection_name].drop
35
35
  Mongoid.default_client[Crypt::Car.collection_name].drop
36
36
  Mongoid.default_client[Crypt::Folder.collection_name].drop
37
+ Mongoid.default_client[Crypt::Dossier.collection_name].drop
38
+ Mongoid.default_client[Crypt::Archive.collection_name].drop
37
39
  existing_key_id = Crypt::Patient.encrypt_metadata[:key_id]
38
40
  Crypt::Patient.set_key_id(data_key_id)
39
41
  Crypt::Car.set_key_id(data_key_id)
40
42
  Crypt::Note.set_key_id(data_key_id)
43
+ Crypt::Dossier.set_key_id(data_key_id)
44
+ Crypt::Archive.set_key_id(data_key_id)
41
45
  Mongoid::Config.send(:clients=, config)
42
46
  Mongoid::Clients.with_name(:key_vault)[key_vault_collection].drop
43
47
  Crypt::Patient.store_in(client: :encrypted)
44
48
  Crypt::Car.store_in(client: :encrypted, database: Crypt::Car.storage_options[:database])
45
49
  Crypt::Folder.store_in(client: :encrypted)
50
+ Crypt::Dossier.store_in(client: :encrypted)
51
+ Crypt::Archive.store_in(client: :encrypted)
46
52
 
47
53
  example.run
48
54
 
49
55
  Crypt::Patient.reset_storage_options!
50
56
  Crypt::Folder.reset_storage_options!
57
+ Crypt::Dossier.reset_storage_options!
58
+ Crypt::Archive.reset_storage_options!
51
59
  Crypt::Patient.set_key_id(existing_key_id)
52
60
  Crypt::Car.set_key_id(existing_key_id)
53
61
  Crypt::Note.set_key_id(existing_key_id)
62
+ Crypt::Dossier.set_key_id(existing_key_id)
63
+ Crypt::Archive.set_key_id(existing_key_id)
54
64
  end
55
65
 
56
66
  it 'encrypts and decrypts fields' do
@@ -101,6 +111,27 @@ describe 'Encryption' do
101
111
  end
102
112
  end
103
113
 
114
+ # The document is persisted under the store_as key, not the association
115
+ # name, so the schema has to be keyed by it or the field is stored in the
116
+ # clear.
117
+ it 'stores an embedded field encrypted when the association uses store_as' do
118
+ dossier = Crypt::Dossier.create!(secret: Crypt::DossierSecret.new(token: 'SECRET'))
119
+ unencrypted_client[Crypt::Dossier.collection.name].find(_id: dossier.id).first.tap do |doc|
120
+ expect(doc['s']['token']).to be_a(BSON::Binary)
121
+ expect(doc['s']['token'].type).to eq(:ciphertext)
122
+ end
123
+ expect(Crypt::Dossier.find(dossier.id).secret.token).to eq('SECRET')
124
+ end
125
+
126
+ it 'stores a nested embedded field encrypted when the associations use store_as' do
127
+ archive = Crypt::Archive.create!(entry: Crypt::ArchiveEntry.new(payload: Crypt::ArchivePayload.new(token: 'SECRET')))
128
+ unencrypted_client[Crypt::Archive.collection.name].find(_id: archive.id).first.tap do |doc|
129
+ expect(doc['e']['p']['token']).to be_a(BSON::Binary)
130
+ expect(doc['e']['p']['token'].type).to eq(:ciphertext)
131
+ end
132
+ expect(Crypt::Archive.find(archive.id).entry.payload.token).to eq('SECRET')
133
+ end
134
+
104
135
  it 'stores data encrypted in the non-default database' do
105
136
  car = Crypt::Car.create!(vin: 'VA1234')
106
137
  unencrypted_client
@@ -394,4 +425,242 @@ describe 'Encryption' do
394
425
  end
395
426
  end
396
427
  end
428
+
429
+ describe 'an encrypted belongs_to foreign key' do
430
+ let(:foreign_key_models) { [] }
431
+
432
+ let(:owner_class) do
433
+ klass = stub_const('Crypt::ForeignKeyOwner', Class.new)
434
+ klass.include(Mongoid::Document)
435
+ foreign_key_models << klass
436
+ klass
437
+ end
438
+
439
+ let(:reference_class) do
440
+ owner_class
441
+ klass = stub_const('Crypt::ForeignKeyReference', Class.new)
442
+ klass.include(Mongoid::Document)
443
+ foreign_key_models << klass
444
+ klass.encrypt_with(key_id: data_key_id) if deterministic
445
+ klass.store_in(client: :encrypted)
446
+ association_options = { class_name: 'Crypt::ForeignKeyOwner', inverse_of: nil }
447
+ association_options[:foreign_key] = foreign_key if foreign_key != :owner_id
448
+ encryption_options = { deterministic: deterministic }
449
+ encryption_options[:key_id] = data_key_id unless deterministic
450
+
451
+ klass.field(foreign_key, type: BSON::ObjectId, encrypt: encryption_options)
452
+ klass.belongs_to(:owner, association_options)
453
+
454
+ # The schema map is built when the client is constructed.
455
+ Mongoid::Clients.clear
456
+ klass
457
+ end
458
+
459
+ after do
460
+ foreign_key_models.each { |model| Mongoid.deregister_model(model) }
461
+ Mongoid::Clients.clear
462
+ end
463
+
464
+ foreign_keys = %i[owner_id secret_owner_id]
465
+ [ true, false ].each do |deterministic|
466
+ foreign_keys.each do |foreign_key|
467
+ key_type = (foreign_key == :owner_id) ? 'default' : 'custom'
468
+ context "with #{deterministic ? 'deterministic' : 'random'} encryption and the " \
469
+ "#{key_type} foreign key" do
470
+ let(:deterministic) { deterministic }
471
+ let(:foreign_key) { foreign_key }
472
+
473
+ it 'encrypts the key and preserves association behavior', :aggregate_failures do
474
+ owner = owner_class.create!
475
+ other_owner = owner_class.create!
476
+ reference = reference_class.create!(owner: owner)
477
+ same_owner = reference_class.create!(owner: owner)
478
+ collection = unencrypted_client[reference_class.collection_name.to_s]
479
+
480
+ stored = collection.find(_id: reference.id).first
481
+ expect(stored[foreign_key.to_s]).to be_a(BSON::Binary).and(have_attributes(type: :ciphertext))
482
+ other_ciphertext = collection.find(_id: same_owner.id).first[foreign_key.to_s]
483
+ if deterministic
484
+ expect(stored[foreign_key.to_s]).to eq(other_ciphertext)
485
+ else
486
+ expect(stored[foreign_key.to_s]).not_to eq(other_ciphertext)
487
+ end
488
+
489
+ reference.reload
490
+ expect(reference.public_send(foreign_key)).to eq(owner.id)
491
+ expect(reference.owner.id).to eq(owner.id)
492
+
493
+ # Assigning the foreign key must also invalidate the cached association.
494
+ reference.public_send("#{foreign_key}=", other_owner.id)
495
+ expect(reference.owner.id).to eq(other_owner.id)
496
+ reference.save!
497
+
498
+ stored = collection.find(_id: reference.id).first
499
+ expect(stored[foreign_key.to_s]).to be_a(BSON::Binary).and(have_attributes(type: :ciphertext))
500
+ expect(reference.reload.owner.id).to eq(other_owner.id)
501
+ end
502
+ end
503
+ end
504
+ end
505
+ end
506
+
507
+ # A belongs_to declared on a parent generates the foreign key on the whole
508
+ # hierarchy. An encrypted declaration of that key on a subclass must survive
509
+ # the propagation, or the subclass silently loses its encryption.
510
+ describe 'an encrypted belongs_to foreign key declared on a subclass' do
511
+ let(:models) { [] }
512
+
513
+ let(:owner_class) do
514
+ klass = stub_const('Crypt::InheritedForeignKeyOwner', Class.new)
515
+ klass.include(Mongoid::Document)
516
+ models << klass
517
+ klass
518
+ end
519
+
520
+ let(:parent_class) do
521
+ klass = stub_const('Crypt::InheritedForeignKeyParent', Class.new)
522
+ klass.include(Mongoid::Document)
523
+ models << klass
524
+ klass
525
+ end
526
+
527
+ let(:child_class) do
528
+ parent_class
529
+ klass = stub_const('Crypt::InheritedForeignKeyChild', Class.new(parent_class))
530
+ models << klass
531
+ klass.store_in(client: :encrypted)
532
+ klass.encrypt_with(key_id: data_key_id) if model_key
533
+ klass.field(foreign_key, type: BSON::ObjectId, encrypt: encryption_options)
534
+ klass.belongs_to(:owner, association_options) if child_association
535
+ klass
536
+ end
537
+
538
+ let(:association_options) do
539
+ { class_name: 'Crypt::InheritedForeignKeyOwner', inverse_of: nil }.tap do |options|
540
+ options[:foreign_key] = foreign_key if foreign_key != :owner_id
541
+ end
542
+ end
543
+
544
+ let(:encryption_options) do
545
+ { deterministic: deterministic }.tap do |options|
546
+ options[:key_id] = data_key_id unless model_key
547
+ end
548
+ end
549
+
550
+ let(:algorithm) do
551
+ if deterministic
552
+ 'AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic'
553
+ else
554
+ 'AEAD_AES_256_CBC_HMAC_SHA_512-Random'
555
+ end
556
+ end
557
+
558
+ before do
559
+ child_class
560
+ parent_class.belongs_to(:owner, association_options)
561
+ # The schema map is built when the client is constructed.
562
+ Mongoid::Clients.clear
563
+ end
564
+
565
+ after do
566
+ models.each { |model| Mongoid.deregister_model(model) }
567
+ Mongoid::Clients.clear
568
+ end
569
+
570
+ shared_examples 'an encrypted inherited foreign key' do
571
+ it 'keeps the encryption on the subclass and supports the association', :aggregate_failures do
572
+ field = child_class.fields[foreign_key.to_s]
573
+ expect(field).to be_a(Mongoid::Fields::EncryptedForeignKey)
574
+ expect(field).to be_foreign_key
575
+ expect(field.type).to eq(BSON::ObjectId)
576
+ expect(field.options[:encrypt]).to eq(encryption_options)
577
+ expect(field.deterministic?).to eq(deterministic)
578
+ if model_key
579
+ expect(field.key_id).to be_nil
580
+ else
581
+ expect(field.key_id).to eq(data_key_id)
582
+ end
583
+ expect(child_class.encrypted?).to be true
584
+ expect(parent_class.encrypted?).to be false
585
+
586
+ # The classes share a collection, and only the subclass contributes an
587
+ # entry to the schema map for it.
588
+ expect(child_class.collection_name).to eq(parent_class.collection_name)
589
+ schema = Mongoid.config.encryption_schema_map(
590
+ database_id, [ parent_class, child_class ]
591
+ ).fetch("#{database_id}.#{child_class.collection_name}")
592
+ encryption = schema.dig('properties', foreign_key.to_s, 'encrypt')
593
+ expect(encryption['bsonType']).to eq('objectId')
594
+ expect(encryption['algorithm']).to eq(algorithm)
595
+ if model_key
596
+ expect(encryption).not_to have_key('keyId')
597
+ expect(schema.dig('encryptMetadata', 'keyId')).to be_a(Array)
598
+ else
599
+ expect(encryption['keyId']).to be_a(Array)
600
+ end
601
+
602
+ owner = owner_class.create!
603
+ other_owner = owner_class.create!
604
+ child = child_class.create!(owner: owner)
605
+ same_owner = child_class.create!(owner: owner)
606
+ collection = unencrypted_client[child_class.collection_name.to_s]
607
+
608
+ stored = collection.find(_id: child.id).first
609
+ expect(stored[foreign_key.to_s]).to be_a(BSON::Binary).and(have_attributes(type: :ciphertext))
610
+ other_ciphertext = collection.find(_id: same_owner.id).first[foreign_key.to_s]
611
+ if deterministic
612
+ expect(stored[foreign_key.to_s]).to eq(other_ciphertext)
613
+ else
614
+ expect(stored[foreign_key.to_s]).not_to eq(other_ciphertext)
615
+ end
616
+
617
+ child.reload
618
+ expect(child.public_send(foreign_key)).to eq(owner.id)
619
+ expect(child.owner.id).to eq(owner.id)
620
+
621
+ child.public_send("#{foreign_key}=", other_owner.id)
622
+ expect(child.owner.id).to eq(other_owner.id)
623
+ end
624
+ end
625
+
626
+ context 'when only the subclass declares the field' do
627
+ let(:child_association) { false }
628
+
629
+ context 'with deterministic encryption and the default foreign key' do
630
+ let(:deterministic) { true }
631
+ let(:model_key) { false }
632
+ let(:foreign_key) { :owner_id }
633
+
634
+ it_behaves_like 'an encrypted inherited foreign key'
635
+ end
636
+
637
+ context 'with random encryption, a custom foreign key and a model-level key' do
638
+ let(:deterministic) { false }
639
+ let(:model_key) { true }
640
+ let(:foreign_key) { :secret_owner_id }
641
+
642
+ it_behaves_like 'an encrypted inherited foreign key'
643
+ end
644
+ end
645
+
646
+ context 'when the subclass also declares the association' do
647
+ let(:child_association) { true }
648
+
649
+ context 'with deterministic encryption, a custom foreign key and a model-level key' do
650
+ let(:deterministic) { true }
651
+ let(:model_key) { true }
652
+ let(:foreign_key) { :secret_owner_id }
653
+
654
+ it_behaves_like 'an encrypted inherited foreign key'
655
+ end
656
+
657
+ context 'with random encryption and the default foreign key' do
658
+ let(:deterministic) { false }
659
+ let(:model_key) { false }
660
+ let(:foreign_key) { :owner_id }
661
+
662
+ it_behaves_like 'an encrypted inherited foreign key'
663
+ end
664
+ end
665
+ end
397
666
  end
@@ -122,21 +122,50 @@ describe Mongoid::Association::Referenced::BelongsTo::Buildable do
122
122
  end
123
123
  end
124
124
 
125
- context 'when provided an array of hashes' do
125
+ context 'when provided preloaded documents' do
126
126
  let(:object) do
127
- [
128
- { '_id' => BSON::ObjectId.new, 'username' => 'user1' },
129
- { '_id' => BSON::ObjectId.new, 'username' => 'user2' }
130
- ]
127
+ Mongoid::Association::PreloadedDocuments.new(
128
+ [
129
+ { '_id' => BSON::ObjectId.new, 'username' => 'user1' },
130
+ { '_id' => BSON::ObjectId.new, 'username' => 'user2' }
131
+ ]
132
+ )
131
133
  end
132
134
 
133
- it 'queries and returns the document' do
135
+ it 'returns the preloaded document' do
134
136
  first_doc = document
135
137
  expect(first_doc).to be_a(Person)
136
138
  expect(first_doc.username).to eq('user1')
137
139
  end
138
140
  end
139
141
 
142
+ context 'when the foreign key is supplied as attributes' do
143
+ it 'does not build a document from a hash-valued foreign key' do
144
+ game = Game.new(person_id: { '_id' => BSON::ObjectId.new, '_type' => 'Canvas' })
145
+
146
+ expect(game.person).to be_nil
147
+ end
148
+
149
+ it 'does not build a document from an array-valued foreign key' do
150
+ game = Game.new(person_id: [ { '_id' => BSON::ObjectId.new, '_type' => 'Canvas' } ])
151
+
152
+ expect(game.person).to be_nil
153
+ end
154
+
155
+ it 'does not build a document from a stored hash-valued foreign key' do
156
+ game = Game.new(person_id: { '_id' => BSON::ObjectId.new, '_type' => 'Canvas' })
157
+ game.save!(validate: false)
158
+
159
+ expect(Game.find(game.id).person).to be_nil
160
+ end
161
+
162
+ it 'does not treat an array of ids as a lookup result' do
163
+ game = Game.new(person_id: [ BSON::ObjectId.new ])
164
+
165
+ expect { game.person }.not_to raise_error
166
+ end
167
+ end
168
+
140
169
  context 'when provided a object' do
141
170
  let!(:person) do
142
171
  Person.create!