Class: RuboCop::Cop::Rails::LinkToBlank

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Defined in:
lib/rubocop/cop/rails/link_to_blank.rb

Overview

Checks for calls to ‘link_to`, `link_to_if`, and `link_to_unless` methods that contain a `target: ’_blank’‘ but no `rel: ’noopener’‘. This can be a security risk as the loaded page will have control over the previous page and could change its location for phishing purposes.

The option ‘rel: ’noreferrer’‘ also blocks this behavior and removes the http-referrer header.

Examples:

# bad
link_to 'Click here', url, target: '_blank'

# good
link_to 'Click here', url, target: '_blank', rel: 'noopener'

# good
link_to 'Click here', url, target: '_blank', rel: 'noreferrer'

Constant Summary collapse

MSG =
'Specify a `:rel` option containing noopener.'
RESTRICT_ON_SEND =
%i[link_to link_to_if link_to_unless].freeze

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/rubocop/cop/rails/link_to_blank.rb', line 41

def on_send(node)
  option_nodes = node.each_child_node(:hash)

  option_nodes.map(&:children).each do |options|
    blank = options.find { |o| blank_target?(o) }
    next unless blank && options.none? { |o| includes_noopener?(o) }

    add_offense(blank) do |corrector|
      autocorrect(corrector, node, blank, option_nodes)
    end
  end
end