Skip to content

Commit

Permalink
Merge pull request #65 from fritzmg/patch-1
Browse files Browse the repository at this point in the history
Generate nonce also when only `default-src` policy is applied
  • Loading branch information
paragonie-security authored Dec 18, 2023
2 parents 2a68e22 + 4815f61 commit 9a2f733
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/CSPBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -526,7 +526,7 @@ public function injectCSPHeader(MessageInterface $message, bool $legacy = false)
public function nonce(string $directive = 'script-src', string $nonce = ''): string
{
$ruleKeys = array_keys($this->policies);
if (!in_array($directive, $ruleKeys)) {
if (!in_array($directive, $ruleKeys) && !in_array('default-src', $ruleKeys)) {
return '';
}

Expand Down
31 changes: 31 additions & 0 deletions test/BasicTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,37 @@ public function testAllowUnsafeInline()
$this->assertStringContainsString("'unsafe-inline'", $compiled);
}

/**
* @covers CSPBuilder::nonce()
* @throws \Exception
*/
public function testNonce()
{
$csp = new CSPBuilder();

$this->assertEmpty($csp->nonce('script-src'));
$this->assertEmpty($csp->nonce('style-src'));

$csp->setSelfAllowed('script-src', true);
$csp->setSelfAllowed('style-src', true);

$this->assertNotEmpty($csp->nonce('script-src'));
$this->assertNotEmpty($csp->nonce('style-src'));
}

/**
* @covers CSPBuilder::nonce()
* @throws \Exception
*/
public function testNonceWithDefaultSrc()
{
$csp = new CSPBuilder();
$csp->setSelfAllowed('default-src', true);

$this->assertNotEmpty($csp->nonce('script-src'));
$this->assertNotEmpty($csp->nonce('style-src'));
}

/**
* @covers \ParagonIE\CSPBuilder\CSPBuilder
*/
Expand Down

0 comments on commit 9a2f733

Please sign in to comment.