public function UrlTest::testLinkXSS in Drupal 9
Same name and namespace in other branches
- 10 core/modules/system/tests/src/Kernel/Common/UrlTest.php \Drupal\Tests\system\Kernel\Common\UrlTest::testLinkXSS()
Confirms that invalid URLs are filtered in link generating functions.
File
- core/modules/ system/ tests/ src/ Kernel/ Common/ UrlTest.php, line 30 
Class
- UrlTest
- Confirm that \Drupal\Core\Url, \Drupal\Component\Utility\UrlHelper::filterQueryParameters(), \Drupal\Component\Utility\UrlHelper::buildQuery(), and \Drupal\Core\Utility\LinkGeneratorInterface::generate() work correctly with various input.
Namespace
Drupal\Tests\system\Kernel\CommonCode
public function testLinkXSS() {
  // Test link generator.
  $text = $this
    ->randomMachineName();
  $path = "<SCRIPT>alert('XSS')</SCRIPT>";
  $encoded_path = "3CSCRIPT%3Ealert%28%27XSS%27%29%3C/SCRIPT%3E";
  $link = Link::fromTextAndUrl($text, Url::fromUserInput('/' . $path))
    ->toString();
  $this
    ->assertStringContainsString($encoded_path, $link, new FormattableMarkup('XSS attack @path was filtered by \\Drupal\\Core\\Utility\\LinkGeneratorInterface::generate().', [
    '@path' => $path,
  ]));
  $this
    ->assertStringNotContainsString($path, $link, new FormattableMarkup('XSS attack @path was filtered by \\Drupal\\Core\\Utility\\LinkGeneratorInterface::generate().', [
    '@path' => $path,
  ]));
  // Test \Drupal\Core\Url.
  $link = Url::fromUri('base:' . $path)
    ->toString();
  $this
    ->assertStringContainsString($encoded_path, $link, new FormattableMarkup('XSS attack @path was filtered by #theme', [
    '@path' => $path,
  ]));
  $this
    ->assertStringNotContainsString($path, $link, new FormattableMarkup('XSS attack @path was filtered by #theme', [
    '@path' => $path,
  ]));
}