rails/rails — pull request #15777 by xuchu (2014-06-17 19:44:12+00:00)
Title: Add Content Security Policy(CSP)

This middleware is going to add support for Content Security Policy(CSP) for Rails. CSP helps to detect and mitigate XSS attacks and data injection attacks by setting the content-security-policy HTTP header.

The value of content-security-policy header is made up of one or more directives and each directive come with a source whitelists to specify the trusted resources that can be load by the browser. Any resources that are not specified in the source whitelists will be blocked by the browser.

For more information about the directives and source whitelists, check out here http://content-security-policy.com/

The middleware provides convenient API to set the CSP:

config.csp = {
:enforce => true,
:default_src => 'self',
:script_src => 'inline eval https://api.google.com"
}

will set the content-security-policy header like below:

Content-Security-Policy:default-src 'self';script-src 'unsafe-inline' 'unsafe-eval' https://api.google.com;

The option :enforce is used to indicate if the browser will block the untrusted resources. By default, the option is set to false. So the browser will only report violations of the policy rather than blocking untrusted resource.

Here is also a good introduction, http://www.html5rocks.com/en/tutorials/security/content-security-policy/

cc @rafaelfranca @chancancode