comments (not for humans)

The brand new Rails 3.0 by default escapes data used in views. This is great news, because it hopefully means the applications will be protected from XSS by default, as long as you stick to the built-in helpers (UrlHelper etc.).

The syntax

In earlier versions you had to manually insert the encoding like so:<%= h(some_data) %>If you forgot the h()-method you would be vulnerable.

In the new version, data is automatically escaped:<%= some_data %>If you want it to be unescaped, you still can:<%= raw(some_data) %>

How does it work?

From what I understand, strings have two new methods: html_safe? and html_safe. The helpers use the html_safe? method to determine if a string needs to be escaped. The other method html_safe tells the framework that a given string is safe.

So if you want to implement your own helpers, you still need to take care of the escaping yourself. As an example (borrowed from Rails cast 204):

def strong(content)
"<strong>#{h(content)}</strong>".html_safe
end

As you can see her, the helper tells the framework that the output is safe, and takes care of escaping the input by using h()-method.

Also remember that you have to escape for javascript whenever you print input inside a javascript variable ("Do you really want to delete nnn?")

But this is indeed good news. Great work by the rails team!

Comments closed for this post