Class: RuboCop::Cop::GitlabSecurity::JsonSerialization

Inherits:
Cop
  • Object
show all
Defined in:
lib/rubocop/cop/gitlab-security/json_serialization.rb

Overview

Checks for to_json / as_json without whitelisting via only.

Either method called on an instance of a Serializer class will be ignored. Associations included via include are subject to the same rules.

See gitlab.com/gitlab-org/gitlab-ce/issues/29661

Examples:


# bad
render json: @user.to_json
render json: @user.to_json(except: i[password])
render json: @user.to_json(
  only: i[username],
  include: [:identities]
)

# acceptable
render json: UserSerializer.new.to_json

# good
render json: @user.to_json(only: i[name username])
render json: @user.to_json(
  only: i[username],
  include: { identities: { only: i[provider] } }
)

Constant Summary collapse

MSG =
"Don't use `%s` without specifying `only`".freeze

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ Object



60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/rubocop/cop/gitlab-security/json_serialization.rb', line 60

def on_send(node)
  matched = json_serialization?(node)
  return unless matched

  @_has_top_level_only = false
  @method = matched.first

  if matched.last.nil? || matched.last.empty?
    # Empty `to_json` call
    add_offense(node, location: :selector, message: format_message)
  else
    check_arguments(node, matched)
  end
end