Skip to content

Commit 6808429

Browse files
committed
Addressing the case when both $CSPEnabled and $autoNonce are false.
1 parent 10c90dc commit 6808429

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

system/HTTP/ContentSecurityPolicy.php

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -429,6 +429,14 @@ public function finalize(ResponseInterface $response)
429429
{
430430
if ($this->autoNonce) {
431431
$this->generateNonces($response);
432+
} else {
433+
// If we're not auto-generating nonces, we should remove any nonce placeholders from the body to prevent them from being rendered.
434+
$body = (string) $response->getBody();
435+
436+
if ($body !== '') {
437+
$body = str_replace([$this->styleNonceTag, $this->scriptNonceTag], '', $body);
438+
$response->setBody($body);
439+
}
432440
}
433441

434442
$this->buildHeaders($response);

tests/system/HTTP/ResponseTest.php

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -698,4 +698,36 @@ public function testSendRemovesMultiplePlaceholdersWhenCSPDisabled(): void
698698
$this->assertStringContainsString('<style >.test{}</style>', $actual);
699699
$this->assertStringContainsString('<style >.test2{}</style>', $actual);
700700
}
701+
702+
public function testSendRemovesPlaceholdersWhenBothCSPAndAutoNonceAreDisabled(): void
703+
{
704+
$appConfig = new App();
705+
$appConfig->CSPEnabled = false;
706+
707+
// Create custom CSP config with custom nonce tags
708+
$cspConfig = new \Config\ContentSecurityPolicy();
709+
$cspConfig->autoNonce = false;
710+
711+
$response = new Response($appConfig);
712+
$response->pretend(true);
713+
714+
// Inject the custom CSP config
715+
$reflection = new ReflectionClass($response);
716+
$cspProperty = $reflection->getProperty('CSP');
717+
$cspProperty->setValue($response, new ContentSecurityPolicy($cspConfig));
718+
719+
$body = '<html><script {csp-script-nonce}>test()</script><style {csp-style-nonce}>.x{}</style></html>';
720+
$response->setBody($body);
721+
722+
ob_start();
723+
$response->send();
724+
$actual = ob_get_clean();
725+
726+
// Custom nonce placeholders should be removed when CSP is disabled
727+
$this->assertIsString($actual);
728+
$this->assertStringNotContainsString('{csp-script-nonce}', $actual);
729+
$this->assertStringNotContainsString('{csp-style-nonce}', $actual);
730+
$this->assertStringContainsString('<script >test()</script>', $actual);
731+
$this->assertStringContainsString('<style >.x{}</style>', $actual);
732+
}
701733
}

0 commit comments

Comments
 (0)