Class: RuboCop::Cop::Betterment::UnscopedFind

Inherits:
RuboCop::Cop
  • Object
show all
Defined in:
lib/rubocop/cop/betterment/unscoped_find.rb

Constant Summary collapse

MSG =
<<~MSG
  Records are being retrieved directly using user input.
  Please query for the associated record in a way that enforces authorization (e.g. "trust-root chaining").

  INSTEAD OF THIS:
  Post.find(params[:post_id])

  DO THIS:
  current_user.posts.find(params[:post_id])

  See here for more information on this error:
  https://github.com/Betterment/betterlint/blob/main/README.md#bettermentunscopedfind
MSG
METHOD_PATTERN =
/^find_by_(.+?)(!)?$/
FINDS =
%i(find find_by find_by! where).freeze
GRAPHQL_PATTERN =
/\bGraphQL\b/i

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config = nil, options = nil) ⇒ UnscopedFind

Returns a new instance of UnscopedFind.



38
39
40
41
42
# File 'lib/rubocop/cop/betterment/unscoped_find.rb', line 38

def initialize(config = nil, options = nil)
  super(config, options)
  config = @config.for_cop(self)
  @unauthenticated_models = config.fetch("unauthenticated_models", []).map(&:to_sym)
end

Instance Attribute Details

#unauthenticated_modelsObject

Returns the value of attribute unauthenticated_models.



7
8
9
# File 'lib/rubocop/cop/betterment/unscoped_find.rb', line 7

def unauthenticated_models
  @unauthenticated_models
end

Instance Method Details

#on_class(node) ⇒ Object



44
45
46
# File 'lib/rubocop/cop/betterment/unscoped_find.rb', line 44

def on_class(node)
  Utils::MethodReturnTable.populate_index(node)
end

#on_send(node) ⇒ Object



48
49
50
51
52
53
54
55
56
57
58
# File 'lib/rubocop/cop/betterment/unscoped_find.rb', line 48

def on_send(node)
  _, _, *arg_nodes = *node # rubocop:disable InternalAffairs/NodeDestructuring
  return unless
    (
      find?(node) ||
      custom_scope_find?(node) ||
      static_method_name(node.method_name)
    ) && !@unauthenticated_models.include?(Utils::Parser.get_root_token(node))

  add_offense(node) if find_param_arg(arg_nodes) || graphql_file? || graphql_namespace?(node)
end