Skip to content

Commit 48d13b9

Browse files
authored
Merge pull request #6611 from kenjis/fix-add-script-nonce
fix: script_tag() does not work with CSP
2 parents 4a6fecb + acad5b6 commit 48d13b9

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

system/Helpers/html_helper.php

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -194,7 +194,9 @@ function doctype(string $type = 'html5'): string
194194
*/
195195
function script_tag($src = '', bool $indexPage = false): string
196196
{
197-
$script = '<script ';
197+
$cspNonce = csp_script_nonce();
198+
$cspNonce = $cspNonce ? ' ' . $cspNonce : $cspNonce;
199+
$script = '<script' . $cspNonce . ' ';
198200
if (! is_array($src)) {
199201
$src = ['src' => $src];
200202
}

tests/system/Helpers/HTMLHelperTest.php

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,10 @@
1111

1212
namespace CodeIgniter\Helpers;
1313

14+
use CodeIgniter\Config\Factories;
1415
use CodeIgniter\Files\Exceptions\FileNotFoundException;
1516
use CodeIgniter\Test\CIUnitTestCase;
17+
use Config\App;
1618

1719
/**
1820
* @internal
@@ -269,6 +271,28 @@ public function testScriptTagWithSrcAndAttributes()
269271
$this->assertSame($expected, script_tag($target));
270272
}
271273

274+
public function testScriptTagWithCsp()
275+
{
276+
// Reset CSP object
277+
$this->resetServices();
278+
279+
$config = new App();
280+
$config->CSPEnabled = true;
281+
Factories::injectMock('config', 'App', $config);
282+
283+
$target = 'http://site.com/js/mystyles.js';
284+
$html = script_tag($target);
285+
286+
$this->assertMatchesRegularExpression(
287+
'!<script nonce="\w+?" src="http://site.com/js/mystyles.js".*?>!u',
288+
$html
289+
);
290+
291+
// Reset CSP object
292+
$this->resetFactories();
293+
$this->resetServices();
294+
}
295+
272296
/**
273297
* This test has probably no real-world value but may help detecting
274298
* a change in the default behaviour.

0 commit comments

Comments
 (0)