• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2013 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "url/url_util.h"
6 
7 #include <stddef.h>
8 
9 #include <optional>
10 #include <string_view>
11 
12 #include "base/test/scoped_feature_list.h"
13 #include "build/build_config.h"
14 #include "testing/gtest/include/gtest/gtest-message.h"
15 #include "testing/gtest/include/gtest/gtest.h"
16 #include "url/third_party/mozilla/url_parse.h"
17 #include "url/url_canon.h"
18 #include "url/url_canon_stdstring.h"
19 #include "url/url_features.h"
20 #include "url/url_test_utils.h"
21 
22 namespace url {
23 
24 class URLUtilTest : public testing::Test {
25  public:
26   URLUtilTest() = default;
27 
28   URLUtilTest(const URLUtilTest&) = delete;
29   URLUtilTest& operator=(const URLUtilTest&) = delete;
30 
31   ~URLUtilTest() override = default;
32 
33  private:
34   ScopedSchemeRegistryForTests scoped_registry_;
35 };
36 
TEST_F(URLUtilTest,FindAndCompareScheme)37 TEST_F(URLUtilTest, FindAndCompareScheme) {
38   Component found_scheme;
39 
40   // Simple case where the scheme is found and matches.
41   const char kStr1[] = "http://www.com/";
42   EXPECT_TRUE(FindAndCompareScheme(kStr1, static_cast<int>(strlen(kStr1)),
43                                    "http", nullptr));
44   EXPECT_TRUE(FindAndCompareScheme(
45       kStr1, static_cast<int>(strlen(kStr1)), "http", &found_scheme));
46   EXPECT_TRUE(found_scheme == Component(0, 4));
47 
48   // A case where the scheme is found and doesn't match.
49   EXPECT_FALSE(FindAndCompareScheme(
50       kStr1, static_cast<int>(strlen(kStr1)), "https", &found_scheme));
51   EXPECT_TRUE(found_scheme == Component(0, 4));
52 
53   // A case where there is no scheme.
54   const char kStr2[] = "httpfoobar";
55   EXPECT_FALSE(FindAndCompareScheme(
56       kStr2, static_cast<int>(strlen(kStr2)), "http", &found_scheme));
57   EXPECT_TRUE(found_scheme == Component());
58 
59   // When there is an empty scheme, it should match the empty scheme.
60   const char kStr3[] = ":foo.com/";
61   EXPECT_TRUE(FindAndCompareScheme(
62       kStr3, static_cast<int>(strlen(kStr3)), "", &found_scheme));
63   EXPECT_TRUE(found_scheme == Component(0, 0));
64 
65   // But when there is no scheme, it should fail.
66   EXPECT_FALSE(FindAndCompareScheme("", 0, "", &found_scheme));
67   EXPECT_TRUE(found_scheme == Component());
68 
69   // When there is a whitespace char in scheme, it should canonicalize the URL
70   // before comparison.
71   const char whtspc_str[] = " \r\n\tjav\ra\nscri\tpt:alert(1)";
72   EXPECT_TRUE(FindAndCompareScheme(whtspc_str,
73                                    static_cast<int>(strlen(whtspc_str)),
74                                    "javascript", &found_scheme));
75   EXPECT_TRUE(found_scheme == Component(1, 10));
76 
77   // Control characters should be stripped out on the ends, and kept in the
78   // middle.
79   const char ctrl_str[] = "\02jav\02scr\03ipt:alert(1)";
80   EXPECT_FALSE(FindAndCompareScheme(ctrl_str,
81                                     static_cast<int>(strlen(ctrl_str)),
82                                     "javascript", &found_scheme));
83   EXPECT_TRUE(found_scheme == Component(1, 11));
84 }
85 
TEST_F(URLUtilTest,IsStandard)86 TEST_F(URLUtilTest, IsStandard) {
87   const char kHTTPScheme[] = "http";
88   EXPECT_TRUE(IsStandard(kHTTPScheme, Component(0, strlen(kHTTPScheme))));
89 
90   const char kFooScheme[] = "foo";
91   EXPECT_FALSE(IsStandard(kFooScheme, Component(0, strlen(kFooScheme))));
92 }
93 
TEST_F(URLUtilTest,IsReferrerScheme)94 TEST_F(URLUtilTest, IsReferrerScheme) {
95   const char kHTTPScheme[] = "http";
96   EXPECT_TRUE(IsReferrerScheme(kHTTPScheme, Component(0, strlen(kHTTPScheme))));
97 
98   const char kFooScheme[] = "foo";
99   EXPECT_FALSE(IsReferrerScheme(kFooScheme, Component(0, strlen(kFooScheme))));
100 }
101 
TEST_F(URLUtilTest,AddReferrerScheme)102 TEST_F(URLUtilTest, AddReferrerScheme) {
103   static const char kFooScheme[] = "foo";
104   EXPECT_FALSE(IsReferrerScheme(kFooScheme, Component(0, strlen(kFooScheme))));
105 
106   url::ScopedSchemeRegistryForTests scoped_registry;
107   AddReferrerScheme(kFooScheme, url::SCHEME_WITH_HOST);
108   EXPECT_TRUE(IsReferrerScheme(kFooScheme, Component(0, strlen(kFooScheme))));
109 }
110 
TEST_F(URLUtilTest,ShutdownCleansUpSchemes)111 TEST_F(URLUtilTest, ShutdownCleansUpSchemes) {
112   static const char kFooScheme[] = "foo";
113   EXPECT_FALSE(IsReferrerScheme(kFooScheme, Component(0, strlen(kFooScheme))));
114 
115   {
116     url::ScopedSchemeRegistryForTests scoped_registry;
117     AddReferrerScheme(kFooScheme, url::SCHEME_WITH_HOST);
118     EXPECT_TRUE(IsReferrerScheme(kFooScheme, Component(0, strlen(kFooScheme))));
119   }
120 
121   EXPECT_FALSE(IsReferrerScheme(kFooScheme, Component(0, strlen(kFooScheme))));
122 }
123 
TEST_F(URLUtilTest,GetStandardSchemeType)124 TEST_F(URLUtilTest, GetStandardSchemeType) {
125   url::SchemeType scheme_type;
126 
127   const char kHTTPScheme[] = "http";
128   scheme_type = url::SCHEME_WITHOUT_AUTHORITY;
129   EXPECT_TRUE(GetStandardSchemeType(kHTTPScheme,
130                                     Component(0, strlen(kHTTPScheme)),
131                                     &scheme_type));
132   EXPECT_EQ(url::SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION, scheme_type);
133 
134   const char kFilesystemScheme[] = "filesystem";
135   scheme_type = url::SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION;
136   EXPECT_TRUE(GetStandardSchemeType(kFilesystemScheme,
137                                     Component(0, strlen(kFilesystemScheme)),
138                                     &scheme_type));
139   EXPECT_EQ(url::SCHEME_WITHOUT_AUTHORITY, scheme_type);
140 
141   const char kFooScheme[] = "foo";
142   scheme_type = url::SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION;
143   EXPECT_FALSE(GetStandardSchemeType(kFooScheme,
144                                      Component(0, strlen(kFooScheme)),
145                                      &scheme_type));
146 }
147 
TEST_F(URLUtilTest,GetStandardSchemes)148 TEST_F(URLUtilTest, GetStandardSchemes) {
149   std::vector<std::string> expected = {
150       kHttpsScheme, kHttpScheme, kFileScheme,       kFtpScheme,
151       kWssScheme,   kWsScheme,   kFileSystemScheme, "foo",
152   };
153   AddStandardScheme("foo", url::SCHEME_WITHOUT_AUTHORITY);
154   EXPECT_EQ(expected, GetStandardSchemes());
155 }
156 
TEST_F(URLUtilTest,ReplaceComponents)157 TEST_F(URLUtilTest, ReplaceComponents) {
158   Parsed parsed;
159   RawCanonOutputT<char> output;
160   Parsed new_parsed;
161 
162   // Check that the following calls do not cause crash
163   Replacements<char> replacements;
164   replacements.SetRef("test", Component(0, 4));
165   ReplaceComponents(nullptr, 0, parsed, replacements, nullptr, &output,
166                     &new_parsed);
167   ReplaceComponents("", 0, parsed, replacements, nullptr, &output, &new_parsed);
168   replacements.ClearRef();
169   replacements.SetHost("test", Component(0, 4));
170   ReplaceComponents(nullptr, 0, parsed, replacements, nullptr, &output,
171                     &new_parsed);
172   ReplaceComponents("", 0, parsed, replacements, nullptr, &output, &new_parsed);
173 
174   replacements.ClearHost();
175   ReplaceComponents(nullptr, 0, parsed, replacements, nullptr, &output,
176                     &new_parsed);
177   ReplaceComponents("", 0, parsed, replacements, nullptr, &output, &new_parsed);
178   ReplaceComponents(nullptr, 0, parsed, replacements, nullptr, &output,
179                     &new_parsed);
180   ReplaceComponents("", 0, parsed, replacements, nullptr, &output, &new_parsed);
181 }
182 
CheckReplaceScheme(const char * base_url,const char * scheme)183 static std::string CheckReplaceScheme(const char* base_url,
184                                       const char* scheme) {
185   // Make sure the input is canonicalized.
186   RawCanonOutput<32> original;
187   Parsed original_parsed;
188   Canonicalize(base_url, strlen(base_url), true, nullptr, &original,
189                &original_parsed);
190 
191   Replacements<char> replacements;
192   replacements.SetScheme(scheme, Component(0, strlen(scheme)));
193 
194   std::string output_string;
195   StdStringCanonOutput output(&output_string);
196   Parsed output_parsed;
197   ReplaceComponents(original.data(), original.length(), original_parsed,
198                     replacements, nullptr, &output, &output_parsed);
199 
200   output.Complete();
201   return output_string;
202 }
203 
TEST_F(URLUtilTest,ReplaceScheme)204 TEST_F(URLUtilTest, ReplaceScheme) {
205   EXPECT_EQ("https://google.com/",
206             CheckReplaceScheme("http://google.com/", "https"));
207   EXPECT_EQ("file://google.com/",
208             CheckReplaceScheme("http://google.com/", "file"));
209   EXPECT_EQ("http://home/Build",
210             CheckReplaceScheme("file:///Home/Build", "http"));
211   EXPECT_EQ("javascript:foo",
212             CheckReplaceScheme("about:foo", "javascript"));
213   EXPECT_EQ("://google.com/",
214             CheckReplaceScheme("http://google.com/", ""));
215   EXPECT_EQ("http://google.com/",
216             CheckReplaceScheme("about:google.com", "http"));
217   EXPECT_EQ("http:", CheckReplaceScheme("", "http"));
218 
219 #ifdef WIN32
220   // Magic Windows drive letter behavior when converting to a file URL.
221   EXPECT_EQ("file:///E:/foo/",
222             CheckReplaceScheme("http://localhost/e:foo/", "file"));
223 #endif
224 
225   // This will probably change to "about://google.com/" when we fix
226   // http://crbug.com/160 which should also be an acceptable result.
227   EXPECT_EQ("about://google.com/",
228             CheckReplaceScheme("http://google.com/", "about"));
229 
230   EXPECT_EQ("http://example.com/%20hello%20#%20world",
231             CheckReplaceScheme("myscheme:example.com/ hello # world ", "http"));
232 }
233 
TEST_F(URLUtilTest,DecodeURLEscapeSequences)234 TEST_F(URLUtilTest, DecodeURLEscapeSequences) {
235   struct DecodeCase {
236     const char* input;
237     const char* output;
238   } decode_cases[] = {
239       {"hello, world", "hello, world"},
240       {"%01%02%03%04%05%06%07%08%09%0a%0B%0C%0D%0e%0f/",
241        "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0B\x0C\x0D\x0e\x0f/"},
242       {"%10%11%12%13%14%15%16%17%18%19%1a%1B%1C%1D%1e%1f/",
243        "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1B\x1C\x1D\x1e\x1f/"},
244       {"%20%21%22%23%24%25%26%27%28%29%2a%2B%2C%2D%2e%2f/",
245        " !\"#$%&'()*+,-.//"},
246       {"%30%31%32%33%34%35%36%37%38%39%3a%3B%3C%3D%3e%3f/",
247        "0123456789:;<=>?/"},
248       {"%40%41%42%43%44%45%46%47%48%49%4a%4B%4C%4D%4e%4f/",
249        "@ABCDEFGHIJKLMNO/"},
250       {"%50%51%52%53%54%55%56%57%58%59%5a%5B%5C%5D%5e%5f/",
251        "PQRSTUVWXYZ[\\]^_/"},
252       {"%60%61%62%63%64%65%66%67%68%69%6a%6B%6C%6D%6e%6f/",
253        "`abcdefghijklmno/"},
254       {"%70%71%72%73%74%75%76%77%78%79%7a%7B%7C%7D%7e%7f/",
255        "pqrstuvwxyz{|}~\x7f/"},
256       {"%e4%bd%a0%e5%a5%bd", "\xe4\xbd\xa0\xe5\xa5\xbd"},
257       // U+FFFF (Noncharacter) should not be replaced with U+FFFD (Replacement
258       // Character) (http://crbug.com/1416021)
259       {"%ef%bf%bf", "\xef\xbf\xbf"},
260       // U+FDD0 (Noncharacter)
261       {"%ef%b7%90", "\xef\xb7\x90"},
262       // U+FFFD (Replacement Character)
263       {"%ef%bf%bd", "\xef\xbf\xbd"},
264   };
265 
266   for (const auto& decode_case : decode_cases) {
267     RawCanonOutputT<char16_t> output;
268     DecodeURLEscapeSequences(decode_case.input,
269                              DecodeURLMode::kUTF8OrIsomorphic, &output);
270     EXPECT_EQ(decode_case.output, base::UTF16ToUTF8(std::u16string(
271                                       output.data(), output.length())));
272 
273     RawCanonOutputT<char16_t> output_utf8;
274     DecodeURLEscapeSequences(decode_case.input, DecodeURLMode::kUTF8,
275                              &output_utf8);
276     EXPECT_EQ(decode_case.output,
277               base::UTF16ToUTF8(
278                   std::u16string(output_utf8.data(), output_utf8.length())));
279   }
280 
281   // Our decode should decode %00
282   const char zero_input[] = "%00";
283   RawCanonOutputT<char16_t> zero_output;
284   DecodeURLEscapeSequences(zero_input, DecodeURLMode::kUTF8, &zero_output);
285   EXPECT_NE("%00", base::UTF16ToUTF8(std::u16string(zero_output.data(),
286                                                     zero_output.length())));
287 
288   // Test the error behavior for invalid UTF-8.
289   struct Utf8DecodeCase {
290     const char* input;
291     std::vector<char16_t> expected_iso;
292     std::vector<char16_t> expected_utf8;
293   } utf8_decode_cases[] = {
294       // %e5%a5%bd is a valid UTF-8 sequence. U+597D
295       {"%e4%a0%e5%a5%bd",
296        {0x00e4, 0x00a0, 0x00e5, 0x00a5, 0x00bd, 0},
297        {0xfffd, 0x597d, 0}},
298       {"%e5%a5%bd%e4%a0",
299        {0x00e5, 0x00a5, 0x00bd, 0x00e4, 0x00a0, 0},
300        {0x597d, 0xfffd, 0}},
301       {"%e4%a0%e5%bd",
302        {0x00e4, 0x00a0, 0x00e5, 0x00bd, 0},
303        {0xfffd, 0xfffd, 0}},
304   };
305 
306   for (const auto& utf8_decode_case : utf8_decode_cases) {
307     RawCanonOutputT<char16_t> output_iso;
308     DecodeURLEscapeSequences(utf8_decode_case.input,
309                              DecodeURLMode::kUTF8OrIsomorphic, &output_iso);
310     EXPECT_EQ(std::u16string(utf8_decode_case.expected_iso.data()),
311               std::u16string(output_iso.data(), output_iso.length()));
312 
313     RawCanonOutputT<char16_t> output_utf8;
314     DecodeURLEscapeSequences(utf8_decode_case.input, DecodeURLMode::kUTF8,
315                              &output_utf8);
316     EXPECT_EQ(std::u16string(utf8_decode_case.expected_utf8.data()),
317               std::u16string(output_utf8.data(), output_utf8.length()));
318   }
319 }
320 
TEST_F(URLUtilTest,TestEncodeURIComponent)321 TEST_F(URLUtilTest, TestEncodeURIComponent) {
322   struct EncodeCase {
323     const char* input;
324     const char* output;
325   } encode_cases[] = {
326     {"hello, world", "hello%2C%20world"},
327     {"\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F",
328      "%01%02%03%04%05%06%07%08%09%0A%0B%0C%0D%0E%0F"},
329     {"\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F",
330      "%10%11%12%13%14%15%16%17%18%19%1A%1B%1C%1D%1E%1F"},
331     {" !\"#$%&'()*+,-./",
332      "%20!%22%23%24%25%26%27()*%2B%2C-.%2F"},
333     {"0123456789:;<=>?",
334      "0123456789%3A%3B%3C%3D%3E%3F"},
335     {"@ABCDEFGHIJKLMNO",
336      "%40ABCDEFGHIJKLMNO"},
337     {"PQRSTUVWXYZ[\\]^_",
338      "PQRSTUVWXYZ%5B%5C%5D%5E_"},
339     {"`abcdefghijklmno",
340      "%60abcdefghijklmno"},
341     {"pqrstuvwxyz{|}~\x7f",
342      "pqrstuvwxyz%7B%7C%7D~%7F"},
343   };
344 
345   for (const auto& encode_case : encode_cases) {
346     RawCanonOutputT<char> buffer;
347     EncodeURIComponent(encode_case.input, &buffer);
348     std::string output(buffer.data(), buffer.length());
349     EXPECT_EQ(encode_case.output, output);
350   }
351 }
352 
TEST_F(URLUtilTest,PotentiallyDanglingMarkup)353 TEST_F(URLUtilTest, PotentiallyDanglingMarkup) {
354   struct ResolveRelativeCase {
355     const char* base;
356     const char* rel;
357     bool potentially_dangling_markup;
358     const char* out;
359   } cases[] = {
360       {"https://example.com/", "/path<", false, "https://example.com/path%3C"},
361       {"https://example.com/", "\n/path<", true, "https://example.com/path%3C"},
362       {"https://example.com/", "\r/path<", true, "https://example.com/path%3C"},
363       {"https://example.com/", "\t/path<", true, "https://example.com/path%3C"},
364       {"https://example.com/", "/pa\nth<", true, "https://example.com/path%3C"},
365       {"https://example.com/", "/pa\rth<", true, "https://example.com/path%3C"},
366       {"https://example.com/", "/pa\tth<", true, "https://example.com/path%3C"},
367       {"https://example.com/", "/path\n<", true, "https://example.com/path%3C"},
368       {"https://example.com/", "/path\r<", true, "https://example.com/path%3C"},
369       {"https://example.com/", "/path\r<", true, "https://example.com/path%3C"},
370       {"https://example.com/", "\n/<path", true, "https://example.com/%3Cpath"},
371       {"https://example.com/", "\r/<path", true, "https://example.com/%3Cpath"},
372       {"https://example.com/", "\t/<path", true, "https://example.com/%3Cpath"},
373       {"https://example.com/", "/<pa\nth", true, "https://example.com/%3Cpath"},
374       {"https://example.com/", "/<pa\rth", true, "https://example.com/%3Cpath"},
375       {"https://example.com/", "/<pa\tth", true, "https://example.com/%3Cpath"},
376       {"https://example.com/", "/<path\n", true, "https://example.com/%3Cpath"},
377       {"https://example.com/", "/<path\r", true, "https://example.com/%3Cpath"},
378       {"https://example.com/", "/<path\r", true, "https://example.com/%3Cpath"},
379   };
380 
381   for (const auto& test : cases) {
382     SCOPED_TRACE(::testing::Message() << test.base << ", " << test.rel);
383     Parsed base_parsed = ParseStandardURL(test.base);
384 
385     std::string resolved;
386     StdStringCanonOutput output(&resolved);
387     Parsed resolved_parsed;
388     bool valid =
389         ResolveRelative(test.base, strlen(test.base), base_parsed, test.rel,
390                         strlen(test.rel), nullptr, &output, &resolved_parsed);
391     ASSERT_TRUE(valid);
392     output.Complete();
393 
394     EXPECT_EQ(test.potentially_dangling_markup,
395               resolved_parsed.potentially_dangling_markup);
396     EXPECT_EQ(test.out, resolved);
397   }
398 }
399 
TEST_F(URLUtilTest,PotentiallyDanglingMarkupAfterReplacement)400 TEST_F(URLUtilTest, PotentiallyDanglingMarkupAfterReplacement) {
401   // Parse a URL with potentially dangling markup.
402   Parsed original_parsed;
403   RawCanonOutput<32> original;
404   const char* url = "htt\nps://example.com/<path";
405   Canonicalize(url, strlen(url), false, nullptr, &original, &original_parsed);
406   ASSERT_TRUE(original_parsed.potentially_dangling_markup);
407 
408   // Perform a replacement, and validate that the potentially_dangling_markup
409   // flag carried over to the new Parsed object.
410   Replacements<char> replacements;
411   replacements.ClearRef();
412   Parsed replaced_parsed;
413   RawCanonOutput<32> replaced;
414   ReplaceComponents(original.data(), original.length(), original_parsed,
415                     replacements, nullptr, &replaced, &replaced_parsed);
416   EXPECT_TRUE(replaced_parsed.potentially_dangling_markup);
417 }
418 
TEST_F(URLUtilTest,PotentiallyDanglingMarkupAfterSchemeOnlyReplacement)419 TEST_F(URLUtilTest, PotentiallyDanglingMarkupAfterSchemeOnlyReplacement) {
420   // Parse a URL with potentially dangling markup.
421   Parsed original_parsed;
422   RawCanonOutput<32> original;
423   const char* url = "http://example.com/\n/<path";
424   Canonicalize(url, strlen(url), false, nullptr, &original, &original_parsed);
425   ASSERT_TRUE(original_parsed.potentially_dangling_markup);
426 
427   // Perform a replacement, and validate that the potentially_dangling_markup
428   // flag carried over to the new Parsed object.
429   Replacements<char> replacements;
430   const char* new_scheme = "https";
431   replacements.SetScheme(new_scheme, Component(0, strlen(new_scheme)));
432   Parsed replaced_parsed;
433   RawCanonOutput<32> replaced;
434   ReplaceComponents(original.data(), original.length(), original_parsed,
435                     replacements, nullptr, &replaced, &replaced_parsed);
436   EXPECT_TRUE(replaced_parsed.potentially_dangling_markup);
437 }
438 
TEST_F(URLUtilTest,TestDomainIs)439 TEST_F(URLUtilTest, TestDomainIs) {
440   const struct {
441     const char* canonicalized_host;
442     const char* lower_ascii_domain;
443     bool expected_domain_is;
444   } kTestCases[] = {
445       {"google.com", "google.com", true},
446       {"www.google.com", "google.com", true},      // Subdomain is ignored.
447       {"www.google.com.cn", "google.com", false},  // Different TLD.
448       {"www.google.comm", "google.com", false},
449       {"www.iamnotgoogle.com", "google.com", false},  // Different hostname.
450       {"www.google.com", "Google.com", false},  // The input is not lower-cased.
451 
452       // If the host ends with a dot, it matches domains with or without a dot.
453       {"www.google.com.", "google.com", true},
454       {"www.google.com.", "google.com.", true},
455       {"www.google.com.", ".com", true},
456       {"www.google.com.", ".com.", true},
457 
458       // But, if the host doesn't end with a dot and the input domain does, then
459       // it's considered to not match.
460       {"www.google.com", "google.com.", false},
461 
462       // If the host ends with two dots, it doesn't match.
463       {"www.google.com..", "google.com", false},
464 
465       // Empty parameters.
466       {"www.google.com", "", false},
467       {"", "www.google.com", false},
468       {"", "", false},
469   };
470 
471   for (const auto& test_case : kTestCases) {
472     SCOPED_TRACE(testing::Message() << "(host, domain): ("
473                                     << test_case.canonicalized_host << ", "
474                                     << test_case.lower_ascii_domain << ")");
475 
476     EXPECT_EQ(
477         test_case.expected_domain_is,
478         DomainIs(test_case.canonicalized_host, test_case.lower_ascii_domain));
479   }
480 }
481 
482 namespace {
CanonicalizeSpec(std::string_view spec,bool trim_path_end)483 std::optional<std::string> CanonicalizeSpec(std::string_view spec,
484                                             bool trim_path_end) {
485   std::string canonicalized;
486   StdStringCanonOutput output(&canonicalized);
487   Parsed parsed;
488   if (!Canonicalize(spec.data(), spec.size(), trim_path_end,
489                     /*charset_converter=*/nullptr, &output, &parsed)) {
490     return {};
491   }
492   output.Complete();  // Must be called before string is used.
493   return canonicalized;
494 }
495 }  // namespace
496 
497 #if BUILDFLAG(IS_WIN)
498 // Regression test for https://crbug.com/1252658.
TEST_F(URLUtilTest,TestCanonicalizeWindowsPathWithLeadingNUL)499 TEST_F(URLUtilTest, TestCanonicalizeWindowsPathWithLeadingNUL) {
500   auto PrefixWithNUL = [](std::string&& s) -> std::string { return '\0' + s; };
501   EXPECT_EQ(CanonicalizeSpec(PrefixWithNUL("w:"), /*trim_path_end=*/false),
502             std::make_optional("file:///W:"));
503   EXPECT_EQ(CanonicalizeSpec(PrefixWithNUL("\\\\server\\share"),
504                              /*trim_path_end=*/false),
505             std::make_optional("file://server/share"));
506 }
507 #endif
508 
TEST_F(URLUtilTest,TestCanonicalizeIdempotencyWithLeadingControlCharacters)509 TEST_F(URLUtilTest, TestCanonicalizeIdempotencyWithLeadingControlCharacters) {
510   std::string spec = "_w:";
511   // Loop over all C0 control characters and the space character.
512   for (char c = '\0'; c <= ' '; c++) {
513     SCOPED_TRACE(testing::Message() << "c: " << c);
514 
515     // Overwrite the first character of `spec`. Note that replacing the first
516     // character with NUL will not change the length!
517     spec[0] = c;
518 
519     for (bool trim_path_end : {false, true}) {
520       SCOPED_TRACE(testing::Message() << "trim_path_end: " << trim_path_end);
521 
522       std::optional<std::string> canonicalized =
523           CanonicalizeSpec(spec, trim_path_end);
524       ASSERT_TRUE(canonicalized);
525       EXPECT_EQ(canonicalized, CanonicalizeSpec(*canonicalized, trim_path_end));
526     }
527   }
528 }
529 
TEST_F(URLUtilTest,TestHasInvalidURLEscapeSequences)530 TEST_F(URLUtilTest, TestHasInvalidURLEscapeSequences) {
531   struct TestCase {
532     const char* input;
533     bool is_invalid;
534   } cases[] = {
535       // Edge cases.
536       {"", false},
537       {"%", true},
538 
539       // Single regular chars with no escaping are valid.
540       {"a", false},
541       {"g", false},
542       {"A", false},
543       {"G", false},
544       {":", false},
545       {"]", false},
546       {"\x00", false},      // ASCII 'NUL' char
547       {"\x01", false},      // ASCII 'SOH' char
548       {"\xC2\xA3", false},  // UTF-8 encoded '£'.
549 
550       // Longer strings without escaping are valid.
551       {"Hello world", false},
552       {"Here: [%25] <-- a percent-encoded percent character.", false},
553 
554       // Valid %-escaped sequences ('%' followed by two hex digits).
555       {"%00", false},
556       {"%20", false},
557       {"%02", false},
558       {"%ff", false},
559       {"%FF", false},
560       {"%0a", false},
561       {"%0A", false},
562       {"abc%FF", false},
563       {"%FFabc", false},
564       {"abc%FFabc", false},
565       {"hello %FF world", false},
566       {"%20hello%20world", false},
567       {"%25", false},
568       {"%25%25", false},
569       {"%250", false},
570       {"%259", false},
571       {"%25A", false},
572       {"%25F", false},
573       {"%0a:", false},
574 
575       // '%' followed by a single character is never a valid sequence.
576       {"%%", true},
577       {"%2", true},
578       {"%a", true},
579       {"%A", true},
580       {"%g", true},
581       {"%G", true},
582       {"%:", true},
583       {"%[", true},
584       {"%F", true},
585       {"%\xC2\xA3", true},  //% followed by UTF-8 encoded '£'.
586 
587       // String ends on a potential escape sequence but without two hex-digits
588       // is invalid.
589       {"abc%", true},
590       {"abc%%", true},
591       {"abc%%%", true},
592       {"abc%a", true},
593 
594       // One hex and one non-hex digit is invalid.
595       {"%a:", true},
596       {"%:a", true},
597       {"%::", true},
598       {"%ag", true},
599       {"%ga", true},
600       {"%-1", true},
601       {"%1-", true},
602       {"%0\xC2\xA3", true},  // %0£.
603   };
604 
605   for (TestCase test_case : cases) {
606     const char* input = test_case.input;
607     bool result = HasInvalidURLEscapeSequences(input);
608     EXPECT_EQ(test_case.is_invalid, result)
609         << "Invalid result for '" << input << "'";
610   }
611 }
612 
613 class URLUtilTypedTest : public ::testing::TestWithParam<bool> {
614  public:
URLUtilTypedTest()615   URLUtilTypedTest()
616       : use_standard_compliant_non_special_scheme_url_parsing_(GetParam()) {
617     if (use_standard_compliant_non_special_scheme_url_parsing_) {
618       scoped_feature_list_.InitAndEnableFeature(
619           kStandardCompliantNonSpecialSchemeURLParsing);
620     } else {
621       scoped_feature_list_.InitAndDisableFeature(
622           kStandardCompliantNonSpecialSchemeURLParsing);
623     }
624   }
625 
626  protected:
627   struct URLCase {
628     const std::string_view input;
629     const std::string_view expected;
630     bool expected_success;
631   };
632 
633   struct ResolveRelativeCase {
634     const std::string_view base;
635     const std::string_view rel;
636     std::optional<std::string_view> expected;
637   };
638 
TestCanonicalize(const URLCase & url_case)639   void TestCanonicalize(const URLCase& url_case) {
640     std::string canonicalized;
641     StdStringCanonOutput output(&canonicalized);
642     Parsed parsed;
643     bool success =
644         Canonicalize(url_case.input.data(), url_case.input.size(),
645                      /*trim_path_end=*/false,
646                      /*charset_converter=*/nullptr, &output, &parsed);
647     output.Complete();
648     EXPECT_EQ(success, url_case.expected_success);
649     EXPECT_EQ(output.view(), url_case.expected);
650   }
651 
TestResolveRelative(const ResolveRelativeCase & test)652   void TestResolveRelative(const ResolveRelativeCase& test) {
653     SCOPED_TRACE(testing::Message()
654                  << "base: " << test.base << ", rel: " << test.rel);
655 
656     Parsed base_parsed =
657         url::IsUsingStandardCompliantNonSpecialSchemeURLParsing()
658             ? ParseNonSpecialURL(test.base)
659             : ParsePathURL(test.base, /*trim_path_end=*/true);
660 
661     std::string resolved;
662     StdStringCanonOutput output(&resolved);
663 
664     Parsed resolved_parsed;
665     bool valid = ResolveRelative(test.base.data(), test.base.size(),
666                                  base_parsed, test.rel.data(), test.rel.size(),
667                                  nullptr, &output, &resolved_parsed);
668     output.Complete();
669 
670     if (valid) {
671       ASSERT_TRUE(test.expected);
672       EXPECT_EQ(resolved, *test.expected);
673     } else {
674       EXPECT_FALSE(test.expected);
675     }
676   }
677 
678   bool use_standard_compliant_non_special_scheme_url_parsing_;
679 
680  private:
681   base::test::ScopedFeatureList scoped_feature_list_;
682 };
683 
TEST_P(URLUtilTypedTest,TestResolveRelativeWithNonStandardBase)684 TEST_P(URLUtilTypedTest, TestResolveRelativeWithNonStandardBase) {
685   // This tests non-standard (in the sense that IsStandard() == false)
686   // hierarchical schemes.
687   struct ResolveRelativeCase {
688     const char* base;
689     const char* rel;
690     bool is_valid;
691     const char* out;
692     // Optional expected output when the feature is enabled.
693     // If the result doesn't change, you can omit this field.
694     const char* out_when_non_special_url_feature_is_enabled;
695   } resolve_non_standard_cases[] = {
696       // Resolving a relative path against a non-hierarchical URL should fail.
697       {"scheme:opaque_data", "/path", false, ""},
698       // Resolving a relative path against a non-standard authority-based base
699       // URL doesn't alter the authority section.
700       {"scheme://Authority/", "../path", true, "scheme://Authority/path"},
701       // A non-standard hierarchical base is resolved with path URL
702       // canonicalization rules.
703       {"data:/Blah:Blah/", "file.html", true, "data:/Blah:Blah/file.html"},
704       {"data:/Path/../part/part2", "file.html", true,
705        "data:/Path/../part/file.html"},
706       {"data://text/html,payload", "//user:pass@host:33////payload22", true,
707        "data://user:pass@host:33////payload22"},
708       // Path URL canonicalization rules also apply to non-standard authority-
709       // based URLs.
710       {"custom://Authority/", "file.html", true,
711        "custom://Authority/file.html"},
712       {"custom://Authority/", "other://Auth/", true, "other://Auth/"},
713       {"custom://Authority/", "../../file.html", true,
714        "custom://Authority/file.html"},
715       {"custom://Authority/path/", "file.html", true,
716        "custom://Authority/path/file.html"},
717       {"custom://Authority:NoCanon/path/", "file.html", true,
718        "custom://Authority:NoCanon/path/file.html"},
719       // A path with an authority section gets canonicalized under standard URL
720       // rules, even though the base was non-standard.
721       {"content://content.Provider/", "//other.Provider", true,
722        "content://other.provider/",
723        // With the feature enabled:
724        // - Host case sensitivity should be preserved.
725        // - Trailing slash after a host is no longer necessary.
726        "content://other.Provider"},
727       // Resolving an absolute URL doesn't cause canonicalization of the
728       // result.
729       {"about:blank", "custom://Authority", true, "custom://Authority"},
730       // Fragment URLs can be resolved against a non-standard base.
731       {"scheme://Authority/path", "#fragment", true,
732        "scheme://Authority/path#fragment"},
733       {"scheme://Authority/", "#fragment", true,
734        "scheme://Authority/#fragment"},
735       // Test resolving a fragment (only) against any kind of base-URL.
736       {"about:blank", "#id42", true, "about:blank#id42"},
737       {"about:blank", " #id42", true, "about:blank#id42"},
738       {"about:blank#oldfrag", "#newfrag", true, "about:blank#newfrag"},
739       {"about:blank", " #id:42", true, "about:blank#id:42"},
740       // A surprising side effect of allowing fragments to resolve against
741       // any URL scheme is we might break javascript: URLs by doing so...
742       {"javascript:alert('foo#bar')", "#badfrag", true,
743        "javascript:alert('foo#badfrag"},
744   };
745 
746   for (const auto& test : resolve_non_standard_cases) {
747     SCOPED_TRACE(testing::Message()
748                  << "base: " << test.base << ", rel: " << test.rel);
749 
750     Parsed base_parsed = use_standard_compliant_non_special_scheme_url_parsing_
751                              ? ParseNonSpecialURL(test.base)
752                              : ParsePathURL(test.base, /*trim_path_end=*/true);
753 
754     std::string resolved;
755     StdStringCanonOutput output(&resolved);
756     Parsed resolved_parsed;
757     bool valid =
758         ResolveRelative(test.base, strlen(test.base), base_parsed, test.rel,
759                         strlen(test.rel), nullptr, &output, &resolved_parsed);
760     output.Complete();
761 
762     EXPECT_EQ(test.is_valid, valid);
763     if (test.is_valid && valid) {
764       if (use_standard_compliant_non_special_scheme_url_parsing_ &&
765           test.out_when_non_special_url_feature_is_enabled) {
766         EXPECT_EQ(test.out_when_non_special_url_feature_is_enabled, resolved);
767       } else {
768         EXPECT_EQ(test.out, resolved);
769       }
770     }
771   }
772 }
773 
TEST_P(URLUtilTypedTest,TestNoRefComponent)774 TEST_P(URLUtilTypedTest, TestNoRefComponent) {
775   // This test was originally written before full support for non-special URLs
776   // became available. We need a flag-dependent test here because the test uses
777   // an internal parse function. See http://crbug.com/40063064 for details.
778   //
779   // The test case corresponds to the following user scenario:
780   //
781   // > const url = new URL("any#body", "mailto://to/");
782   // > assertEquals(url.href, "mailto://to/any#body");
783   //
784   // TODO(crbug.com/40063064): Remove this test once the flag is enabled.
785   const std::string_view base = "mailto://to/";
786   const std::string_view rel = "any#body";
787   if (use_standard_compliant_non_special_scheme_url_parsing_) {
788     // We probably don't need to test with the flag enabled, however, including
789     // a test with the flag enabled would be beneficial for comparison purposes,
790     // at least until we enable the flag by default.
791     Parsed base_parsed = ParseNonSpecialURL(base);
792 
793     std::string resolved;
794     StdStringCanonOutput output(&resolved);
795     Parsed resolved_parsed;
796 
797     bool valid =
798         ResolveRelative(base.data(), base.size(), base_parsed, rel.data(),
799                         rel.size(), nullptr, &output, &resolved_parsed);
800     EXPECT_TRUE(valid);
801     // Note: If the flag is enabled and the correct parsing function is used,
802     // resolved_parsed.ref becomes valid correctly.
803     EXPECT_TRUE(resolved_parsed.ref.is_valid());
804     output.Complete();
805     EXPECT_EQ(resolved, "mailto://to/any#body");
806   } else {
807     // Note: See the description of https://codereview.chromium.org/767713002/
808     // for the intention of this test, which added this test to record a wrong
809     // result if a wrong parser function is used. I kept the following original
810     // comment as is:
811     //
812     // The hash-mark must be ignored when mailto: scheme is parsed,
813     // even if the URL has a base and relative part.
814     std::string resolved;
815     StdStringCanonOutput output(&resolved);
816     Parsed resolved_parsed;
817 
818     bool valid = ResolveRelative(
819         base.data(), base.size(), ParsePathURL(base, false), rel.data(),
820         rel.size(), nullptr, &output, &resolved_parsed);
821     EXPECT_TRUE(valid);
822     EXPECT_FALSE(resolved_parsed.ref.is_valid());
823   }
824 }
825 
TEST_P(URLUtilTypedTest,Cannolicalize)826 TEST_P(URLUtilTypedTest, Cannolicalize) {
827   // Verify that the feature flag changes canonicalization behavior,
828   // focusing on key cases here as comprehesive testing is covered in other unit
829   // tests.
830   if (use_standard_compliant_non_special_scheme_url_parsing_) {
831     URLCase cases[] = {
832         {"git://host/..", "git://host/", true},
833         {"git:// /", "git:///", false},
834         {"git:/..", "git:/", true},
835         {"mailto:/..", "mailto:/", true},
836     };
837     for (const auto& i : cases) {
838       TestCanonicalize(i);
839     }
840   } else {
841     // Every non-special URL is considered as an opaque path if the feature is
842     // disabled.
843     URLCase cases[] = {
844         {"git://host/..", "git://host/..", true},
845         {"git:// /", "git:// /", true},
846         {"git:/..", "git:/..", true},
847         {"mailto:/..", "mailto:/..", true},
848     };
849     for (const auto& i : cases) {
850       TestCanonicalize(i);
851     }
852   }
853 }
854 
TEST_P(URLUtilTypedTest,TestResolveRelativeWithNonSpecialBase)855 TEST_P(URLUtilTypedTest, TestResolveRelativeWithNonSpecialBase) {
856   // Test flag-dependent behaviors. Existing tests in
857   // URLUtilTest::TestResolveRelativeWithNonStandardBase cover common cases.
858   //
859   // TODO(crbug.com/40063064): Test common cases in this typed test too.
860   if (use_standard_compliant_non_special_scheme_url_parsing_) {
861     ResolveRelativeCase cases[] = {
862         {"scheme://Authority", "path", "scheme://Authority/path"},
863     };
864     for (const auto& i : cases) {
865       TestResolveRelative(i);
866     }
867   } else {
868     ResolveRelativeCase cases[] = {
869         // It's still possible to get an invalid path URL.
870         //
871         // Note: If the flag is enabled, "custom://Invalid:!#Auth/" is an
872         // invalid URL.
873         // ResolveRelative() should be never called.
874         {"custom://Invalid:!#Auth/", "file.html", std::nullopt},
875 
876         // Resolving should fail if the base URL is authority-based but is
877         // missing a path component (the '/' at the end).
878         {"scheme://Authority", "path", std::nullopt},
879 
880         // In this case, the backslashes will not be canonicalized because it's
881         // a non-standard URL, but they will be treated as a path separators,
882         // giving the base URL here a path of "\".
883         //
884         // The result here is somewhat arbitrary. One could argue it should be
885         // either "aaa://a\" or "aaa://a/" since the path is being replaced with
886         // the "current directory". But in the context of resolving on data
887         // URLs, adding the requested dot doesn't seem wrong either.
888         //
889         // Note: If the flag is enabled, "aaa://a\\" is an invalid URL.
890         // ResolveRelative() should be never called.
891         {"aaa://a\\", "aaa:.", "aaa://a\\."}};
892     for (const auto& i : cases) {
893       TestResolveRelative(i);
894     }
895   }
896 }
897 
TEST_P(URLUtilTypedTest,OpaqueNonSpecialScheme)898 TEST_P(URLUtilTypedTest, OpaqueNonSpecialScheme) {
899   // Ensure that the behavior of "android:" scheme URL is preserved, which is
900   // not URL Standard compliant.
901   //
902   // URL Standard-wise, "android://a b" is an invalid URL because the host part
903   // includes a space character, which is not allowed.
904   std::optional<std::string> res = CanonicalizeSpec("android://a b", false);
905   ASSERT_TRUE(res);
906   EXPECT_EQ(*res, "android://a b");
907 
908   // Test a "git:" scheme URL for comparison.
909   res = CanonicalizeSpec("git://a b", false);
910   if (use_standard_compliant_non_special_scheme_url_parsing_) {
911     // This is correct behavior because "git://a b" is an invalid URL.
912     EXPECT_FALSE(res);
913   } else {
914     ASSERT_TRUE(res);
915     EXPECT_EQ(*res, "git://a b");
916   }
917 }
918 
919 INSTANTIATE_TEST_SUITE_P(All, URLUtilTypedTest, ::testing::Bool());
920 
921 }  // namespace url
922