Skip to content

Commit

Permalink
feat: add csp_script_nonce and csp_style_nonce plugin for View Parser
Browse files Browse the repository at this point in the history
  • Loading branch information
kenjis committed Jan 4, 2022
1 parent c7aa8ce commit d9c8608
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 0 deletions.
2 changes: 2 additions & 0 deletions system/Config/View.php
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,8 @@ class View extends BaseConfig
* @var array
*/
protected $corePlugins = [
'csp_script_nonce' => '\CodeIgniter\View\Plugins::cspScriptNonce',
'csp_style_nonce' => '\CodeIgniter\View\Plugins::cspStyleNonce',
'current_url' => '\CodeIgniter\View\Plugins::currentURL',
'previous_url' => '\CodeIgniter\View\Plugins::previousURL',
'mailto' => '\CodeIgniter\View\Plugins::mailto',
Expand Down
16 changes: 16 additions & 0 deletions system/View/Plugins.php
Original file line number Diff line number Diff line change
Expand Up @@ -103,4 +103,20 @@ public static function siteURL(array $params = []): string
{
return site_url(...$params);
}

/**
* Wrap csp_script_nonce() function to use as view plugin.
*/
public static function cspScriptNonce(): string
{
return csp_script_nonce();
}

/**
* Wrap csp_style_nonce() function to use as view plugin.
*/
public static function cspStyleNonce(): string
{
return csp_style_nonce();
}
}
13 changes: 13 additions & 0 deletions tests/system/View/ParserPluginTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -133,4 +133,17 @@ public function setHints($output)
{
return preg_replace('/(<!-- DEBUG-VIEW+) (\w+) (\d+)/', '${1}', $output);
}

public function testCspScriptNonceWithCspEnabled()
{
$config = config('App');
$config->CSPEnabled = true;

$template = 'aaa {+ csp_script_nonce +} bbb';

$this->assertMatchesRegularExpression(
'/aaa nonce="[0-9a-z]{24}" bbb/',
$this->parser->renderString($template)
);
}
}

0 comments on commit d9c8608

Please sign in to comment.