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,TestResolveRelativeWithNonStandardBase)353 TEST_F(URLUtilTest, TestResolveRelativeWithNonStandardBase) {
354 // This tests non-standard (in the sense that IsStandard() == false)
355 // hierarchical schemes.
356 struct ResolveRelativeCase {
357 const char* base;
358 const char* rel;
359 bool is_valid;
360 const char* out;
361 } resolve_non_standard_cases[] = {
362 // Resolving a relative path against a non-hierarchical URL should fail.
363 {"scheme:opaque_data", "/path", false, ""},
364 // Resolving a relative path against a non-standard authority-based base
365 // URL doesn't alter the authority section.
366 {"scheme://Authority/", "../path", true, "scheme://Authority/path"},
367 // A non-standard hierarchical base is resolved with path URL
368 // canonicalization rules.
369 {"data:/Blah:Blah/", "file.html", true, "data:/Blah:Blah/file.html"},
370 {"data:/Path/../part/part2", "file.html", true,
371 "data:/Path/../part/file.html"},
372 {"data://text/html,payload", "//user:pass@host:33////payload22", true,
373 "data://user:pass@host:33////payload22"},
374 // Path URL canonicalization rules also apply to non-standard authority-
375 // based URLs.
376 {"custom://Authority/", "file.html", true,
377 "custom://Authority/file.html"},
378 {"custom://Authority/", "other://Auth/", true, "other://Auth/"},
379 {"custom://Authority/", "../../file.html", true,
380 "custom://Authority/file.html"},
381 {"custom://Authority/path/", "file.html", true,
382 "custom://Authority/path/file.html"},
383 {"custom://Authority:NoCanon/path/", "file.html", true,
384 "custom://Authority:NoCanon/path/file.html"},
385 // A path with an authority section gets canonicalized under standard URL
386 // rules, even though the base was non-standard.
387 {"content://content.Provider/", "//other.Provider", true,
388 "content://other.provider/"},
389 // Resolving an absolute URL doesn't cause canonicalization of the
390 // result.
391 {"about:blank", "custom://Authority", true, "custom://Authority"},
392 // Fragment URLs can be resolved against a non-standard base.
393 {"scheme://Authority/path", "#fragment", true,
394 "scheme://Authority/path#fragment"},
395 {"scheme://Authority/", "#fragment", true,
396 "scheme://Authority/#fragment"},
397 // Test resolving a fragment (only) against any kind of base-URL.
398 {"about:blank", "#id42", true, "about:blank#id42"},
399 {"about:blank", " #id42", true, "about:blank#id42"},
400 {"about:blank#oldfrag", "#newfrag", true, "about:blank#newfrag"},
401 {"about:blank", " #id:42", true, "about:blank#id:42"},
402 // A surprising side effect of allowing fragments to resolve against
403 // any URL scheme is we might break javascript: URLs by doing so...
404 {"javascript:alert('foo#bar')", "#badfrag", true,
405 "javascript:alert('foo#badfrag"},
406 };
407
408 for (const auto& test : resolve_non_standard_cases) {
409 SCOPED_TRACE(testing::Message()
410 << "base: " << test.base << ", rel: " << test.rel);
411
412 Parsed base_parsed;
413 if (url::IsUsingStandardCompliantNonSpecialSchemeURLParsing()) {
414 ParseNonSpecialURL(test.base, strlen(test.base), &base_parsed);
415 } else {
416 ParsePathURL(test.base, strlen(test.base), /*trim_path_end=*/true,
417 &base_parsed);
418 }
419
420 std::string resolved;
421 StdStringCanonOutput output(&resolved);
422 Parsed resolved_parsed;
423 bool valid =
424 ResolveRelative(test.base, strlen(test.base), base_parsed, test.rel,
425 strlen(test.rel), nullptr, &output, &resolved_parsed);
426 output.Complete();
427
428 EXPECT_EQ(test.is_valid, valid);
429 if (test.is_valid && valid) {
430 EXPECT_EQ(test.out, resolved);
431 }
432 }
433 }
434
TEST_F(URLUtilTest,PotentiallyDanglingMarkup)435 TEST_F(URLUtilTest, PotentiallyDanglingMarkup) {
436 struct ResolveRelativeCase {
437 const char* base;
438 const char* rel;
439 bool potentially_dangling_markup;
440 const char* out;
441 } cases[] = {
442 {"https://example.com/", "/path<", false, "https://example.com/path%3C"},
443 {"https://example.com/", "\n/path<", true, "https://example.com/path%3C"},
444 {"https://example.com/", "\r/path<", true, "https://example.com/path%3C"},
445 {"https://example.com/", "\t/path<", true, "https://example.com/path%3C"},
446 {"https://example.com/", "/pa\nth<", true, "https://example.com/path%3C"},
447 {"https://example.com/", "/pa\rth<", true, "https://example.com/path%3C"},
448 {"https://example.com/", "/pa\tth<", true, "https://example.com/path%3C"},
449 {"https://example.com/", "/path\n<", true, "https://example.com/path%3C"},
450 {"https://example.com/", "/path\r<", true, "https://example.com/path%3C"},
451 {"https://example.com/", "/path\r<", true, "https://example.com/path%3C"},
452 {"https://example.com/", "\n/<path", true, "https://example.com/%3Cpath"},
453 {"https://example.com/", "\r/<path", true, "https://example.com/%3Cpath"},
454 {"https://example.com/", "\t/<path", true, "https://example.com/%3Cpath"},
455 {"https://example.com/", "/<pa\nth", true, "https://example.com/%3Cpath"},
456 {"https://example.com/", "/<pa\rth", true, "https://example.com/%3Cpath"},
457 {"https://example.com/", "/<pa\tth", true, "https://example.com/%3Cpath"},
458 {"https://example.com/", "/<path\n", true, "https://example.com/%3Cpath"},
459 {"https://example.com/", "/<path\r", true, "https://example.com/%3Cpath"},
460 {"https://example.com/", "/<path\r", true, "https://example.com/%3Cpath"},
461 };
462
463 for (const auto& test : cases) {
464 SCOPED_TRACE(::testing::Message() << test.base << ", " << test.rel);
465 Parsed base_parsed;
466 ParseStandardURL(test.base, strlen(test.base), &base_parsed);
467
468 std::string resolved;
469 StdStringCanonOutput output(&resolved);
470 Parsed resolved_parsed;
471 bool valid =
472 ResolveRelative(test.base, strlen(test.base), base_parsed, test.rel,
473 strlen(test.rel), nullptr, &output, &resolved_parsed);
474 ASSERT_TRUE(valid);
475 output.Complete();
476
477 EXPECT_EQ(test.potentially_dangling_markup,
478 resolved_parsed.potentially_dangling_markup);
479 EXPECT_EQ(test.out, resolved);
480 }
481 }
482
TEST_F(URLUtilTest,PotentiallyDanglingMarkupAfterReplacement)483 TEST_F(URLUtilTest, PotentiallyDanglingMarkupAfterReplacement) {
484 // Parse a URL with potentially dangling markup.
485 Parsed original_parsed;
486 RawCanonOutput<32> original;
487 const char* url = "htt\nps://example.com/<path";
488 Canonicalize(url, strlen(url), false, nullptr, &original, &original_parsed);
489 ASSERT_TRUE(original_parsed.potentially_dangling_markup);
490
491 // Perform a replacement, and validate that the potentially_dangling_markup
492 // flag carried over to the new Parsed object.
493 Replacements<char> replacements;
494 replacements.ClearRef();
495 Parsed replaced_parsed;
496 RawCanonOutput<32> replaced;
497 ReplaceComponents(original.data(), original.length(), original_parsed,
498 replacements, nullptr, &replaced, &replaced_parsed);
499 EXPECT_TRUE(replaced_parsed.potentially_dangling_markup);
500 }
501
TEST_F(URLUtilTest,PotentiallyDanglingMarkupAfterSchemeOnlyReplacement)502 TEST_F(URLUtilTest, PotentiallyDanglingMarkupAfterSchemeOnlyReplacement) {
503 // Parse a URL with potentially dangling markup.
504 Parsed original_parsed;
505 RawCanonOutput<32> original;
506 const char* url = "http://example.com/\n/<path";
507 Canonicalize(url, strlen(url), false, nullptr, &original, &original_parsed);
508 ASSERT_TRUE(original_parsed.potentially_dangling_markup);
509
510 // Perform a replacement, and validate that the potentially_dangling_markup
511 // flag carried over to the new Parsed object.
512 Replacements<char> replacements;
513 const char* new_scheme = "https";
514 replacements.SetScheme(new_scheme, Component(0, strlen(new_scheme)));
515 Parsed replaced_parsed;
516 RawCanonOutput<32> replaced;
517 ReplaceComponents(original.data(), original.length(), original_parsed,
518 replacements, nullptr, &replaced, &replaced_parsed);
519 EXPECT_TRUE(replaced_parsed.potentially_dangling_markup);
520 }
521
TEST_F(URLUtilTest,TestDomainIs)522 TEST_F(URLUtilTest, TestDomainIs) {
523 const struct {
524 const char* canonicalized_host;
525 const char* lower_ascii_domain;
526 bool expected_domain_is;
527 } kTestCases[] = {
528 {"google.com", "google.com", true},
529 {"www.google.com", "google.com", true}, // Subdomain is ignored.
530 {"www.google.com.cn", "google.com", false}, // Different TLD.
531 {"www.google.comm", "google.com", false},
532 {"www.iamnotgoogle.com", "google.com", false}, // Different hostname.
533 {"www.google.com", "Google.com", false}, // The input is not lower-cased.
534
535 // If the host ends with a dot, it matches domains with or without a dot.
536 {"www.google.com.", "google.com", true},
537 {"www.google.com.", "google.com.", true},
538 {"www.google.com.", ".com", true},
539 {"www.google.com.", ".com.", true},
540
541 // But, if the host doesn't end with a dot and the input domain does, then
542 // it's considered to not match.
543 {"www.google.com", "google.com.", false},
544
545 // If the host ends with two dots, it doesn't match.
546 {"www.google.com..", "google.com", false},
547
548 // Empty parameters.
549 {"www.google.com", "", false},
550 {"", "www.google.com", false},
551 {"", "", false},
552 };
553
554 for (const auto& test_case : kTestCases) {
555 SCOPED_TRACE(testing::Message() << "(host, domain): ("
556 << test_case.canonicalized_host << ", "
557 << test_case.lower_ascii_domain << ")");
558
559 EXPECT_EQ(
560 test_case.expected_domain_is,
561 DomainIs(test_case.canonicalized_host, test_case.lower_ascii_domain));
562 }
563 }
564
565 namespace {
CanonicalizeSpec(std::string_view spec,bool trim_path_end)566 std::optional<std::string> CanonicalizeSpec(std::string_view spec,
567 bool trim_path_end) {
568 std::string canonicalized;
569 StdStringCanonOutput output(&canonicalized);
570 Parsed parsed;
571 if (!Canonicalize(spec.data(), spec.size(), trim_path_end,
572 /*charset_converter=*/nullptr, &output, &parsed)) {
573 return {};
574 }
575 output.Complete(); // Must be called before string is used.
576 return canonicalized;
577 }
578 } // namespace
579
580 #if BUILDFLAG(IS_WIN)
581 // Regression test for https://crbug.com/1252658.
TEST_F(URLUtilTest,TestCanonicalizeWindowsPathWithLeadingNUL)582 TEST_F(URLUtilTest, TestCanonicalizeWindowsPathWithLeadingNUL) {
583 auto PrefixWithNUL = [](std::string&& s) -> std::string { return '\0' + s; };
584 EXPECT_EQ(CanonicalizeSpec(PrefixWithNUL("w:"), /*trim_path_end=*/false),
585 std::make_optional("file:///W:"));
586 EXPECT_EQ(CanonicalizeSpec(PrefixWithNUL("\\\\server\\share"),
587 /*trim_path_end=*/false),
588 std::make_optional("file://server/share"));
589 }
590 #endif
591
TEST_F(URLUtilTest,TestCanonicalizeIdempotencyWithLeadingControlCharacters)592 TEST_F(URLUtilTest, TestCanonicalizeIdempotencyWithLeadingControlCharacters) {
593 std::string spec = "_w:";
594 // Loop over all C0 control characters and the space character.
595 for (char c = '\0'; c <= ' '; c++) {
596 SCOPED_TRACE(testing::Message() << "c: " << c);
597
598 // Overwrite the first character of `spec`. Note that replacing the first
599 // character with NUL will not change the length!
600 spec[0] = c;
601
602 for (bool trim_path_end : {false, true}) {
603 SCOPED_TRACE(testing::Message() << "trim_path_end: " << trim_path_end);
604
605 std::optional<std::string> canonicalized =
606 CanonicalizeSpec(spec, trim_path_end);
607 ASSERT_TRUE(canonicalized);
608 EXPECT_EQ(canonicalized, CanonicalizeSpec(*canonicalized, trim_path_end));
609 }
610 }
611 }
612
TEST_F(URLUtilTest,TestHasInvalidURLEscapeSequences)613 TEST_F(URLUtilTest, TestHasInvalidURLEscapeSequences) {
614 struct TestCase {
615 const char* input;
616 bool is_invalid;
617 } cases[] = {
618 // Edge cases.
619 {"", false},
620 {"%", true},
621
622 // Single regular chars with no escaping are valid.
623 {"a", false},
624 {"g", false},
625 {"A", false},
626 {"G", false},
627 {":", false},
628 {"]", false},
629 {"\x00", false}, // ASCII 'NUL' char
630 {"\x01", false}, // ASCII 'SOH' char
631 {"\xC2\xA3", false}, // UTF-8 encoded '£'.
632
633 // Longer strings without escaping are valid.
634 {"Hello world", false},
635 {"Here: [%25] <-- a percent-encoded percent character.", false},
636
637 // Valid %-escaped sequences ('%' followed by two hex digits).
638 {"%00", false},
639 {"%20", false},
640 {"%02", false},
641 {"%ff", false},
642 {"%FF", false},
643 {"%0a", false},
644 {"%0A", false},
645 {"abc%FF", false},
646 {"%FFabc", false},
647 {"abc%FFabc", false},
648 {"hello %FF world", false},
649 {"%20hello%20world", false},
650 {"%25", false},
651 {"%25%25", false},
652 {"%250", false},
653 {"%259", false},
654 {"%25A", false},
655 {"%25F", false},
656 {"%0a:", false},
657
658 // '%' followed by a single character is never a valid sequence.
659 {"%%", true},
660 {"%2", true},
661 {"%a", true},
662 {"%A", true},
663 {"%g", true},
664 {"%G", true},
665 {"%:", true},
666 {"%[", true},
667 {"%F", true},
668 {"%\xC2\xA3", true}, //% followed by UTF-8 encoded '£'.
669
670 // String ends on a potential escape sequence but without two hex-digits
671 // is invalid.
672 {"abc%", true},
673 {"abc%%", true},
674 {"abc%%%", true},
675 {"abc%a", true},
676
677 // One hex and one non-hex digit is invalid.
678 {"%a:", true},
679 {"%:a", true},
680 {"%::", true},
681 {"%ag", true},
682 {"%ga", true},
683 {"%-1", true},
684 {"%1-", true},
685 {"%0\xC2\xA3", true}, // %0£.
686 };
687
688 for (TestCase test_case : cases) {
689 const char* input = test_case.input;
690 bool result = HasInvalidURLEscapeSequences(input);
691 EXPECT_EQ(test_case.is_invalid, result)
692 << "Invalid result for '" << input << "'";
693 }
694 }
695
696 class URLUtilTypedTest : public ::testing::TestWithParam<bool> {
697 public:
URLUtilTypedTest()698 URLUtilTypedTest()
699 : use_standard_compliant_non_special_scheme_url_parsing_(GetParam()) {
700 if (use_standard_compliant_non_special_scheme_url_parsing_) {
701 scoped_feature_list_.InitAndEnableFeature(
702 kStandardCompliantNonSpecialSchemeURLParsing);
703 } else {
704 scoped_feature_list_.InitAndDisableFeature(
705 kStandardCompliantNonSpecialSchemeURLParsing);
706 }
707 }
708
709 protected:
710 struct URLCase {
711 const std::string_view input;
712 const std::string_view expected;
713 bool expected_success;
714 };
715
716 struct ResolveRelativeCase {
717 const std::string_view base;
718 const std::string_view rel;
719 std::optional<std::string_view> expected;
720 };
721
TestCanonicalize(const URLCase & url_case)722 void TestCanonicalize(const URLCase& url_case) {
723 std::string canonicalized;
724 StdStringCanonOutput output(&canonicalized);
725 Parsed parsed;
726 bool success =
727 Canonicalize(url_case.input.data(), url_case.input.size(),
728 /*trim_path_end=*/false,
729 /*charset_converter=*/nullptr, &output, &parsed);
730 output.Complete();
731 EXPECT_EQ(success, url_case.expected_success);
732 EXPECT_EQ(output.view(), url_case.expected);
733 }
734
TestResolveRelative(const ResolveRelativeCase & test)735 void TestResolveRelative(const ResolveRelativeCase& test) {
736 SCOPED_TRACE(testing::Message()
737 << "base: " << test.base << ", rel: " << test.rel);
738
739 Parsed base_parsed;
740 if (url::IsUsingStandardCompliantNonSpecialSchemeURLParsing()) {
741 ParseNonSpecialURL(test.base.data(), test.base.size(), &base_parsed);
742 } else {
743 ParsePathURL(test.base.data(), test.base.size(), /*trim_path_end=*/true,
744 &base_parsed);
745 }
746
747 std::string resolved;
748 StdStringCanonOutput output(&resolved);
749
750 Parsed resolved_parsed;
751 bool valid = ResolveRelative(test.base.data(), test.base.size(),
752 base_parsed, test.rel.data(), test.rel.size(),
753 nullptr, &output, &resolved_parsed);
754 output.Complete();
755
756 if (valid) {
757 ASSERT_TRUE(test.expected);
758 EXPECT_EQ(resolved, *test.expected);
759 } else {
760 EXPECT_FALSE(test.expected);
761 }
762 }
763
764 bool use_standard_compliant_non_special_scheme_url_parsing_;
765
766 private:
767 base::test::ScopedFeatureList scoped_feature_list_;
768 };
769
TEST_P(URLUtilTypedTest,TestNoRefComponent)770 TEST_P(URLUtilTypedTest, TestNoRefComponent) {
771 // This test was originally written before full support for non-special URLs
772 // became available. We need a flag-dependent test here because the test uses
773 // an internal parse function. See http://crbug.com/40063064 for details.
774 //
775 // The test case corresponds to the following user scenario:
776 //
777 // > const url = new URL("any#body", "mailto://to/");
778 // > assertEquals(url.href, "mailto://to/any#body");
779 //
780 // TODO(crbug.com/40063064): Remove this test once the flag is enabled.
781 const std::string_view base = "mailto://to/";
782 const std::string_view rel = "any#body";
783 if (use_standard_compliant_non_special_scheme_url_parsing_) {
784 // We probably don't need to test with the flag enabled, however, including
785 // a test with the flag enabled would be beneficial for comparison purposes,
786 // at least until we enable the flag by default.
787 Parsed base_parsed;
788 ParseNonSpecialURL(base.data(), base.size(), &base_parsed);
789
790 std::string resolved;
791 StdStringCanonOutput output(&resolved);
792 Parsed resolved_parsed;
793
794 bool valid =
795 ResolveRelative(base.data(), base.size(), base_parsed, rel.data(),
796 rel.size(), nullptr, &output, &resolved_parsed);
797 EXPECT_TRUE(valid);
798 // Note: If the flag is enabled and the correct parsing function is used,
799 // resolved_parsed.ref becomes valid correctly.
800 EXPECT_TRUE(resolved_parsed.ref.is_valid());
801 output.Complete();
802 EXPECT_EQ(resolved, "mailto://to/any#body");
803 } else {
804 // Note: See the description of https://codereview.chromium.org/767713002/
805 // for the intention of this test, which added this test to record a wrong
806 // result if a wrong parser function is used. I kept the following original
807 // comment as is:
808 //
809 // The hash-mark must be ignored when mailto: scheme is parsed,
810 // even if the URL has a base and relative part.
811 Parsed base_parsed;
812 ParsePathURL(base.data(), base.size(), false, &base_parsed);
813
814 std::string resolved;
815 StdStringCanonOutput output(&resolved);
816 Parsed resolved_parsed;
817
818 bool valid =
819 ResolveRelative(base.data(), base.size(), base_parsed, 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/1416006): 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
898 INSTANTIATE_TEST_SUITE_P(All, URLUtilTypedTest, ::testing::Bool());
899
900 } // namespace url
901