Automatic json escaping to help mitigate XSS

98 views
Skip to first unread message

Ricardo Duncan

unread,
Nov 24, 2020, 9:52:49 AM11/24/20
to Grape Framework Discussion
I just wanted to confirm that response HTML/ JSON, etc. sanitization is built into the Grape Framework? My tests indicate that it is so I'd just like to confirm that calling `to_json` on a Ruby Hash for instance will result in escaping/ encoding special characters appropriately e.g. the `<` and `>` tags in the string `<script>alert('hello');</script>. Result: `\u003cscript\u003ealert('hello\");\u003c/script\u003e`

Daniel D.

unread,
Nov 24, 2020, 10:01:47 AM11/24/20
to Grape Framework Discussion
I think the answer is "it depends".

For JSON, JSON libraries guarantee that when you call `.to_json` you can also call `.parse` on the output and get identical JSON back. So in that sense there's some escaping that works in both directions. That said, YMMV depending on which JSON encoder you're using (default json, oj, etc.) and what each object being rendered does when `.as_json` or `.to_json` is called on it. But that doesn't necessarily mean that if you put HTML into a value of JSON object that it's somehow safe to render on a web page.

You're probably not asking the right question. What is your scenario for using the output of the API? You should sanitize any input before rendering (e.g. with the sanitize gem, or via a renderer such as ERB), and not rely on any API's output to be safe for rendering inline in HTML.

Hope this helps!

cheers
dB.
 



On Tue, Nov 24, 2020 at 9:52 AM Ricardo Duncan <ricardo...@gmail.com> wrote:
I just wanted to confirm that response HTML/ JSON, etc. sanitization is built into the Grape Framework? My tests indicate that it is so I'd just like to confirm that calling `to_json` on a Ruby Hash for instance will result in escaping/ encoding special characters appropriately e.g. the `<` and `>` tags in the string `<script>alert('hello');</script>. Result: `\u003cscript\u003ealert('hello\");\u003c/script\u003e`

--
You received this message because you are subscribed to the Google Groups "Grape Framework Discussion" group.
To unsubscribe from this group and stop receiving emails from it, send an email to ruby-grape+...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/ruby-grape/b004b9b4-22cd-43ec-a514-0db6d9a2392bn%40googlegroups.com.


--

Ricardo Duncan

unread,
Nov 24, 2020, 12:36:24 PM11/24/20
to ruby-...@googlegroups.com
Hi Daniel,

Thanks so much for your response. Yes I realized after posting that the question was too generalized, and lacked context. At least your answer does confirm my understanding - I have decided to use the Ruby "sanitize" gem to apply additional sanitization (customizable, based on context).

Cheers,
Ricardo

Reply all
Reply to author
Forward
0 new messages