| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import io |
| 4 |
import logging |
| 5 |
import socket |
| 6 |
import ssl |
| 7 |
import sys |
| 8 |
import typing |
| 9 |
import warnings |
| 10 |
from test import ImportBlocker, ModuleStash, notBrotli, notZstd, onlyBrotli, onlyZstd |
| 11 |
from unittest import mock |
| 12 |
from unittest.mock import MagicMock, Mock, patch |
| 13 |
from urllib.parse import urlparse |
| 14 |
|
| 15 |
import pytest |
| 16 |
|
| 17 |
from urllib3 import add_stderr_logger, disable_warnings |
| 18 |
from urllib3.connection import ProxyConfig |
| 19 |
from urllib3.exceptions import ( |
| 20 |
InsecureRequestWarning, |
| 21 |
LocationParseError, |
| 22 |
TimeoutStateError, |
| 23 |
UnrewindableBodyError, |
| 24 |
) |
| 25 |
from urllib3.util import is_fp_closed |
| 26 |
from urllib3.util.connection import _has_ipv6, allowed_gai_family, create_connection |
| 27 |
from urllib3.util.proxy import connection_requires_http_tunnel |
| 28 |
from urllib3.util.request import _FAILEDTELL, make_headers, rewind_body |
| 29 |
from urllib3.util.response import assert_header_parsing |
| 30 |
from urllib3.util.ssl_ import ( |
| 31 |
_is_has_never_check_common_name_reliable, |
| 32 |
resolve_cert_reqs, |
| 33 |
resolve_ssl_version, |
| 34 |
ssl_wrap_socket, |
| 35 |
) |
| 36 |
from urllib3.util.timeout import _DEFAULT_TIMEOUT, Timeout |
| 37 |
from urllib3.util.url import _PATH_CHARS, Url, _encode_invalid_chars, parse_url |
| 38 |
from urllib3.util.util import to_bytes, to_str |
| 39 |
|
| 40 |
from . import clear_warnings |
| 41 |
|
| 42 |
# This number represents a time in seconds, it doesn't mean anything in |
| 43 |
# isolation. Setting to a high-ish value to avoid conflicts with the smaller |
| 44 |
# numbers used for timeouts |
| 45 |
TIMEOUT_EPOCH = 1000 |
| 46 |
|
| 47 |
|
| 48 |
class TestUtil: |
| 49 |
url_host_map = [ |
| 50 |
# Hosts |
| 51 |
("http://google.com/mail", ("http", "google.com", None)), |
| 52 |
("http://google.com/mail/", ("http", "google.com", None)), |
| 53 |
("google.com/mail", ("http", "google.com", None)), |
| 54 |
("http://google.com/", ("http", "google.com", None)), |
| 55 |
("http://google.com", ("http", "google.com", None)), |
| 56 |
("http://www.google.com", ("http", "www.google.com", None)), |
| 57 |
("http://mail.google.com", ("http", "mail.google.com", None)), |
| 58 |
("http://google.com:8000/mail/", ("http", "google.com", 8000)), |
| 59 |
("http://google.com:8000", ("http", "google.com", 8000)), |
| 60 |
("https://google.com", ("https", "google.com", None)), |
| 61 |
("https://google.com:8000", ("https", "google.com", 8000)), |
| 62 |
("http://user:[email protected]:1234", ("http", "127.0.0.1", 1234)), |
| 63 |
("http://google.com/foo=http://bar:42/baz", ("http", "google.com", None)), |
| 64 |
("http://google.com?foo=http://bar:42/baz", ("http", "google.com", None)), |
| 65 |
("http://google.com#foo=http://bar:42/baz", ("http", "google.com", None)), |
| 66 |
# IPv4 |
| 67 |
("173.194.35.7", ("http", "173.194.35.7", None)), |
| 68 |
("http://173.194.35.7", ("http", "173.194.35.7", None)), |
| 69 |
("http://173.194.35.7/test", ("http", "173.194.35.7", None)), |
| 70 |
("http://173.194.35.7:80", ("http", "173.194.35.7", 80)), |
| 71 |
("http://173.194.35.7:80/test", ("http", "173.194.35.7", 80)), |
| 72 |
# IPv6 |
| 73 |
("[2a00:1450:4001:c01::67]", ("http", "[2a00:1450:4001:c01::67]", None)), |
| 74 |
("http://[2a00:1450:4001:c01::67]", ("http", "[2a00:1450:4001:c01::67]", None)), |
| 75 |
( |
| 76 |
"http://[2a00:1450:4001:c01::67]/test", |
| 77 |
("http", "[2a00:1450:4001:c01::67]", None), |
| 78 |
), |
| 79 |
( |
| 80 |
"http://[2a00:1450:4001:c01::67]:80", |
| 81 |
("http", "[2a00:1450:4001:c01::67]", 80), |
| 82 |
), |
| 83 |
( |
| 84 |
"http://[2a00:1450:4001:c01::67]:80/test", |
| 85 |
("http", "[2a00:1450:4001:c01::67]", 80), |
| 86 |
), |
| 87 |
# More IPv6 from http://www.ietf.org/rfc/rfc2732.txt |
| 88 |
( |
| 89 |
"http://[fedc:ba98:7654:3210:fedc:ba98:7654:3210]:8000/index.html", |
| 90 |
("http", "[fedc:ba98:7654:3210:fedc:ba98:7654:3210]", 8000), |
| 91 |
), |
| 92 |
( |
| 93 |
"http://[1080:0:0:0:8:800:200c:417a]/index.html", |
| 94 |
("http", "[1080:0:0:0:8:800:200c:417a]", None), |
| 95 |
), |
| 96 |
("http://[3ffe:2a00:100:7031::1]", ("http", "[3ffe:2a00:100:7031::1]", None)), |
| 97 |
( |
| 98 |
"http://[1080::8:800:200c:417a]/foo", |
| 99 |
("http", "[1080::8:800:200c:417a]", None), |
| 100 |
), |
| 101 |
("http://[::192.9.5.5]/ipng", ("http", "[::192.9.5.5]", None)), |
| 102 |
( |
| 103 |
"http://[::ffff:129.144.52.38]:42/index.html", |
| 104 |
("http", "[::ffff:129.144.52.38]", 42), |
| 105 |
), |
| 106 |
( |
| 107 |
"http://[2010:836b:4179::836b:4179]", |
| 108 |
("http", "[2010:836b:4179::836b:4179]", None), |
| 109 |
), |
| 110 |
# Scoped IPv6 (with ZoneID), both RFC 6874 compliant and not. |
| 111 |
("http://[a::b%25zone]", ("http", "[a::b%zone]", None)), |
| 112 |
("http://[a::b%zone]", ("http", "[a::b%zone]", None)), |
| 113 |
# Hosts |
| 114 |
("HTTP://GOOGLE.COM/mail/", ("http", "google.com", None)), |
| 115 |
("GOogle.COM/mail", ("http", "google.com", None)), |
| 116 |
("HTTP://GoOgLe.CoM:8000/mail/", ("http", "google.com", 8000)), |
| 117 |
("HTTP://user:[email protected]:1234", ("http", "example.com", 1234)), |
| 118 |
("173.194.35.7", ("http", "173.194.35.7", None)), |
| 119 |
("HTTP://173.194.35.7", ("http", "173.194.35.7", None)), |
| 120 |
( |
| 121 |
"HTTP://[2a00:1450:4001:c01::67]:80/test", |
| 122 |
("http", "[2a00:1450:4001:c01::67]", 80), |
| 123 |
), |
| 124 |
( |
| 125 |
"HTTP://[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:8000/index.html", |
| 126 |
("http", "[fedc:ba98:7654:3210:fedc:ba98:7654:3210]", 8000), |
| 127 |
), |
| 128 |
( |
| 129 |
"HTTPS://[1080:0:0:0:8:800:200c:417A]/index.html", |
| 130 |
("https", "[1080:0:0:0:8:800:200c:417a]", None), |
| 131 |
), |
| 132 |
("abOut://eXamPlE.com?info=1", ("about", "eXamPlE.com", None)), |
| 133 |
( |
| 134 |
"http+UNIX://%2fvar%2frun%2fSOCKET/path", |
| 135 |
("http+unix", "%2fvar%2frun%2fSOCKET", None), |
| 136 |
), |
| 137 |
] |
| 138 |
|
| 139 |
@pytest.mark.parametrize(["url", "scheme_host_port"], url_host_map) |
| 140 |
def test_scheme_host_port( |
| 141 |
self, url: str, scheme_host_port: tuple[str, str, int | None] |
| 142 |
) -> None: |
| 143 |
parsed_url = parse_url(url) |
| 144 |
scheme, host, port = scheme_host_port |
| 145 |
|
| 146 |
assert (parsed_url.scheme or "http") == scheme |
| 147 |
assert parsed_url.hostname == parsed_url.host == host |
| 148 |
assert parsed_url.port == port |
| 149 |
|
| 150 |
def test_encode_invalid_chars_none(self) -> None: |
| 151 |
assert _encode_invalid_chars(None, set()) is None |
| 152 |
|
| 153 |
@pytest.mark.parametrize( |
| 154 |
"component, expected", |
| 155 |
[ |
| 156 |
# Already valid components are returned unchanged. |
| 157 |
("", ""), |
| 158 |
("/", "/"), |
| 159 |
("/path/to/resource", "/path/to/resource"), |
| 160 |
(b"/bytes/path", "/bytes/path"), |
| 161 |
# Invalid ASCII characters are percent-encoded (uppercase hex). |
| 162 |
("/a b|c", "/a%20b%7Cc"), |
| 163 |
(b"/a b", "/a%20b"), |
| 164 |
# Non-ASCII characters are encoded as UTF-8 bytes. |
| 165 |
("/caf\xe9", "/caf%C3%A9"), |
| 166 |
("/日本/\U0001f600", "/%E6%97%A5%E6%9C%AC/%F0%9F%98%80"), |
| 167 |
# Lone surrogates are encoded with 'surrogatepass' (3 bytes). |
| 168 |
("/a\udc80b", "/a%ED%B2%80b"), |
| 169 |
("\ud800", "%ED%A0%80"), |
| 170 |
# Fully percent-encoded components keep their '%' and get their |
| 171 |
# hex digits normalized to uppercase. |
| 172 |
("/%2f%2F", "/%2F%2F"), |
| 173 |
("/a%20b c", "/a%20b%20c"), |
| 174 |
("%C3%A9\xe9", "%C3%A9%C3%A9"), |
| 175 |
# A single bare '%' makes every '%' get encoded, even valid ones. |
| 176 |
("%", "%25"), |
| 177 |
("%2", "%252"), |
| 178 |
("%%20", "%25%2520"), |
| 179 |
("/%2F%", "/%252F%25"), |
| 180 |
("/%2f%2F%zz", "/%252F%252F%25zz"), |
| 181 |
], |
| 182 |
) |
| 183 |
def test_encode_invalid_chars(self, component: str | bytes, expected: str) -> None: |
| 184 |
assert _encode_invalid_chars(component, _PATH_CHARS) == expected # type: ignore[arg-type] |
| 185 |
|
| 186 |
def test_encode_invalid_chars_respects_allowed_chars(self) -> None: |
| 187 |
# Only characters in ``allowed_chars`` are kept, and any container |
| 188 |
# type works, not only the module's own sets. |
| 189 |
assert _encode_invalid_chars("abc", {"a", "b"}) == "ab%63" |
| 190 |
assert _encode_invalid_chars("abc", "ab") == "ab%63" |
| 191 |
assert _encode_invalid_chars("abc", ["a", "b"]) == "ab%63" |
| 192 |
assert _encode_invalid_chars("abc", frozenset()) == "%61%62%63" |
| 193 |
assert _encode_invalid_chars("abc", set()) == "%61%62%63" |
| 194 |
# Non-ASCII characters are always encoded, even if "allowed". |
| 195 |
assert _encode_invalid_chars("\xe9", {"\xe9"}) == "%C3%A9" |
| 196 |
# '%' is only kept when the whole component is percent-encoded, |
| 197 |
# or when it is explicitly allowed. |
| 198 |
assert _encode_invalid_chars("a%", {"a"}) == "a%25" |
| 199 |
assert _encode_invalid_chars("a%", {"a", "%"}) == "a%" |
| 200 |
assert _encode_invalid_chars("a%41%", {"a"}) == "a%25%34%31%25" |
| 201 |
assert _encode_invalid_chars("a%41%", {"a", "%"}) == "a%%34%31%" |
| 202 |
|
| 203 |
@pytest.mark.parametrize( |
| 204 |
"url", |
| 205 |
[ |
| 206 |
"http://google.com:foo", |
| 207 |
"http://::1/", |
| 208 |
"http://::1:80/", |
| 209 |
"http://google.com:-80", |
| 210 |
"http://google.com:65536", |
| 211 |
"http://google.com:\xb2\xb2", # \xb2 = ^2 |
| 212 |
"http://foo%.example/", |
| 213 |
"http://foo%zz.example/", |
| 214 |
# Invalid IDNA labels |
| 215 |
"http://\ud7ff.com", |
| 216 |
"http://❤️", |
| 217 |
# Unicode surrogates |
| 218 |
"http://\ud800.com", |
| 219 |
"http://\udc00.com", |
| 220 |
], |
| 221 |
) |
| 222 |
def test_invalid_url(self, url: str) -> None: |
| 223 |
with pytest.raises(LocationParseError): |
| 224 |
parse_url(url) |
| 225 |
|
| 226 |
@pytest.mark.parametrize( |
| 227 |
"url, expected_normalized_url", |
| 228 |
[ |
| 229 |
("HTTP://GOOGLE.COM/MAIL/", "http://google.com/MAIL/"), |
| 230 |
( |
| 231 |
"http://[email protected]:[email protected]/~tilde@?@", |
| 232 |
"http://user%40domain.com:[email protected]/~tilde@?@", |
| 233 |
), |
| 234 |
( |
| 235 |
"HTTP://JeremyCline:[email protected]:8080/", |
| 236 |
"http://JeremyCline:[email protected]:8080/", |
| 237 |
), |
| 238 |
("HTTPS://Example.Com/?Key=Value", "https://example.com/?Key=Value"), |
| 239 |
("Https://Example.Com/#Fragment", "https://example.com/#Fragment"), |
| 240 |
# IPv6 addresses with zone IDs. Both RFC 6874 (%25) as well as |
| 241 |
# non-standard (unquoted %) variants. |
| 242 |
("[::1%zone]", "[::1%zone]"), |
| 243 |
("[::1%25zone]", "[::1%zone]"), |
| 244 |
("[::1%0d]", "[::1%0d]"), |
| 245 |
("[::1%25]", "[::1%25]"), |
| 246 |
("[::Ff%etH0%Ff]/%ab%Af", "[::ff%etH0%FF]/%AB%AF"), |
| 247 |
( |
| 248 |
"http://user:pass@[AaAa::Ff%25etH0%Ff]/%ab%Af", |
| 249 |
"http://user:pass@[aaaa::ff%etH0%FF]/%AB%AF", |
| 250 |
), |
| 251 |
# Invalid characters for the query/fragment getting encoded |
| 252 |
( |
| 253 |
'http://google.com/p[]?parameter[]="hello"#fragment#', |
| 254 |
"http://google.com/p%5B%5D?parameter%5B%5D=%22hello%22#fragment%23", |
| 255 |
), |
| 256 |
# Percent encoding isn't applied twice despite '%' being invalid |
| 257 |
# but the percent encoding is still normalized. |
| 258 |
( |
| 259 |
"http://google.com/p%5B%5d?parameter%5b%5D=%22hello%22#fragment%23", |
| 260 |
"http://google.com/p%5B%5D?parameter%5B%5D=%22hello%22#fragment%23", |
| 261 |
), |
| 262 |
], |
| 263 |
) |
| 264 |
def test_parse_url_normalization( |
| 265 |
self, url: str, expected_normalized_url: str |
| 266 |
) -> None: |
| 267 |
"""Assert parse_url normalizes the scheme/host, and only the scheme/host""" |
| 268 |
actual_normalized_url = parse_url(url).url |
| 269 |
assert actual_normalized_url == expected_normalized_url |
| 270 |
|
| 271 |
@pytest.mark.parametrize("char", [chr(i) for i in range(0x00, 0x21)] + ["\x7f"]) |
| 272 |
def test_control_characters_are_percent_encoded(self, char: str) -> None: |
| 273 |
percent_char = "%" + (hex(ord(char))[2:].zfill(2).upper()) |
| 274 |
url = parse_url( |
| 275 |
f"http://user{char}@example.com/path{char}?query{char}#fragment{char}" |
| 276 |
) |
| 277 |
|
| 278 |
assert url == Url( |
| 279 |
"http", |
| 280 |
auth="user" + percent_char, |
| 281 |
host="example.com", |
| 282 |
path="/path" + percent_char, |
| 283 |
query="query" + percent_char, |
| 284 |
fragment="fragment" + percent_char, |
| 285 |
) |
| 286 |
|
| 287 |
@pytest.mark.parametrize( |
| 288 |
"url_template", |
| 289 |
[ |
| 290 |
"http://victim.example{}Injected/path", |
| 291 |
"gopher://victim.example{}Injected/path", |
| 292 |
"victim.example{}Injected/path", |
| 293 |
"http://127.0.0.1{}/path", |
| 294 |
"http://[::1]{}/path", |
| 295 |
], |
| 296 |
) |
| 297 |
@pytest.mark.parametrize("char", [chr(i) for i in range(0x00, 0x21)] + ["\x7f"]) |
| 298 |
def test_control_characters_in_host_raise( |
| 299 |
self, url_template: str, char: str |
| 300 |
) -> None: |
| 301 |
with pytest.raises(LocationParseError, match="contains invalid character"): |
| 302 |
parse_url(url_template.format(char)) |
| 303 |
|
| 304 |
@pytest.mark.parametrize( |
| 305 |
"url, expected_host", |
| 306 |
[ |
| 307 |
("http://Königsgäßchen.de/path", "xn--knigsgchen-b4a3dun.de"), |
| 308 |
("http://例え.テスト/path", "xn--r8jz45g.xn--zckzah"), |
| 309 |
], |
| 310 |
) |
| 311 |
def test_non_ascii_hosts_are_idna_encoded( |
| 312 |
self, url: str, expected_host: str |
| 313 |
) -> None: |
| 314 |
assert parse_url(url).host == expected_host |
| 315 |
|
| 316 |
@pytest.mark.parametrize( |
| 317 |
"url, expected_host", |
| 318 |
[ |
| 319 |
( |
| 320 |
"http://K%C3%B6nigsg%C3%A4%C3%9Fchen.de/path", |
| 321 |
"k%C3%B6nigsg%C3%A4%C3%9Fchen.de", |
| 322 |
), |
| 323 |
( |
| 324 |
"http://%E4%BE%8B%E3%81%88.%E3%83%86%E3%82%B9%E3%83%88/path", |
| 325 |
"%E4%BE%8B%E3%81%88.%E3%83%86%E3%82%B9%E3%83%88", |
| 326 |
), |
| 327 |
], |
| 328 |
) |
| 329 |
def test_percent_encoded_non_unreserved_hosts_are_preserved( |
| 330 |
self, url: str, expected_host: str |
| 331 |
) -> None: |
| 332 |
assert parse_url(url).host == expected_host |
| 333 |
|
| 334 |
@pytest.mark.parametrize( |
| 335 |
"url, expected_host", |
| 336 |
[ |
| 337 |
("http://%65xample.com/path", "example.com"), |
| 338 |
("http://example.com%2E/path", "example.com."), |
| 339 |
("http://EXAMPLE%2Ecom%2E/path", "example.com."), |
| 340 |
("http://%2eexample.com/path", ".example.com"), |
| 341 |
("http://example%2e%2ecom/path", "example..com"), |
| 342 |
("http://foo%7Ebar.com/path", "foo~bar.com"), |
| 343 |
("http://%31%32%37.0.0.1/path", "127.0.0.1"), |
| 344 |
], |
| 345 |
) |
| 346 |
def test_percent_encoded_unreserved_hosts_are_decoded( |
| 347 |
self, url: str, expected_host: str |
| 348 |
) -> None: |
| 349 |
assert parse_url(url).host == expected_host |
| 350 |
|
| 351 |
@pytest.mark.parametrize( |
| 352 |
"url, expected_host", |
| 353 |
[ |
| 354 |
("http://%FF.example/", "%FF.example"), |
| 355 |
("http://%C3%28.example/", "%C3%28.example"), |
| 356 |
("http://%ED%A0%80.example/", "%ED%A0%80.example"), |
| 357 |
], |
| 358 |
) |
| 359 |
def test_percent_encoded_hosts_that_are_not_valid_utf8_are_preserved( |
| 360 |
self, url: str, expected_host: str |
| 361 |
) -> None: |
| 362 |
assert parse_url(url).host == expected_host |
| 363 |
|
| 364 |
@pytest.mark.parametrize( |
| 365 |
"url, expected_host", |
| 366 |
[ |
| 367 |
("http://foo%20bar.com/", "foo%20bar.com"), |
| 368 |
("http://%20.example/", "%20.example"), |
| 369 |
("http://example%2F.com/", "example%2F.com"), |
| 370 |
("http://victim%40evil.com/", "victim%40evil.com"), |
| 371 |
("http://example%5C.com/", "example%5C.com"), |
| 372 |
("http://example%5B.com/", "example%5B.com"), |
| 373 |
("http://example%5D.com/", "example%5D.com"), |
| 374 |
("http://example%3A80.com/", "example%3A80.com"), |
| 375 |
("http://example%3Fquery.com/", "example%3Fquery.com"), |
| 376 |
("http://example%23fragment.com/", "example%23fragment.com"), |
| 377 |
("http://a%25b.example/", "a%25b.example"), |
| 378 |
], |
| 379 |
) |
| 380 |
def test_percent_encoded_reserved_hosts_are_preserved( |
| 381 |
self, url: str, expected_host: str |
| 382 |
) -> None: |
| 383 |
assert parse_url(url).host == expected_host |
| 384 |
|
| 385 |
@pytest.mark.parametrize( |
| 386 |
"url", |
| 387 |
[ |
| 388 |
"http://%00.example/", |
| 389 |
"http://%1F.example/", |
| 390 |
"http://%7F.example/", |
| 391 |
], |
| 392 |
) |
| 393 |
def test_percent_encoded_control_hosts_raise(self, url: str) -> None: |
| 394 |
with pytest.raises( |
| 395 |
LocationParseError, match="invalid percent-encoded control character" |
| 396 |
): |
| 397 |
parse_url(url) |
| 398 |
|
| 399 |
@pytest.mark.parametrize( |
| 400 |
"url", |
| 401 |
[ |
| 402 |
"http://[::1%25%00]/", |
| 403 |
"http://[::1%25%1F]/", |
| 404 |
"http://[::1%25%7F]/", |
| 405 |
"http://[::1%25%0d%0a]/", |
| 406 |
"http://[::1%%0d%0a]/", |
| 407 |
], |
| 408 |
) |
| 409 |
def test_percent_encoded_control_ipv6_zone_ids_raise(self, url: str) -> None: |
| 410 |
with pytest.raises( |
| 411 |
LocationParseError, match="invalid percent-encoded control character" |
| 412 |
): |
| 413 |
parse_url(url) |
| 414 |
|
| 415 |
parse_url_host_map = [ |
| 416 |
("http://google.com/mail", Url("http", host="google.com", path="/mail")), |
| 417 |
("http://google.com/mail/", Url("http", host="google.com", path="/mail/")), |
| 418 |
("http://google.com/mail", Url("http", host="google.com", path="mail")), |
| 419 |
("google.com/mail", Url(host="google.com", path="/mail")), |
| 420 |
("http://google.com/", Url("http", host="google.com", path="/")), |
| 421 |
("http://google.com", Url("http", host="google.com")), |
| 422 |
("http://google.com?foo", Url("http", host="google.com", path="", query="foo")), |
| 423 |
# Path/query/fragment |
| 424 |
("", Url()), |
| 425 |
("/", Url(path="/")), |
| 426 |
("#?/!google.com/?foo", Url(path="", fragment="?/!google.com/?foo")), |
| 427 |
("/foo", Url(path="/foo")), |
| 428 |
("/foo?bar=baz", Url(path="/foo", query="bar=baz")), |
| 429 |
( |
| 430 |
"/foo?bar=baz#banana?apple/orange", |
| 431 |
Url(path="/foo", query="bar=baz", fragment="banana?apple/orange"), |
| 432 |
), |
| 433 |
( |
| 434 |
"/redirect?target=http://localhost:61020/", |
| 435 |
Url(path="redirect", query="target=http://localhost:61020/"), |
| 436 |
), |
| 437 |
# Port |
| 438 |
("http://google.com/", Url("http", host="google.com", path="/")), |
| 439 |
("http://google.com:80/", Url("http", host="google.com", port=80, path="/")), |
| 440 |
("http://google.com:80", Url("http", host="google.com", port=80)), |
| 441 |
# Auth |
| 442 |
( |
| 443 |
"http://foo:bar@localhost/", |
| 444 |
Url("http", auth="foo:bar", host="localhost", path="/"), |
| 445 |
), |
| 446 |
("http://foo@localhost/", Url("http", auth="foo", host="localhost", path="/")), |
| 447 |
( |
| 448 |
"http://foo:bar@localhost/", |
| 449 |
Url("http", auth="foo:bar", host="localhost", path="/"), |
| 450 |
), |
| 451 |
] |
| 452 |
|
| 453 |
non_round_tripping_parse_url_host_map = [ |
| 454 |
# Path/query/fragment |
| 455 |
("?", Url(path="", query="")), |
| 456 |
("#", Url(path="", fragment="")), |
| 457 |
# Path normalization |
| 458 |
("/abc/../def", Url(path="/def")), |
| 459 |
# Empty Port |
| 460 |
("http://google.com:", Url("http", host="google.com")), |
| 461 |
("http://google.com:/", Url("http", host="google.com", path="/")), |
| 462 |
# Uppercase IRI |
| 463 |
( |
| 464 |
"http://Königsgäßchen.de/straße", |
| 465 |
Url("http", host="xn--knigsgchen-b4a3dun.de", path="/stra%C3%9Fe"), |
| 466 |
), |
| 467 |
# Percent-encode in userinfo |
| 468 |
( |
| 469 |
"http://[email protected]:[email protected]/", |
| 470 |
Url("http", auth="user%40email.com:password", host="example.com", path="/"), |
| 471 |
), |
| 472 |
( |
| 473 |
'http://user":[email protected]/', |
| 474 |
Url("http", auth="user%22:quoted", host="example.com", path="/"), |
| 475 |
), |
| 476 |
# Unicode Surrogates |
| 477 |
("http://google.com/\ud800", Url("http", host="google.com", path="%ED%A0%80")), |
| 478 |
( |
| 479 |
"http://google.com?q=\udc00", |
| 480 |
Url("http", host="google.com", path="", query="q=%ED%B0%80"), |
| 481 |
), |
| 482 |
( |
| 483 |
"http://google.com#\udc00", |
| 484 |
Url("http", host="google.com", path="", fragment="%ED%B0%80"), |
| 485 |
), |
| 486 |
] |
| 487 |
|
| 488 |
@pytest.mark.parametrize( |
| 489 |
"url, expected_url", |
| 490 |
[*parse_url_host_map, *non_round_tripping_parse_url_host_map], |
| 491 |
) |
| 492 |
def test_parse_url(self, url: str, expected_url: Url) -> None: |
| 493 |
returned_url = parse_url(url) |
| 494 |
assert returned_url == expected_url |
| 495 |
assert returned_url.hostname == returned_url.host == expected_url.host |
| 496 |
|
| 497 |
@pytest.mark.parametrize("url, expected_url", parse_url_host_map) |
| 498 |
def test_unparse_url(self, url: str, expected_url: Url) -> None: |
| 499 |
assert url == expected_url.url |
| 500 |
|
| 501 |
@pytest.mark.parametrize( |
| 502 |
["url", "expected_url"], |
| 503 |
[ |
| 504 |
# RFC 3986 5.2.4 |
| 505 |
("/abc/../def", Url(path="/def")), |
| 506 |
("/..", Url(path="/")), |
| 507 |
("/./abc/./def/", Url(path="/abc/def/")), |
| 508 |
("/.", Url(path="/")), |
| 509 |
("/./", Url(path="/")), |
| 510 |
("/abc/./.././d/././e/.././f/./../../ghi", Url(path="/ghi")), |
| 511 |
], |
| 512 |
) |
| 513 |
def test_parse_and_normalize_url_paths(self, url: str, expected_url: Url) -> None: |
| 514 |
actual_url = parse_url(url) |
| 515 |
assert actual_url == expected_url |
| 516 |
assert actual_url.url == expected_url.url |
| 517 |
|
| 518 |
def test_parse_url_invalid_IPv6(self) -> None: |
| 519 |
with pytest.raises(LocationParseError): |
| 520 |
parse_url("[::1") |
| 521 |
|
| 522 |
def test_parse_url_negative_port(self) -> None: |
| 523 |
with pytest.raises(LocationParseError): |
| 524 |
parse_url("https://www.google.com:-80/") |
| 525 |
|
| 526 |
def test_parse_url_remove_leading_zeros(self) -> None: |
| 527 |
url = parse_url("https://example.com:0000000000080") |
| 528 |
assert url.port == 80 |
| 529 |
|
| 530 |
def test_parse_url_only_zeros(self) -> None: |
| 531 |
url = parse_url("https://example.com:0") |
| 532 |
assert url.port == 0 |
| 533 |
|
| 534 |
url = parse_url("https://example.com:000000000000") |
| 535 |
assert url.port == 0 |
| 536 |
|
| 537 |
def test_Url_str(self) -> None: |
| 538 |
U = Url("http", host="google.com") |
| 539 |
assert str(U) == U.url |
| 540 |
|
| 541 |
request_uri_map = [ |
| 542 |
("http://google.com/mail", "/mail"), |
| 543 |
("http://google.com/mail/", "/mail/"), |
| 544 |
("http://google.com/", "/"), |
| 545 |
("http://google.com", "/"), |
| 546 |
("", "/"), |
| 547 |
("/", "/"), |
| 548 |
("?", "/?"), |
| 549 |
("#", "/"), |
| 550 |
("/foo?bar=baz", "/foo?bar=baz"), |
| 551 |
] |
| 552 |
|
| 553 |
@pytest.mark.parametrize("url, expected_request_uri", request_uri_map) |
| 554 |
def test_request_uri(self, url: str, expected_request_uri: str) -> None: |
| 555 |
returned_url = parse_url(url) |
| 556 |
assert returned_url.request_uri == expected_request_uri |
| 557 |
|
| 558 |
url_authority_map: list[tuple[str, str | None]] = [ |
| 559 |
("http://user:[email protected]/mail", "user:[email protected]"), |
| 560 |
("http://user:[email protected]:80/mail", "user:[email protected]:80"), |
| 561 |
("http://[email protected]:80/mail", "[email protected]:80"), |
| 562 |
("http://user:[email protected]/path", "user:[email protected]"), |
| 563 |
("http://user:[email protected]:80/path", "user:[email protected]:80"), |
| 564 |
("http://[email protected]:80/path", "[email protected]:80"), |
| 565 |
("http://user:pass@[::1]/path", "user:pass@[::1]"), |
| 566 |
("http://user:pass@[::1]:80/path", "user:pass@[::1]:80"), |
| 567 |
("http://user@[::1]:80/path", "user@[::1]:80"), |
| 568 |
("http://user:pass@localhost/path", "user:pass@localhost"), |
| 569 |
("http://user:pass@localhost:80/path", "user:pass@localhost:80"), |
| 570 |
("http://user@localhost:80/path", "user@localhost:80"), |
| 571 |
] |
| 572 |
|
| 573 |
url_netloc_map = [ |
| 574 |
("http://google.com/mail", "google.com"), |
| 575 |
("http://google.com:80/mail", "google.com:80"), |
| 576 |
("http://google.com:0/mail", "google.com:0"), |
| 577 |
("http://192.168.0.1/path", "192.168.0.1"), |
| 578 |
("http://192.168.0.1:80/path", "192.168.0.1:80"), |
| 579 |
("http://[::1]/path", "[::1]"), |
| 580 |
("http://[::1]:80/path", "[::1]:80"), |
| 581 |
("http://localhost", "localhost"), |
| 582 |
("http://localhost:80", "localhost:80"), |
| 583 |
("http://localhost:0", "localhost:0"), |
| 584 |
("google.com/foobar", "google.com"), |
| 585 |
("google.com:12345", "google.com:12345"), |
| 586 |
("/", None), |
| 587 |
] |
| 588 |
|
| 589 |
combined_netloc_authority_map = url_authority_map + url_netloc_map |
| 590 |
|
| 591 |
# We compose this list due to variances between parse_url |
| 592 |
# and urlparse when URIs don't provide a scheme. |
| 593 |
url_authority_with_schemes_map = [ |
| 594 |
u for u in combined_netloc_authority_map if u[0].startswith("http") |
| 595 |
] |
| 596 |
|
| 597 |
@pytest.mark.parametrize("url, expected_authority", combined_netloc_authority_map) |
| 598 |
def test_authority(self, url: str, expected_authority: str | None) -> None: |
| 599 |
assert parse_url(url).authority == expected_authority |
| 600 |
|
| 601 |
@pytest.mark.parametrize("url, expected_authority", url_authority_with_schemes_map) |
| 602 |
def test_authority_matches_urllib_netloc( |
| 603 |
self, url: str, expected_authority: str | None |
| 604 |
) -> None: |
| 605 |
"""Validate this matches the behavior of urlparse().netloc""" |
| 606 |
assert urlparse(url).netloc == expected_authority |
| 607 |
|
| 608 |
@pytest.mark.parametrize("url, expected_netloc", url_netloc_map) |
| 609 |
def test_netloc(self, url: str, expected_netloc: str | None) -> None: |
| 610 |
assert parse_url(url).netloc == expected_netloc |
| 611 |
|
| 612 |
url_auth_decoded_map: list[tuple[str, tuple[str | None, str | None]]] = [ |
| 613 |
# Basic username and password |
| 614 |
("http://foo:[email protected]/", ("foo", "bar")), |
| 615 |
("http://[email protected]/", ("foo", None)), |
| 616 |
("http://foo:@example.com/", ("foo", "")), |
| 617 |
# Unreserved chars (not encoded): - . _ ~ |
| 618 |
("http://user-name:[email protected]/", ("user-name", "pass_word")), |
| 619 |
("http://user.name:[email protected]/", ("user.name", "pass~word")), |
| 620 |
# Sub-delims (not encoded): ! $ & ' ( ) * + , ; = |
| 621 |
("http://user!id:[email protected]/", ("user!id", "pass$word")), |
| 622 |
("http://user&co:pass'[email protected]/", ("user&co", "pass'word")), |
| 623 |
("http://user(test):pass*[email protected]/", ("user(test)", "pass*word")), |
| 624 |
("http://user+id:pass,[email protected]/", ("user+id", "pass,word")), |
| 625 |
("http://user;id:[email protected]/", ("user;id", "pass=word")), |
| 626 |
# Encoded colon in username, unencoded colon in password |
| 627 |
("http://user%3Aname:pass:[email protected]/", ("user:name", "pass:word")), |
| 628 |
# Percent-encoded credentials (unreserved chars: - . _ ~) |
| 629 |
("http://user%2Dname:pass%[email protected]/", ("user-name", "pass.word")), |
| 630 |
# Percent-encoded credentials (reserved/special chars) |
| 631 |
("http://user%40email:pass%[email protected]/", ("user@email", "pass/word")), |
| 632 |
("http://user%20space:pass%[email protected]/", ("user space", "pass:colon")), |
| 633 |
# Multiple @ signs (@ is percent-encoded in username part) |
| 634 |
( |
| 635 |
"http://user%40email.com:[email protected]/", |
| 636 |
("[email protected]", "password"), |
| 637 |
), |
| 638 |
# Special characters already percent-encoded |
| 639 |
("http://user%22:[email protected]/", ('user"', "quoted")), |
| 640 |
# No auth |
| 641 |
("http://example.com/", (None, None)), |
| 642 |
] |
| 643 |
|
| 644 |
@pytest.mark.parametrize("url, expected_auth_decoded", url_auth_decoded_map) |
| 645 |
def test_auth_decoded( |
| 646 |
self, url: str, expected_auth_decoded: tuple[str | None, str | None] |
| 647 |
) -> None: |
| 648 |
parsed_url = parse_url(url) |
| 649 |
assert parsed_url.auth_decoded == expected_auth_decoded |
| 650 |
username, password = expected_auth_decoded |
| 651 |
if username is None and password is None: |
| 652 |
assert parsed_url.auth_decoded_joined is None |
| 653 |
elif password is None: |
| 654 |
# There is no distinction between an empty password and no |
| 655 |
# password in the Basic authentication according to RFC 7617, |
| 656 |
# so the colon is always included. |
| 657 |
assert parsed_url.auth_decoded_joined == f"{username}:" |
| 658 |
else: |
| 659 |
assert parsed_url.auth_decoded_joined == f"{username}:{password}" |
| 660 |
|
| 661 |
url_vulnerabilities = [ |
| 662 |
# urlparse doesn't follow RFC 3986 Section 3.2 |
| 663 |
( |
| 664 |
"http://google.com#@evil.com/", |
| 665 |
Url("http", host="google.com", path="", fragment="@evil.com/"), |
| 666 |
), |
| 667 |
# CVE-2016-5699 |
| 668 |
( |
| 669 |
"http://127.0.0.1%0d%0aConnection%3a%20keep-alive", |
| 670 |
False, |
| 671 |
), |
| 672 |
# NodeJS unicode -> double dot |
| 673 |
( |
| 674 |
"http://google.com/\uff2e\uff2e/abc", |
| 675 |
Url("http", host="google.com", path="/%EF%BC%AE%EF%BC%AE/abc"), |
| 676 |
), |
| 677 |
# Scheme without :// |
| 678 |
( |
| 679 |
"javascript:a='@google.com:12345/';alert(0)", |
| 680 |
Url(scheme="javascript", path="a='@google.com:12345/';alert(0)"), |
| 681 |
), |
| 682 |
("//google.com/a/b/c", Url(host="google.com", path="/a/b/c")), |
| 683 |
# International URLs |
| 684 |
( |
| 685 |
"http://ヒ:キ@ヒ.abc.ニ/ヒ?キ#ワ", |
| 686 |
Url( |
| 687 |
"http", |
| 688 |
host="xn--pdk.abc.xn--idk", |
| 689 |
auth="%E3%83%92:%E3%82%AD", |
| 690 |
path="/%E3%83%92", |
| 691 |
query="%E3%82%AD", |
| 692 |
fragment="%E3%83%AF", |
| 693 |
), |
| 694 |
), |
| 695 |
# Injected headers (CVE-2016-5699, CVE-2019-9740, CVE-2019-9947) |
| 696 |
( |
| 697 |
"10.251.0.83:7777?a=1 HTTP/1.1\r\nX-injected: header", |
| 698 |
Url( |
| 699 |
host="10.251.0.83", |
| 700 |
port=7777, |
| 701 |
path="", |
| 702 |
query="a=1%20HTTP/1.1%0D%0AX-injected:%20header", |
| 703 |
), |
| 704 |
), |
| 705 |
( |
| 706 |
"http://127.0.0.1:6379?\r\nSET test failure12\r\n:8080/test/?test=a", |
| 707 |
Url( |
| 708 |
scheme="http", |
| 709 |
host="127.0.0.1", |
| 710 |
port=6379, |
| 711 |
path="", |
| 712 |
query="%0D%0ASET%20test%20failure12%0D%0A:8080/test/?test=a", |
| 713 |
), |
| 714 |
), |
| 715 |
# See https://bugs.xdavidhu.me/google/2020/03/08/the-unexpected-google-wide-domain-check-bypass/ |
| 716 |
( |
| 717 |
"https://user:[email protected]\\test.corp.google.com:8080/path/to/something?param=value#hash", |
| 718 |
Url( |
| 719 |
scheme="https", |
| 720 |
auth="user:pass", |
| 721 |
host="xdavidhu.me", |
| 722 |
path="/%5Ctest.corp.google.com:8080/path/to/something", |
| 723 |
query="param=value", |
| 724 |
fragment="hash", |
| 725 |
), |
| 726 |
), |
| 727 |
# Tons of '@' causing backtracking |
| 728 |
pytest.param( |
| 729 |
"https://" + ("@" * 10000) + "[", |
| 730 |
False, |
| 731 |
id="Tons of '@' causing backtracking 1", |
| 732 |
), |
| 733 |
pytest.param( |
| 734 |
"https://user:" + ("@" * 10000) + "example.com", |
| 735 |
Url( |
| 736 |
scheme="https", |
| 737 |
auth="user:" + ("%40" * 9999), |
| 738 |
host="example.com", |
| 739 |
), |
| 740 |
id="Tons of '@' causing backtracking 2", |
| 741 |
), |
| 742 |
] |
| 743 |
|
| 744 |
@pytest.mark.parametrize("url, expected_url", url_vulnerabilities) |
| 745 |
def test_url_vulnerabilities( |
| 746 |
self, url: str, expected_url: typing.Literal[False] | Url |
| 747 |
) -> None: |
| 748 |
if expected_url is False: |
| 749 |
with pytest.raises(LocationParseError): |
| 750 |
parse_url(url) |
| 751 |
else: |
| 752 |
assert parse_url(url) == expected_url |
| 753 |
|
| 754 |
def test_parse_url_bytes_type_error(self) -> None: |
| 755 |
with pytest.raises(TypeError): |
| 756 |
parse_url(b"https://www.google.com/") # type: ignore[arg-type] |
| 757 |
|
| 758 |
@pytest.mark.parametrize( |
| 759 |
"kwargs, expected", |
| 760 |
[ |
| 761 |
pytest.param( |
| 762 |
{"accept_encoding": True}, |
| 763 |
{"accept-encoding": "gzip,deflate,br,zstd"}, |
| 764 |
marks=[onlyBrotli(), onlyZstd()], # type: ignore[list-item] |
| 765 |
), |
| 766 |
pytest.param( |
| 767 |
{"accept_encoding": True}, |
| 768 |
{"accept-encoding": "gzip,deflate,br"}, |
| 769 |
marks=[onlyBrotli(), notZstd()], # type: ignore[list-item] |
| 770 |
), |
| 771 |
pytest.param( |
| 772 |
{"accept_encoding": True}, |
| 773 |
{"accept-encoding": "gzip,deflate,zstd"}, |
| 774 |
marks=[notBrotli(), onlyZstd()], # type: ignore[list-item] |
| 775 |
), |
| 776 |
pytest.param( |
| 777 |
{"accept_encoding": True}, |
| 778 |
{"accept-encoding": "gzip,deflate"}, |
| 779 |
marks=[notBrotli(), notZstd()], # type: ignore[list-item] |
| 780 |
), |
| 781 |
({"accept_encoding": "foo,bar"}, {"accept-encoding": "foo,bar"}), |
| 782 |
({"accept_encoding": ["foo", "bar"]}, {"accept-encoding": "foo,bar"}), |
| 783 |
pytest.param( |
| 784 |
{"accept_encoding": True, "user_agent": "banana"}, |
| 785 |
{"accept-encoding": "gzip,deflate,br,zstd", "user-agent": "banana"}, |
| 786 |
marks=[onlyBrotli(), onlyZstd()], # type: ignore[list-item] |
| 787 |
), |
| 788 |
pytest.param( |
| 789 |
{"accept_encoding": True, "user_agent": "banana"}, |
| 790 |
{"accept-encoding": "gzip,deflate,br", "user-agent": "banana"}, |
| 791 |
marks=[onlyBrotli(), notZstd()], # type: ignore[list-item] |
| 792 |
), |
| 793 |
pytest.param( |
| 794 |
{"accept_encoding": True, "user_agent": "banana"}, |
| 795 |
{"accept-encoding": "gzip,deflate,zstd", "user-agent": "banana"}, |
| 796 |
marks=[notBrotli(), onlyZstd()], # type: ignore[list-item] |
| 797 |
), |
| 798 |
pytest.param( |
| 799 |
{"accept_encoding": True, "user_agent": "banana"}, |
| 800 |
{"accept-encoding": "gzip,deflate", "user-agent": "banana"}, |
| 801 |
marks=[notBrotli(), notZstd()], # type: ignore[list-item] |
| 802 |
), |
| 803 |
({"user_agent": "banana"}, {"user-agent": "banana"}), |
| 804 |
({"keep_alive": True}, {"connection": "keep-alive"}), |
| 805 |
({"basic_auth": "foo:bar"}, {"authorization": "Basic Zm9vOmJhcg=="}), |
| 806 |
({"basic_auth": "user:passé"}, {"authorization": "Basic dXNlcjpwYXNz6Q=="}), |
| 807 |
( |
| 808 |
{"basic_auth": "user:passé", "basic_auth_encoding": "utf-8"}, |
| 809 |
{"authorization": "Basic dXNlcjpwYXNzw6k="}, |
| 810 |
), |
| 811 |
( |
| 812 |
{"proxy_basic_auth": "foo:bar"}, |
| 813 |
{"proxy-authorization": "Basic Zm9vOmJhcg=="}, |
| 814 |
), |
| 815 |
( |
| 816 |
{"proxy_basic_auth": "proxy:passé"}, |
| 817 |
{"proxy-authorization": "Basic cHJveHk6cGFzc+k="}, |
| 818 |
), |
| 819 |
( |
| 820 |
{ |
| 821 |
"proxy_basic_auth": "proxy:passé", |
| 822 |
"proxy_basic_auth_encoding": "utf-8", |
| 823 |
}, |
| 824 |
{"proxy-authorization": "Basic cHJveHk6cGFzc8Op"}, |
| 825 |
), |
| 826 |
( |
| 827 |
{ |
| 828 |
"basic_auth": "user:passé", |
| 829 |
"proxy_basic_auth": "proxy:passé", |
| 830 |
"basic_auth_encoding": "utf-8", |
| 831 |
}, |
| 832 |
{ |
| 833 |
"authorization": "Basic dXNlcjpwYXNzw6k=", |
| 834 |
"proxy-authorization": "Basic cHJveHk6cGFzc+k=", |
| 835 |
}, |
| 836 |
), |
| 837 |
( |
| 838 |
{ |
| 839 |
"basic_auth": "user:passé", |
| 840 |
"proxy_basic_auth": "proxy:passé", |
| 841 |
"proxy_basic_auth_encoding": "utf-8", |
| 842 |
}, |
| 843 |
{ |
| 844 |
"authorization": "Basic dXNlcjpwYXNz6Q==", |
| 845 |
"proxy-authorization": "Basic cHJveHk6cGFzc8Op", |
| 846 |
}, |
| 847 |
), |
| 848 |
({"disable_cache": True}, {"cache-control": "no-cache"}), |
| 849 |
], |
| 850 |
) |
| 851 |
def test_make_headers( |
| 852 |
self, kwargs: dict[str, bool | str], expected: dict[str, str] |
| 853 |
) -> None: |
| 854 |
assert make_headers(**kwargs) == expected # type: ignore[arg-type] |
| 855 |
|
| 856 |
def test_make_headers_basic_auth_encoding_error(self) -> None: |
| 857 |
with pytest.raises(UnicodeEncodeError): |
| 858 |
make_headers(basic_auth="ім'я:пароль") |
| 859 |
|
| 860 |
def test_make_headers_basic_auth_utf8_allows_non_latin1(self) -> None: |
| 861 |
assert make_headers(basic_auth="ім'я:пароль", basic_auth_encoding="utf-8") == { |
| 862 |
"authorization": "Basic 0ZbQvCfRjzrQv9Cw0YDQvtC70Yw=" |
| 863 |
} |
| 864 |
|
| 865 |
def test_make_headers_proxy_basic_auth_encoding_error(self) -> None: |
| 866 |
with pytest.raises(UnicodeEncodeError): |
| 867 |
make_headers(proxy_basic_auth="ім'я:пароль") |
| 868 |
|
| 869 |
def test_make_headers_proxy_basic_auth_utf8_allows_non_latin1(self) -> None: |
| 870 |
assert make_headers( |
| 871 |
proxy_basic_auth="ім'я:пароль", proxy_basic_auth_encoding="utf-8" |
| 872 |
) == {"proxy-authorization": "Basic 0ZbQvCfRjzrQv9Cw0YDQvtC70Yw="} |
| 873 |
|
| 874 |
def test_rewind_body(self) -> None: |
| 875 |
body = io.BytesIO(b"test data") |
| 876 |
assert body.read() == b"test data" |
| 877 |
|
| 878 |
# Assert the file object has been consumed |
| 879 |
assert body.read() == b"" |
| 880 |
|
| 881 |
# Rewind it back to just be b'data' |
| 882 |
rewind_body(body, 5) |
| 883 |
assert body.read() == b"data" |
| 884 |
|
| 885 |
def test_rewind_body_failed_tell(self) -> None: |
| 886 |
body = io.BytesIO(b"test data") |
| 887 |
body.read() # Consume body |
| 888 |
|
| 889 |
# Simulate failed tell() |
| 890 |
body_pos = _FAILEDTELL |
| 891 |
with pytest.raises(UnrewindableBodyError): |
| 892 |
rewind_body(body, body_pos) |
| 893 |
|
| 894 |
def test_rewind_body_bad_position(self) -> None: |
| 895 |
body = io.BytesIO(b"test data") |
| 896 |
body.read() # Consume body |
| 897 |
|
| 898 |
# Pass non-integer position |
| 899 |
with pytest.raises(ValueError): |
| 900 |
rewind_body(body, body_pos=None) # type: ignore[arg-type] |
| 901 |
with pytest.raises(ValueError): |
| 902 |
rewind_body(body, body_pos=object()) # type: ignore[arg-type] |
| 903 |
|
| 904 |
def test_rewind_body_failed_seek(self) -> None: |
| 905 |
class BadSeek(io.StringIO): |
| 906 |
def seek(self, offset: int, whence: int = 0) -> typing.NoReturn: |
| 907 |
raise OSError |
| 908 |
|
| 909 |
with pytest.raises(UnrewindableBodyError): |
| 910 |
rewind_body(BadSeek(), body_pos=2) |
| 911 |
|
| 912 |
def test_rewind_body_no_seek(self) -> None: |
| 913 |
class NoSeek(io.StringIO): |
| 914 |
seek = None # type: ignore[assignment] |
| 915 |
|
| 916 |
with pytest.raises(UnrewindableBodyError): |
| 917 |
rewind_body(NoSeek(), body_pos=2) |
| 918 |
|
| 919 |
def test_add_stderr_logger(self) -> None: |
| 920 |
handler = add_stderr_logger(level=logging.INFO) # Don't actually print debug |
| 921 |
logger = logging.getLogger("urllib3") |
| 922 |
assert handler in logger.handlers |
| 923 |
|
| 924 |
logger.debug("Testing add_stderr_logger") |
| 925 |
logger.removeHandler(handler) |
| 926 |
|
| 927 |
def test_disable_warnings(self) -> None: |
| 928 |
with warnings.catch_warnings(record=True) as w: |
| 929 |
clear_warnings() |
| 930 |
warnings.simplefilter("default", InsecureRequestWarning) |
| 931 |
warnings.warn("This is a test.", InsecureRequestWarning) |
| 932 |
assert len(w) == 1 |
| 933 |
disable_warnings() |
| 934 |
warnings.warn("This is a test.", InsecureRequestWarning) |
| 935 |
assert len(w) == 1 |
| 936 |
|
| 937 |
def _make_time_pass( |
| 938 |
self, seconds: int, timeout: Timeout, time_mock: Mock |
| 939 |
) -> Timeout: |
| 940 |
"""Make some time pass for the timeout object""" |
| 941 |
time_mock.return_value = TIMEOUT_EPOCH |
| 942 |
timeout.start_connect() |
| 943 |
time_mock.return_value = TIMEOUT_EPOCH + seconds |
| 944 |
return timeout |
| 945 |
|
| 946 |
@pytest.mark.parametrize( |
| 947 |
"kwargs, message", |
| 948 |
[ |
| 949 |
({"total": -1}, "less than"), |
| 950 |
({"connect": 2, "total": -1}, "less than"), |
| 951 |
({"read": -1}, "less than"), |
| 952 |
({"connect": False}, "cannot be a boolean"), |
| 953 |
({"read": True}, "cannot be a boolean"), |
| 954 |
({"connect": 0}, "less than or equal"), |
| 955 |
({"read": "foo"}, "int, float or None"), |
| 956 |
({"read": "1.0"}, "int, float or None"), |
| 957 |
], |
| 958 |
) |
| 959 |
def test_invalid_timeouts( |
| 960 |
self, kwargs: dict[str, int | bool], message: str |
| 961 |
) -> None: |
| 962 |
with pytest.raises(ValueError, match=message): |
| 963 |
Timeout(**kwargs) |
| 964 |
|
| 965 |
@patch("time.monotonic") |
| 966 |
def test_timeout(self, time_monotonic: MagicMock) -> None: |
| 967 |
timeout = Timeout(total=3) |
| 968 |
|
| 969 |
# make 'no time' elapse |
| 970 |
timeout = self._make_time_pass( |
| 971 |
seconds=0, timeout=timeout, time_mock=time_monotonic |
| 972 |
) |
| 973 |
assert timeout.read_timeout == 3 |
| 974 |
assert timeout.connect_timeout == 3 |
| 975 |
|
| 976 |
timeout = Timeout(total=3, connect=2) |
| 977 |
assert timeout.connect_timeout == 2 |
| 978 |
|
| 979 |
timeout = Timeout() |
| 980 |
assert timeout.connect_timeout == _DEFAULT_TIMEOUT |
| 981 |
|
| 982 |
# Connect takes 5 seconds, leaving 5 seconds for read |
| 983 |
timeout = Timeout(total=10, read=7) |
| 984 |
timeout = self._make_time_pass( |
| 985 |
seconds=5, timeout=timeout, time_mock=time_monotonic |
| 986 |
) |
| 987 |
assert timeout.read_timeout == 5 |
| 988 |
|
| 989 |
# Connect takes 2 seconds, read timeout still 7 seconds |
| 990 |
timeout = Timeout(total=10, read=7) |
| 991 |
timeout = self._make_time_pass( |
| 992 |
seconds=2, timeout=timeout, time_mock=time_monotonic |
| 993 |
) |
| 994 |
assert timeout.read_timeout == 7 |
| 995 |
|
| 996 |
timeout = Timeout(total=10, read=7) |
| 997 |
assert timeout.read_timeout == 7 |
| 998 |
|
| 999 |
timeout = Timeout(total=None, read=None, connect=None) |
| 1000 |
assert timeout.connect_timeout is None |
| 1001 |
assert timeout.read_timeout is None |
| 1002 |
assert timeout.total is None |
| 1003 |
|
| 1004 |
timeout = Timeout(5) |
| 1005 |
assert timeout.total == 5 |
| 1006 |
|
| 1007 |
def test_timeout_default_resolve(self) -> None: |
| 1008 |
"""The timeout default is resolved when read_timeout is accessed.""" |
| 1009 |
timeout = Timeout() |
| 1010 |
with patch("urllib3.util.timeout.getdefaulttimeout", return_value=2): |
| 1011 |
assert timeout.read_timeout == 2 |
| 1012 |
|
| 1013 |
with patch("urllib3.util.timeout.getdefaulttimeout", return_value=3): |
| 1014 |
assert timeout.read_timeout == 3 |
| 1015 |
|
| 1016 |
def test_timeout_str(self) -> None: |
| 1017 |
timeout = Timeout(connect=1, read=2, total=3) |
| 1018 |
assert str(timeout) == "Timeout(connect=1, read=2, total=3)" |
| 1019 |
timeout = Timeout(connect=1, read=None, total=3) |
| 1020 |
assert str(timeout) == "Timeout(connect=1, read=None, total=3)" |
| 1021 |
|
| 1022 |
@patch("time.monotonic") |
| 1023 |
def test_timeout_elapsed(self, time_monotonic: MagicMock) -> None: |
| 1024 |
time_monotonic.return_value = TIMEOUT_EPOCH |
| 1025 |
timeout = Timeout(total=3) |
| 1026 |
with pytest.raises(TimeoutStateError): |
| 1027 |
timeout.get_connect_duration() |
| 1028 |
|
| 1029 |
timeout.start_connect() |
| 1030 |
with pytest.raises(TimeoutStateError): |
| 1031 |
timeout.start_connect() |
| 1032 |
|
| 1033 |
time_monotonic.return_value = TIMEOUT_EPOCH + 2 |
| 1034 |
assert timeout.get_connect_duration() == 2 |
| 1035 |
time_monotonic.return_value = TIMEOUT_EPOCH + 37 |
| 1036 |
assert timeout.get_connect_duration() == 37 |
| 1037 |
|
| 1038 |
def test_is_fp_closed_object_supports_closed(self) -> None: |
| 1039 |
class ClosedFile: |
| 1040 |
@property |
| 1041 |
def closed(self) -> typing.Literal[True]: |
| 1042 |
return True |
| 1043 |
|
| 1044 |
assert is_fp_closed(ClosedFile()) |
| 1045 |
|
| 1046 |
def test_is_fp_closed_object_has_none_fp(self) -> None: |
| 1047 |
class NoneFpFile: |
| 1048 |
@property |
| 1049 |
def fp(self) -> None: |
| 1050 |
return None |
| 1051 |
|
| 1052 |
assert is_fp_closed(NoneFpFile()) |
| 1053 |
|
| 1054 |
def test_is_fp_closed_object_has_fp(self) -> None: |
| 1055 |
class FpFile: |
| 1056 |
@property |
| 1057 |
def fp(self) -> typing.Literal[True]: |
| 1058 |
return True |
| 1059 |
|
| 1060 |
assert not is_fp_closed(FpFile()) |
| 1061 |
|
| 1062 |
def test_is_fp_closed_object_has_neither_fp_nor_closed(self) -> None: |
| 1063 |
class NotReallyAFile: |
| 1064 |
pass |
| 1065 |
|
| 1066 |
with pytest.raises(ValueError): |
| 1067 |
is_fp_closed(NotReallyAFile()) |
| 1068 |
|
| 1069 |
def test_has_ipv6_disabled_on_compile(self) -> None: |
| 1070 |
with patch("socket.has_ipv6", False): |
| 1071 |
assert not _has_ipv6("::1") |
| 1072 |
|
| 1073 |
def test_has_ipv6_enabled_but_fails(self) -> None: |
| 1074 |
with patch("socket.has_ipv6", True): |
| 1075 |
with patch("socket.socket") as mock: |
| 1076 |
instance = mock.return_value |
| 1077 |
instance.bind = Mock(side_effect=Exception("No IPv6 here!")) |
| 1078 |
assert not _has_ipv6("::1") |
| 1079 |
|
| 1080 |
def test_has_ipv6_enabled_and_working(self) -> None: |
| 1081 |
with patch("socket.has_ipv6", True): |
| 1082 |
with patch("socket.socket") as mock: |
| 1083 |
instance = mock.return_value |
| 1084 |
instance.bind.return_value = True |
| 1085 |
assert _has_ipv6("::1") |
| 1086 |
|
| 1087 |
def test_ip_family_ipv6_enabled(self) -> None: |
| 1088 |
with patch("urllib3.util.connection.HAS_IPV6", True): |
| 1089 |
assert allowed_gai_family() == socket.AF_UNSPEC |
| 1090 |
|
| 1091 |
def test_ip_family_ipv6_disabled(self) -> None: |
| 1092 |
with patch("urllib3.util.connection.HAS_IPV6", False): |
| 1093 |
assert allowed_gai_family() == socket.AF_INET |
| 1094 |
|
| 1095 |
@pytest.mark.parametrize("headers", [b"foo", None, object]) |
| 1096 |
def test_assert_header_parsing_throws_typeerror_with_non_headers( |
| 1097 |
self, headers: bytes | object | None |
| 1098 |
) -> None: |
| 1099 |
with pytest.raises(TypeError): |
| 1100 |
assert_header_parsing(headers) # type: ignore[arg-type] |
| 1101 |
|
| 1102 |
def test_connection_requires_http_tunnel_no_proxy(self) -> None: |
| 1103 |
assert not connection_requires_http_tunnel( |
| 1104 |
proxy_url=None, proxy_config=None, destination_scheme=None |
| 1105 |
) |
| 1106 |
|
| 1107 |
def test_connection_requires_http_tunnel_http_proxy(self) -> None: |
| 1108 |
proxy = parse_url("http://proxy:8080") |
| 1109 |
proxy_config = ProxyConfig( |
| 1110 |
ssl_context=None, |
| 1111 |
use_forwarding_for_https=False, |
| 1112 |
assert_hostname=None, |
| 1113 |
assert_fingerprint=None, |
| 1114 |
) |
| 1115 |
destination_scheme = "http" |
| 1116 |
assert not connection_requires_http_tunnel( |
| 1117 |
proxy, proxy_config, destination_scheme |
| 1118 |
) |
| 1119 |
|
| 1120 |
destination_scheme = "https" |
| 1121 |
assert connection_requires_http_tunnel(proxy, proxy_config, destination_scheme) |
| 1122 |
|
| 1123 |
def test_connection_requires_http_tunnel_https_proxy(self) -> None: |
| 1124 |
proxy = parse_url("https://proxy:8443") |
| 1125 |
proxy_config = ProxyConfig( |
| 1126 |
ssl_context=None, |
| 1127 |
use_forwarding_for_https=False, |
| 1128 |
assert_hostname=None, |
| 1129 |
assert_fingerprint=None, |
| 1130 |
) |
| 1131 |
destination_scheme = "http" |
| 1132 |
assert not connection_requires_http_tunnel( |
| 1133 |
proxy, proxy_config, destination_scheme |
| 1134 |
) |
| 1135 |
|
| 1136 |
def test_assert_header_parsing_no_error_on_multipart(self) -> None: |
| 1137 |
from http import client |
| 1138 |
|
| 1139 |
header_msg = io.BytesIO() |
| 1140 |
header_msg.write( |
| 1141 |
b'Content-Type: multipart/encrypted;protocol="application/' |
| 1142 |
b'HTTP-SPNEGO-session-encrypted";boundary="Encrypted Boundary"' |
| 1143 |
b"\nServer: Microsoft-HTTPAPI/2.0\nDate: Fri, 16 Aug 2019 19:28:01 GMT" |
| 1144 |
b"\nContent-Length: 1895\n\n\n" |
| 1145 |
) |
| 1146 |
header_msg.seek(0) |
| 1147 |
assert_header_parsing(client.parse_headers(header_msg)) |
| 1148 |
|
| 1149 |
@pytest.mark.parametrize("host", [".localhost", "...", "t" * 64]) |
| 1150 |
def test_create_connection_with_invalid_idna_labels(self, host: str) -> None: |
| 1151 |
with pytest.raises( |
| 1152 |
LocationParseError, |
| 1153 |
match=f"Failed to parse: '{host}', label empty or too long", |
| 1154 |
): |
| 1155 |
create_connection((host, 80)) |
| 1156 |
|
| 1157 |
@pytest.mark.parametrize( |
| 1158 |
"host", |
| 1159 |
[ |
| 1160 |
"a.example.com", |
| 1161 |
"localhost.", |
| 1162 |
"[dead::beef]", |
| 1163 |
"[dead::beef%en5]", |
| 1164 |
"[dead::beef%en5.]", |
| 1165 |
], |
| 1166 |
) |
| 1167 |
@patch("socket.getaddrinfo") |
| 1168 |
@patch("socket.socket") |
| 1169 |
def test_create_connection_with_valid_idna_labels( |
| 1170 |
self, socket: MagicMock, getaddrinfo: MagicMock, host: str |
| 1171 |
) -> None: |
| 1172 |
getaddrinfo.return_value = [(None, None, None, None, None)] |
| 1173 |
socket.return_value = Mock() |
| 1174 |
create_connection((host, 80)) |
| 1175 |
|
| 1176 |
@patch("socket.getaddrinfo") |
| 1177 |
def test_create_connection_error(self, getaddrinfo: MagicMock) -> None: |
| 1178 |
getaddrinfo.return_value = [] |
| 1179 |
with pytest.raises(OSError, match="getaddrinfo returns an empty list"): |
| 1180 |
create_connection(("example.com", 80)) |
| 1181 |
|
| 1182 |
@patch("socket.getaddrinfo") |
| 1183 |
def test_dnsresolver_forced_error(self, getaddrinfo: MagicMock) -> None: |
| 1184 |
getaddrinfo.side_effect = socket.gaierror() |
| 1185 |
with pytest.raises(socket.gaierror): |
| 1186 |
# dns is valid but we force the error just for the sake of the test |
| 1187 |
create_connection(("example.com", 80)) |
| 1188 |
|
| 1189 |
def test_dnsresolver_expected_error(self) -> None: |
| 1190 |
with pytest.raises(socket.gaierror): |
| 1191 |
# windows: [Errno 11001] getaddrinfo failed in windows |
| 1192 |
# linux: [Errno -2] Name or service not known |
| 1193 |
# macos: [Errno 8] nodename nor servname provided, or not known |
| 1194 |
create_connection(("badhost.invalid", 80)) |
| 1195 |
|
| 1196 |
@patch("socket.getaddrinfo") |
| 1197 |
@patch("socket.socket") |
| 1198 |
def test_create_connection_with_scoped_ipv6( |
| 1199 |
self, socket: MagicMock, getaddrinfo: MagicMock |
| 1200 |
) -> None: |
| 1201 |
# Check that providing create_connection with a scoped IPv6 address |
| 1202 |
# properly propagates the scope to getaddrinfo, and that the returned |
| 1203 |
# scoped ID makes it to the socket creation call. |
| 1204 |
fake_scoped_sa6 = ("a::b", 80, 0, 42) |
| 1205 |
getaddrinfo.return_value = [ |
| 1206 |
( |
| 1207 |
socket.AF_INET6, |
| 1208 |
socket.SOCK_STREAM, |
| 1209 |
socket.IPPROTO_TCP, |
| 1210 |
"", |
| 1211 |
fake_scoped_sa6, |
| 1212 |
) |
| 1213 |
] |
| 1214 |
socket.return_value = fake_sock = MagicMock() |
| 1215 |
|
| 1216 |
create_connection(("a::b%iface", 80)) |
| 1217 |
assert getaddrinfo.call_args[0][0] == "a::b%iface" |
| 1218 |
fake_sock.connect.assert_called_once_with(fake_scoped_sa6) |
| 1219 |
|
| 1220 |
@pytest.mark.parametrize( |
| 1221 |
"input,params,expected", |
| 1222 |
( |
| 1223 |
("test", {}, "test"), # str input |
| 1224 |
(b"test", {}, "test"), # bytes input |
| 1225 |
(b"test", {"encoding": "utf-8"}, "test"), # bytes input with utf-8 |
| 1226 |
(b"test", {"encoding": "ascii"}, "test"), # bytes input with ascii |
| 1227 |
), |
| 1228 |
) |
| 1229 |
def test_to_str( |
| 1230 |
self, input: bytes | str, params: dict[str, str], expected: str |
| 1231 |
) -> None: |
| 1232 |
assert to_str(input, **params) == expected |
| 1233 |
|
| 1234 |
def test_to_str_error(self) -> None: |
| 1235 |
with pytest.raises(TypeError, match="not expecting type int"): |
| 1236 |
to_str(1) # type: ignore[arg-type] |
| 1237 |
|
| 1238 |
@pytest.mark.parametrize( |
| 1239 |
"input,params,expected", |
| 1240 |
( |
| 1241 |
(b"test", {}, b"test"), # str input |
| 1242 |
("test", {}, b"test"), # bytes input |
| 1243 |
("é", {}, b"\xc3\xa9"), # bytes input |
| 1244 |
("test", {"encoding": "utf-8"}, b"test"), # bytes input with utf-8 |
| 1245 |
("test", {"encoding": "ascii"}, b"test"), # bytes input with ascii |
| 1246 |
), |
| 1247 |
) |
| 1248 |
def test_to_bytes( |
| 1249 |
self, input: bytes | str, params: dict[str, str], expected: bytes |
| 1250 |
) -> None: |
| 1251 |
assert to_bytes(input, **params) == expected |
| 1252 |
|
| 1253 |
def test_to_bytes_error(self) -> None: |
| 1254 |
with pytest.raises(TypeError, match="not expecting type int"): |
| 1255 |
to_bytes(1) # type: ignore[arg-type] |
| 1256 |
|
| 1257 |
|
| 1258 |
class TestUtilSSL: |
| 1259 |
"""Test utils that use an SSL backend.""" |
| 1260 |
|
| 1261 |
@pytest.mark.parametrize( |
| 1262 |
"candidate, requirements", |
| 1263 |
[ |
| 1264 |
(None, ssl.CERT_REQUIRED), |
| 1265 |
(ssl.CERT_NONE, ssl.CERT_NONE), |
| 1266 |
(ssl.CERT_REQUIRED, ssl.CERT_REQUIRED), |
| 1267 |
("REQUIRED", ssl.CERT_REQUIRED), |
| 1268 |
("CERT_REQUIRED", ssl.CERT_REQUIRED), |
| 1269 |
], |
| 1270 |
) |
| 1271 |
def test_resolve_cert_reqs( |
| 1272 |
self, candidate: int | str | None, requirements: int |
| 1273 |
) -> None: |
| 1274 |
assert resolve_cert_reqs(candidate) == requirements |
| 1275 |
|
| 1276 |
candidate_version = [ |
| 1277 |
(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv23), |
| 1278 |
("PROTOCOL_SSLv23", ssl.PROTOCOL_SSLv23), |
| 1279 |
("SSLv23", ssl.PROTOCOL_SSLv23), |
| 1280 |
] |
| 1281 |
if hasattr(ssl, "PROTOCOL_TLSv1"): |
| 1282 |
candidate_version.extend( |
| 1283 |
[ |
| 1284 |
(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLSv1), |
| 1285 |
("PROTOCOL_TLSv1", ssl.PROTOCOL_TLSv1), |
| 1286 |
("TLSv1", ssl.PROTOCOL_TLSv1), |
| 1287 |
] |
| 1288 |
) |
| 1289 |
|
| 1290 |
@pytest.mark.parametrize("candidate, version", candidate_version) |
| 1291 |
def test_resolve_ssl_version(self, candidate: int | str, version: int) -> None: |
| 1292 |
assert resolve_ssl_version(candidate) == version |
| 1293 |
|
| 1294 |
def test_ssl_wrap_socket_loads_the_cert_chain(self) -> None: |
| 1295 |
socket = Mock() |
| 1296 |
mock_context = Mock() |
| 1297 |
ssl_wrap_socket( |
| 1298 |
ssl_context=mock_context, sock=socket, certfile="/path/to/certfile" |
| 1299 |
) |
| 1300 |
|
| 1301 |
mock_context.load_cert_chain.assert_called_once_with("/path/to/certfile", None) |
| 1302 |
|
| 1303 |
@patch("urllib3.util.ssl_.create_urllib3_context") |
| 1304 |
def test_ssl_wrap_socket_creates_new_context( |
| 1305 |
self, create_urllib3_context: mock.MagicMock |
| 1306 |
) -> None: |
| 1307 |
socket = Mock() |
| 1308 |
ssl_wrap_socket(socket, cert_reqs=ssl.CERT_REQUIRED) |
| 1309 |
|
| 1310 |
create_urllib3_context.assert_called_once_with(None, 2, ciphers=None) |
| 1311 |
|
| 1312 |
def test_ssl_wrap_socket_loads_verify_locations(self) -> None: |
| 1313 |
socket = Mock() |
| 1314 |
mock_context = Mock() |
| 1315 |
ssl_wrap_socket(ssl_context=mock_context, ca_certs="/path/to/pem", sock=socket) |
| 1316 |
mock_context.load_verify_locations.assert_called_once_with( |
| 1317 |
"/path/to/pem", None, None |
| 1318 |
) |
| 1319 |
|
| 1320 |
def test_ssl_wrap_socket_loads_certificate_directories(self) -> None: |
| 1321 |
socket = Mock() |
| 1322 |
mock_context = Mock() |
| 1323 |
ssl_wrap_socket( |
| 1324 |
ssl_context=mock_context, ca_cert_dir="/path/to/pems", sock=socket |
| 1325 |
) |
| 1326 |
mock_context.load_verify_locations.assert_called_once_with( |
| 1327 |
None, "/path/to/pems", None |
| 1328 |
) |
| 1329 |
|
| 1330 |
def test_ssl_wrap_socket_loads_certificate_data(self) -> None: |
| 1331 |
socket = Mock() |
| 1332 |
mock_context = Mock() |
| 1333 |
ssl_wrap_socket( |
| 1334 |
ssl_context=mock_context, ca_cert_data="TOTALLY PEM DATA", sock=socket |
| 1335 |
) |
| 1336 |
mock_context.load_verify_locations.assert_called_once_with( |
| 1337 |
None, None, "TOTALLY PEM DATA" |
| 1338 |
) |
| 1339 |
|
| 1340 |
def _wrap_socket_and_mock_warn( |
| 1341 |
self, sock: socket.socket, server_hostname: str | None |
| 1342 |
) -> tuple[Mock, MagicMock]: |
| 1343 |
mock_context = Mock() |
| 1344 |
with patch("warnings.warn") as warn: |
| 1345 |
ssl_wrap_socket( |
| 1346 |
ssl_context=mock_context, |
| 1347 |
sock=sock, |
| 1348 |
server_hostname=server_hostname, |
| 1349 |
) |
| 1350 |
return mock_context, warn |
| 1351 |
|
| 1352 |
def test_ssl_wrap_socket_sni_ip_address_no_warn(self) -> None: |
| 1353 |
"""Test that a warning is not made if server_hostname is an IP address.""" |
| 1354 |
sock = Mock() |
| 1355 |
context, warn = self._wrap_socket_and_mock_warn(sock, "8.8.8.8") |
| 1356 |
context.wrap_socket.assert_called_once_with(sock, server_hostname="8.8.8.8") |
| 1357 |
warn.assert_not_called() |
| 1358 |
|
| 1359 |
def test_ssl_wrap_socket_sni_none_no_warn(self) -> None: |
| 1360 |
"""Test that a warning is not made if server_hostname is not given.""" |
| 1361 |
sock = Mock() |
| 1362 |
context, warn = self._wrap_socket_and_mock_warn(sock, None) |
| 1363 |
context.wrap_socket.assert_called_once_with(sock, server_hostname=None) |
| 1364 |
warn.assert_not_called() |
| 1365 |
|
| 1366 |
@pytest.mark.parametrize( |
| 1367 |
"openssl_version, reliable", |
| 1368 |
[ |
| 1369 |
# any OpenSSL 1.1.1+ -> reliable since Python 3.10.0b1 according to |
| 1370 |
# https://github.com/python/cpython/issues/87688#issuecomment-1093906646 |
| 1371 |
("OpenSSL 1.1.1", True), |
| 1372 |
# not OpenSSSL -> unreliable |
| 1373 |
("LibreSSL 2.8.3", False), |
| 1374 |
], |
| 1375 |
) |
| 1376 |
def test_is_has_never_check_common_name_reliable( |
| 1377 |
self, |
| 1378 |
openssl_version: str, |
| 1379 |
reliable: bool, |
| 1380 |
) -> None: |
| 1381 |
assert ( |
| 1382 |
_is_has_never_check_common_name_reliable( |
| 1383 |
openssl_version, |
| 1384 |
) |
| 1385 |
== reliable |
| 1386 |
) |
| 1387 |
|
| 1388 |
|
| 1389 |
idna_blocker = ImportBlocker("idna") |
| 1390 |
module_stash = ModuleStash("urllib3") |
| 1391 |
|
| 1392 |
|
| 1393 |
class TestUtilWithoutIdna: |
| 1394 |
@classmethod |
| 1395 |
def setup_class(cls) -> None: |
| 1396 |
sys.modules.pop("idna", None) |
| 1397 |
|
| 1398 |
module_stash.stash() |
| 1399 |
sys.meta_path.insert(0, idna_blocker) |
| 1400 |
|
| 1401 |
@classmethod |
| 1402 |
def teardown_class(cls) -> None: |
| 1403 |
sys.meta_path.remove(idna_blocker) |
| 1404 |
module_stash.pop() |
| 1405 |
|
| 1406 |
@pytest.mark.parametrize( |
| 1407 |
"url", |
| 1408 |
[ |
| 1409 |
"http://\ud7ff.com/", |
| 1410 |
"http://Königsgäßchen.de/path", |
| 1411 |
], |
| 1412 |
) |
| 1413 |
def test_parse_url_raw_non_ascii_without_idna_raises(self, url: str) -> None: |
| 1414 |
with pytest.raises( |
| 1415 |
LocationParseError, match="Unable to parse URL without the 'idna' module" |
| 1416 |
): |
| 1417 |
parse_url(url) |
| 1418 |
|
| 1419 |
@pytest.mark.parametrize( |
| 1420 |
"url, expected_host", |
| 1421 |
[ |
| 1422 |
("http://%ED%9F%BF.com/", "%ED%9F%BF.com"), |
| 1423 |
( |
| 1424 |
"http://K%C3%B6nigsg%C3%A4%C3%9Fchen.de/path", |
| 1425 |
"k%C3%B6nigsg%C3%A4%C3%9Fchen.de", |
| 1426 |
), |
| 1427 |
("http://%65x%C3%A4mple.com/", "ex%C3%A4mple.com"), |
| 1428 |
], |
| 1429 |
) |
| 1430 |
def test_parse_url_percent_encoded_non_ascii_without_idna( |
| 1431 |
self, url: str, expected_host: str |
| 1432 |
) -> None: |
| 1433 |
assert parse_url(url).host == expected_host |
| 1434 |
|
| 1435 |
@pytest.mark.parametrize( |
| 1436 |
"url, expected_host", |
| 1437 |
[ |
| 1438 |
("http://%65xample.com/", "example.com"), |
| 1439 |
("http://example.com%2E/", "example.com."), |
| 1440 |
], |
| 1441 |
) |
| 1442 |
def test_parse_url_percent_encoded_ascii_without_idna( |
| 1443 |
self, url: str, expected_host: str |
| 1444 |
) -> None: |
| 1445 |
assert parse_url(url).host == expected_host |