Saturday, December 1, 2007

Why The h Can't Rails Escape HTML Automatically?

We all know about the dangers of cross-site scripting. The solution is simple: if you're not sure the data you're displaying is absolutely safe, run it through a filter that escapes HTML tag characters. Do this with data entered by users, data you get from other applications, etc. Be paranoid.

Rails has an html_escape method that does exactly this. Its alias is h, and you'll see it sprinkled throughout templates:
<%= h foo.bar %>
So where's the wart? The wart is that you, the developer, have to do this. Rails should escape HTML automatically, by default. That's what you want, 99% of the time. Instead, you have to remember the h. You have to put it in manually, again and again. Nothing DRY about that. And, if you forget even once, you've left a security hole in your application.

Yes, you can use plugins or alternative template engines to fix this. But many developers will use Rails out of the box, and some of them will forget an h or two. Django escapes HTML automatically now. Rails is nearing 2.0. Time to catch up.