mongoid 8.0.12 → 8.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 (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 +387 -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 +18 -0
  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 +1862 -1826
@@ -791,6 +791,12 @@ module Mongoid
791
791
  # only ever specify one criterion to #where.
792
792
  @criterion = criterion
793
793
  if criterion.is_a?(String)
794
+ unless Mongoid.allow_unsafe_query_operators?
795
+ raise Errors::InvalidQuery,
796
+ "String criteria are not allowed because they compile to the '$where' operator, " \
797
+ 'which is not allowed in a query expression. Set Mongoid.allow_unsafe_query_operators = true ' \
798
+ 'to permit all operators.'
799
+ end
794
800
  js_query(criterion)
795
801
  else
796
802
  expr_query(criterion)
@@ -800,6 +806,19 @@ module Mongoid
800
806
 
801
807
  private
802
808
 
809
+ # Operators permitted at the top level of a query expression without
810
+ # opt-in. Excludes $where (JS execution) and other operators not needed
811
+ # for ordinary application queries.
812
+ ALLOWED_QUERY_OPERATORS = %w[
813
+ $and $or $nor $not $text $comment $expr $jsonSchema $alwaysFalse $alwaysTrue
814
+ ].freeze
815
+
816
+ # Operators that execute server-side JavaScript. These are rejected at
817
+ # any depth, not just at the top level: the allowlist above permits
818
+ # $expr and the logical operators, and their values are arbitrary
819
+ # nested expressions that can carry $function or $where.
820
+ JAVASCRIPT_QUERY_OPERATORS = %w[$where $function $accumulator].freeze
821
+
803
822
  # Adds the specified expression to the query.
804
823
  #
805
824
  # Criterion must be a hash in one of the following forms:
@@ -825,6 +844,8 @@ module Mongoid
825
844
  raise Errors::InvalidQuery, "Expression must be a Hash: #{Errors::InvalidQuery.truncate_expr(criterion)}"
826
845
  end
827
846
 
847
+ # The operator guard is applied by _mongoid_expand_keys, which every
848
+ # query method that accepts a user-supplied expression passes through.
828
849
  normalized = _mongoid_expand_keys(criterion)
829
850
  clone.tap do |query|
830
851
  normalized.each do |field, value|
@@ -840,6 +861,94 @@ module Mongoid
840
861
  end
841
862
  end
842
863
 
864
+ # Enforces the operator rules governed by the
865
+ # +allow_unsafe_query_operators+ configuration option against a
866
+ # normalized query expression.
867
+ #
868
+ # Two rules apply, and both are skipped when the option is true:
869
+ #
870
+ # - An operator at the top level of the expression must appear in
871
+ # ALLOWED_QUERY_OPERATORS.
872
+ # - An operator in JAVASCRIPT_QUERY_OPERATORS is rejected at any depth.
873
+ #
874
+ # This is called from #_mongoid_expand_keys rather than from the
875
+ # individual query methods, because that is the one point every query
876
+ # method taking a user-supplied expression passes through on its way to
877
+ # the selector.
878
+ #
879
+ # It deliberately does not cover the APIs that ask for JavaScript
880
+ # outright, such as #js_query and Criteria#for_js: there the developer
881
+ # has chosen server-side JavaScript, so there is nothing to guard
882
+ # against. The same goes for the low-level Storable methods
883
+ # (#add_field_expression, #add_operator_expression), which write to the
884
+ # selector directly.
885
+ #
886
+ # @param [ Hash ] expr A normalized query expression.
887
+ #
888
+ # @raise [ Errors::InvalidQuery ] If a disallowed operator is present.
889
+ #
890
+ # @api private
891
+ def _mongoid_validate_operators!(expr)
892
+ return if Mongoid.allow_unsafe_query_operators?
893
+
894
+ expr.each_key do |field|
895
+ field_s = field.to_s
896
+ next unless field_s.start_with?('$')
897
+ next if ALLOWED_QUERY_OPERATORS.include?(field_s)
898
+
899
+ raise Errors::InvalidQuery,
900
+ "Operator '#{field_s}' is not allowed in a query expression. " \
901
+ 'Set Mongoid.allow_unsafe_query_operators = true to permit all operators.'
902
+ end
903
+
904
+ _mongoid_validate_no_javascript!(expr)
905
+ end
906
+
907
+ # Walks a query expression looking for operators that execute
908
+ # server-side JavaScript, descending through both hashes and arrays so
909
+ # that nested forms such as {'$expr' => {'$function' => ...}} and
910
+ # {'$or' => [ {'$where' => ...} ]} are caught.
911
+ #
912
+ # The walk does not distinguish operator position from value position,
913
+ # so it also rejects queries where a JavaScript operator name appears as
914
+ # data rather than as an operator. Server 5.0+ permits $-prefixed field
915
+ # names in stored documents, which makes this reachable:
916
+ #
917
+ # Doc.where(payload: { '$eq' => { '$function' => 'abc' } })
918
+ #
919
+ # Here the $eq marks its argument as a literal value to compare, so the
920
+ # server never evaluates it, but the guard raises anyway. The only
921
+ # workaround today is the global allow_unsafe_query_operators flag.
922
+ #
923
+ # TODO: discuss whether to track operator position (skipping the subtree
924
+ # under $eq, $ne, $in, $nin, and $elemMatch values) in a future
925
+ # iteration. It removes the false positive but adds exactly the kind of
926
+ # state that a real bypass could hide in, so it was left out for now.
927
+ #
928
+ # @param [ Object ] object A fragment of a query expression.
929
+ #
930
+ # @raise [ Errors::InvalidQuery ] If a JavaScript operator is present.
931
+ #
932
+ # @api private
933
+ def _mongoid_validate_no_javascript!(object)
934
+ case object
935
+ when Hash
936
+ object.each do |key, value|
937
+ key_s = key.to_s
938
+ if JAVASCRIPT_QUERY_OPERATORS.include?(key_s)
939
+ raise Errors::InvalidQuery,
940
+ "Operator '#{key_s}' executes server-side JavaScript and is not allowed " \
941
+ 'anywhere in a query expression. Set Mongoid.allow_unsafe_query_operators = true ' \
942
+ 'to permit all operators.'
943
+ end
944
+
945
+ _mongoid_validate_no_javascript!(value)
946
+ end
947
+ when Array
948
+ object.each { |value| _mongoid_validate_no_javascript!(value) }
949
+ end
950
+ end
951
+
843
952
  # Force the values of the criterion to be evolved.
844
953
  #
845
954
  # @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?
@@ -448,6 +464,34 @@ module Mongoid
448
464
 
449
465
  private
450
466
 
467
+ # The kind of none on this criteria, if any. An explicit none is +true+,
468
+ # a none coming only from the default scope is +:default+, and a criteria
469
+ # that is not none returns +nil+.
470
+ #
471
+ # @api private
472
+ #
473
+ # @example Get the none state.
474
+ # criteria.send(:none_state)
475
+ #
476
+ # @return [ true | :default | nil ] The none state.
477
+ def none_state
478
+ @none
479
+ end
480
+
481
+ # Removes the none flag if it was set only by the default scope. An
482
+ # explicitly requested none is never removed.
483
+ #
484
+ # @api private
485
+ #
486
+ # @example Clear a default scope none.
487
+ # criteria.send(:clear_default_scope_none)
488
+ #
489
+ # @return [ Criteria ] The criteria.
490
+ def clear_default_scope_none
491
+ @none = nil if @none == :default
492
+ self
493
+ end
494
+
451
495
  # Are documents in the query missing, and are we configured to raise an
452
496
  # error?
453
497
  #
@@ -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
@@ -8,6 +8,7 @@ require "mongoid/errors/document_not_destroyed"
8
8
  require "mongoid/errors/document_not_found"
9
9
  require "mongoid/errors/empty_config_file"
10
10
  require "mongoid/errors/in_memory_collation_not_supported"
11
+ require "mongoid/errors/in_memory_regexp_timeout"
11
12
  require "mongoid/errors/invalid_collection"
12
13
  require "mongoid/errors/invalid_config_file"
13
14
  require "mongoid/errors/invalid_config_option"
@@ -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