Skip to content

Commit

Permalink
Merge pull request #8 from GravitateNZ/fixes
Browse files Browse the repository at this point in the history
updates to csp headers for styles vs scripts
  • Loading branch information
yakmoose authored Jan 3, 2023
2 parents 2ed228c + 7ae7dd5 commit 7633437
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 5 deletions.
10 changes: 5 additions & 5 deletions src/Twig/CspExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
class CspExtension extends AbstractExtension
{

protected ?string $nonce = null;
protected array|null $nonce = [];

public function __construct(protected CspHeaderListener $listener)
{}
Expand Down Expand Up @@ -47,11 +47,11 @@ public function getTokenParsers(): array
public function addCspNonce(string $directive = 'script-src'): string
{
//generate a nonce, return it and stuff it into a page...
if (!$this->nonce) {
$this->nonce = base64_encode(random_bytes(32));
$this->listener->addCspDirective($directive, "'nonce-{$this->nonce}'");
if (!isset($this->nonce[$directive])) {
$this->nonce[$directive] = base64_encode(random_bytes(32));
$this->listener->addCspDirective($directive, "'nonce-{$this->nonce[$directive]}'");
}
return $this->nonce;
return $this->nonce[$directive];
}

public function hash(string $body, string $algo = 'sha384'): array
Expand Down
21 changes: 21 additions & 0 deletions tests/CspNonceExtensionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,4 +46,25 @@ public function testNonce(): void
$this->assertStringContainsString("'nonce-{$nonce}'", $h);

}


public function testCssNonce(): void
{
$scriptNonce = $this->extension->addCspNonce('script-src');
$styleNonce = $this->extension->addCspNonce('style-src');
$this->assertNotNull($scriptNonce);
$this->assertNotNull($styleNonce);

$this->assertNotEquals($styleNonce, $scriptNonce);

$this->assertEquals($scriptNonce, $this->extension->addCspNonce());
$this->assertEquals($styleNonce, $this->extension->addCspNonce('style-src'));

$h = $this->extension->getListener()->getCspHeader();

$this->assertStringContainsString("'nonce-{$scriptNonce}'", $h);
$this->assertStringContainsString("'nonce-{$styleNonce}'", $h);

}

}

0 comments on commit 7633437

Please sign in to comment.