Permitting an unsafe script in a Rails development environment

Viewed 548

In a development environment, I'd like to allow script-src unsafe-inline in a Rails app. I'm trying to use the heavens_door gem, to produce system tests.

customizing content security policy on content security policy initializer.

It's OK for it to be unsafe, as the server is the local Rails server, but how can I configure my Rails app to allow it?

2 Answers

You should have all Javascript code in separately loaded .js files. Then you can add trusted origins to the content security policy in an initializer like for example config/initializers/csp.rb like this:

my_custom_script_sources = ["https://kit.fontawesome.com", "http://localhost:3000"]
Rails.application.config.content_security_policy do |policy|
  policy.script_src(:self, *my_custom_script_sources)
end

You can of course check for Rails.env and set the custom script sources accordingly so you don't disclose your internal development urls in production.

Also you can add :unsafe_inline to any policy element, but you should probably not. It's a lot more secure to explicitly list your sources than to allow any inline script to run that would eliminate protection from XSS. You might want to accept the risk of :unsafe_inline though if you have no way to change a 3rd party component to not use inline Javascript. I don't know heavens_door unfortunately, I'm not sure whether that is the case or not.

You can use this tool for example to evaluate your CSP against best practices.

Thank you to Gabor Lengyel for the solution. In summary, you just need to add this line to the ApplicationController

content_security_policy false

Ensure it is not committed and pushed to production!

Related