Rails 3: Permitting Users to Use Basic HTML Tags

597 views Asked by At

Throughout my site, users can leave comments. I want them to be able to insert basic HTML in their comments, including bold, italic, and link tags. Unfortunately, Rails automatically escapes all user-generated HTML.

I can bypass this behavior by calling .html_safe, but then I leave my site vulnerable to XSS. Is there a way to permit bold, italic, and link tags, while still escaping other content?

1

There are 1 answers

2
ronalchn On BEST ANSWER

You can use something like markdown to support formatting via alternative (not html directly) means. Markdown can be supported via a number of rubygems, including Redcarpet, markitup, etc. Markdown creates an alternative syntax for bold/italics etc (like bbcode).

https://github.com/jwigal/markitup_rails

You can also use a whitelisting sanitizer like Loofah - https://github.com/flavorjones/loofah/. Loofah is a higher end solution, supporting any html tags you want. The users will submit HTML, then Loofah will read it, and build an html node tree using nokogiri. Then it traverses the tree making sure all tag nodes use whitelisted html tags, allowing you to allow any mix of tags you want, including <a>, <img>, <table> etc. It is highly configurable.

Loofah also checks the attributes (depending on configuration), to make sure nothing is hidden in forbidden attributes like onclick=""