XssUnitTest.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. namespace Drupal\KernelTests\Core\Common;
  3. use Drupal\Component\Utility\UrlHelper;
  4. use Drupal\KernelTests\KernelTestBase;
  5. /**
  6. * Confirm that \Drupal\Component\Utility\Xss::filter() and check_url() work
  7. * correctly, including invalid multi-byte sequences.
  8. *
  9. * @group Common
  10. */
  11. class XssUnitTest extends KernelTestBase {
  12. /**
  13. * Modules to enable.
  14. *
  15. * @var array
  16. */
  17. public static $modules = ['filter', 'system'];
  18. protected function setUp() {
  19. parent::setUp();
  20. $this->installConfig(['system']);
  21. }
  22. /**
  23. * Tests t() functionality.
  24. */
  25. public function testT() {
  26. $text = t('Simple text');
  27. $this->assertEqual($text, 'Simple text', 't leaves simple text alone.');
  28. $text = t('Escaped text: @value', ['@value' => '<script>']);
  29. $this->assertEqual($text, 'Escaped text: &lt;script&gt;', 't replaces and escapes string.');
  30. $text = t('Placeholder text: %value', ['%value' => '<script>']);
  31. $this->assertEqual($text, 'Placeholder text: <em class="placeholder">&lt;script&gt;</em>', 't replaces, escapes and themes string.');
  32. }
  33. /**
  34. * Checks that harmful protocols are stripped.
  35. */
  36. public function testBadProtocolStripping() {
  37. // Ensure that check_url() strips out harmful protocols, and encodes for
  38. // HTML.
  39. // Ensure \Drupal\Component\Utility\UrlHelper::stripDangerousProtocols() can
  40. // be used to return a plain-text string stripped of harmful protocols.
  41. $url = 'javascript:http://www.example.com/?x=1&y=2';
  42. $expected_plain = 'http://www.example.com/?x=1&y=2';
  43. $expected_html = 'http://www.example.com/?x=1&amp;y=2';
  44. $this->assertIdentical(UrlHelper::filterBadProtocol($url), $expected_html, '\Drupal\Component\Utility\UrlHelper::filterBadProtocol() filters a URL and encodes it for HTML.');
  45. $this->assertIdentical(UrlHelper::stripDangerousProtocols($url), $expected_plain, '\Drupal\Component\Utility\UrlHelper::stripDangerousProtocols() filters a URL and returns plain text.');
  46. }
  47. /**
  48. * Tests deprecation of the check_url() function.
  49. *
  50. * @group legacy
  51. * @expectedDeprecation check_url() is deprecated in Drupal 8.0.0 and will be removed before Drupal 9.0.0. Use UrlHelper::stripDangerousProtocols() or UrlHelper::filterBadProtocol() instead. See https://www.drupal.org/node/2560027
  52. */
  53. public function testCheckUrl() {
  54. $url = 'javascript:http://www.example.com/?x=1&y=2';
  55. $expected_html = 'http://www.example.com/?x=1&amp;y=2';
  56. $this->assertSame($expected_html, check_url($url));
  57. }
  58. }