to_json Cross Site Scripting security issue (XSS)

Bart t. B. brought the following to_json security issue to my attention, the Rails Trac at http://dev.rubyonrails.org/ticket/8371 has more on that:

To json is almost only used for injecting object hashes into javascript.

var client = <%= client.to_json %>;

Because to_json does not escape its values, it's easy to construct a Cross Site Scripting exploit. If client has a name attribute, to_json will come up with something like: var client = {attributes: {name: "TEST"}};

If we change the name to say: TEST"}}; alert('XSS!!') ;a={{" we have no problem in the rest of our application, as we use <%= h client.name %>, but when we render our javascript, there is a problem:

var client = {attributes: {name: "TEST"}}; alert('XSS!!');a={{""}};

There is currently no easy way to safely escape to_json as escaping the result will result in a broken hash. The implementation of the current to_json is as such that no difference is made between the value and the key, making an easy fix dificult.

This seems to be somewhat refactored in the trunk, but the problem is still there. I understand that this is not really a to_json problem, but as 99% of the users probably uses it this way, something like a :secure_values option would be nice.