mongoid 8.1.12 → 8.1.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 (57) 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 +103 -2
  7. data/lib/mongoid/attributes/readonly.rb +19 -1
  8. data/lib/mongoid/changeable.rb +22 -4
  9. data/lib/mongoid/config.rb +62 -0
  10. data/lib/mongoid/contextual/aggregable/memory.rb +5 -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 +109 -0
  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/associations/has_and_belongs_to_many_spec.rb +17 -2
  32. data/spec/integration/dots_and_dollars_spec.rb +12 -2
  33. data/spec/integration/matcher_operator_data/regex.yml +21 -0
  34. data/spec/integration/matcher_regexp_timeout_spec.rb +215 -0
  35. data/spec/integration/query_operator_guard_spec.rb +89 -0
  36. data/spec/mongoid/association/referenced/has_and_belongs_to_many/proxy_spec.rb +96 -0
  37. data/spec/mongoid/association/referenced/has_many/proxy_spec.rb +228 -0
  38. data/spec/mongoid/attributes/nested_spec.rb +204 -10
  39. data/spec/mongoid/attributes/readonly_dotted_spec.rb +332 -0
  40. data/spec/mongoid/attributes/readonly_spec.rb +389 -0
  41. data/spec/mongoid/changeable_spec.rb +18 -0
  42. data/spec/mongoid/config_spec.rb +7 -0
  43. data/spec/mongoid/contextual/aggregable/memory_spec.rb +91 -0
  44. data/spec/mongoid/contextual/memory_spec.rb +202 -0
  45. data/spec/mongoid/contextual/none_spec.rb +22 -5
  46. data/spec/mongoid/criteria/queryable/selectable_logical_spec.rb +2 -0
  47. data/spec/mongoid/criteria/queryable/selectable_where_spec.rb +235 -0
  48. data/spec/mongoid/criteria_spec.rb +19 -0
  49. data/spec/mongoid/findable_spec.rb +14 -0
  50. data/spec/mongoid/matcher/regexp_budget_spec.rb +576 -0
  51. data/spec/mongoid/scopable_spec.rb +116 -2
  52. data/spec/spec_helper.rb +8 -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. metadata +1900 -1860
@@ -822,6 +822,12 @@ module Mongoid
822
822
  # only ever specify one criterion to #where.
823
823
  @criterion = criterion
824
824
  if criterion.is_a?(String)
825
+ unless Mongoid.allow_unsafe_query_operators?
826
+ raise Errors::InvalidQuery,
827
+ "String criteria are not allowed because they compile to the '$where' operator, " \
828
+ 'which is not allowed in a query expression. Set Mongoid.allow_unsafe_query_operators = true ' \
829
+ 'to permit all operators.'
830
+ end
825
831
  js_query(criterion)
826
832
  else
827
833
  expr_query(criterion)
@@ -831,6 +837,19 @@ module Mongoid
831
837
 
832
838
  private
833
839
 
840
+ # Operators permitted at the top level of a query expression without
841
+ # opt-in. Excludes $where (JS execution) and other operators not needed
842
+ # for ordinary application queries.
843
+ ALLOWED_QUERY_OPERATORS = %w[
844
+ $and $or $nor $not $text $comment $expr $jsonSchema $alwaysFalse $alwaysTrue
845
+ ].freeze
846
+
847
+ # Operators that execute server-side JavaScript. These are rejected at
848
+ # any depth, not just at the top level: the allowlist above permits
849
+ # $expr and the logical operators, and their values are arbitrary
850
+ # nested expressions that can carry $function or $where.
851
+ JAVASCRIPT_QUERY_OPERATORS = %w[$where $function $accumulator].freeze
852
+
834
853
  # Adds the specified expression to the query.
835
854
  #
836
855
  # Criterion must be a hash in one of the following forms:
@@ -856,6 +875,8 @@ module Mongoid
856
875
  raise Errors::InvalidQuery, "Expression must be a Hash: #{Errors::InvalidQuery.truncate_expr(criterion)}"
857
876
  end
858
877
 
878
+ # The operator guard is applied by _mongoid_expand_keys, which every
879
+ # query method that accepts a user-supplied expression passes through.
859
880
  normalized = _mongoid_expand_keys(criterion)
860
881
  clone.tap do |query|
861
882
  normalized.each do |field, value|
@@ -871,6 +892,94 @@ module Mongoid
871
892
  end
872
893
  end
873
894
 
895
+ # Enforces the operator rules governed by the
896
+ # +allow_unsafe_query_operators+ configuration option against a
897
+ # normalized query expression.
898
+ #
899
+ # Two rules apply, and both are skipped when the option is true:
900
+ #
901
+ # - An operator at the top level of the expression must appear in
902
+ # ALLOWED_QUERY_OPERATORS.
903
+ # - An operator in JAVASCRIPT_QUERY_OPERATORS is rejected at any depth.
904
+ #
905
+ # This is called from #_mongoid_expand_keys rather than from the
906
+ # individual query methods, because that is the one point every query
907
+ # method taking a user-supplied expression passes through on its way to
908
+ # the selector.
909
+ #
910
+ # It deliberately does not cover the APIs that ask for JavaScript
911
+ # outright, such as #js_query and Criteria#for_js: there the developer
912
+ # has chosen server-side JavaScript, so there is nothing to guard
913
+ # against. The same goes for the low-level Storable methods
914
+ # (#add_field_expression, #add_operator_expression), which write to the
915
+ # selector directly.
916
+ #
917
+ # @param [ Hash ] expr A normalized query expression.
918
+ #
919
+ # @raise [ Errors::InvalidQuery ] If a disallowed operator is present.
920
+ #
921
+ # @api private
922
+ def _mongoid_validate_operators!(expr)
923
+ return if Mongoid.allow_unsafe_query_operators?
924
+
925
+ expr.each_key do |field|
926
+ field_s = field.to_s
927
+ next unless field_s.start_with?('$')
928
+ next if ALLOWED_QUERY_OPERATORS.include?(field_s)
929
+
930
+ raise Errors::InvalidQuery,
931
+ "Operator '#{field_s}' is not allowed in a query expression. " \
932
+ 'Set Mongoid.allow_unsafe_query_operators = true to permit all operators.'
933
+ end
934
+
935
+ _mongoid_validate_no_javascript!(expr)
936
+ end
937
+
938
+ # Walks a query expression looking for operators that execute
939
+ # server-side JavaScript, descending through both hashes and arrays so
940
+ # that nested forms such as {'$expr' => {'$function' => ...}} and
941
+ # {'$or' => [ {'$where' => ...} ]} are caught.
942
+ #
943
+ # The walk does not distinguish operator position from value position,
944
+ # so it also rejects queries where a JavaScript operator name appears as
945
+ # data rather than as an operator. Server 5.0+ permits $-prefixed field
946
+ # names in stored documents, which makes this reachable:
947
+ #
948
+ # Doc.where(payload: { '$eq' => { '$function' => 'abc' } })
949
+ #
950
+ # Here the $eq marks its argument as a literal value to compare, so the
951
+ # server never evaluates it, but the guard raises anyway. The only
952
+ # workaround today is the global allow_unsafe_query_operators flag.
953
+ #
954
+ # TODO: discuss whether to track operator position (skipping the subtree
955
+ # under $eq, $ne, $in, $nin, and $elemMatch values) in a future
956
+ # iteration. It removes the false positive but adds exactly the kind of
957
+ # state that a real bypass could hide in, so it was left out for now.
958
+ #
959
+ # @param [ Object ] object A fragment of a query expression.
960
+ #
961
+ # @raise [ Errors::InvalidQuery ] If a JavaScript operator is present.
962
+ #
963
+ # @api private
964
+ def _mongoid_validate_no_javascript!(object)
965
+ case object
966
+ when Hash
967
+ object.each do |key, value|
968
+ key_s = key.to_s
969
+ if JAVASCRIPT_QUERY_OPERATORS.include?(key_s)
970
+ raise Errors::InvalidQuery,
971
+ "Operator '#{key_s}' executes server-side JavaScript and is not allowed " \
972
+ 'anywhere in a query expression. Set Mongoid.allow_unsafe_query_operators = true ' \
973
+ 'to permit all operators.'
974
+ end
975
+
976
+ _mongoid_validate_no_javascript!(value)
977
+ end
978
+ when Array
979
+ object.each { |value| _mongoid_validate_no_javascript!(value) }
980
+ end
981
+ end
982
+
874
983
  # Force the values of the criterion to be evolved.
875
984
  #
876
985
  # @api private
@@ -11,9 +11,13 @@ module Mongoid
11
11
  #
12
12
  # @return [ Criteria ] The criteria.
13
13
  def apply_default_scope
14
+ explicit_none = none_state == true
14
15
  klass.without_default_scope do
15
16
  merge!(klass.default_scoping.call)
16
17
  end
18
+ # A none coming from the default scope is not an explicit none, so it
19
+ # may be removed by unscoping.
20
+ @none = :default if !explicit_none && @none
17
21
  self.scoping_options = true, false
18
22
  end
19
23
 
@@ -98,7 +102,9 @@ module Mongoid
98
102
  crit = clone
99
103
  unless unscoped?
100
104
  crit.scoping_options = false, true
101
- crit.selector.clear; crit.options.clear
105
+ crit.selector.clear
106
+ crit.options.clear
107
+ crit.send(:clear_default_scope_none)
102
108
  end
103
109
  crit
104
110
  end
@@ -256,6 +256,20 @@ module Mongoid
256
256
  self.documents = criteria.documents.dup unless criteria.documents.empty?
257
257
  self.scoping_options = criteria.scoping_options
258
258
  self.inclusions = (inclusions + criteria.inclusions).uniq
259
+ if criteria.empty_and_chainable?
260
+ # An explicit none wins over a none that only came from a default
261
+ # scope. Association proxies forward is_a? to their target, so the
262
+ # runtime class is checked instead; anything that is not a criteria is
263
+ # treated as an explicit none.
264
+ explicit = if Criteria === criteria # rubocop:disable Style/CaseEquality
265
+ criteria.send(:none_state) == true
266
+ else
267
+ true
268
+ end
269
+ @none = true if @none == true || explicit
270
+ @none ||= :default
271
+ @context = nil
272
+ end
259
273
  self
260
274
  end
261
275
 
@@ -267,7 +281,9 @@ module Mongoid
267
281
  #
268
282
  # @return [ Criteria ] The none criteria.
269
283
  def none
270
- @none = true and self
284
+ @none = true
285
+ @context = nil
286
+ self
271
287
  end
272
288
 
273
289
  # Is the criteria an empty but chainable criteria?
@@ -449,6 +465,34 @@ module Mongoid
449
465
 
450
466
  private
451
467
 
468
+ # The kind of none on this criteria, if any. An explicit none is +true+,
469
+ # a none coming only from the default scope is +:default+, and a criteria
470
+ # that is not none returns +nil+.
471
+ #
472
+ # @api private
473
+ #
474
+ # @example Get the none state.
475
+ # criteria.send(:none_state)
476
+ #
477
+ # @return [ true | :default | nil ] The none state.
478
+ def none_state
479
+ @none
480
+ end
481
+
482
+ # Removes the none flag if it was set only by the default scope. An
483
+ # explicitly requested none is never removed.
484
+ #
485
+ # @api private
486
+ #
487
+ # @example Clear a default scope none.
488
+ # criteria.send(:clear_default_scope_none)
489
+ #
490
+ # @return [ Criteria ] The criteria.
491
+ def clear_default_scope_none
492
+ @none = nil if @none == :default
493
+ self
494
+ end
495
+
452
496
  # Are documents in the query missing, and are we configured to raise an
453
497
  # error?
454
498
  #
@@ -193,6 +193,12 @@ module Mongoid
193
193
  new_errors.copy!(errors)
194
194
  became.instance_variable_set(:@errors, new_errors)
195
195
  became.instance_variable_set(:@new_record, new_record?)
196
+ # The document was constructed as new, collecting pre-create change
197
+ # markers. Drop them when the copied state is that of a persisted
198
+ # document: its pending changes were all tracked after the document
199
+ # was persisted, and stale markers would let in-place changes to
200
+ # readonly attributes bypass the dirty filter.
201
+ became.instance_variable_set(:@pre_create_changed_attributes, nil) unless new_record?
196
202
  became.instance_variable_set(:@destroyed, destroyed?)
197
203
  became.changed_attributes[klass.discriminator_key] = self.class.discriminator_value
198
204
  became[klass.discriminator_key] = klass.discriminator_value
@@ -203,6 +209,10 @@ module Mongoid
203
209
  relation = became.__send__(name)
204
210
  Array.wrap(relation).each do |r|
205
211
  r.instance_variable_set(:@new_record, new_record?)
212
+ # The embedded documents were also constructed as new; drop
213
+ # their pre-create change markers when they are marked as
214
+ # persisted, as is done for the parent document.
215
+ r.instance_variable_set(:@pre_create_changed_attributes, nil) unless new_record?
206
216
  end
207
217
  end
208
218
  end
@@ -0,0 +1,26 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Mongoid
4
+ module Errors
5
+ # This error is raised when evaluating a query in memory exceeds
6
+ # Mongoid::Config.in_memory_regexp_time_limit.
7
+ #
8
+ # What the limit bounds depends on the Ruby in use. Where per-Regexp
9
+ # timeouts are available it is the time spent executing regular
10
+ # expressions; elsewhere it is the elapsed time of the whole in-memory
11
+ # evaluation. The message is worded to hold either way.
12
+ class InMemoryRegexpTimeout < MongoidError
13
+ # Create the new error.
14
+ #
15
+ # @example Create the new in-memory regexp timeout error.
16
+ # InMemoryRegexpTimeout.new(5.0)
17
+ #
18
+ # @param [ Float ] limit The limit that was exceeded, in seconds. Not
19
+ # always the configured one: a global Regexp.timeout stricter than the
20
+ # configuration takes its place.
21
+ def initialize(limit)
22
+ super(compose_message('in_memory_regexp_timeout', limit: limit))
23
+ end
24
+ end
25
+ end
26
+ end
@@ -10,6 +10,7 @@ require "mongoid/errors/document_not_found"
10
10
  require "mongoid/errors/empty_config_file"
11
11
  require "mongoid/errors/immutable_attribute"
12
12
  require "mongoid/errors/in_memory_collation_not_supported"
13
+ require "mongoid/errors/in_memory_regexp_timeout"
13
14
  require "mongoid/errors/invalid_async_query_executor"
14
15
  require "mongoid/errors/invalid_collection"
15
16
  require "mongoid/errors/invalid_config_file"
@@ -0,0 +1,70 @@
1
+ # frozen_string_literal: true
2
+ # rubocop:todo all
3
+
4
+ module Mongoid
5
+ # Reads the value of a field name from a document without dispatching the
6
+ # name as an arbitrary method.
7
+ #
8
+ # Field names may come from application input, where a name like +destroy+
9
+ # or +attributes+ would delete the document or disclose its contents.
10
+ # Declared field and association names are validated when they are declared
11
+ # (see Mongoid.destructive_fields), so a name that resolves to one of them
12
+ # is safe to send to a document. Any other name is read from the attributes
13
+ # hash, which is what the database-backed query contexts do.
14
+ #
15
+ # @api private
16
+ module FieldReadable
17
+ private
18
+
19
+ # Read the value of the given field name from the given document.
20
+ #
21
+ # @param [ Document ] document The document to read from.
22
+ # @param [ String | Symbol ] name The name of the field.
23
+ #
24
+ # @return [ Object | nil ] The value of the field, or nil when the name
25
+ # is neither a declared field nor present in the attributes.
26
+ def read_field_value(document, name)
27
+ name = name.to_s
28
+ # A blank name cannot name a field. Return nil, which is what reading
29
+ # one has always done.
30
+ return nil if name.blank?
31
+
32
+ if (meth = readable_method_for(document.class, name))
33
+ document.public_send(meth)
34
+ else
35
+ document.attributes[document.class.database_field_name(name)]
36
+ end
37
+ end
38
+
39
+ # Resolve the given name to a method that is declared by the given class,
40
+ # and therefore safe to send to one of its instances.
41
+ #
42
+ # @param [ Class ] klass The document class.
43
+ # @param [ String ] name The name of the field.
44
+ #
45
+ # @return [ String | nil ] The method to send, or nil when the name is
46
+ # not declared by the class.
47
+ def readable_method_for(klass, name)
48
+ # Fields, associations, and field aliases each define a reader of their
49
+ # own name. Note that associations must be resolved before aliases: a
50
+ # belongs_to aliases its own name to its foreign key, and reading
51
+ # `band` must give the document, not the id.
52
+ return name if klass.relations.key?(name) ||
53
+ klass.fields.key?(name) ||
54
+ klass.aliased_fields.key?(name)
55
+
56
+ # An association may also be named by its `store_as`, which has no
57
+ # reader of its own, or by its ids accessor, which does.
58
+ if (assoc = klass.relations[klass.aliased_associations[name]])
59
+ return (assoc.store_as == name) ? assoc.name.to_s : name
60
+ end
61
+
62
+ # Localized fields also get a _translations reader, which does not
63
+ # appear in the fields hash.
64
+ base = name.delete_suffix(Fields::TRANSLATIONS_SFX)
65
+ return nil if base == name
66
+
67
+ name if klass.fields[klass.database_field_name(base)]&.localized?
68
+ end
69
+ end
70
+ end
@@ -17,7 +17,12 @@ module Mongoid
17
17
  #
18
18
  # @return [ true | false ] True if matches, false if not.
19
19
  def _matches?(selector)
20
- Matcher::Expression.matches?(self, selector)
20
+ # Opens a regexp budget for this document only. Callers that match many
21
+ # documents against one selector open a budget of their own first, and
22
+ # this one joins it rather than giving every document a fresh limit.
23
+ Matcher::RegexpBudget.open(selector) do
24
+ Matcher::Expression.matches?(self, selector)
25
+ end
21
26
  end
22
27
  end
23
28
  end
@@ -6,12 +6,10 @@ module Mongoid
6
6
  #
7
7
  # @api private
8
8
  module EqImplWithRegexp
9
- module_function def matches?(original_operator, value, condition)
9
+ module_function def matches?(_original_operator, value, condition)
10
10
  case condition
11
- when Regexp
12
- value =~ condition
13
- when ::BSON::Regexp::Raw
14
- value =~ condition.compile
11
+ when Regexp, ::BSON::Regexp::Raw
12
+ value.respond_to?(:=~) && RegexpBudget.match?(value, condition)
15
13
  else
16
14
  if Mongoid.compare_time_by_ms &&
17
15
  value.kind_of?(Time) && condition.kind_of?(Time)
@@ -3,25 +3,24 @@ module Mongoid
3
3
 
4
4
  # @api private
5
5
  module Regex
6
- module_function def matches?(exists, value, condition)
7
- condition = case condition
8
- when Regexp
9
- condition
10
- when BSON::Regexp::Raw
11
- condition.compile
12
- else
6
+ module_function def matches?(_exists, value, condition)
7
+ unless condition.is_a?(Regexp) || condition.is_a?(BSON::Regexp::Raw)
13
8
  # Note that strings must have been converted to a regular expression
14
9
  # instance already (with $options taken into account, if provided).
15
10
  raise Errors::InvalidQuery, "$regex requires a regular expression argument: #{Errors::InvalidQuery.truncate_expr(condition)}"
16
11
  end
17
12
 
13
+ # The condition is compiled by RegexpBudget rather than here, so that
14
+ # the budget's timeout can be baked into the pattern.
18
15
  case value
19
16
  when Array
17
+ # Object#=~ is gone as of Ruby 3.2, so an element that cannot be
18
+ # matched against has to be rejected rather than passed to =~.
20
19
  value.any? do |v|
21
- v =~ condition
20
+ v.respond_to?(:=~) && RegexpBudget.match?(v, condition)
22
21
  end
23
22
  when String
24
- value =~ condition
23
+ RegexpBudget.match?(value, condition)
25
24
  else
26
25
  false
27
26
  end