1<?php
2
3namespace Drupal\Tests\system\Kernel\Common;
4
5use Drupal\Component\Render\FormattableMarkup;
6use Drupal\Component\Utility\UrlHelper;
7use Drupal\Core\Cache\Cache;
8use Drupal\Core\Language\Language;
9use Drupal\Core\Link;
10use Drupal\Core\Render\RenderContext;
11use Drupal\Core\Url;
12use Drupal\KernelTests\KernelTestBase;
13
14/**
15 * Confirm that \Drupal\Core\Url,
16 * \Drupal\Component\Utility\UrlHelper::filterQueryParameters(),
17 * \Drupal\Component\Utility\UrlHelper::buildQuery(), and
18 * \Drupal\Core\Utility\LinkGeneratorInterface::generate()
19 * work correctly with various input.
20 *
21 * @group Common
22 */
23class UrlTest extends KernelTestBase {
24
25  protected static $modules = ['common_test', 'url_alter_test'];
26
27  /**
28   * Confirms that invalid URLs are filtered in link generating functions.
29   */
30  public function testLinkXSS() {
31    // Test link generator.
32    $text = $this->randomMachineName();
33    $path = "<SCRIPT>alert('XSS')</SCRIPT>";
34    $encoded_path = "3CSCRIPT%3Ealert%28%27XSS%27%29%3C/SCRIPT%3E";
35
36    $link = Link::fromTextAndUrl($text, Url::fromUserInput('/' . $path))->toString();
37    $this->assertStringContainsString($encoded_path, $link, new FormattableMarkup('XSS attack @path was filtered by \Drupal\Core\Utility\LinkGeneratorInterface::generate().', ['@path' => $path]));
38    $this->assertStringNotContainsString($path, $link, new FormattableMarkup('XSS attack @path was filtered by \Drupal\Core\Utility\LinkGeneratorInterface::generate().', ['@path' => $path]));
39
40    // Test \Drupal\Core\Url.
41    $link = Url::fromUri('base:' . $path)->toString();
42    $this->assertStringContainsString($encoded_path, $link, new FormattableMarkup('XSS attack @path was filtered by #theme', ['@path' => $path]));
43    $this->assertStringNotContainsString($path, $link, new FormattableMarkup('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  public function testLinkBubbleableMetadata() {
50    \Drupal::service('module_installer')->install(['user']);
51
52    $cases = [
53      ['Regular link', 'internal:/user', [], ['contexts' => [], 'tags' => [], 'max-age' => Cache::PERMANENT], []],
54      ['Regular link, absolute', 'internal:/user', ['absolute' => TRUE], ['contexts' => ['url.site'], 'tags' => [], 'max-age' => Cache::PERMANENT], []],
55      ['Route processor link', 'route:system.run_cron', [], ['contexts' => ['session'], 'tags' => [], 'max-age' => Cache::PERMANENT], ['placeholders' => []]],
56      ['Route processor link, absolute', 'route:system.run_cron', ['absolute' => TRUE], ['contexts' => ['url.site', 'session'], 'tags' => [], 'max-age' => Cache::PERMANENT], ['placeholders' => []]],
57      ['Path processor link', 'internal:/user/1', [], ['contexts' => [], 'tags' => ['user:1'], 'max-age' => Cache::PERMANENT], []],
58      ['Path processor link, absolute', 'internal:/user/1', ['absolute' => TRUE], ['contexts' => ['url.site'], 'tags' => ['user:1'], 'max-age' => Cache::PERMANENT], []],
59    ];
60
61    foreach ($cases as $case) {
62      list($title, $uri, $options, $expected_cacheability, $expected_attachments) = $case;
63      $expected_cacheability['contexts'] = Cache::mergeContexts($expected_cacheability['contexts'], ['languages:language_interface', 'theme', 'user.permissions']);
64      $link = [
65        '#type' => 'link',
66        '#title' => $title,
67        '#options' => $options,
68        '#url' => Url::fromUri($uri),
69      ];
70      \Drupal::service('renderer')->renderRoot($link);
71      $this->assertEquals($expected_cacheability, $link['#cache']);
72      $this->assertEquals($expected_attachments, $link['#attached']);
73    }
74  }
75
76  /**
77   * Tests that default and custom attributes are handled correctly on links.
78   */
79  public function testLinkAttributes() {
80    /** @var \Drupal\Core\Render\RendererInterface $renderer */
81    $renderer = $this->container->get('renderer');
82
83    // Test that hreflang is added when a link has a known language.
84    $language = new Language(['id' => 'fr', 'name' => 'French']);
85    $hreflang_link = [
86      '#type' => 'link',
87      '#options' => [
88        'language' => $language,
89      ],
90      '#url' => Url::fromUri('https://www.drupal.org'),
91      '#title' => 'bar',
92    ];
93    $langcode = $language->getId();
94
95    // Test that the default hreflang handling for links does not override a
96    // hreflang attribute explicitly set in the render array.
97    $hreflang_override_link = $hreflang_link;
98    $hreflang_override_link['#options']['attributes']['hreflang'] = 'foo';
99
100    $rendered = $renderer->renderRoot($hreflang_link);
101    $this->assertTrue($this->hasAttribute('hreflang', $rendered, $langcode), new FormattableMarkup('hreflang attribute with value @langcode is present on a rendered link when langcode is provided in the render array.', ['@langcode' => $langcode]));
102
103    $rendered = $renderer->renderRoot($hreflang_override_link);
104    $this->assertTrue($this->hasAttribute('hreflang', $rendered, 'foo'), new FormattableMarkup('hreflang attribute with value @hreflang is present on a rendered link when @hreflang is provided in the render array.', ['@hreflang' => 'foo']));
105
106    // Test adding a custom class in links produced by
107    // \Drupal\Core\Utility\LinkGeneratorInterface::generate() and #type 'link'.
108    // Test the link generator.
109    $class_l = $this->randomMachineName();
110    $link_l = Link::fromTextAndUrl($this->randomMachineName(), Url::fromRoute('common_test.destination', [], ['attributes' => ['class' => [$class_l]]]))->toString();
111    $this->assertTrue($this->hasAttribute('class', $link_l, $class_l), new FormattableMarkup('Custom class @class is present on link when requested by Link::toString()', ['@class' => $class_l]));
112
113    // Test #type.
114    $class_theme = $this->randomMachineName();
115    $type_link = [
116      '#type' => 'link',
117      '#title' => $this->randomMachineName(),
118      '#url' => Url::fromRoute('common_test.destination'),
119      '#options' => [
120        'attributes' => [
121          'class' => [$class_theme],
122        ],
123      ],
124    ];
125    $link_theme = $renderer->renderRoot($type_link);
126    $this->assertTrue($this->hasAttribute('class', $link_theme, $class_theme), new FormattableMarkup('Custom class @class is present on link when requested by #type', ['@class' => $class_theme]));
127  }
128
129  /**
130   * Tests that link functions support render arrays as 'text'.
131   */
132  public function testLinkRenderArrayText() {
133    /** @var \Drupal\Core\Render\RendererInterface $renderer */
134    $renderer = $this->container->get('renderer');
135
136    // Build a link with the link generator for reference.
137    $l = Link::fromTextAndUrl('foo', Url::fromUri('https://www.drupal.org'))->toString();
138
139    // Test a renderable array passed to the link generator.
140    $renderer->executeInRenderContext(new RenderContext(), function () use ($renderer, $l) {
141      $renderable_text = ['#markup' => 'foo'];
142      $l_renderable_text = \Drupal::service('link_generator')->generate($renderable_text, Url::fromUri('https://www.drupal.org'));
143      $this->assertEquals($l, $l_renderable_text);
144    });
145
146    // Test a themed link with plain text 'text'.
147    $type_link_plain_array = [
148      '#type' => 'link',
149      '#title' => 'foo',
150      '#url' => Url::fromUri('https://www.drupal.org'),
151    ];
152    $type_link_plain = $renderer->renderRoot($type_link_plain_array);
153    $this->assertEquals($l, $type_link_plain);
154
155    // Build a themed link with renderable 'text'.
156    $type_link_nested_array = [
157      '#type' => 'link',
158      '#title' => ['#markup' => 'foo'],
159      '#url' => Url::fromUri('https://www.drupal.org'),
160    ];
161    $type_link_nested = $renderer->renderRoot($type_link_nested_array);
162    $this->assertEquals($l, $type_link_nested);
163  }
164
165  /**
166   * Checks for class existence in link.
167   *
168   * @param $attribute
169   * @param $link
170   *   URL to search.
171   * @param $class
172   *   Element class to search for.
173   *
174   * @return bool
175   *   TRUE if the class is found, FALSE otherwise.
176   */
177  private function hasAttribute($attribute, $link, $class) {
178    return (bool) preg_match('|' . $attribute . '="([^\"\s]+\s+)*' . $class . '|', $link);
179  }
180
181  /**
182   * Tests UrlHelper::filterQueryParameters().
183   */
184  public function testDrupalGetQueryParameters() {
185    $original = [
186      'a' => 1,
187      'b' => [
188        'd' => 4,
189        'e' => [
190          'f' => 5,
191        ],
192      ],
193      'c' => 3,
194    ];
195
196    // First-level exclusion.
197    $result = $original;
198    unset($result['b']);
199    $this->assertEquals(UrlHelper::filterQueryParameters($original, ['b']), $result, "'b' was removed.");
200
201    // Second-level exclusion.
202    $result = $original;
203    unset($result['b']['d']);
204    $this->assertEquals(UrlHelper::filterQueryParameters($original, ['b[d]']), $result, "'b[d]' was removed.");
205
206    // Third-level exclusion.
207    $result = $original;
208    unset($result['b']['e']['f']);
209    $this->assertEquals(UrlHelper::filterQueryParameters($original, ['b[e][f]']), $result, "'b[e][f]' was removed.");
210
211    // Multiple exclusions.
212    $result = $original;
213    unset($result['a'], $result['b']['e'], $result['c']);
214    $this->assertEquals(UrlHelper::filterQueryParameters($original, ['a', 'b[e]', 'c']), $result, "'a', 'b[e]', 'c' were removed.");
215  }
216
217  /**
218   * Tests UrlHelper::parse().
219   */
220  public function testDrupalParseUrl() {
221    // Relative, absolute, and external URLs, without/with explicit script path,
222    // without/with Drupal path.
223    foreach (['', '/', 'https://www.drupal.org/'] as $absolute) {
224      foreach (['', 'index.php/'] as $script) {
225        foreach (['', 'foo/bar'] as $path) {
226          $url = $absolute . $script . $path . '?foo=bar&bar=baz&baz#foo';
227          $expected = [
228            'path' => $absolute . $script . $path,
229            'query' => ['foo' => 'bar', 'bar' => 'baz', 'baz' => ''],
230            'fragment' => 'foo',
231          ];
232          $this->assertEquals($expected, UrlHelper::parse($url), 'URL parsed correctly.');
233        }
234      }
235    }
236
237    // Relative URL that is known to confuse parse_url().
238    $url = 'foo/bar:1';
239    $result = [
240      'path' => 'foo/bar:1',
241      'query' => [],
242      'fragment' => '',
243    ];
244    $this->assertEquals($result, UrlHelper::parse($url), 'Relative URL parsed correctly.');
245
246    // Test that drupal can recognize an absolute URL. Used to prevent attack vectors.
247    $url = 'https://www.drupal.org/foo/bar?foo=bar&bar=baz&baz#foo';
248    $this->assertTrue(UrlHelper::isExternal($url), 'Correctly identified an external URL.');
249
250    // Test that UrlHelper::parse() does not allow spoofing a URL to force a malicious redirect.
251    $parts = UrlHelper::parse('forged:http://cwe.mitre.org/data/definitions/601.html');
252    $this->assertFalse(UrlHelper::isValid($parts['path'], TRUE), '\Drupal\Component\Utility\UrlHelper::isValid() correctly parsed a forged URL.');
253  }
254
255  /**
256   * Tests external URL handling.
257   */
258  public function testExternalUrls() {
259    $test_url = 'https://www.drupal.org/';
260
261    // Verify external URL can contain a fragment.
262    $url = $test_url . '#drupal';
263    $result = Url::fromUri($url)->toString();
264    $this->assertEquals($url, $result, 'External URL with fragment works without a fragment in $options.');
265
266    // Verify fragment can be overridden in an external URL.
267    $url = $test_url . '#drupal';
268    $fragment = $this->randomMachineName(10);
269    $result = Url::fromUri($url, ['fragment' => $fragment])->toString();
270    $this->assertEquals($test_url . '#' . $fragment, $result, 'External URL fragment is overridden with a custom fragment in $options.');
271
272    // Verify external URL can contain a query string.
273    $url = $test_url . '?drupal=awesome';
274    $result = Url::fromUri($url)->toString();
275    $this->assertEquals($url, $result);
276
277    // Verify external URL can contain a query string with an integer key.
278    $url = $test_url . '?120=1';
279    $result = Url::fromUri($url)->toString();
280    $this->assertEquals($url, $result);
281
282    // Verify external URL can be extended with a query string.
283    $url = $test_url;
284    $query = ['awesome' => 'drupal'];
285    $result = Url::fromUri($url, ['query' => $query])->toString();
286    $this->assertSame('https://www.drupal.org/?awesome=drupal', $result);
287
288    // Verify query string can be extended in an external URL.
289    $url = $test_url . '?drupal=awesome';
290    $query = ['awesome' => 'drupal'];
291    $result = Url::fromUri($url, ['query' => $query])->toString();
292    $this->assertEquals('https://www.drupal.org/?drupal=awesome&awesome=drupal', $result);
293  }
294
295}
296