This blog is part of our Rails 5.2 series.
Content Security Policy (CSP) is an added layer of security that helps to detect and mitigate various types of attacks on our web applications, including Cross Site Scripting (XSS) and data injection attacks.
What is XSS ?
In this attack, victim’s browser may execute malicious scripts because browser trusts the source of the content even when it’s not coming from the correct source.
Here is our blog on XSS written sometime back.
How CSP can be used to mitigate and report this attack ?
By using CSP, we can specify domains that are valid sources of executable scripts. Then a browser with CSP compatibility will only execute those scripts that are loaded from these whitelisted domains.
In Rails 5.2, a DSL was added for configuring Content Security Policy header.
Let’s check the configuration.
We can define global policy for the project in an initializer.
We can override global policy within a controller as well.
Content Security Policy can be deployed in report-only mode as well.
Here is global setting in an initializer.
Here we are putting an override at controller level.
Policy specified in
content_security_policy_report_only header will not be enforced,
but any violations will be reported to a provided URI. We can provide this violation report URI in
content_security_policy headers are present in the same response
then policy specified in
content_security_policy header will be enforced while
content_security_policy_report_only policy will generate reports but will not be enforced.