Protecting Against XSS In RAILS - JavaScript Contexts

Recently my team was working to implement Brakeman in our CI processes to automatically scan our codebase for security vulnerabilities. Among a few other issues, it identified a handful of similar XSS vulnerabilities of a similar pattern:

<script type="text/javascript">
  var FOO = "<%= raw whatever %>";
  ReactDOM.render(<Blah
    foo={window.FOO}
  />, document.getElementById('some_place'));
</script>

This is a pretty straight forward vulnerability, since passing "; alert(1); " for whatever will result in the code being rendered as var FOO = ""; alert(1); ""; which isn’t good.

The fix, isn’t so simple. I’ve searched high and low, and couldn’t find a single source that had the correct solution to the problem. So here it is…