Rails: html_safe 不安全?

Rails: html_safe not safe?

我有这段代码:

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

我正在使用 RuboCop,它告诉我“将字符串标记为 html 安全可能存在安全风险”。 (也使用 raw()

正如我在 中所理解的那样,使用 & 应该没有问题,因为如果字符串为空,它会忽略 html_safe,但似乎并非如此。

有没有其他方法可以解决这个问题,或者我可以忽略 RuboCop。

Rubocop 将 params[:text]&.html_safe 标记为不良做法,因为这会使您的代码暴露于跨站点脚本攻击。

对于这种情况,即使是刹车员也会提出问题。 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建议改用sanitize


使用sanitize方法后的代码看起来像-

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