function PageTitleTest::testTitleXSS

Same name and namespace in other branches
  1. 11.x core/modules/system/tests/src/Functional/System/PageTitleTest.php \Drupal\Tests\system\Functional\System\PageTitleTest::testTitleXSS()
  2. 10 core/modules/system/tests/src/Functional/System/PageTitleTest.php \Drupal\Tests\system\Functional\System\PageTitleTest::testTitleXSS()
  3. 9 core/modules/system/tests/src/Functional/System/PageTitleTest.php \Drupal\Tests\system\Functional\System\PageTitleTest::testTitleXSS()

Test if the title of the site is XSS proof.

File

core/modules/system/tests/src/Functional/System/PageTitleTest.php, line 75

Class

PageTitleTest
Tests HTML output escaping of page title, site name, and slogan.

Namespace

Drupal\Tests\system\Functional\System

Code

public function testTitleXSS() {
  // Set some title with JavaScript and HTML chars to escape.
  $title = '</title><script type="text/javascript">alert("Title XSS!");</script> & < > " \' ';
  $title_filtered = Html::escape($title);
  $slogan = '<script type="text/javascript">alert("Slogan XSS!");</script>';
  $slogan_filtered = Xss::filterAdmin($slogan);
  // Set title and slogan.
  $edit = [
    'site_name' => $title,
    'site_slogan' => $slogan,
  ];
  $this->drupalPostForm('admin/config/system/site-information', $edit, t('Save configuration'));
  // Place branding block with site name and slogan into header region.
  $this->drupalPlaceBlock('system_branding_block', [
    'region' => 'header',
  ]);
  // Load frontpage.
  $this->drupalGet('');
  // Test the title.
  $this->assertNoRaw($title, 'Check for the lack of the unfiltered version of the title.');
  // Add </title> to make sure we're checking the title tag, rather than the
  // first 'heading' on the page.
  $this->assertRaw($title_filtered . '</title>', 'Check for the filtered version of the title in a <title> tag.');
  // Test the slogan.
  $this->assertNoRaw($slogan, 'Check for the unfiltered version of the slogan.');
  $this->assertRaw($slogan_filtered, 'Check for the filtered version of the slogan.');
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.