mongoid 9.0.13 → 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 (42) hide show
  1. checksums.yaml +4 -4
  2. data/lib/config/locales/en.yml +13 -0
  3. data/lib/mongoid/association/referenced/belongs_to.rb +16 -8
  4. data/lib/mongoid/association/referenced/has_and_belongs_to_many.rb +12 -0
  5. data/lib/mongoid/association/referenced/has_many/proxy.rb +4 -2
  6. data/lib/mongoid/attributes/readonly.rb +19 -1
  7. data/lib/mongoid/changeable.rb +21 -1
  8. data/lib/mongoid/config/encryption.rb +5 -3
  9. data/lib/mongoid/contextual/none.rb +51 -0
  10. data/lib/mongoid/criteria/scopable.rb +7 -1
  11. data/lib/mongoid/criteria.rb +45 -1
  12. data/lib/mongoid/document.rb +10 -0
  13. data/lib/mongoid/encryptable.rb +1 -1
  14. data/lib/mongoid/errors/invalid_encrypted_association.rb +28 -0
  15. data/lib/mongoid/errors.rb +1 -0
  16. data/lib/mongoid/fields/encrypted.rb +14 -3
  17. data/lib/mongoid/fields/foreign_key.rb +9 -0
  18. data/lib/mongoid/fields/standard.rb +10 -0
  19. data/lib/mongoid/fields/validators/macro.rb +29 -0
  20. data/lib/mongoid/fields.rb +42 -2
  21. data/lib/mongoid/reloadable.rb +1 -0
  22. data/lib/mongoid/version.rb +1 -1
  23. data/spec/integration/encryption_spec.rb +269 -0
  24. data/spec/mongoid/association/referenced/encrypted_foreign_key_spec.rb +144 -0
  25. data/spec/mongoid/association/referenced/has_and_belongs_to_many/proxy_spec.rb +48 -0
  26. data/spec/mongoid/association/referenced/has_many/proxy_spec.rb +83 -0
  27. data/spec/mongoid/attributes/readonly_dotted_spec.rb +332 -0
  28. data/spec/mongoid/attributes/readonly_spec.rb +389 -0
  29. data/spec/mongoid/changeable_spec.rb +18 -0
  30. data/spec/mongoid/config/encryption_spec.rb +227 -0
  31. data/spec/mongoid/contextual/none_spec.rb +22 -5
  32. data/spec/mongoid/criteria_spec.rb +17 -0
  33. data/spec/mongoid/fields_spec.rb +29 -0
  34. data/spec/mongoid/findable_spec.rb +14 -0
  35. data/spec/mongoid/scopable_spec.rb +103 -2
  36. data/spec/spec_helper.rb +8 -0
  37. data/spec/support/crypt/models.rb +42 -0
  38. data/spec/support/models/delete_all_account.rb +10 -0
  39. data/spec/support/models/delete_all_item.rb +9 -0
  40. data/spec/support/models/delete_all_scoped_item.rb +11 -0
  41. data/spec/support/models/delete_all_tag.rb +7 -0
  42. metadata +1995 -1961
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 030d90a4693fc5b3ccb72a7069ce6dc912089351df98fd04ead3595a414433a0
4
- data.tar.gz: 10362c8758cb9ec1e535b9940eab11088261e7cf4831b8a07bfffb6be231e8df
3
+ metadata.gz: 63461fddbbd4f1544e96e291c730597139e28fdc92631d4c43499cbcddb89d6a
4
+ data.tar.gz: 5cba7e07269662025db60f0f89a3f5b80d4a2e1d020bd368186c79a1b1cdb11f
5
5
  SHA512:
6
- metadata.gz: 8e5d6bfa84e64cd80f756e55d6fe846f10b5a820c79881b26a54c305f08fb02ef98d27990d7b51b595342844b38c11e04b6e9be911cd3306748c023d226bf9a2
7
- data.tar.gz: 5a92a5485360f68cea7bbfa48259f0441f0df723d634926230c80b78784e6f8719083b3fef9d81537223b0da8f2b96563c8d267c4bbe9a372c592b781163fe45
6
+ metadata.gz: e2b1c80725b0807a30c7a238a2007be6ea2ed851563db4a0dfed748f94a40143045eb48a6d3662af8c9a23021419841464595cad3bcb67563e02fb2ae3950580
7
+ data.tar.gz: 04a57c874d0f94569cbc579cdef32b4211eb65d2cd047a741b53b2e89a9f98f79ca5563cdc8c61959072e058a5c3ebc9d4342366489fb777f2caee583816b27e
@@ -239,6 +239,19 @@ en:
239
239
  Mongoid does not support."
240
240
  resolution: "Valid field operators are: %{valid_operators}.
241
241
  Ensure you are using one of these operators."
242
+ invalid_encrypted_association:
243
+ message: "The %{association} association of %{klass} uses the encrypted
244
+ field %{field} as its foreign key."
245
+ summary: "Client-side field level encryption can encrypt an array
246
+ only as a whole, using the random algorithm; the deterministic
247
+ algorithm does not support arrays at all. A
248
+ has_and_belongs_to_many association stores its foreign key in an
249
+ array and queries and atomically updates individual elements of
250
+ it, which encryption does not support. Mongoid raises this error
251
+ when the association or the field is defined, whichever comes
252
+ first, rather than defining a key the association cannot manage."
253
+ resolution: "Remove the encryption from %{field}, or store a single
254
+ encrypted value with a belongs_to association instead."
242
255
  invalid_encryption_schema:
243
256
  message: "The encryption schema for %{namespace} is invalid."
244
257
  summary: "Two models writing to %{namespace} describe %{path}
@@ -227,14 +227,22 @@ module Mongoid
227
227
  end
228
228
 
229
229
  def create_foreign_key_field!
230
- @owner_class.field(
231
- foreign_key,
232
- type: FOREIGN_KEY_FIELD_TYPE,
233
- identity: true,
234
- overwrite: true,
235
- association: self,
236
- default: nil
237
- )
230
+ options = {
231
+ type: FOREIGN_KEY_FIELD_TYPE,
232
+ identity: true,
233
+ overwrite: true,
234
+ association: self,
235
+ default: nil
236
+ }
237
+ # The association must not replace an encrypted field with a plain
238
+ # foreign key: the key would then be stored in the clear. Keep the
239
+ # declared type as well, so the encryption schema describes it
240
+ # correctly.
241
+ if (existing = @owner_class.fields[foreign_key])&.encrypted?
242
+ options[:type] = existing.type
243
+ options[:encrypt] = existing.options[:encrypt]
244
+ end
245
+ @owner_class.field(foreign_key, options)
238
246
  end
239
247
  end
240
248
  end
@@ -231,6 +231,18 @@ module Mongoid
231
231
  end
232
232
 
233
233
  def create_foreign_key_field!
234
+ # An encrypted array field cannot be used as the foreign key:
235
+ # encryption protects the array only as a whole, while this
236
+ # association queries and atomically updates its elements. Reject
237
+ # the association rather than replace the field and store the key in
238
+ # plaintext. The field may already be declared on a parent, whose
239
+ # declaration is propagated to the descendants.
240
+ ([ @owner_class ] + @owner_class.descendants).each do |candidate|
241
+ next unless candidate.fields[foreign_key]&.encrypted?
242
+
243
+ raise Errors::InvalidEncryptedAssociation.new(candidate, name, foreign_key)
244
+ end
245
+
234
246
  inverse_class.aliased_associations[foreign_key] = name.to_s
235
247
  @owner_class.field(
236
248
  foreign_key,
@@ -533,8 +533,10 @@ module Mongoid
533
533
  #
534
534
  # @return [ Integer ] The number of documents deleted.
535
535
  def remove_all(conditions = nil, method = :delete_all)
536
- selector = conditions || {}
537
- selector.merge!(criteria.selector)
536
+ # Conjoin the conditions with the association selector so that a
537
+ # key present in both is intersected rather than overwritten. This
538
+ # also leaves the caller's Hash alone.
539
+ selector = criteria.where(conditions || {}).selector
538
540
 
539
541
  # Scanning before the delete means scanning only what is already in
540
542
  # memory, so it is only done where there is a pattern whose cost has
@@ -23,7 +23,25 @@ module Mongoid
23
23
  # @return [ true | false ] If the document is new, or if the field is not
24
24
  # readonly.
25
25
  def attribute_writable?(name)
26
- new_record? || (!self.class.readonly_attributes.include?(name) && _loaded?(name))
26
+ return true if new_record?
27
+
28
+ readonly = self.class.readonly_attributes
29
+ return _loaded?(name) if readonly.empty?
30
+
31
+ path = name.to_s
32
+ return false if readonly.include?(path)
33
+
34
+ readonly.each do |field|
35
+ # A readonly attribute that is a declared field with a dotted name
36
+ # is that literal field, not a path prefix.
37
+ next if field.include?('.') && self.class.fields.key?(field)
38
+
39
+ # A path that is a declared field with a dotted name addresses that
40
+ # literal field, not a descendant of the readonly attribute.
41
+ return false if path.start_with?("#{field}.") && !self.class.fields.key?(path)
42
+ end
43
+
44
+ _loaded?(name)
27
45
  end
28
46
 
29
47
  private
@@ -80,6 +80,7 @@ module Mongoid
80
80
  @children_may_have_changed = false
81
81
  reset_atomic_updates!
82
82
  changed_attributes.clear
83
+ @pre_create_changed_attributes = nil
83
84
  end
84
85
 
85
86
  # Things that need to execute after a document has been persisted.
@@ -263,15 +264,24 @@ module Mongoid
263
264
  # @param [ Object ] to The object the attribute was changed to (optional).
264
265
  #
265
266
  # @return [ true | false ] Whether the attribute has changed.
267
+ # rubocop:disable Metrics/AbcSize
266
268
  def attribute_changed?(attr, from: ATTRIBUTE_UNCHANGED, to: ATTRIBUTE_UNCHANGED)
267
269
  attr = database_field_name(attr)
268
270
  return false unless changed_attributes.key?(attr)
271
+ # An in-place change to a readonly attribute of a persisted document
272
+ # is not part of the dirty tracking API and will not be persisted. A
273
+ # change tracked while the document was new initializes the document,
274
+ # and new documents may set readonly attributes, so it is still
275
+ # reported as a saved change.
276
+ return false if !new_record? && self.class.readonly_attributes.include?(attr) &&
277
+ !@pre_create_changed_attributes&.include?(attr)
269
278
  return false if changed_attributes[attr] == attributes[attr]
270
279
  return false if from != changed_attributes[attr]
271
280
  return false if to != attributes[attr]
272
281
 
273
282
  true
274
283
  end
284
+ # rubocop:enable Metrics/AbcSize
275
285
 
276
286
  # Get whether or not the field has a different value from the default.
277
287
  #
@@ -328,6 +338,13 @@ module Mongoid
328
338
  def attribute_will_change!(attr)
329
339
  return if changed_attributes.key?(attr)
330
340
 
341
+ # The snapshot is taken for readonly attributes as well. Their changes
342
+ # are hidden from the dirty tracking API (see #attribute_changed?), but
343
+ # the snapshot is needed to reset an in-place change. Changes tracked
344
+ # while the document is new initialize it, and new documents may set
345
+ # readonly attributes, so they are remembered here and still reported
346
+ # when the document is created.
347
+ (@pre_create_changed_attributes ||= ::Set.new).add(attr) if new_record?
331
348
  changed_attributes[attr] = read_raw_attribute(attr).__deep_copy__
332
349
  end
333
350
 
@@ -341,7 +358,10 @@ module Mongoid
341
358
  # @return [ Object ] The old value.
342
359
  def reset_attribute!(attr)
343
360
  attr = database_field_name(attr)
344
- attributes[attr] = changed_attributes.delete(attr) if attribute_changed?(attr)
361
+ return unless changed_attributes.key?(attr)
362
+ return if changed_attributes[attr] == attributes[attr]
363
+
364
+ attributes[attr] = changed_attributes.delete(attr)
345
365
  end
346
366
 
347
367
  def reset_attribute_to_default!(attr)
@@ -153,7 +153,7 @@ module Mongoid
153
153
  # @return [ Hash ] The encryption properties.
154
154
  def properties_for_fields(model)
155
155
  model.fields.each_with_object({}) do |(name, field), props|
156
- next unless field.is_a?(Mongoid::Fields::Encrypted)
156
+ next unless field.encrypted?
157
157
 
158
158
  props[name] = {
159
159
  'encrypt' => {
@@ -182,7 +182,7 @@ module Mongoid
182
182
  #
183
183
  # @return [ Hash ] The encryption properties.
184
184
  def properties_for_relations(model, path, namespace = nil)
185
- model.relations.each_with_object({}) do |(name, relation), props|
185
+ model.relations.each_with_object({}) do |(_name, relation), props|
186
186
  # relation_class constantizes, and a polymorphic embedded_in has no
187
187
  # class to resolve, so the relation type has to be checked first.
188
188
  next unless relation.is_a?(Association::Embedded::EmbedsOne)
@@ -211,7 +211,9 @@ module Mongoid
211
211
  namespace
212
212
  )
213
213
  end
214
- props[name] = { 'bsonType' => 'object' }.merge(properties) unless properties.empty?
214
+ # The document is persisted under the store_as key, not under the
215
+ # name of the association, so that is the key the schema needs.
216
+ props[relation.store_as] = { 'bsonType' => 'object' }.merge(properties) unless properties.empty?
215
217
  end
216
218
  end
217
219
 
@@ -28,6 +28,31 @@ module Mongoid
28
28
  other.is_a?(None)
29
29
  end
30
30
 
31
+ # Delete all documents in the database that match the selector. There
32
+ # are no documents in the null context, so nothing is deleted.
33
+ #
34
+ # @example Delete all the documents.
35
+ # context.delete
36
+ #
37
+ # @return [ Integer ] Always zero.
38
+ def delete
39
+ 0
40
+ end
41
+ alias delete_all delete
42
+
43
+ # Destroy all documents in the database that match the selector. There
44
+ # are no documents in the null context, so nothing is destroyed and no
45
+ # callbacks are run.
46
+ #
47
+ # @example Destroy all the documents.
48
+ # context.destroy
49
+ #
50
+ # @return [ Integer ] Always zero.
51
+ def destroy
52
+ 0
53
+ end
54
+ alias destroy_all destroy
55
+
31
56
  # Get the distinct field values in null context.
32
57
  #
33
58
  # @example Get the distinct values in null context.
@@ -111,6 +136,32 @@ module Mongoid
111
136
  {}
112
137
  end
113
138
 
139
+ # Update the first matching document atomically. There are no documents
140
+ # in the null context, so nothing is updated.
141
+ #
142
+ # @example Update the matching document.
143
+ # context.update(name: "Smiths")
144
+ #
145
+ # @param [ Hash ] attributes The new attributes for the document.
146
+ #
147
+ # @return [ nil | false ] False if no attributes were provided.
148
+ def update(attributes = nil, _opts = {})
149
+ attributes ? nil : false
150
+ end
151
+
152
+ # Update all the matching documents atomically. There are no documents
153
+ # in the null context, so nothing is updated.
154
+ #
155
+ # @example Update all the matching documents.
156
+ # context.update_all(name: "Smiths")
157
+ #
158
+ # @param [ Hash ] attributes The new attributes for each document.
159
+ #
160
+ # @return [ nil | false ] False if no attributes were provided.
161
+ def update_all(attributes = nil, _opts = {})
162
+ attributes ? nil : false
163
+ end
164
+
114
165
  # Create the new null context.
115
166
  #
116
167
  # @example Create the new context.
@@ -16,9 +16,13 @@ module Mongoid
16
16
  #
17
17
  # @return [ Criteria ] The criteria.
18
18
  def apply_default_scope
19
+ explicit_none = none_state == true
19
20
  klass.without_default_scope do
20
21
  merge!(klass.default_scoping.call)
21
22
  end
23
+ # A none coming from the default scope is not an explicit none, so it
24
+ # may be removed by unscoping.
25
+ @none = :default if !explicit_none && @none
22
26
  self.scoping_options = true, false
23
27
  end
24
28
 
@@ -103,7 +107,9 @@ module Mongoid
103
107
  crit = clone
104
108
  unless unscoped?
105
109
  crit.scoping_options = false, true
106
- crit.selector.clear; crit.options.clear
110
+ crit.selector.clear
111
+ crit.options.clear
112
+ crit.send(:clear_default_scope_none)
107
113
  end
108
114
  crit
109
115
  end
@@ -312,6 +312,20 @@ module Mongoid
312
312
  self.documents = other.documents.dup unless other.documents.empty?
313
313
  self.scoping_options = other.scoping_options
314
314
  self.inclusions = (inclusions + other.inclusions).uniq
315
+ if other.empty_and_chainable?
316
+ # An explicit none wins over a none that only came from a default
317
+ # scope. Association proxies forward is_a? to their target, so the
318
+ # runtime class is checked instead; anything that is not a criteria is
319
+ # treated as an explicit none.
320
+ explicit = if Criteria === other # rubocop:disable Style/CaseEquality
321
+ other.send(:none_state) == true
322
+ else
323
+ true
324
+ end
325
+ @none = true if @none == true || explicit
326
+ @none ||= :default
327
+ @context = nil
328
+ end
315
329
  self
316
330
  end
317
331
 
@@ -323,7 +337,9 @@ module Mongoid
323
337
  #
324
338
  # @return [ Criteria ] The none criteria.
325
339
  def none
326
- @none = true and self
340
+ @none = true
341
+ @context = nil
342
+ self
327
343
  end
328
344
 
329
345
  # Is the criteria an empty but chainable criteria?
@@ -510,6 +526,34 @@ module Mongoid
510
526
 
511
527
  private
512
528
 
529
+ # The kind of none on this criteria, if any. An explicit none is +true+,
530
+ # a none coming only from the default scope is +:default+, and a criteria
531
+ # that is not none returns +nil+.
532
+ #
533
+ # @api private
534
+ #
535
+ # @example Get the none state.
536
+ # criteria.send(:none_state)
537
+ #
538
+ # @return [ true | :default | nil ] The none state.
539
+ def none_state
540
+ @none
541
+ end
542
+
543
+ # Removes the none flag if it was set only by the default scope. An
544
+ # explicitly requested none is never removed.
545
+ #
546
+ # @api private
547
+ #
548
+ # @example Clear a default scope none.
549
+ # criteria.send(:clear_default_scope_none)
550
+ #
551
+ # @return [ Criteria ] The criteria.
552
+ def clear_default_scope_none
553
+ @none = nil if @none == :default
554
+ self
555
+ end
556
+
513
557
  # Are documents in the query missing, and are we configured to raise an
514
558
  # error?
515
559
  #
@@ -166,6 +166,12 @@ module Mongoid
166
166
  def internal_state=(state)
167
167
  self._id = state[:id]
168
168
  @changed_attributes = state[:changed_attributes]
169
+ # The document was constructed as new in #becomes, collecting
170
+ # pre-create change markers. Drop them when the copied state is that
171
+ # of a persisted document: its pending changes were all tracked after
172
+ # the document was persisted, and stale markers would let in-place
173
+ # changes to readonly attributes bypass the dirty filter.
174
+ @pre_create_changed_attributes = nil unless state[:new_record]
169
175
  @errors = ActiveModel::Errors.new(self).tap { |e| e.copy!(state[:errors]) }
170
176
  @new_record = state[:new_record]
171
177
  @destroyed = state[:destroyed]
@@ -337,6 +343,10 @@ module Mongoid
337
343
  relation = __send__(name)
338
344
  Array.wrap(relation).each do |r|
339
345
  r.instance_variable_set(:@new_record, new_record)
346
+ # The embedded documents were also constructed as new; drop
347
+ # their pre-create change markers when they are marked as
348
+ # persisted, as #internal_state= does for the parent document.
349
+ r.instance_variable_set(:@pre_create_changed_attributes, nil) unless new_record
340
350
  end
341
351
  end
342
352
  end
@@ -34,7 +34,7 @@ module Mongoid
34
34
  #
35
35
  # @return [ true | false ] Whether the model is encrypted.
36
36
  def encrypted?
37
- !encrypt_metadata.empty? || fields.any? { |_, field| field.is_a?(Mongoid::Fields::Encrypted) }
37
+ !encrypt_metadata.empty? || fields.any? { |_, field| field.encrypted? }
38
38
  end
39
39
 
40
40
  # Whether an encryption schema has to be generated for this model.
@@ -0,0 +1,28 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Mongoid
4
+ module Errors
5
+ # This error is raised when an encrypted field is used as the foreign key
6
+ # of a has_and_belongs_to_many association. Encryption protects an array
7
+ # only as a whole, while the association queries and atomically updates
8
+ # individual elements of it, so the association cannot manage the key.
9
+ class InvalidEncryptedAssociation < MongoidError
10
+ # Create the new error.
11
+ #
12
+ # @example Create the error.
13
+ # InvalidEncryptedAssociation.new(Person, :preferences, 'preference_ids')
14
+ #
15
+ # @param [ Class ] klass The model declaring the association.
16
+ # @param [ Symbol | String ] association The association name.
17
+ # @param [ String ] field The encrypted foreign key field.
18
+ def initialize(klass, association, field)
19
+ super(
20
+ compose_message(
21
+ 'invalid_encrypted_association',
22
+ { klass: klass.name, association: association, field: field }
23
+ )
24
+ )
25
+ end
26
+ end
27
+ end
28
+ end
@@ -20,6 +20,7 @@ require "mongoid/errors/invalid_collection"
20
20
  require "mongoid/errors/invalid_config_file"
21
21
  require "mongoid/errors/invalid_config_option"
22
22
  require "mongoid/errors/invalid_dependent_strategy"
23
+ require "mongoid/errors/invalid_encrypted_association"
23
24
  require "mongoid/errors/invalid_encryption_schema"
24
25
  require "mongoid/errors/invalid_field"
25
26
  require "mongoid/errors/invalid_field_option"
@@ -3,8 +3,8 @@
3
3
 
4
4
  module Mongoid
5
5
  module Fields
6
- # Represents a field that should be encrypted.
7
- class Encrypted < Standard
6
+ # Behavior shared by the field types whose value is encrypted.
7
+ module EncryptionOptions
8
8
  def initialize(name, options = {})
9
9
  @encryption_options = if options[:encrypt].is_a?(Hash)
10
10
  options[:encrypt]
@@ -14,6 +14,11 @@ module Mongoid
14
14
  super
15
15
  end
16
16
 
17
+ # @return [ true ] Always true: this field is encrypted.
18
+ def encrypted?
19
+ true
20
+ end
21
+
17
22
  # @return [ true | false | nil ] Whether the field should be encrypted using a
18
23
  # deterministic encryption algorithm; if not specified, nil is returned.
19
24
  def deterministic?
@@ -27,7 +32,8 @@ module Mongoid
27
32
  end
28
33
 
29
34
  # @return [ String | nil ] The name of the field that contains the
30
- # key alt name to use for encryption; if not specified, nil is returned.
35
+ # key alt name to use for encryption; if not specified, nil is
36
+ # returned.
31
37
  def key_name_field
32
38
  @encryption_options[:key_name_field]
33
39
  end
@@ -44,5 +50,10 @@ module Mongoid
44
50
  @encryption_options[:key_id] = key_id
45
51
  end
46
52
  end
53
+
54
+ # Represents a field that should be encrypted.
55
+ class Encrypted < Standard
56
+ include EncryptionOptions
57
+ end
47
58
  end
48
59
  end
@@ -188,5 +188,14 @@ module Mongoid
188
188
  # @return [ Object ] The serialized default.
189
189
  def serialize_default(object); object; end
190
190
  end
191
+
192
+ # Represents a foreign key field whose value is encrypted.
193
+ #
194
+ # A belongs_to association stores its key in a single value, so it can be
195
+ # encrypted like any other field. The encryption options of the field
196
+ # declared before the association are preserved here.
197
+ class EncryptedForeignKey < ForeignKey
198
+ include EncryptionOptions
199
+ end
191
200
  end
192
201
  end
@@ -58,6 +58,16 @@ module Mongoid
58
58
  false
59
59
  end
60
60
 
61
+ # Is this field encrypted?
62
+ #
63
+ # @example Is the field encrypted?
64
+ # field.encrypted?
65
+ #
66
+ # @return [ true | false ] If the field is encrypted.
67
+ def encrypted?
68
+ false
69
+ end
70
+
61
71
  # Create the new field with a name and optional additional options.
62
72
  #
63
73
  # @example Create the new field.
@@ -36,6 +36,7 @@ module Mongoid
36
36
  validate_field_name(klass, name)
37
37
  validate_name_uniqueness(klass, name, options)
38
38
  validate_options(klass, name, options)
39
+ validate_encrypted_association(klass, name, options)
39
40
  end
40
41
 
41
42
  # Validate the association definition.
@@ -120,6 +121,34 @@ module Mongoid
120
121
  end
121
122
  end
122
123
  end
124
+
125
+ # Determine if an encrypted field is the foreign key of a
126
+ # has_and_belongs_to_many association. Defining the field after the
127
+ # association has to be rejected, and so does defining it on a parent
128
+ # of the class that declares the association: the field is propagated
129
+ # to the descendants and would replace their association key.
130
+ #
131
+ # @api private
132
+ #
133
+ # @param [ Class ] klass The model class.
134
+ # @param [ Symbol | String ] name The field name.
135
+ # @param [ Hash ] options The provided options.
136
+ #
137
+ # @raise [ Errors::InvalidEncryptedAssociation ] If the field is the
138
+ # foreign key of a has_and_belongs_to_many association.
139
+ def validate_encrypted_association(klass, name, options)
140
+ return unless options[:encrypt]
141
+
142
+ ([ klass ] + klass.descendants).each do |candidate|
143
+ field = candidate.fields[name.to_s]
144
+ next unless field&.foreign_key?
145
+
146
+ association = field.association
147
+ next unless association.is_a?(Association::Referenced::HasAndBelongsToMany)
148
+
149
+ raise Errors::InvalidEncryptedAssociation.new(candidate, association.name, name)
150
+ end
151
+ end
123
152
  end
124
153
  end
125
154
  end
@@ -485,7 +485,7 @@ module Mongoid
485
485
  Validators::Macro.validate(self, name, options)
486
486
  added = add_field(named, options)
487
487
  descendants.each do |subclass|
488
- subclass.add_field(named, options)
488
+ subclass.add_field(named, descendant_field_options(subclass, named, options))
489
489
  end
490
490
  added
491
491
  end
@@ -580,6 +580,41 @@ module Mongoid
580
580
  field
581
581
  end
582
582
 
583
+ # Build the options to apply to a descendant when a belongs_to
584
+ # association declared on an ancestor generates its foreign key. A
585
+ # descendant may declare the field as encrypted before the association
586
+ # is declared on the parent. The encryption options and the declared
587
+ # type belong to the descendant and must survive the propagation, as
588
+ # must the foreign key behavior.
589
+ #
590
+ # When the descendant's encryption options differ from the ancestor's,
591
+ # the difference is preserved: the schema generation reports it instead
592
+ # of one declaration silently overriding the other.
593
+ #
594
+ # A field declared without an association is not covered: the ancestor's
595
+ # declaration keeps replacing the descendant's field as before.
596
+ #
597
+ # @api private
598
+ #
599
+ # @param [ Class ] subclass The descendant the field is propagated to.
600
+ # @param [ String ] name The field name.
601
+ # @param [ Hash ] options The options of the ancestor's declaration.
602
+ #
603
+ # @return [ Hash ] The options to apply to the descendant.
604
+ def descendant_field_options(subclass, name, options)
605
+ return options unless options[:identity]
606
+ return options unless options[:association].is_a?(Association::Referenced::BelongsTo)
607
+
608
+ existing = subclass.fields[name]
609
+ return options unless existing&.encrypted?
610
+
611
+ preserved = options.merge(type: existing.type, encrypt: existing.options[:encrypt])
612
+ if existing.foreign_key? && existing.association
613
+ preserved[:association] = existing.association
614
+ end
615
+ preserved
616
+ end
617
+
583
618
  # Run through all custom options stored in Mongoid::Fields.options and
584
619
  # execute the handler if the option is provided.
585
620
  #
@@ -803,7 +838,12 @@ module Mongoid
803
838
  opts = options.merge(klass: self)
804
839
  opts[:type] = retrieve_and_validate_type(name, options[:type])
805
840
  return Fields::Localized.new(name, opts) if options[:localize]
806
- return Fields::ForeignKey.new(name, opts) if options[:identity]
841
+
842
+ if options[:identity]
843
+ return Fields::EncryptedForeignKey.new(name, opts) if options[:encrypt]
844
+
845
+ return Fields::ForeignKey.new(name, opts)
846
+ end
807
847
  return Fields::Encrypted.new(name, opts) if options[:encrypt]
808
848
  Fields::Standard.new(name, opts)
809
849
  end
@@ -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.0.13'
8
+ VERSION = '9.0.14'
9
9
  end