Skip to content

fix: script_tag() does not work with CSP #6611

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 30, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion system/Helpers/html_helper.php
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,9 @@ function doctype(string $type = 'html5'): string
*/
function script_tag($src = '', bool $indexPage = false): string
{
$script = '<script ';
$cspNonce = csp_script_nonce();
$cspNonce = $cspNonce ? ' ' . $cspNonce : $cspNonce;
$script = '<script' . $cspNonce . ' ';
if (! is_array($src)) {
$src = ['src' => $src];
}
Expand Down
24 changes: 24 additions & 0 deletions tests/system/Helpers/HTMLHelperTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,10 @@

namespace CodeIgniter\Helpers;

use CodeIgniter\Config\Factories;
use CodeIgniter\Files\Exceptions\FileNotFoundException;
use CodeIgniter\Test\CIUnitTestCase;
use Config\App;

/**
* @internal
Expand Down Expand Up @@ -269,6 +271,28 @@ public function testScriptTagWithSrcAndAttributes()
$this->assertSame($expected, script_tag($target));
}

public function testScriptTagWithCsp()
{
// Reset CSP object
$this->resetServices();

$config = new App();
$config->CSPEnabled = true;
Factories::injectMock('config', 'App', $config);

$target = 'http://site.com/js/mystyles.js';
$html = script_tag($target);

$this->assertMatchesRegularExpression(
'!<script nonce="\w+?" src="http://site.com/js/mystyles.js".*?>!u',
$html
);

// Reset CSP object
$this->resetFactories();
$this->resetServices();
}

/**
* This test has probably no real-world value but may help detecting
* a change in the default behaviour.
Expand Down