diff --git a/system/HTTP/Response.php b/system/HTTP/Response.php index 866106ae6bb7..5d535c5d0c63 100644 --- a/system/HTTP/Response.php +++ b/system/HTTP/Response.php @@ -239,13 +239,10 @@ public function __construct($config) // Also ensures that a Cache-control header exists. $this->noCache(); - // Are we enforcing a Content Security Policy? - if ($config->CSPEnabled === true) - { - $this->CSP = new ContentSecurityPolicy(new \Config\ContentSecurityPolicy()); - $this->CSPEnabled = true; - } + // We need CSP object even if not enabled to avoid calls to non existing methods + $this->CSP = new ContentSecurityPolicy(new \Config\ContentSecurityPolicy()); + $this->CSPEnabled = $config->CSPEnabled; $this->cookiePrefix = $config->cookiePrefix; $this->cookieDomain = $config->cookieDomain; $this->cookiePath = $config->cookiePath; diff --git a/tests/system/HTTP/ContentSecurityPolicyTest.php b/tests/system/HTTP/ContentSecurityPolicyTest.php index 3e93b491725a..6993c5bb00cd 100644 --- a/tests/system/HTTP/ContentSecurityPolicyTest.php +++ b/tests/system/HTTP/ContentSecurityPolicyTest.php @@ -13,10 +13,10 @@ class ContentSecurityPolicyTest extends \CIUnitTestCase { // Having this method as setUp() doesn't work - can't find Config\App !? - protected function prepare() + protected function prepare(bool $CSPEnabled = true) { $config = new App(); - $config->CSPEnabled = true; + $config->CSPEnabled = $CSPEnabled; $this->response = new Response($config); $this->response->pretend(false); $this->csp = $this->response->CSP; @@ -490,4 +490,17 @@ public function testHeaderIgnoreCase() $this->assertContains("base-uri 'self';", $result); } + /** + * @runInSeparateProcess + * @preserveGlobalState disabled + */ + public function testCSPDisabled() + { + $this->prepare(false); + $result = $this->work(); + $this->response->CSP->addStyleSrc('https://example.com'); + + $this->assertHeaderNotEmitted('content-security-policy', true); + } + }