CSP In Magento 2
Tags: csp, magento2
Published: 2020-09-24 11:38:53

# What is CSP?
CSP is a standard introduced to prevent attacks on your website. Attacks mean an XSS, clickjacking, or malicious code injection. CSP is widely supported by all the modern web browsers and it gives privilege to website owners to approve origins of content that browsers should be allowed to load on that website. 

There are two ways that can be used to configure CSP for your website. The first one is by configuring your web server(apache or nGinx to set headers) or another method is to set <meta value on your website. Configuring web servers is beyond the scope of this blog post. Let’s take a look at how Magento configures CSP. 

# Magento and CSP
CSP was introduced in Magento version 2.3.5 to prevent the loading of malicious scripts on websites. It helps to prevent websites from clickjacking, XSS(cross-site scripting) and session hijacking, and other attacks like that. Magento has a Magento_Csp module while helping to set the policy rules for adminhtml and for the frontend area separately to accommodate different use cases. CSP has two modes. The first one is to report only and another one is restrict mode.

#CSP Modes

**Report Only Mode**: In this mode, Magento only reports the CSP policy violations errors in the console log but it will not act on those errors. It helps whenever you are in developer mode and needs to debug your functionality.
Restrict Mode: In this mode, Magento acts on any policy violations. Magento will restrict the loading of CSS, JS, and inline script which violates the CSP policy. 
To configure report-only mode or restrict mode in your Magento application, you need to set the value in your etc/config.xml file.

To enable the restrict mode we will set attribute value report_only to 1, or else if we need to set a report-only model set the report_only attribute value to 0.

**Report Only Mode: report_only = 0**

**Restrict Mode: report_only = 1**
```
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Store:etc/config.xsd">
    <default>
        <csp>
            <mode>
                <storefront>
                    <report_only>0</report_only>
                </storefront>
                <admin>
                    <report_only>0</report_only>
                </admin>
            </mode>
        </csp>
    </default>
</config>
```
# How To Configure CSP for Custom Module
We can add our whitelisted style, scripts, hashes domains in the csp_whitelist.xml file. 
```
<?xml version="1.0"?>
<csp_whitelist xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Csp:etc/csp_whitelist.xsd">
    <policies>
        <policy id="script-src">
            <values>
                <value id="<your_unique_id>" type="host">*.domain.com</value>
                <value id="<your_unique_id>" type="host">https://my-custom-domain.com</value>
            </values>
        </policy>
        <policy id="connect-src">
            <values>
                <value id="<your_unique_id>" type="host">https://my-custom-domain-2.com</value>
            </values>
        </policy>
    </policies>
</csp_whitelist>
```
We have other types of CSP also, in the above example we have declared our whitelist domain under connect-src and script-src. The other types are.
```
POLICY NAME	DESCRIPTION
default-src	The default policy.
base-uri	Defines which URLs can appear in a page’s <base> element.
child-src	Defines the sources for workers and embedded frame contents.
connect-src	Defines the sources that can be loaded using script interfaces.
font-src	Defines which sources can serve fonts.
form-action	Defines valid endpoints for submission from <form> tags.
frame-ancestors	Defines the sources that can embed the current page.
frame-src	Defines the sources for elements such as <frame> and <iframe>.
img-src	Defines the sources from which images can be loaded.
manifest-src	Defines the allowable contents of web app manifests.
media-src	Defines the sources from which images can be loaded.
object-src	Defines the sources for the <object>, <embed>, and <applet> elements.
script-src	Defines the sources for JavaScript <script> elements.
style-src	Defines the sources for stylesheets.
```
If the domains are not whitelisted for your script and styles, you may see the following error like “[Report Only] Refused to load the script ‘<URL>’ because it violates the following Content Security Policy directive” in your developer console. To resolve this issue we need to add that domain under the whitelisted domain using the csp_whilelist.xml file.

# Inline Script Validation
To validate our in-line script, styles, or hashes we can use the SecureHtmlRenderer class from Magento\Framework\View\Helper. We can create an object of this class and use the renderTag method to whitelist our inline script. 
```
/** @var \Magento\Framework\View\Helper\SecureHtmlRenderer */
private $secureRenderer;
function someMethod() {
   ....
   $html .= $this->secureRenderer->renderTag('style', [], "#element { color: blue } ", false);
   ....
}
```
But, that is implementation from your block class, let’s say if we need to use the same implementation in your phtml file then we need to create a function in your custom block class and pass the SecureHtmlRenderer object through the public method.
```
<div id="alert-div">Some text value</div>
<?= $secureRenderer->renderEventListenerAsTag('onclick', 'alert("Whitelist me!");', '#alert-div'); ?>
```
This is all about CSP in Magento 2. Please let me know what you think about this post through the comment section or you can write me an email on my email id i.e. admin@asolutions.co.in. Happy coding :). Thanks!