Class: RuboCop::Cop::Neeto::HtmlSafeOnDynamicString

Inherits:
Base
  • Object
show all
Defined in:
lib/rubocop/cop/neeto/html_safe_on_dynamic_string.rb

Overview

html_safe, raw and safe_concat mark a string as already safe, so Rails prints it without escaping. Calling them on a dynamic value (interpolation, a method result, a variable) turns escaping off for whatever that value holds, which lets user input inject markup. Build markup with tag, content_tag, link_to, mail_to or safe_join instead. A call that has been reviewed can be kept by adding # neeto:html-safe-reviewed <reason> on or above it.

Examples:

HtmlSafeOnDynamicString: true (default)

# bad
"<b>#{booking.name}</b>".html_safe

# bad
raw(message.body)

# good
tag.b(booking.name)

# good
"<br>".html_safe

# good
# neeto:html-safe-reviewed admin-authored rich text
meeting.cancellation_policy.html_safe

Constant Summary collapse

MSG =
"Do not call `%<method>s` on a dynamic value. Build the markup with `tag`, `content_tag`, " \
"`link_to`, `mail_to` or `safe_join`, or add `# neeto:html-safe-reviewed <reason>` if the value " \
"is known to be safe."
REVIEWED_ANNOTATION =
/#\s*neeto:html-safe-reviewed\s+\S/
RESTRICT_ON_SEND =
%i[html_safe raw safe_concat].freeze

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ Object Also known as: on_csend



40
41
42
43
44
45
# File 'lib/rubocop/cop/neeto/html_safe_on_dynamic_string.rb', line 40

def on_send(node)
  value = trusted_value(node)
  return if value.nil? || static_string?(value) || reviewed?(node)

  add_offense(node.loc.selector, message: format(MSG, method: node.method_name))
end