mongoid 7.6.1 → 7.6.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 (63) hide show
  1. checksums.yaml +4 -4
  2. data/lib/config/locales/en.yml +26 -0
  3. data/lib/mongoid/association/depending.rb +8 -4
  4. data/lib/mongoid/association/nested/many.rb +38 -3
  5. data/lib/mongoid/association/nested/nested_buildable.rb +14 -0
  6. data/lib/mongoid/association/referenced/has_many/proxy.rb +105 -4
  7. data/lib/mongoid/attributes/readonly.rb +33 -3
  8. data/lib/mongoid/changeable.rb +22 -4
  9. data/lib/mongoid/config.rb +62 -0
  10. data/lib/mongoid/contextual/aggregable/memory.rb +8 -2
  11. data/lib/mongoid/contextual/memory.rb +19 -8
  12. data/lib/mongoid/contextual/none.rb +51 -0
  13. data/lib/mongoid/criteria/queryable/mergeable.rb +12 -0
  14. data/lib/mongoid/criteria/queryable/selectable.rb +124 -10
  15. data/lib/mongoid/criteria/scopable.rb +7 -1
  16. data/lib/mongoid/criteria.rb +45 -1
  17. data/lib/mongoid/document.rb +10 -0
  18. data/lib/mongoid/errors/in_memory_regexp_timeout.rb +26 -0
  19. data/lib/mongoid/errors.rb +1 -0
  20. data/lib/mongoid/field_readable.rb +70 -0
  21. data/lib/mongoid/matchable.rb +6 -1
  22. data/lib/mongoid/matcher/eq_impl_with_regexp.rb +3 -5
  23. data/lib/mongoid/matcher/regex.rb +8 -9
  24. data/lib/mongoid/matcher/regexp_budget.rb +389 -0
  25. data/lib/mongoid/matcher.rb +1 -0
  26. data/lib/mongoid/reloadable.rb +1 -0
  27. data/lib/mongoid/threaded.rb +3 -0
  28. data/lib/mongoid/version.rb +1 -1
  29. data/lib/mongoid/warnings.rb +1 -0
  30. data/spec/integration/app_spec.rb +8 -0
  31. data/spec/integration/matcher_operator_data/regex.yml +21 -0
  32. data/spec/integration/matcher_regexp_timeout_spec.rb +215 -0
  33. data/spec/integration/query_operator_guard_spec.rb +94 -0
  34. data/spec/mongoid/association/referenced/has_and_belongs_to_many/proxy_spec.rb +96 -0
  35. data/spec/mongoid/association/referenced/has_many/proxy_spec.rb +228 -0
  36. data/spec/mongoid/attributes/nested_spec.rb +202 -8
  37. data/spec/mongoid/attributes/readonly_dotted_spec.rb +286 -0
  38. data/spec/mongoid/attributes/readonly_spec.rb +387 -0
  39. data/spec/mongoid/changeable_spec.rb +18 -0
  40. data/spec/mongoid/contextual/aggregable/memory_spec.rb +98 -0
  41. data/spec/mongoid/contextual/memory_spec.rb +196 -0
  42. data/spec/mongoid/contextual/none_spec.rb +18 -0
  43. data/spec/mongoid/criteria/queryable/selectable_logical_spec.rb +29 -0
  44. data/spec/mongoid/criteria/queryable/selectable_where_spec.rb +200 -0
  45. data/spec/mongoid/criteria_spec.rb +19 -0
  46. data/spec/mongoid/findable_spec.rb +14 -0
  47. data/spec/mongoid/matcher/regexp_budget_spec.rb +576 -0
  48. data/spec/mongoid/scopable_spec.rb +116 -2
  49. data/spec/shared/lib/mrss/cluster_config.rb +5 -40
  50. data/spec/shared/lib/mrss/constraints.rb +7 -46
  51. data/spec/shared/lib/mrss/docker_runner.rb +10 -21
  52. data/spec/shared/lib/mrss/eg_config_utils.rb +0 -31
  53. data/spec/shared/lib/mrss/release/candidate.rb +18 -12
  54. data/spec/shared/lib/mrss/server_version_registry.rb +1 -5
  55. data/spec/shared/share/Dockerfile.erb +6 -8
  56. data/spec/shared/shlib/server.sh +0 -50
  57. data/spec/shared/shlib/set_env.sh +4 -10
  58. data/spec/spec_helper.rb +8 -0
  59. data/spec/support/models/delete_all_account.rb +10 -0
  60. data/spec/support/models/delete_all_item.rb +9 -0
  61. data/spec/support/models/delete_all_scoped_item.rb +11 -0
  62. data/spec/support/models/delete_all_tag.rb +7 -0
  63. metadata +1817 -1781
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 7d6b4091f7d54b2e65649f2c41aa1ae9d79ba5d45eda1f25402a977921af378b
4
- data.tar.gz: 11c42c8f504d870e6d49a823874855c88bec5cae51254b2e3246d4e6fe3b5992
3
+ metadata.gz: 392d6b1bb74f5a5a42854b8570d46f882832e03712899538e242031905f846cf
4
+ data.tar.gz: 692b7ed4b30243d0af63498ae24912a346b5720a094d54662f62ad818cace43d
5
5
  SHA512:
6
- metadata.gz: 42b67f419f6e4632f25d6b498e774627d0f7111c7d05cdab5d02fe9f33189448a7abb572b2c351d97d2ce97a22cf2cdc3e96e61b3163337a6d4e6f921c69522a
7
- data.tar.gz: 48991d86f760c6f3a1b5cd87b8a19f501a1c7ebbb5cf07c5f9164c116e999ae0e4304b92b55225e7b3ca1252ee9675e4987f5998cd627f0fa1db451ddf524b50
6
+ metadata.gz: 3ff42af86c18207426f73c76d6c74142ad47f4e2aea68d2be60d1dd5e0bbc616419437e506515f7568195a322c0282a298c4b61f17716b0ac47d35983f6fae15
7
+ data.tar.gz: 2510038577fde763eeb486cd671b3960b1b2a0990fe43badec5ce2860686801d6801fb6fc9d78c0238ceb6402f67815ac748e9009b8ef07458965caf59d68f83
@@ -99,6 +99,32 @@ en:
99
99
  A collation option is only supported if the query is executed on a MongoDB server
100
100
  with version >= 3.4."
101
101
  resolution: "Remove the collation option from the query."
102
+ in_memory_regexp_timeout:
103
+ message: "Evaluating this query in memory exceeded the %{limit} second
104
+ limit that applies to conditions containing a regular expression."
105
+ summary: "Mongoid evaluates some conditions in the calling thread
106
+ rather than sending them to the server: queries against an embedded
107
+ association, removing documents from an association by condition,
108
+ and Document#_matches?. A regular expression in such a condition
109
+ runs locally. Mongoid limits the total time one in-memory
110
+ evaluation may spend matching, because both the cost of a single
111
+ match and the number of matches performed grow with the condition,
112
+ and a pattern built from end-user input can be made to consume an
113
+ unbounded amount of CPU. The limit is cumulative over the whole
114
+ evaluation rather than per match. Where the Ruby in use offers no
115
+ per-Regexp timeout the limit is enforced as wall clock over the
116
+ whole in-memory evaluation, so there it can be exceeded by a large
117
+ scan even when the pattern itself is cheap."
118
+ resolution: "Check whether the pattern in this query comes from user
119
+ input; if it does, validate it before querying. If the query is
120
+ legitimate and simply large, raise
121
+ Mongoid::Config.in_memory_regexp_time_limit, or set it to nil to
122
+ remove the limit entirely. The limit in force is the smaller of
123
+ that setting and any global Regexp.timeout the application has set,
124
+ so check both. On JRuby, and on MRI before 3.2, there is no
125
+ per-Regexp timeout, so what the limit bounds there is the elapsed
126
+ time of the whole in-memory evaluation rather than the time spent
127
+ matching."
102
128
  invalid_config_file:
103
129
  message: "Invalid configuration file: %{path}."
104
130
  summary: "Your mongoid.yml configuration file does not contain the
@@ -11,11 +11,15 @@ module Mongoid
11
11
  included do
12
12
  class_attribute :dependents
13
13
 
14
+ # Note the leading underscore: without it, ActiveSupport's
15
+ # class_attribute would generate a helper method for this attribute
16
+ # that collides with one it generates for :dependents.
17
+ #
14
18
  # @api private
15
- class_attribute :dependents_owner
19
+ class_attribute :_dependents_owner
16
20
 
17
21
  self.dependents = []
18
- self.dependents_owner = self
22
+ self._dependents_owner = self
19
23
  end
20
24
 
21
25
  class_methods do
@@ -50,9 +54,9 @@ module Mongoid
50
54
  def self.define_dependency!(association)
51
55
  validate!(association)
52
56
  association.inverse_class.tap do |klass|
53
- if klass.dependents_owner != klass
57
+ if klass._dependents_owner != klass
54
58
  klass.dependents = []
55
- klass.dependents_owner = klass
59
+ klass._dependents_owner = klass
56
60
  end
57
61
 
58
62
  if association.dependent && !klass.dependents.include?(association)
@@ -168,7 +168,7 @@ module Mongoid
168
168
  # @param [ Hash ] attrs The single document attributes to process.
169
169
  def update_nested_relation(parent, id, attrs)
170
170
  first = existing.first
171
- converted = first ? convert_id(first.class, id) : id
171
+ converted = convert_id(first ? first.class : association.klass, id)
172
172
 
173
173
  if existing.where(_id: converted).exists?
174
174
  # document exists in association
@@ -178,11 +178,46 @@ module Mongoid
178
178
  else
179
179
  update_document(doc, attrs)
180
180
  end
181
- else
181
+ elsif association.embedded?
182
+ raise Errors::DocumentNotFound.new(association.klass, id)
183
+ elsif destroyable?(attrs)
184
+ # A destroy of a document that is not in the association is
185
+ # ignored, rather than reaching for it outside the association.
186
+ nil
187
+ elsif Mongoid.allow_reparenting_via_nested_attributes?
188
+ Mongoid::Warnings.warn_reparenting_via_nested_attributes
189
+
182
190
  # push existing document to association
183
191
  doc = association.klass.unscoped.find(converted)
192
+ # find returns nil instead of raising when
193
+ # Mongoid.raise_not_found_error is false; a missing document
194
+ # must still be an error here, consistent with the other
195
+ # not-found branches.
196
+ raise Errors::DocumentNotFound.new(association.klass, id) if doc.nil?
197
+
184
198
  update_document(doc, attrs)
185
- existing.push(doc) unless destroyable?(attrs)
199
+ existing.push(doc)
200
+ else
201
+ raise Errors::DocumentNotFound.new(association.klass, not_found_params(parent, id))
202
+ end
203
+ end
204
+
205
+ # The params to report when an id in the nested attributes could not
206
+ # be resolved within the association.
207
+ #
208
+ # @api private
209
+ #
210
+ # @param [ Document ] parent The parent document.
211
+ # @param [ String | BSON::ObjectId ] id of the related document.
212
+ #
213
+ # @return [ Hash | Object ] The params for the not found error.
214
+ def not_found_params(parent, id)
215
+ if association.is_a?(Association::Referenced::HasAndBelongsToMany)
216
+ # A many-to-many association has no foreign key on the child, so
217
+ # the id is only ever resolved within the association itself.
218
+ id
219
+ else
220
+ { _id: id, association.foreign_key => parent.id }
186
221
  end
187
222
  end
188
223
  end
@@ -53,12 +53,26 @@ module Mongoid
53
53
  # @example Convert the id.
54
54
  # builder.convert_id(Person, "4d371b444835d98b8b000010")
55
55
  #
56
+ # Ids arriving from a form are always scalars. A Hash or an Array
57
+ # here means the parameters were crafted, and letting one through
58
+ # would turn the id into a query operator, so they are rejected.
59
+ #
56
60
  # @param [ Class ] klass The class we're trying to convert for.
57
61
  # @param [ String ] id The id, usually coming from the form.
58
62
  #
59
63
  # @return [ BSON::ObjectId, String, Object ] The converted id.
64
+ #
65
+ # @raise [ Errors::DocumentNotFound ] if the id is not a scalar, or
66
+ # cannot be converted to the type the class uses for its ids.
67
+ # The BSON::Error rescue is defensive: a value that reaches
68
+ # BSON::ObjectId.mongoize and raises there must not surface as an
69
+ # unhandled BSON error in the caller.
60
70
  def convert_id(klass, id)
71
+ raise Errors::DocumentNotFound.new(klass, id) if id.is_a?(::Hash) || id.is_a?(::Array)
72
+
61
73
  klass.using_object_ids? ? BSON::ObjectId.mongoize(id) : id
74
+ rescue BSON::Error
75
+ raise Errors::DocumentNotFound.new(klass, id)
62
76
  end
63
77
  end
64
78
  end
@@ -466,13 +466,114 @@ module Mongoid
466
466
  #
467
467
  # @return [ Integer ] The number of documents deleted.
468
468
  def remove_all(conditions = nil, method = :delete_all)
469
- selector = conditions || {}
470
- removed = klass.send(method, selector.merge!(criteria.selector))
469
+ # Conjoin the conditions with the association selector so that a
470
+ # key present in both is intersected rather than overwritten. This
471
+ # also leaves the caller's Hash alone.
472
+ selector = criteria.where(conditions || {}).selector
473
+
474
+ # Scanning before the delete means scanning only what is already in
475
+ # memory, so it is only done where there is a pattern whose cost has
476
+ # to be bounded. Everywhere else the delete comes first and the scan
477
+ # sees the survivors, which is what this association has always
478
+ # done.
479
+ #
480
+ # The limit is read once and carried into whichever branch is taken.
481
+ # Letting the branch below ask again would read it a second time,
482
+ # across a server round trip, and a limit that had become positive
483
+ # in the meantime would put a deadline on the delete_if -- a query,
484
+ # and an unbind of every match -- which is the arrangement this
485
+ # branch exists to avoid.
486
+ limit = Matcher::RegexpBudget.limit_for(selector)
487
+ return remove_all_bounded(selector, method, limit) if limit
488
+
489
+ removed = klass.send(method, selector)
490
+
491
+ # No scope around this. The scan runs after the delete, so the
492
+ # association this loads comes back holding only what the delete did
493
+ # not match, and there is no pattern here to bound in any case.
494
+ # Opening a scope would save _matches? from deciding once per
495
+ # document -- 0.48us against 1.74us for the match itself -- but a
496
+ # scope with nothing to bound suppresses that decision for
497
+ # everything nested inside it, and loading the association runs
498
+ # find callbacks. A pattern in a selector one of those evaluates
499
+ # would go unguarded, which costs more than the saving is worth on a
500
+ # path that has just made two round trips.
471
501
  _target.delete_if do |doc|
472
- if doc._matches?(selector)
473
- unbind_one(doc) and true
502
+ doc._matches?(selector).tap do |b|
503
+ unbind_one(doc) if b
474
504
  end
475
505
  end
506
+
507
+ removed
508
+ end
509
+
510
+ # Deletes all related documents matching a selector that carries a
511
+ # regular expression, with the whole scan under one regexp budget.
512
+ #
513
+ # The scan runs before anything is deleted, so a budget that runs out
514
+ # leaves both the database and the association untouched rather than
515
+ # reporting a failure for a delete that has already happened. It also
516
+ # means the budget is closed by the time the association is mutated,
517
+ # so where the budget is enforced with Timeout there is no window for
518
+ # the exception to land in the middle of an unbind.
519
+ #
520
+ # @param [ Hash ] selector The selector to delete with.
521
+ # @param [ Symbol ] method The deletion method to call.
522
+ # @param [ Float ] limit The seconds the scan may spend, as read by
523
+ # the caller when it chose this path.
524
+ #
525
+ # @return [ Integer ] The number of documents deleted.
526
+ def remove_all_bounded(selector, method, limit)
527
+ # Only what the association already holds. Iterating it instead
528
+ # would load the whole association before the delete, and for a
529
+ # broad pattern that is every document the association has: /.*/ is
530
+ # both the cheapest pattern an attacker can supply and the one that
531
+ # matches everything, so bounding the cost of the matching would
532
+ # have been paid for with an unbounded amount of memory. Nothing is
533
+ # missed by not loading, because the server evaluates the same
534
+ # selector for the delete itself.
535
+ #
536
+ # It also means the scan runs no query, so no deadline of ours can
537
+ # land on one. Where the budget is enforced with Timeout, covering
538
+ # a query would report a slow network as a regexp timeout and could
539
+ # deliver the asynchronous exception inside the driver's socket
540
+ # read.
541
+ documents = _target.in_memory
542
+
543
+ matching = Matcher::RegexpBudget.open_with(limit) do
544
+ documents.select { |doc| doc._matches?(selector) }
545
+ end
546
+
547
+ removed = klass.send(method, selector)
548
+
549
+ # The ids are already known to be in memory, so the loaded and added
550
+ # documents can be dropped directly. Enumerable#delete would look
551
+ # each one up by id and stop at the first hash that has it, which
552
+ # removes the wrong instance when both hashes hold one for the same
553
+ # id. Enumerable#delete_if drops it from both, as this does, but
554
+ # only after load_all!, which is the load this scan exists to avoid.
555
+ #
556
+ # Which documents get unbound has always depended on which ones
557
+ # happened to be in memory, and scanning only what is in memory
558
+ # keeps that. It matters for has_and_belongs_to_many, whose
559
+ # unbind_one pulls the id out of the foreign key array on _base and
560
+ # marks it dirty; the scan used to run after the delete, against an
561
+ # association that a cold proxy had just reloaded as holding only
562
+ # the survivors, so nothing matched and nothing was unbound.
563
+ #
564
+ # TODO: unbinding should not depend on what was in memory. Every
565
+ # matched document leaves the association, so every one of them
566
+ # should be unbound, which would also stop _base's foreign key
567
+ # array from keeping ids that no longer resolve. That is a
568
+ # behaviour change for has_and_belongs_to_many and belongs in a
569
+ # ticket of its own, with a release note; it should not ride along
570
+ # on this one.
571
+ matching.each do |doc|
572
+ unbind_one(doc)
573
+ _target._loaded.delete(doc._id)
574
+ _target._added.delete(doc._id)
575
+ end
576
+
476
577
  removed
477
578
  end
478
579
 
@@ -22,13 +22,31 @@ module Mongoid
22
22
  # @return [ true, false ] If the document is new, or if the field is not
23
23
  # readonly.
24
24
  def attribute_writable?(name)
25
- new_record? || (!readonly_attributes.include?(name) && _loaded?(name))
25
+ return true if new_record?
26
+
27
+ readonly = self.class.readonly_attributes
28
+ return _loaded?(name) if readonly.empty?
29
+
30
+ path = self.class.readonly_field_name(name)
31
+ return false if readonly.include?(path)
32
+
33
+ readonly.each do |field|
34
+ # A readonly attribute that is a declared field with a dotted name
35
+ # is that literal field, not a path prefix.
36
+ next if field.include?('.') && self.class.fields.key?(field)
37
+
38
+ # A path that is a declared field with a dotted name addresses that
39
+ # literal field, not a descendant of the readonly attribute.
40
+ return false if path.start_with?("#{field}.") && !self.class.fields.key?(path)
41
+ end
42
+
43
+ _loaded?(name)
26
44
  end
27
45
 
28
46
  private
29
47
 
30
48
  def as_writable_attribute!(name, value = :nil)
31
- normalized_name = database_field_name(name)
49
+ normalized_name = self.class.readonly_field_name(name)
32
50
  if attribute_writable?(normalized_name)
33
51
  yield(normalized_name)
34
52
  else
@@ -64,9 +82,21 @@ module Mongoid
64
82
  # @param [ Array<Symbol> ] names The names of the fields.
65
83
  def attr_readonly(*names)
66
84
  names.each do |name|
67
- readonly_attributes << database_field_name(name)
85
+ readonly_attributes << readonly_field_name(name)
68
86
  end
69
87
  end
88
+
89
+ # Returns the database field name for a readonly attribute, also
90
+ # resolving an aliased first segment of a dotted path.
91
+ #
92
+ # @api private
93
+ def readonly_field_name(name)
94
+ name = name.to_s
95
+ return database_field_name(name) if !name.include?('.') || fields.key?(name) || aliased_fields.key?(name)
96
+
97
+ head, tail = name.split('.', 2)
98
+ "#{aliased_fields.fetch(head, head)}.#{tail}"
99
+ end
70
100
  end
71
101
  end
72
102
  end
@@ -73,6 +73,7 @@ module Mongoid
73
73
  send(update).clear
74
74
  end
75
75
  changed_attributes.clear
76
+ @pre_create_changed_attributes = nil
76
77
  end
77
78
 
78
79
  # Things that need to execute after a document has been persisted.
@@ -157,6 +158,13 @@ module Mongoid
157
158
  def attribute_changed?(attr)
158
159
  attr = database_field_name(attr)
159
160
  return false unless changed_attributes.key?(attr)
161
+ # An in-place change to a readonly attribute of a persisted document
162
+ # is not part of the dirty tracking API and will not be persisted. A
163
+ # change tracked while the document was new initializes the document,
164
+ # and new documents may set readonly attributes, so it is still
165
+ # reported as a saved change.
166
+ return false if !new_record? && self.class.readonly_attributes.include?(attr) &&
167
+ !@pre_create_changed_attributes&.include?(attr)
160
168
  changed_attributes[attr] != attributes[attr]
161
169
  end
162
170
 
@@ -194,9 +202,16 @@ module Mongoid
194
202
  #
195
203
  # @return [ Object ] The old value.
196
204
  def attribute_will_change!(attr)
197
- unless changed_attributes.key?(attr)
198
- changed_attributes[attr] = read_raw_attribute(attr).__deep_copy__
199
- end
205
+ return if changed_attributes.key?(attr)
206
+
207
+ # The snapshot is taken for readonly attributes as well. Their changes
208
+ # are hidden from the dirty tracking API (see #attribute_changed?), but
209
+ # the snapshot is needed to reset an in-place change. Changes tracked
210
+ # while the document is new initialize it, and new documents may set
211
+ # readonly attributes, so they are remembered here and still reported
212
+ # when the document is created.
213
+ (@pre_create_changed_attributes ||= ::Set.new).add(attr) if new_record?
214
+ changed_attributes[attr] = read_raw_attribute(attr).__deep_copy__
200
215
  end
201
216
 
202
217
  # Set the attribute back to its old value.
@@ -209,7 +224,10 @@ module Mongoid
209
224
  # @return [ Object ] The old value.
210
225
  def reset_attribute!(attr)
211
226
  attr = database_field_name(attr)
212
- attributes[attr] = changed_attributes.delete(attr) if attribute_changed?(attr)
227
+ return unless changed_attributes.key?(attr)
228
+ return if changed_attributes[attr] == attributes[attr]
229
+
230
+ attributes[attr] = changed_attributes.delete(attr)
213
231
  end
214
232
 
215
233
  def reset_attribute_to_default!(attr)
@@ -122,6 +122,68 @@ module Mongoid
122
122
  # always return a Hash.
123
123
  option :legacy_attributes, default: true
124
124
 
125
+ # The maximum number of seconds that evaluating a single query in memory
126
+ # may spend executing regular expressions. Queries against an embedded
127
+ # association are evaluated in the calling thread, so a pattern built from
128
+ # user input runs locally and can otherwise consume unbounded CPU. The
129
+ # limit is cumulative over the whole query, since cost grows with the
130
+ # number of documents and conditions as well as with the pattern.
131
+ #
132
+ # Set to nil to remove the limit. On Ruby 3.2 and later the remaining
133
+ # budget is compiled into the pattern, so the limit counts only the time
134
+ # spent matching. Earlier Rubies have no per-Regexp timeout, so the query
135
+ # is bounded with Timeout instead and the limit is wall clock over the
136
+ # whole in-memory evaluation.
137
+ #
138
+ # See https://jira.mongodb.org/browse/MONGOID-5981 for details.
139
+ option :in_memory_regexp_time_limit, default: 5.0
140
+
141
+ # When false (default), query operators are restricted when building a
142
+ # selector, so that user-supplied input reaching the query builder cannot
143
+ # make MongoDB execute arbitrary JavaScript. Two rules are enforced:
144
+ #
145
+ # - An operator at the top level of an expression must appear in
146
+ # +Criteria::Queryable::Selectable::ALLOWED_QUERY_OPERATORS+.
147
+ # - +$where+, +$function+, and +$accumulator+ are rejected at any depth,
148
+ # including inside +$expr+ and the logical operators.
149
+ #
150
+ # This applies to every query method that accepts an expression, including
151
+ # +where+, +find_by+, +and+, +or+, +nor+, +not+, +any_of+, and +none_of+.
152
+ # It also governs the string form of +where+, e.g.
153
+ # +where("this.name == 'admin'")+, which the server evaluates as +$where+.
154
+ # Applications relying on that form must set this option to true.
155
+ #
156
+ # The APIs that request JavaScript explicitly, +Criteria#for_js+ and
157
+ # +js_query+, are unaffected: there the developer has asked for it.
158
+ #
159
+ # Set to true to restore the unrestricted pass-through behavior.
160
+ #
161
+ # Note that this option is deliberately not tied to +load_defaults+: an
162
+ # application that has opted into older defaults still gets the guard, and
163
+ # must set this option explicitly to turn it off.
164
+ #
165
+ # See https://jira.mongodb.org/browse/MONGOID-5939,
166
+ # https://jira.mongodb.org/browse/MONGOID-5993,
167
+ # https://jira.mongodb.org/browse/MONGOID-5994 for details.
168
+ option :allow_unsafe_query_operators, default: false
169
+
170
+ # When this flag is true, it will be possible to add a record to a
171
+ # "has_many" or "has_and_belongs_to_many" association by passing that
172
+ # record's id in the nested attributes for another parent record, even
173
+ # when the record does not already belong to that association. For a
174
+ # "has_many" association this moves the record to the new parent.
175
+ #
176
+ # When this flag is false, an id in nested attributes is only resolved
177
+ # within the association itself, and anything else raises an error.
178
+ #
179
+ # The default is `false`. Note that allowing reparenting via nested attributes
180
+ # is a potential security risk, since it could allow a malicious user to move
181
+ # records that they do not own to a parent record that they do own.
182
+ #
183
+ # This option will be removed in Mongoid 10, and the only behavior will be
184
+ # as if this option were set to false.
185
+ option :allow_reparenting_via_nested_attributes, default: false
186
+
125
187
  # Has Mongoid been configured? This is checking that at least a valid
126
188
  # client config exists.
127
189
  #
@@ -1,10 +1,13 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require 'mongoid/field_readable'
4
+
3
5
  module Mongoid
4
6
  module Contextual
5
7
  module Aggregable
6
8
  # Contains behavior for aggregating values in memory.
7
9
  module Memory
10
+ include FieldReadable
8
11
 
9
12
  # Get all the aggregate values for the provided field.
10
13
  # Provided for interface consistency with Aggregable::Mongo.
@@ -88,7 +91,7 @@ module Mongoid
88
91
  if block_given?
89
92
  super()
90
93
  else
91
- count > 0 ? super(0) { |doc| doc.public_send(field) } : 0
94
+ count > 0 ? map { |doc| read_field_value(doc, field) }.compact.sum : 0
92
95
  end
93
96
  end
94
97
 
@@ -106,7 +109,10 @@ module Mongoid
106
109
  #
107
110
  # @return [ Integer ] The aggregate.
108
111
  def aggregate_by(field, method)
109
- count > 0 ? send(method) { |doc| doc.public_send(field) }.public_send(field) : nil
112
+ return nil if count == 0
113
+
114
+ doc = send(method) { |doc| read_field_value(doc, field) }
115
+ read_field_value(doc, field)
110
116
  end
111
117
  end
112
118
  end
@@ -2,6 +2,7 @@
2
2
 
3
3
  require "mongoid/contextual/aggregable/memory"
4
4
  require "mongoid/association/eager_loadable"
5
+ require "mongoid/field_readable"
5
6
 
6
7
  module Mongoid
7
8
  module Contextual
@@ -11,6 +12,7 @@ module Mongoid
11
12
  include Association::EagerLoadable
12
13
  include Queryable
13
14
  include Positional
15
+ include FieldReadable
14
16
 
15
17
  # @attribute [r] root The root document.
16
18
  # @attribute [r] path The atomic path.
@@ -79,7 +81,7 @@ module Mongoid
79
81
  # @return [ Array<Object> ] The distinct values for the field.
80
82
  def distinct(field)
81
83
  if Mongoid.legacy_pluck_distinct
82
- documents.map{ |doc| doc.send(field) }.uniq
84
+ documents.map { |doc| read_field_value(doc, field) }.uniq
83
85
  else
84
86
  pluck(field).uniq
85
87
  end
@@ -142,10 +144,20 @@ module Mongoid
142
144
  # @param [ Criteria ] criteria The criteria.
143
145
  def initialize(criteria)
144
146
  @criteria, @klass = criteria, criteria.klass
145
- @documents = criteria.documents.select do |doc|
146
- @root ||= doc._root
147
- @collection ||= root.collection
148
- doc._matches?(criteria.selector)
147
+
148
+ # Resolving the collection can build a Mongo::Client the first time it
149
+ # runs, so it happens before the budget opens. Where the budget is
150
+ # enforced with Timeout the exception is asynchronous, and landing in
151
+ # the middle of that would leave a half-built client behind.
152
+ if (first = criteria.documents.first)
153
+ @root = first._root
154
+ @collection = @root.collection
155
+ end
156
+
157
+ # One regexp budget covers the whole scan, so that the limit bounds the
158
+ # query rather than each document individually.
159
+ @documents = Matcher::RegexpBudget.open(criteria.selector) do
160
+ criteria.documents.select { |doc| doc._matches?(criteria.selector) }
149
161
  end
150
162
  apply_sorting
151
163
  apply_options
@@ -523,11 +535,10 @@ module Mongoid
523
535
  # _translations hash so that we can get the specified translation in
524
536
  # the remaining
525
537
  if field&.localized?
526
- document.send("#{segment}_translations")
538
+ document.public_send("#{segment}_translations")
527
539
  end
528
540
  end
529
- meth = klass.aliased_associations[segment] || segment
530
- res.nil? ? document.try(meth) : res
541
+ res.nil? ? read_field_value(document, segment) : res
531
542
  elsif document.is_a?(Hash)
532
543
  # TODO: Remove the indifferent access when implementing MONGOID-5410.
533
544
  document.key?(segment.to_s) ?
@@ -45,6 +45,31 @@ module Mongoid
45
45
  other.is_a?(None)
46
46
  end
47
47
 
48
+ # Delete all documents in the database that match the selector. There
49
+ # are no documents in the null context, so nothing is deleted.
50
+ #
51
+ # @example Delete all the documents.
52
+ # context.delete
53
+ #
54
+ # @return [ Integer ] Always zero.
55
+ def delete
56
+ 0
57
+ end
58
+ alias delete_all delete
59
+
60
+ # Destroy all documents in the database that match the selector. There
61
+ # are no documents in the null context, so nothing is destroyed and no
62
+ # callbacks are run.
63
+ #
64
+ # @example Destroy all the documents.
65
+ # context.destroy
66
+ #
67
+ # @return [ Integer ] Always zero.
68
+ def destroy
69
+ 0
70
+ end
71
+ alias destroy_all destroy
72
+
48
73
  # Get the distinct field values in null context.
49
74
  #
50
75
  # @example Get the distinct values in null context.
@@ -95,6 +120,32 @@ module Mongoid
95
120
  []
96
121
  end
97
122
 
123
+ # Update the first matching document atomically. There are no documents
124
+ # in the null context, so nothing is updated.
125
+ #
126
+ # @example Update the matching document.
127
+ # context.update(name: "Smiths")
128
+ #
129
+ # @param [ Hash ] attributes The new attributes for the document.
130
+ #
131
+ # @return [ nil | false ] False if no attributes were provided.
132
+ def update(attributes = nil, _opts = {})
133
+ attributes ? nil : false
134
+ end
135
+
136
+ # Update all the matching documents atomically. There are no documents
137
+ # in the null context, so nothing is updated.
138
+ #
139
+ # @example Update all the matching documents.
140
+ # context.update_all(name: "Smiths")
141
+ #
142
+ # @param [ Hash ] attributes The new attributes for each document.
143
+ #
144
+ # @return [ nil | false ] False if no attributes were provided.
145
+ def update_all(attributes = nil, _opts = {})
146
+ attributes ? nil : false
147
+ end
148
+
98
149
  # Create the new null context.
99
150
  #
100
151
  # @example Create the new context.
@@ -325,6 +325,10 @@ module Mongoid
325
325
  end
326
326
  end
327
327
  end
328
+ # Every query method that takes a user-supplied expression normalizes
329
+ # it here, so this is where the operator guard is enforced. See
330
+ # Selectable#_mongoid_validate_operators! for what it does not cover.
331
+ _mongoid_validate_operators!(result)
328
332
  result
329
333
  end
330
334
 
@@ -343,6 +347,14 @@ module Mongoid
343
347
  if criterion.is_a?(Selectable)
344
348
  criterion = criterion.selector
345
349
  end
350
+
351
+ # The __override__ path writes to the selector directly, so it
352
+ # bypasses _mongoid_expand_keys where the operator guard normally
353
+ # runs. Enforce the guard here so chained override methods
354
+ # (elem_match, exists, eq, gt, in, etc.) cannot smuggle $where or
355
+ # other JavaScript operators under strict mode.
356
+ _mongoid_validate_operators!(criterion)
357
+
346
358
  selection(criterion) do |selector, field, value|
347
359
  expression = prepare(field, operator, value)
348
360
  existing = selector[field]