Search code examples
rubyrubocop

Rails: html_safe not safe?


I have this working piece of code:

content_tag('p', params[:text]&.html_safe, class: 'nice-class')

And I'm using RuboCop, which is telling me that "tagging a string as html safe may be a security risk". (Also using raw())

As I understood in Why Rubocop do not allow html_safe or raw() Rails, there shouldn't be problems using & as it ignores the html_safe if the string is empty, but doesn't seem so.

Is there any other way to solve this or may I just ignore RuboCop.


Solution

  • Rubocop is flagging params[:text]&.html_safe as bad practice because this can expose your code to Cross site scripting attacks.

    Even brakeman raises issue for such cases. Check link

    In Rails 3, templates escaped output by default. Hooray! Sadly, Rails 3 also introduced the unfortunately named html_safe method to bypass this escaping. Quite a few people have been confused into thinking html_safe makes strings safe. What it really does is mark the string as “safe” so that it will not be escaped. (The raw method does the same thing.)

    html_safe api doc suggests to use sanitize instead


    The code after using sanitize method will look like -

    content_tag('p', sanitize params[:text], class: 'nice-class')