Skip to content

Commit 617180a

Browse files
authored
Merge pull request #8025 from kenjis/fix-Honeypot-CSP-style-nonce
fix: CSP style nonce is added even if honeypot is not attached
2 parents 52dbf70 + 4892849 commit 617180a

2 files changed

Lines changed: 24 additions & 6 deletions

File tree

system/Honeypot/Honeypot.php

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -89,16 +89,16 @@ public function attachHoneypot(ResponseInterface $response)
8989

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

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

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

101-
$response->setBody($body);
101+
$response->setBody($bodyAfter);
102102
}
103103

104104
/**

tests/system/Honeypot/HoneypotTest.php

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,24 @@ public function testAttachHoneypotAndContainerWithCSP(): void
100100
$this->assertMatchesRegularExpression($regex, $this->response->getBody());
101101
}
102102

103+
public function testNotAttachHoneypotWithCSP(): void
104+
{
105+
$this->resetServices();
106+
107+
$config = new App();
108+
$config->CSPEnabled = true;
109+
Factories::injectMock('config', 'App', $config);
110+
$this->response = Services::response($config, false);
111+
112+
$this->config = new HoneypotConfig();
113+
$this->honeypot = new Honeypot($this->config);
114+
115+
$this->response->setBody('<head></head><body></body>');
116+
$this->honeypot->attachHoneypot($this->response);
117+
118+
$this->assertSame('<head></head><body></body>', $this->response->getBody());
119+
}
120+
103121
public function testHasntContent(): void
104122
{
105123
unset($_POST[$this->config->name]);

0 commit comments

Comments
 (0)