diff options
author | Robert Speicher <rspeicher@gmail.com> | 2017-03-24 18:04:37 -0400 |
---|---|---|
committer | Robert Speicher <rspeicher@gmail.com> | 2017-03-24 18:04:37 -0400 |
commit | fc312799684f9e6126815f602cef85a75e7887b8 (patch) | |
tree | da75a5ca361535be15bc6f2ba493411d2999a3f8 | |
parent | 9a45b79915a08e95172013ed1e85528f9d027342 (diff) | |
download | gitlab-ce-fc312799684f9e6126815f602cef85a75e7887b8.tar.gz |
Ignore `to_json` sent to a Serializer instance in the ToJson cop
-rw-r--r-- | rubocop/cop/security/to_json.rb | 12 | ||||
-rw-r--r-- | spec/rubocop/cop/security/to_json_spec.rb | 6 |
2 files changed, 17 insertions, 1 deletions
diff --git a/rubocop/cop/security/to_json.rb b/rubocop/cop/security/to_json.rb index 0ba7aaa1ba3..afd3da91136 100644 --- a/rubocop/cop/security/to_json.rb +++ b/rubocop/cop/security/to_json.rb @@ -4,8 +4,10 @@ module RuboCop class ToJson < RuboCop::Cop::Cop MSG = "Don't use `to_json` without specifying `only`".freeze + # Check for `to_json` sent to any object that's not a Hash literal or + # Serializer instance def_node_matcher :to_json?, <<~PATTERN - (send !{nil hash} :to_json $...) + (send !{nil hash #serializer?} :to_json $...) PATTERN # Check if node is a `only: ...` pair @@ -52,6 +54,14 @@ module RuboCop private + def_node_search :constant_init, <<~PATTERN + (send (const nil $_) :new) + PATTERN + + def serializer?(node) + constant_init(node).any? { |name| name.to_s.end_with?('Serializer') } + end + def requires_only? return false if @_has_top_level_only diff --git a/spec/rubocop/cop/security/to_json_spec.rb b/spec/rubocop/cop/security/to_json_spec.rb index 206de6f32e4..2b5a656adf9 100644 --- a/spec/rubocop/cop/security/to_json_spec.rb +++ b/spec/rubocop/cop/security/to_json_spec.rb @@ -16,6 +16,12 @@ describe RuboCop::Cop::Security::ToJson do expect(cop.offenses).to be_empty end + it 'ignores `to_json` sent to a Serializer instance' do + inspect_source(cop, 'MergeRequestSerializer.new.represent(issuable).to_json') + + expect(cop.offenses).to be_empty + end + context 'to_json with options' do it 'does nothing when provided `only`' do inspect_source(cop, <<~EOS) |