Fixed issue with HTML tags in custom head scripts

Fixes a strange issue of HTML tags within script tags being malformed
when part of the HTML custom head content due to the PHP parsing we do.
DOMDocument seemed to cause this upon load.
Adding LIBXML_SCHEMA_CREATE to the ->loadHTML call seems to fix this but
not really sure why. Doesn't seem to cause further issues though.
Tested with multiple scripts and styles and comments and meta tags.

- Also added new testing class to cover.
- As part of testing, added new folder within tests to house setting
  specific tests.

For #2914
This commit is contained in:
Dan Brown 2021-09-05 23:52:39 +01:00
parent d815e1b9f2
commit 88c698796b
No known key found for this signature in database
GPG key ID: 46D9F943C24A2EF9
3 changed files with 34 additions and 3 deletions

View file

@ -24,7 +24,7 @@ class HtmlNonceApplicator
$html = '<body>' . $html . '</body>';
libxml_use_internal_errors(true);
$doc = new DOMDocument();
$doc->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));
$doc->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'), LIBXML_SCHEMA_CREATE);
$xPath = new DOMXPath($doc);
// Apply to scripts
@ -38,7 +38,8 @@ class HtmlNonceApplicator
$returnHtml = '';
$topElems = $doc->documentElement->childNodes->item(0)->childNodes;
foreach ($topElems as $child) {
$returnHtml .= $doc->saveHTML($child);
$content = $doc->saveHTML($child);
$returnHtml .= $content;
}
return $returnHtml;

View file

@ -0,0 +1,30 @@
<?php
namespace Tests\Settings;
use Tests\TestCase;
class CustomHeadContentTest extends TestCase
{
public function test_configured_content_shows_on_pages()
{
$this->setSettings(['app-custom-head' => '<script>console.log("cat");</script>']);
$resp = $this->get('/login');
$resp->assertSee('console.log("cat")');
}
public function test_configured_content_does_not_show_on_settings_page()
{
$this->setSettings(['app-custom-head' => '<script>console.log("cat");</script>']);
$resp = $this->asAdmin()->get('/settings');
$resp->assertDontSee('console.log("cat")');
}
public function test_divs_in_js_preserved_in_configured_content()
{
$this->setSettings(['app-custom-head' => '<script><div id="hello">cat</div></script>']);
$resp = $this->get('/login');
$resp->assertSee('<div id="hello">cat</div>');
}
}

View file

@ -1,4 +1,4 @@
<?php
<?php namespace Tests\Settings;
use Tests\TestCase;