For one who doesn't know, .html_safe
is rails method, which outputs strings as part of html document.
The problem is that string is user inputed. What did I do to prevent some bad actions - regexp inserts after every <
or >
invisible symbol, which breaks all tags, that could be part of html of document.
But still feel a bit unsure - does it protect page? Any other ways of use .html_safe
, except tags, or symbol doesn't protects me enough?
1 Answer
Here's an article explaining in details how html_safe
actually works. In short, you should not call .html_safe
in untrusted strings or in strings that contain other untrusted strings (e.g. "trusted #{untrusted} trusted"
).
If you have a trusted string (not user inputted) that you need unescaped, you can call html_safe
in it, and proceed appending other strings to it (or appending it to other SafeBuffer
s). Every regular string appended to a SafeBuffer
will be escaped, and thus can not cause XSS vulnerabilities. If you concatenate two SafeBuffer
s, however, no escaping will occur.
Also according to the linked article, the rendering of every view starts with am empty SafeBuffer
, so every string you append to it will be escaped by default.