UrlTest.php 13.9 KB
Newer Older
1 2 3 4
<?php

/**
 * @file
5
 * Contains \Drupal\system\Tests\Common\UrlTest.
6 7 8 9
 */

namespace Drupal\system\Tests\Common;

10
use Drupal\Component\Utility\UrlHelper;
11
use Drupal\Core\Cache\Cache;
12
use Drupal\Core\Language\Language;
13
use Drupal\Core\Render\RenderContext;
14
use Drupal\Core\Url;
15 16 17
use Drupal\simpletest\WebTestBase;

/**
18
 * Confirm that \Drupal\Core\Url,
19
 * \Drupal\Component\Utility\UrlHelper::filterQueryParameters(),
20
 * \Drupal\Component\Utility\UrlHelper::buildQuery(), and _l() work correctly
21
 * with various input.
22
 *
23
 * @group Common
24 25
 */
class UrlTest extends WebTestBase {
26

27
  public static $modules = array('common_test', 'url_alter_test');
28

29
  /**
30
   * Confirms that invalid URLs are filtered in link generating functions.
31
   */
32
  function testLinkXSS() {
33
    // Test \Drupal::l().
34
    $text = $this->randomMachineName();
35
    $path = "<SCRIPT>alert('XSS')</SCRIPT>";
36 37
    $encoded_path = "3CSCRIPT%3Ealert%28%27XSS%27%29%3C/SCRIPT%3E";

38
    $link = \Drupal::l($text, Url::fromUserInput('/' . $path));
39
    $this->assertTrue(strpos($link, $encoded_path) !== FALSE && strpos($link, $path) === FALSE, format_string('XSS attack @path was filtered by _l().', array('@path' => $path)));
40

41
    // Test \Drupal\Core\Url.
42
    $link = Url::fromUri('base:' . $path)->toString();
43
    $this->assertTrue(strpos($link, $encoded_path) !== FALSE && strpos($link, $path) === FALSE, format_string('XSS attack @path was filtered by #theme', ['@path' => $path]));
44 45
  }

46
  /**
47
   * Tests that #type=link bubbles outbound route/path processors' metadata.
48
   */
49
  function testLinkBubbleableMetadata() {
50
    $cases = [
51 52 53 54 55 56
      ['Regular link', 'internal:/user', [], ['contexts' => [], 'tags' => [], 'max-age' => Cache::PERMANENT], []],
      ['Regular link, absolute', 'internal:/user', ['absolute' => TRUE], ['contexts' => ['url.site'], 'tags' => [], 'max-age' => Cache::PERMANENT], []],
      ['Route processor link', 'route:system.run_cron', [], ['contexts' => ['session'], 'tags' => [], 'max-age' => Cache::PERMANENT], ['placeholders' => []]],
      ['Route processor link, absolute', 'route:system.run_cron', ['absolute' => TRUE], ['contexts' => ['url.site', 'session'], 'tags' => [], 'max-age' => Cache::PERMANENT], ['placeholders' => []]],
      ['Path processor link', 'internal:/user/1', [], ['contexts' => [], 'tags' => ['user:1'], 'max-age' => Cache::PERMANENT], []],
      ['Path processor link, absolute', 'internal:/user/1', ['absolute' => TRUE], ['contexts' => ['url.site'], 'tags' => ['user:1'], 'max-age' => Cache::PERMANENT], []],
57 58 59
    ];

    foreach ($cases as $case) {
60
      list($title, $uri, $options, $expected_cacheability, $expected_attachments) = $case;
61
      $expected_cacheability['contexts'] = Cache::mergeContexts($expected_cacheability['contexts'], ['languages:language_interface', 'theme', 'user.permissions']);
62 63 64 65 66 67
      $link = [
        '#type' => 'link',
        '#title' => $title,
        '#options' => $options,
        '#url' => Url::fromUri($uri),
      ];
68
      \Drupal::service('renderer')->renderRoot($link);
69 70
      $this->pass($title);
      $this->assertEqual($expected_cacheability, $link['#cache']);
71
      $this->assertEqual($expected_attachments, $link['#attached']);
72 73 74
    }
  }

75
  /**
76
   * Tests that default and custom attributes are handled correctly on links.
77
   */
78
  function testLinkAttributes() {
79 80 81
    /** @var \Drupal\Core\Render\RendererInterface $renderer */
    $renderer = $this->container->get('renderer');

82 83 84 85 86 87 88
    // Test that hreflang is added when a link has a known language.
    $language = new Language(array('id' => 'fr', 'name' => 'French'));
    $hreflang_link = array(
      '#type' => 'link',
      '#options' => array(
        'language' => $language,
      ),
89
      '#url' => Url::fromUri('https://www.drupal.org'),
90 91
      '#title' => 'bar',
    );
92
    $langcode = $language->getId();
93 94 95 96 97 98

    // Test that the default hreflang handling for links does not override a
    // hreflang attribute explicitly set in the render array.
    $hreflang_override_link = $hreflang_link;
    $hreflang_override_link['#options']['attributes']['hreflang'] = 'foo';

99
    $rendered = $renderer->renderRoot($hreflang_link);
100 101
    $this->assertTrue($this->hasAttribute('hreflang', $rendered, $langcode), format_string('hreflang attribute with value @langcode is present on a rendered link when langcode is provided in the render array.', array('@langcode' => $langcode)));

102
    $rendered = $renderer->renderRoot($hreflang_override_link);
103 104
    $this->assertTrue($this->hasAttribute('hreflang', $rendered, 'foo'), format_string('hreflang attribute with value @hreflang is present on a rendered link when @hreflang is provided in the render array.', array('@hreflang' => 'foo')));

105
    // Test the active class in links produced by _l() and #type 'link'.
106 107 108 109 110 111 112 113 114 115 116 117 118 119
    $options_no_query = array();
    $options_query = array(
      'query' => array(
        'foo' => 'bar',
        'one' => 'two',
      ),
    );
    $options_query_reverse = array(
      'query' => array(
        'one' => 'two',
        'foo' => 'bar',
      ),
    );

120 121
    // Test #type link.
    $path = 'common-test/type-link-active-class';
122

123
    $this->drupalGet($path, $options_no_query);
124
    $links = $this->xpath('//a[@href = :href and contains(@class, :class)]', array(':href' => Url::fromRoute('common_test.l_active_class', [], $options_no_query)->toString(), ':class' => 'is-active'));
125
    $this->assertTrue(isset($links[0]), 'A link generated by _l() to the current page is marked active.');
126

127
    $links = $this->xpath('//a[@href = :href and not(contains(@class, :class))]', array(':href' => Url::fromRoute('common_test.l_active_class', [], $options_query)->toString(), ':class' => 'is-active'));
128
    $this->assertTrue(isset($links[0]), 'A link generated by _l() to the current page with a query string when the current page has no query string is not marked active.');
129 130

    $this->drupalGet($path, $options_query);
131
    $links = $this->xpath('//a[@href = :href and contains(@class, :class)]', array(':href' => Url::fromRoute('common_test.l_active_class', [], $options_query)->toString(), ':class' => 'is-active'));
132
    $this->assertTrue(isset($links[0]), 'A link generated by _l() to the current page with a query string that matches the current query string is marked active.');
133

134
    $links = $this->xpath('//a[@href = :href and contains(@class, :class)]', array(':href' => Url::fromRoute('common_test.l_active_class', [], $options_query_reverse)->toString(), ':class' => 'is-active'));
135
    $this->assertTrue(isset($links[0]), 'A link generated by _l() to the current page with a query string that has matching parameters to the current query string but in a different order is marked active.');
136

137
    $links = $this->xpath('//a[@href = :href and not(contains(@class, :class))]', array(':href' => Url::fromRoute('common_test.l_active_class', [], $options_no_query)->toString(), ':class' => 'is-active'));
138
    $this->assertTrue(isset($links[0]), 'A link generated by _l() to the current page without a query string when the current page has a query string is not marked active.');
139

140 141
    // Test adding a custom class in links produced by _l() and #type 'link'.
    // Test _l().
142
    $class_l = $this->randomMachineName();
143 144
    $link_l = \Drupal::l($this->randomMachineName(), new Url('<current>', [], ['attributes' => ['class' => [$class_l]]]));
    $this->assertTrue($this->hasAttribute('class', $link_l, $class_l), format_string('Custom class @class is present on link when requested by l()', array('@class' => $class_l)));
145

146
    // Test #type.
147
    $class_theme = $this->randomMachineName();
148 149
    $type_link = array(
      '#type' => 'link',
150
      '#title' => $this->randomMachineName(),
151
      '#url' => Url::fromRoute('<current>'),
152 153 154 155 156 157
      '#options' => array(
        'attributes' => array(
          'class' => array($class_theme),
        ),
      ),
    );
158
    $link_theme = $renderer->renderRoot($type_link);
159
    $this->assertTrue($this->hasAttribute('class', $link_theme, $class_theme), format_string('Custom class @class is present on link when requested by #type', array('@class' => $class_theme)));
160 161 162
  }

  /**
163
   * Tests that link functions support render arrays as 'text'.
164
   */
165
  function testLinkRenderArrayText() {
166 167 168
    /** @var \Drupal\Core\Render\RendererInterface $renderer */
    $renderer = $this->container->get('renderer');

169
    // Build a link with _l() for reference.
170
    $l = \Drupal::l('foo', Url::fromUri('https://www.drupal.org'));
171

172
    // Test a renderable array passed to _l().
173 174 175 176 177
    $renderer->executeInRenderContext(new RenderContext(), function() use ($renderer, $l) {
      $renderable_text = array('#markup' => 'foo');
      $l_renderable_text = \Drupal::l($renderable_text, Url::fromUri('https://www.drupal.org'));
      $this->assertEqual($l_renderable_text, $l);
    });
178

179
    // Test a themed link with plain text 'text'.
180 181 182
    $type_link_plain_array = array(
      '#type' => 'link',
      '#title' => 'foo',
183
      '#url' => Url::fromUri('https://www.drupal.org'),
184
    );
185
    $type_link_plain = $renderer->renderRoot($type_link_plain_array);
186
    $this->assertEqual($type_link_plain, $l);
187 188

    // Build a themed link with renderable 'text'.
189 190 191
    $type_link_nested_array = array(
      '#type' => 'link',
      '#title' => array('#markup' => 'foo'),
192
      '#url' => Url::fromUri('https://www.drupal.org'),
193
    );
194
    $type_link_nested = $renderer->renderRoot($type_link_nested_array);
195
    $this->assertEqual($type_link_nested, $l);
196 197
  }

198 199 200 201 202 203 204 205 206 207 208
  /**
   * Checks for class existence in link.
   *
   * @param $link
   *   URL to search.
   * @param $class
   *   Element class to search for.
   *
   * @return bool
   *   TRUE if the class is found, FALSE otherwise.
   */
209 210
  private function hasAttribute($attribute, $link, $class) {
    return preg_match('|' . $attribute . '="([^\"\s]+\s+)*' . $class . '|', $link);
211 212 213
  }

  /**
214
   * Tests UrlHelper::filterQueryParameters().
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
   */
  function testDrupalGetQueryParameters() {
    $original = array(
      'a' => 1,
      'b' => array(
        'd' => 4,
        'e' => array(
          'f' => 5,
        ),
      ),
      'c' => 3,
    );

    // First-level exclusion.
    $result = $original;
    unset($result['b']);
231
    $this->assertEqual(UrlHelper::filterQueryParameters($original, array('b')), $result, "'b' was removed.");
232 233 234 235

    // Second-level exclusion.
    $result = $original;
    unset($result['b']['d']);
236
    $this->assertEqual(UrlHelper::filterQueryParameters($original, array('b[d]')), $result, "'b[d]' was removed.");
237 238 239 240

    // Third-level exclusion.
    $result = $original;
    unset($result['b']['e']['f']);
241
    $this->assertEqual(UrlHelper::filterQueryParameters($original, array('b[e][f]')), $result, "'b[e][f]' was removed.");
242 243 244 245

    // Multiple exclusions.
    $result = $original;
    unset($result['a'], $result['b']['e'], $result['c']);
246
    $this->assertEqual(UrlHelper::filterQueryParameters($original, array('a', 'b[e]', 'c')), $result, "'a', 'b[e]', 'c' were removed.");
247 248 249
  }

  /**
250
   * Tests UrlHelper::parse().
251 252 253 254
   */
  function testDrupalParseUrl() {
    // Relative, absolute, and external URLs, without/with explicit script path,
    // without/with Drupal path.
255
    foreach (array('', '/', 'https://www.drupal.org/') as $absolute) {
256 257 258 259 260 261 262 263
      foreach (array('', 'index.php/') as $script) {
        foreach (array('', 'foo/bar') as $path) {
          $url = $absolute . $script . $path . '?foo=bar&bar=baz&baz#foo';
          $expected = array(
            'path' => $absolute . $script . $path,
            'query' => array('foo' => 'bar', 'bar' => 'baz', 'baz' => ''),
            'fragment' => 'foo',
          );
264
          $this->assertEqual(UrlHelper::parse($url), $expected, 'URL parsed correctly.');
265 266 267 268 269 270 271 272 273 274 275
        }
      }
    }

    // Relative URL that is known to confuse parse_url().
    $url = 'foo/bar:1';
    $result = array(
      'path' => 'foo/bar:1',
      'query' => array(),
      'fragment' => '',
    );
276
    $this->assertEqual(UrlHelper::parse($url), $result, 'Relative URL parsed correctly.');
277 278

    // Test that drupal can recognize an absolute URL. Used to prevent attack vectors.
279
    $url = 'https://www.drupal.org/foo/bar?foo=bar&bar=baz&baz#foo';
280
    $this->assertTrue(UrlHelper::isExternal($url), 'Correctly identified an external URL.');
281

282 283 284
    // Test that UrlHelper::parse() does not allow spoofing a URL to force a malicious redirect.
    $parts = UrlHelper::parse('forged:http://cwe.mitre.org/data/definitions/601.html');
    $this->assertFalse(UrlHelper::isValid($parts['path'], TRUE), '\Drupal\Component\Utility\UrlHelper::isValid() correctly parsed a forged URL.');
285 286 287
  }

  /**
288
   * Tests external URL handling.
289 290
   */
  function testExternalUrls() {
291
    $test_url = 'https://www.drupal.org/';
292 293 294

    // Verify external URL can contain a fragment.
    $url = $test_url . '#drupal';
295
    $result = Url::fromUri($url)->toString();
296
    $this->assertEqual($url, $result, 'External URL with fragment works without a fragment in $options.');
297

298
    // Verify fragment can be overridden in an external URL.
299
    $url = $test_url . '#drupal';
300
    $fragment = $this->randomMachineName(10);
301
    $result = Url::fromUri($url, array('fragment' => $fragment))->toString();
302
    $this->assertEqual($test_url . '#' . $fragment, $result, 'External URL fragment is overridden with a custom fragment in $options.');
303 304 305

    // Verify external URL can contain a query string.
    $url = $test_url . '?drupal=awesome';
306
    $result = Url::fromUri($url)->toString();
307
    $this->assertEqual($url, $result);
308 309 310

    // Verify external URL can be extended with a query string.
    $url = $test_url;
311
    $query = array($this->randomMachineName(5) => $this->randomMachineName(5));
312
    $result = Url::fromUri($url, array('query' => $query))->toString();
313
    $this->assertEqual($url . '?' . http_build_query($query, '', '&'), $result, 'External URL can be extended with a query string in $options.');
314 315 316

    // Verify query string can be extended in an external URL.
    $url = $test_url . '?drupal=awesome';
317
    $query = array($this->randomMachineName(5) => $this->randomMachineName(5));
318
    $result = Url::fromUri($url, array('query' => $query))->toString();
319
    $this->assertEqual($url . '&' . http_build_query($query, '', '&'), $result);
320 321
  }
}