Skip to content

Commit

Permalink
Merge pull request #8025 from kenjis/fix-Honeypot-CSP-style-nonce
Browse files Browse the repository at this point in the history
fix: CSP style nonce is added even if honeypot is not attached
  • Loading branch information
kenjis authored Oct 13, 2023
2 parents 52dbf70 + 4892849 commit 617180a
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 6 deletions.
12 changes: 6 additions & 6 deletions system/Honeypot/Honeypot.php
Original file line number Diff line number Diff line change
Expand Up @@ -89,16 +89,16 @@ public function attachHoneypot(ResponseInterface $response)

$prepField = $this->prepareTemplate($this->config->template);

$body = $response->getBody();
$body = str_ireplace('</form>', $prepField . '</form>', $body);
$bodyBefore = $response->getBody();
$bodyAfter = str_ireplace('</form>', $prepField . '</form>', $bodyBefore);

if ($response->getCSP()->enabled()) {
if ($response->getCSP()->enabled() && ($bodyBefore !== $bodyAfter)) {
// Add style tag for the container tag in the head tag.
$style = '<style ' . csp_style_nonce() . '>#' . $this->config->containerId . ' { display:none }</style>';
$body = str_ireplace('</head>', $style . '</head>', $body);
$style = '<style ' . csp_style_nonce() . '>#' . $this->config->containerId . ' { display:none }</style>';
$bodyAfter = str_ireplace('</head>', $style . '</head>', $bodyAfter);
}

$response->setBody($body);
$response->setBody($bodyAfter);
}

/**
Expand Down
18 changes: 18 additions & 0 deletions tests/system/Honeypot/HoneypotTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,24 @@ public function testAttachHoneypotAndContainerWithCSP(): void
$this->assertMatchesRegularExpression($regex, $this->response->getBody());
}

public function testNotAttachHoneypotWithCSP(): void
{
$this->resetServices();

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

$this->config = new HoneypotConfig();
$this->honeypot = new Honeypot($this->config);

$this->response->setBody('<head></head><body></body>');
$this->honeypot->attachHoneypot($this->response);

$this->assertSame('<head></head><body></body>', $this->response->getBody());
}

public function testHasntContent(): void
{
unset($_POST[$this->config->name]);
Expand Down

0 comments on commit 617180a

Please sign in to comment.