| 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 itertools import chain |
| 11 |
from test import ImportBlocker, ModuleStash, notBrotli, notZstd, onlyBrotli, onlyZstd |
| 12 |
from unittest import mock |
| 13 |
from unittest.mock import MagicMock, Mock, patch |
| 14 |
from urllib.parse import urlparse |
| 15 |
|
| 16 |
import pytest |
| 17 |
|
| 18 |
from urllib3 import add_stderr_logger, disable_warnings |
| 19 |
from urllib3.connection import ProxyConfig |
| 20 |
from urllib3.exceptions import ( |
| 21 |
InsecureRequestWarning, |
| 22 |
LocationParseError, |
| 23 |
TimeoutStateError, |
| 24 |
UnrewindableBodyError, |
| 25 |
) |
| 26 |
from urllib3.util import is_fp_closed |
| 27 |
from urllib3.util.connection import _has_ipv6, allowed_gai_family, create_connection |
| 28 |
from urllib3.util.proxy import connection_requires_http_tunnel |
| 29 |
from urllib3.util.request import _FAILEDTELL, make_headers, rewind_body |
| 30 |
from urllib3.util.response import assert_header_parsing |
| 31 |
from urllib3.util.ssl_ import ( |
| 32 |
_is_has_never_check_common_name_reliable, |
| 33 |
resolve_cert_reqs, |
| 34 |
resolve_ssl_version, |
| 35 |
ssl_wrap_socket, |
| 36 |
) |
| 37 |
from urllib3.util.timeout import _DEFAULT_TIMEOUT, Timeout |
| 38 |
from urllib3.util.url import Url, _encode_invalid_chars, parse_url |
| 39 |
from urllib3.util.util import to_bytes, to_str |
| 40 |
|
| 41 |
from . import clear_warnings |
| 42 |
|
| 43 |
# This number represents a time in seconds, it doesn't mean anything in |
| 44 |
# isolation. Setting to a high-ish value to avoid conflicts with the smaller |
| 45 |
# numbers used for timeouts |
| 46 |
TIMEOUT_EPOCH = 1000 |
| 47 |
|
| 48 |
|
| 49 |
class TestUtil: |
| 50 |
url_host_map = [ |
| 51 |
# Hosts |
| 52 |
("http://google.com/mail", ("http", "google.com", None)), |
| 53 |
("http://google.com/mail/", ("http", "google.com", None)), |
| 54 |
("google.com/mail", ("http", "google.com", None)), |
| 55 |
("http://google.com/", ("http", "google.com", None)), |
| 56 |
("http://google.com", ("http", "google.com", None)), |
| 57 |
("http://www.google.com", ("http", "www.google.com", None)), |
| 58 |
("http://mail.google.com", ("http", "mail.google.com", None)), |
| 59 |
("http://google.com:8000/mail/", ("http", "google.com", 8000)), |
| 60 |
("http://google.com:8000", ("http", "google.com", 8000)), |
| 61 |
("https://google.com", ("https", "google.com", None)), |
| 62 |
("https://google.com:8000", ("https", "google.com", 8000)), |
| 63 |
("http://user:[email protected]:1234", ("http", "127.0.0.1", 1234)), |
| 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 |
("http://google.com#foo=http://bar:42/baz", ("http", "google.com", None)), |
| 67 |
# IPv4 |
| 68 |
("173.194.35.7", ("http", "173.194.35.7", None)), |
| 69 |
("http://173.194.35.7", ("http", "173.194.35.7", None)), |
| 70 |
("http://173.194.35.7/test", ("http", "173.194.35.7", None)), |
| 71 |
("http://173.194.35.7:80", ("http", "173.194.35.7", 80)), |
| 72 |
("http://173.194.35.7:80/test", ("http", "173.194.35.7", 80)), |
| 73 |
# IPv6 |
| 74 |
("[2a00:1450:4001:c01::67]", ("http", "[2a00:1450:4001:c01::67]", None)), |
| 75 |
("http://[2a00:1450:4001:c01::67]", ("http", "[2a00:1450:4001:c01::67]", None)), |
| 76 |
( |
| 77 |
"http://[2a00:1450:4001:c01::67]/test", |
| 78 |
("http", "[2a00:1450:4001:c01::67]", None), |
| 79 |
), |
| 80 |
( |
| 81 |
"http://[2a00:1450:4001:c01::67]:80", |
| 82 |
("http", "[2a00:1450:4001:c01::67]", 80), |
| 83 |
), |
| 84 |
( |
| 85 |
"http://[2a00:1450:4001:c01::67]:80/test", |
| 86 |
("http", "[2a00:1450:4001:c01::67]", 80), |
| 87 |
), |
| 88 |
# More IPv6 from http://www.ietf.org/rfc/rfc2732.txt |
| 89 |
( |
| 90 |
"http://[fedc:ba98:7654:3210:fedc:ba98:7654:3210]:8000/index.html", |
| 91 |
("http", "[fedc:ba98:7654:3210:fedc:ba98:7654:3210]", 8000), |
| 92 |
), |
| 93 |
( |
| 94 |
"http://[1080:0:0:0:8:800:200c:417a]/index.html", |
| 95 |
("http", "[1080:0:0:0:8:800:200c:417a]", None), |
| 96 |
), |
| 97 |
("http://[3ffe:2a00:100:7031::1]", ("http", "[3ffe:2a00:100:7031::1]", None)), |
| 98 |
( |
| 99 |
"http://[1080::8:800:200c:417a]/foo", |
| 100 |
("http", "[1080::8:800:200c:417a]", None), |
| 101 |
), |
| 102 |
("http://[::192.9.5.5]/ipng", ("http", "[::192.9.5.5]", None)), |
| 103 |
( |
| 104 |
"http://[::ffff:129.144.52.38]:42/index.html", |
| 105 |
("http", "[::ffff:129.144.52.38]", 42), |
| 106 |
), |
| 107 |
( |
| 108 |
"http://[2010:836b:4179::836b:4179]", |
| 109 |
("http", "[2010:836b:4179::836b:4179]", None), |
| 110 |
), |
| 111 |
# Scoped IPv6 (with ZoneID), both RFC 6874 compliant and not. |
| 112 |
("http://[a::b%25zone]", ("http", "[a::b%zone]", None)), |
| 113 |
("http://[a::b%zone]", ("http", "[a::b%zone]", None)), |
| 114 |
# Hosts |
| 115 |
("HTTP://GOOGLE.COM/mail/", ("http", "google.com", None)), |
| 116 |
("GOogle.COM/mail", ("http", "google.com", None)), |
| 117 |
("HTTP://GoOgLe.CoM:8000/mail/", ("http", "google.com", 8000)), |
| 118 |
("HTTP://user:[email protected]:1234", ("http", "example.com", 1234)), |
| 119 |
("173.194.35.7", ("http", "173.194.35.7", None)), |
| 120 |
("HTTP://173.194.35.7", ("http", "173.194.35.7", None)), |
| 121 |
( |
| 122 |
"HTTP://[2a00:1450:4001:c01::67]:80/test", |
| 123 |
("http", "[2a00:1450:4001:c01::67]", 80), |
| 124 |
), |
| 125 |
( |
| 126 |
"HTTP://[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:8000/index.html", |
| 127 |
("http", "[fedc:ba98:7654:3210:fedc:ba98:7654:3210]", 8000), |
| 128 |
), |
| 129 |
( |
| 130 |
"HTTPS://[1080:0:0:0:8:800:200c:417A]/index.html", |
| 131 |
("https", "[1080:0:0:0:8:800:200c:417a]", None), |
| 132 |
), |
| 133 |
("abOut://eXamPlE.com?info=1", ("about", "eXamPlE.com", None)), |
| 134 |
( |
| 135 |
"http+UNIX://%2fvar%2frun%2fSOCKET/path", |
| 136 |
("http+unix", "%2fvar%2frun%2fSOCKET", None), |
| 137 |
), |
| 138 |
] |
| 139 |
|
| 140 |
@pytest.mark.parametrize(["url", "scheme_host_port"], url_host_map) |
| 141 |
def test_scheme_host_port( |
| 142 |
self, url: str, scheme_host_port: tuple[str, str, int | None] |
| 143 |
) -> None: |
| 144 |
parsed_url = parse_url(url) |
| 145 |
scheme, host, port = scheme_host_port |
| 146 |
|
| 147 |
assert (parsed_url.scheme or "http") == scheme |
| 148 |
assert parsed_url.hostname == parsed_url.host == host |
| 149 |
assert parsed_url.port == port |
| 150 |
|
| 151 |
def test_encode_invalid_chars_none(self) -> None: |
| 152 |
assert _encode_invalid_chars(None, set()) is None |
| 153 |
|
| 154 |
@pytest.mark.parametrize( |
| 155 |
"url", |
| 156 |
[ |
| 157 |
"http://google.com:foo", |
| 158 |
"http://::1/", |
| 159 |
"http://::1:80/", |
| 160 |
"http://google.com:-80", |
| 161 |
"http://google.com:65536", |
| 162 |
"http://google.com:\xb2\xb2", # \xb2 = ^2 |
| 163 |
# Invalid IDNA labels |
| 164 |
"http://\ud7ff.com", |
| 165 |
"http://❤️", |
| 166 |
# Unicode surrogates |
| 167 |
"http://\ud800.com", |
| 168 |
"http://\udc00.com", |
| 169 |
], |
| 170 |
) |
| 171 |
def test_invalid_url(self, url: str) -> None: |
| 172 |
with pytest.raises(LocationParseError): |
| 173 |
parse_url(url) |
| 174 |
|
| 175 |
@pytest.mark.parametrize( |
| 176 |
"url, expected_normalized_url", |
| 177 |
[ |
| 178 |
("HTTP://GOOGLE.COM/MAIL/", "http://google.com/MAIL/"), |
| 179 |
( |
| 180 |
"http://[email protected]:[email protected]/~tilde@?@", |
| 181 |
"http://user%40domain.com:[email protected]/~tilde@?@", |
| 182 |
), |
| 183 |
( |
| 184 |
"HTTP://JeremyCline:[email protected]:8080/", |
| 185 |
"http://JeremyCline:[email protected]:8080/", |
| 186 |
), |
| 187 |
("HTTPS://Example.Com/?Key=Value", "https://example.com/?Key=Value"), |
| 188 |
("Https://Example.Com/#Fragment", "https://example.com/#Fragment"), |
| 189 |
# IPv6 addresses with zone IDs. Both RFC 6874 (%25) as well as |
| 190 |
# non-standard (unquoted %) variants. |
| 191 |
("[::1%zone]", "[::1%zone]"), |
| 192 |
("[::1%25zone]", "[::1%zone]"), |
| 193 |
("[::1%25]", "[::1%25]"), |
| 194 |
("[::Ff%etH0%Ff]/%ab%Af", "[::ff%etH0%FF]/%AB%AF"), |
| 195 |
( |
| 196 |
"http://user:pass@[AaAa::Ff%25etH0%Ff]/%ab%Af", |
| 197 |
"http://user:pass@[aaaa::ff%etH0%FF]/%AB%AF", |
| 198 |
), |
| 199 |
# Invalid characters for the query/fragment getting encoded |
| 200 |
( |
| 201 |
'http://google.com/p[]?parameter[]="hello"#fragment#', |
| 202 |
"http://google.com/p%5B%5D?parameter%5B%5D=%22hello%22#fragment%23", |
| 203 |
), |
| 204 |
# Percent encoding isn't applied twice despite '%' being invalid |
| 205 |
# but the percent encoding is still normalized. |
| 206 |
( |
| 207 |
"http://google.com/p%5B%5d?parameter%5b%5D=%22hello%22#fragment%23", |
| 208 |
"http://google.com/p%5B%5D?parameter%5B%5D=%22hello%22#fragment%23", |
| 209 |
), |
| 210 |
], |
| 211 |
) |
| 212 |
def test_parse_url_normalization( |
| 213 |
self, url: str, expected_normalized_url: str |
| 214 |
) -> None: |
| 215 |
"""Assert parse_url normalizes the scheme/host, and only the scheme/host""" |
| 216 |
actual_normalized_url = parse_url(url).url |
| 217 |
assert actual_normalized_url == expected_normalized_url |
| 218 |
|
| 219 |
@pytest.mark.parametrize("char", [chr(i) for i in range(0x00, 0x21)] + ["\x7f"]) |
| 220 |
def test_control_characters_are_percent_encoded(self, char: str) -> None: |
| 221 |
percent_char = "%" + (hex(ord(char))[2:].zfill(2).upper()) |
| 222 |
url = parse_url( |
| 223 |
f"http://user{char}@example.com/path{char}?query{char}#fragment{char}" |
| 224 |
) |
| 225 |
|
| 226 |
assert url == Url( |
| 227 |
"http", |
| 228 |
auth="user" + percent_char, |
| 229 |
host="example.com", |
| 230 |
path="/path" + percent_char, |
| 231 |
query="query" + percent_char, |
| 232 |
fragment="fragment" + percent_char, |
| 233 |
) |
| 234 |
|
| 235 |
parse_url_host_map = [ |
| 236 |
("http://google.com/mail", Url("http", host="google.com", path="/mail")), |
| 237 |
("http://google.com/mail/", Url("http", host="google.com", path="/mail/")), |
| 238 |
("http://google.com/mail", Url("http", host="google.com", path="mail")), |
| 239 |
("google.com/mail", Url(host="google.com", path="/mail")), |
| 240 |
("http://google.com/", Url("http", host="google.com", path="/")), |
| 241 |
("http://google.com", Url("http", host="google.com")), |
| 242 |
("http://google.com?foo", Url("http", host="google.com", path="", query="foo")), |
| 243 |
# Path/query/fragment |
| 244 |
("", Url()), |
| 245 |
("/", Url(path="/")), |
| 246 |
("#?/!google.com/?foo", Url(path="", fragment="?/!google.com/?foo")), |
| 247 |
("/foo", Url(path="/foo")), |
| 248 |
("/foo?bar=baz", Url(path="/foo", query="bar=baz")), |
| 249 |
( |
| 250 |
"/foo?bar=baz#banana?apple/orange", |
| 251 |
Url(path="/foo", query="bar=baz", fragment="banana?apple/orange"), |
| 252 |
), |
| 253 |
( |
| 254 |
"/redirect?target=http://localhost:61020/", |
| 255 |
Url(path="redirect", query="target=http://localhost:61020/"), |
| 256 |
), |
| 257 |
# Port |
| 258 |
("http://google.com/", Url("http", host="google.com", path="/")), |
| 259 |
("http://google.com:80/", Url("http", host="google.com", port=80, path="/")), |
| 260 |
("http://google.com:80", Url("http", host="google.com", port=80)), |
| 261 |
# Auth |
| 262 |
( |
| 263 |
"http://foo:bar@localhost/", |
| 264 |
Url("http", auth="foo:bar", host="localhost", path="/"), |
| 265 |
), |
| 266 |
("http://foo@localhost/", Url("http", auth="foo", host="localhost", path="/")), |
| 267 |
( |
| 268 |
"http://foo:bar@localhost/", |
| 269 |
Url("http", auth="foo:bar", host="localhost", path="/"), |
| 270 |
), |
| 271 |
] |
| 272 |
|
| 273 |
non_round_tripping_parse_url_host_map = [ |
| 274 |
# Path/query/fragment |
| 275 |
("?", Url(path="", query="")), |
| 276 |
("#", Url(path="", fragment="")), |
| 277 |
# Path normalization |
| 278 |
("/abc/../def", Url(path="/def")), |
| 279 |
# Empty Port |
| 280 |
("http://google.com:", Url("http", host="google.com")), |
| 281 |
("http://google.com:/", Url("http", host="google.com", path="/")), |
| 282 |
# Uppercase IRI |
| 283 |
( |
| 284 |
"http://Königsgäßchen.de/straße", |
| 285 |
Url("http", host="xn--knigsgchen-b4a3dun.de", path="/stra%C3%9Fe"), |
| 286 |
), |
| 287 |
# Percent-encode in userinfo |
| 288 |
( |
| 289 |
"http://[email protected]:[email protected]/", |
| 290 |
Url("http", auth="user%40email.com:password", host="example.com", path="/"), |
| 291 |
), |
| 292 |
( |
| 293 |
'http://user":[email protected]/', |
| 294 |
Url("http", auth="user%22:quoted", host="example.com", path="/"), |
| 295 |
), |
| 296 |
# Unicode Surrogates |
| 297 |
("http://google.com/\ud800", Url("http", host="google.com", path="%ED%A0%80")), |
| 298 |
( |
| 299 |
"http://google.com?q=\udc00", |
| 300 |
Url("http", host="google.com", path="", query="q=%ED%B0%80"), |
| 301 |
), |
| 302 |
( |
| 303 |
"http://google.com#\udc00", |
| 304 |
Url("http", host="google.com", path="", fragment="%ED%B0%80"), |
| 305 |
), |
| 306 |
] |
| 307 |
|
| 308 |
@pytest.mark.parametrize( |
| 309 |
"url, expected_url", |
| •310 |
list(chain(parse_url_host_map, non_round_tripping_parse_url_host_map)), |
| 311 |
) |
| 312 |
def test_parse_url(self, url: str, expected_url: Url) -> None: |
| 313 |
returned_url = parse_url(url) |
| 314 |
assert returned_url == expected_url |
| 315 |
assert returned_url.hostname == returned_url.host == expected_url.host |
| 316 |
|
| 317 |
@pytest.mark.parametrize("url, expected_url", parse_url_host_map) |
| 318 |
def test_unparse_url(self, url: str, expected_url: Url) -> None: |
| 319 |
assert url == expected_url.url |
| 320 |
|
| 321 |
@pytest.mark.parametrize( |
| 322 |
["url", "expected_url"], |
| 323 |
[ |
| 324 |
# RFC 3986 5.2.4 |
| 325 |
("/abc/../def", Url(path="/def")), |
| 326 |
("/..", Url(path="/")), |
| 327 |
("/./abc/./def/", Url(path="/abc/def/")), |
| 328 |
("/.", Url(path="/")), |
| 329 |
("/./", Url(path="/")), |
| 330 |
("/abc/./.././d/././e/.././f/./../../ghi", Url(path="/ghi")), |
| 331 |
], |
| 332 |
) |
| 333 |
def test_parse_and_normalize_url_paths(self, url: str, expected_url: Url) -> None: |
| 334 |
actual_url = parse_url(url) |
| 335 |
assert actual_url == expected_url |
| 336 |
assert actual_url.url == expected_url.url |
| 337 |
|
| 338 |
def test_parse_url_invalid_IPv6(self) -> None: |
| 339 |
with pytest.raises(LocationParseError): |
| 340 |
parse_url("[::1") |
| 341 |
|
| 342 |
def test_parse_url_negative_port(self) -> None: |
| 343 |
with pytest.raises(LocationParseError): |
| 344 |
parse_url("https://www.google.com:-80/") |
| 345 |
|
| 346 |
def test_parse_url_remove_leading_zeros(self) -> None: |
| 347 |
url = parse_url("https://example.com:0000000000080") |
| 348 |
assert url.port == 80 |
| 349 |
|
| 350 |
def test_parse_url_only_zeros(self) -> None: |
| 351 |
url = parse_url("https://example.com:0") |
| 352 |
assert url.port == 0 |
| 353 |
|
| 354 |
url = parse_url("https://example.com:000000000000") |
| 355 |
assert url.port == 0 |
| 356 |
|
| 357 |
def test_Url_str(self) -> None: |
| 358 |
U = Url("http", host="google.com") |
| 359 |
assert str(U) == U.url |
| 360 |
|
| 361 |
request_uri_map = [ |
| 362 |
("http://google.com/mail", "/mail"), |
| 363 |
("http://google.com/mail/", "/mail/"), |
| 364 |
("http://google.com/", "/"), |
| 365 |
("http://google.com", "/"), |
| 366 |
("", "/"), |
| 367 |
("/", "/"), |
| 368 |
("?", "/?"), |
| 369 |
("#", "/"), |
| 370 |
("/foo?bar=baz", "/foo?bar=baz"), |
| 371 |
] |
| 372 |
|
| 373 |
@pytest.mark.parametrize("url, expected_request_uri", request_uri_map) |
| 374 |
def test_request_uri(self, url: str, expected_request_uri: str) -> None: |
| 375 |
returned_url = parse_url(url) |
| 376 |
assert returned_url.request_uri == expected_request_uri |
| 377 |
|
| 378 |
url_authority_map: list[tuple[str, str | None]] = [ |
| 379 |
("http://user:[email protected]/mail", "user:[email protected]"), |
| 380 |
("http://user:[email protected]:80/mail", "user:[email protected]:80"), |
| 381 |
("http://[email protected]:80/mail", "[email protected]:80"), |
| 382 |
("http://user:[email protected]/path", "user:[email protected]"), |
| 383 |
("http://user:[email protected]:80/path", "user:[email protected]:80"), |
| 384 |
("http://[email protected]:80/path", "[email protected]:80"), |
| 385 |
("http://user:pass@[::1]/path", "user:pass@[::1]"), |
| 386 |
("http://user:pass@[::1]:80/path", "user:pass@[::1]:80"), |
| 387 |
("http://user@[::1]:80/path", "user@[::1]:80"), |
| 388 |
("http://user:pass@localhost/path", "user:pass@localhost"), |
| 389 |
("http://user:pass@localhost:80/path", "user:pass@localhost:80"), |
| 390 |
("http://user@localhost:80/path", "user@localhost:80"), |
| 391 |
] |
| 392 |
|
| 393 |
url_netloc_map = [ |
| 394 |
("http://google.com/mail", "google.com"), |
| 395 |
("http://google.com:80/mail", "google.com:80"), |
| 396 |
("http://192.168.0.1/path", "192.168.0.1"), |
| 397 |
("http://192.168.0.1:80/path", "192.168.0.1:80"), |
| 398 |
("http://[::1]/path", "[::1]"), |
| 399 |
("http://[::1]:80/path", "[::1]:80"), |
| 400 |
("http://localhost", "localhost"), |
| 401 |
("http://localhost:80", "localhost:80"), |
| 402 |
("google.com/foobar", "google.com"), |
| 403 |
("google.com:12345", "google.com:12345"), |
| 404 |
("/", None), |
| 405 |
] |
| 406 |
|
| 407 |
combined_netloc_authority_map = url_authority_map + url_netloc_map |
| 408 |
|
| 409 |
# We compose this list due to variances between parse_url |
| 410 |
# and urlparse when URIs don't provide a scheme. |
| 411 |
url_authority_with_schemes_map = [ |
| 412 |
u for u in combined_netloc_authority_map if u[0].startswith("http") |
| 413 |
] |
| 414 |
|
| 415 |
@pytest.mark.parametrize("url, expected_authority", combined_netloc_authority_map) |
| 416 |
def test_authority(self, url: str, expected_authority: str | None) -> None: |
| 417 |
assert parse_url(url).authority == expected_authority |
| 418 |
|
| 419 |
@pytest.mark.parametrize("url, expected_authority", url_authority_with_schemes_map) |
| 420 |
def test_authority_matches_urllib_netloc( |
| 421 |
self, url: str, expected_authority: str | None |
| 422 |
) -> None: |
| 423 |
"""Validate this matches the behavior of urlparse().netloc""" |
| 424 |
assert urlparse(url).netloc == expected_authority |
| 425 |
|
| 426 |
@pytest.mark.parametrize("url, expected_netloc", url_netloc_map) |
| 427 |
def test_netloc(self, url: str, expected_netloc: str | None) -> None: |
| 428 |
assert parse_url(url).netloc == expected_netloc |
| 429 |
|
| 430 |
url_vulnerabilities = [ |
| 431 |
# urlparse doesn't follow RFC 3986 Section 3.2 |
| 432 |
( |
| 433 |
"http://google.com#@evil.com/", |
| 434 |
Url("http", host="google.com", path="", fragment="@evil.com/"), |
| 435 |
), |
| 436 |
# CVE-2016-5699 |
| 437 |
( |
| 438 |
"http://127.0.0.1%0d%0aConnection%3a%20keep-alive", |
| 439 |
Url("http", host="127.0.0.1%0d%0aconnection%3a%20keep-alive"), |
| 440 |
), |
| 441 |
# NodeJS unicode -> double dot |
| 442 |
( |
| 443 |
"http://google.com/\uff2e\uff2e/abc", |
| 444 |
Url("http", host="google.com", path="/%EF%BC%AE%EF%BC%AE/abc"), |
| 445 |
), |
| 446 |
# Scheme without :// |
| 447 |
( |
| 448 |
"javascript:a='@google.com:12345/';alert(0)", |
| 449 |
Url(scheme="javascript", path="a='@google.com:12345/';alert(0)"), |
| 450 |
), |
| 451 |
("//google.com/a/b/c", Url(host="google.com", path="/a/b/c")), |
| 452 |
# International URLs |
| 453 |
( |
| 454 |
"http://ヒ:キ@ヒ.abc.ニ/ヒ?キ#ワ", |
| 455 |
Url( |
| 456 |
"http", |
| 457 |
host="xn--pdk.abc.xn--idk", |
| 458 |
auth="%E3%83%92:%E3%82%AD", |
| 459 |
path="/%E3%83%92", |
| 460 |
query="%E3%82%AD", |
| 461 |
fragment="%E3%83%AF", |
| 462 |
), |
| 463 |
), |
| 464 |
# Injected headers (CVE-2016-5699, CVE-2019-9740, CVE-2019-9947) |
| 465 |
( |
| 466 |
"10.251.0.83:7777?a=1 HTTP/1.1\r\nX-injected: header", |
| 467 |
Url( |
| 468 |
host="10.251.0.83", |
| 469 |
port=7777, |
| 470 |
path="", |
| 471 |
query="a=1%20HTTP/1.1%0D%0AX-injected:%20header", |
| 472 |
), |
| 473 |
), |
| 474 |
( |
| 475 |
"http://127.0.0.1:6379?\r\nSET test failure12\r\n:8080/test/?test=a", |
| 476 |
Url( |
| 477 |
scheme="http", |
| 478 |
host="127.0.0.1", |
| 479 |
port=6379, |
| 480 |
path="", |
| 481 |
query="%0D%0ASET%20test%20failure12%0D%0A:8080/test/?test=a", |
| 482 |
), |
| 483 |
), |
| 484 |
# See https://bugs.xdavidhu.me/google/2020/03/08/the-unexpected-google-wide-domain-check-bypass/ |
| 485 |
( |
| 486 |
"https://user:[email protected]\\test.corp.google.com:8080/path/to/something?param=value#hash", |
| 487 |
Url( |
| 488 |
scheme="https", |
| 489 |
auth="user:pass", |
| 490 |
host="xdavidhu.me", |
| 491 |
path="/%5Ctest.corp.google.com:8080/path/to/something", |
| 492 |
query="param=value", |
| 493 |
fragment="hash", |
| 494 |
), |
| 495 |
), |
| 496 |
# Tons of '@' causing backtracking |
| 497 |
pytest.param( |
| 498 |
"https://" + ("@" * 10000) + "[", |
| 499 |
False, |
| 500 |
id="Tons of '@' causing backtracking 1", |
| 501 |
), |
| 502 |
pytest.param( |
| 503 |
"https://user:" + ("@" * 10000) + "example.com", |
| 504 |
Url( |
| 505 |
scheme="https", |
| 506 |
auth="user:" + ("%40" * 9999), |
| 507 |
host="example.com", |
| 508 |
), |
| 509 |
id="Tons of '@' causing backtracking 2", |
| 510 |
), |
| 511 |
] |
| 512 |
|
| 513 |
@pytest.mark.parametrize("url, expected_url", url_vulnerabilities) |
| 514 |
def test_url_vulnerabilities( |
| 515 |
self, url: str, expected_url: typing.Literal[False] | Url |
| 516 |
) -> None: |
| 517 |
if expected_url is False: |
| 518 |
with pytest.raises(LocationParseError): |
| 519 |
parse_url(url) |
| 520 |
else: |
| 521 |
assert parse_url(url) == expected_url |
| 522 |
|
| 523 |
def test_parse_url_bytes_type_error(self) -> None: |
| 524 |
with pytest.raises(TypeError): |
| 525 |
parse_url(b"https://www.google.com/") # type: ignore[arg-type] |
| 526 |
|
| 527 |
@pytest.mark.parametrize( |
| 528 |
"kwargs, expected", |
| 529 |
[ |
| 530 |
pytest.param( |
| 531 |
{"accept_encoding": True}, |
| 532 |
{"accept-encoding": "gzip,deflate,br,zstd"}, |
| 533 |
marks=[onlyBrotli(), onlyZstd()], # type: ignore[list-item] |
| 534 |
), |
| 535 |
pytest.param( |
| 536 |
{"accept_encoding": True}, |
| 537 |
{"accept-encoding": "gzip,deflate,br"}, |
| 538 |
marks=[onlyBrotli(), notZstd()], # type: ignore[list-item] |
| 539 |
), |
| 540 |
pytest.param( |
| 541 |
{"accept_encoding": True}, |
| 542 |
{"accept-encoding": "gzip,deflate,zstd"}, |
| 543 |
marks=[notBrotli(), onlyZstd()], # type: ignore[list-item] |
| 544 |
), |
| 545 |
pytest.param( |
| 546 |
{"accept_encoding": True}, |
| 547 |
{"accept-encoding": "gzip,deflate"}, |
| 548 |
marks=[notBrotli(), notZstd()], # type: ignore[list-item] |
| 549 |
), |
| 550 |
({"accept_encoding": "foo,bar"}, {"accept-encoding": "foo,bar"}), |
| 551 |
({"accept_encoding": ["foo", "bar"]}, {"accept-encoding": "foo,bar"}), |
| 552 |
pytest.param( |
| 553 |
{"accept_encoding": True, "user_agent": "banana"}, |
| 554 |
{"accept-encoding": "gzip,deflate,br,zstd", "user-agent": "banana"}, |
| 555 |
marks=[onlyBrotli(), onlyZstd()], # type: ignore[list-item] |
| 556 |
), |
| 557 |
pytest.param( |
| 558 |
{"accept_encoding": True, "user_agent": "banana"}, |
| 559 |
{"accept-encoding": "gzip,deflate,br", "user-agent": "banana"}, |
| 560 |
marks=[onlyBrotli(), notZstd()], # type: ignore[list-item] |
| 561 |
), |
| 562 |
pytest.param( |
| 563 |
{"accept_encoding": True, "user_agent": "banana"}, |
| 564 |
{"accept-encoding": "gzip,deflate,zstd", "user-agent": "banana"}, |
| 565 |
marks=[notBrotli(), onlyZstd()], # type: ignore[list-item] |
| 566 |
), |
| 567 |
pytest.param( |
| 568 |
{"accept_encoding": True, "user_agent": "banana"}, |
| 569 |
{"accept-encoding": "gzip,deflate", "user-agent": "banana"}, |
| 570 |
marks=[notBrotli(), notZstd()], # type: ignore[list-item] |
| 571 |
), |
| 572 |
({"user_agent": "banana"}, {"user-agent": "banana"}), |
| 573 |
({"keep_alive": True}, {"connection": "keep-alive"}), |
| 574 |
({"basic_auth": "foo:bar"}, {"authorization": "Basic Zm9vOmJhcg=="}), |
| 575 |
( |
| 576 |
{"proxy_basic_auth": "foo:bar"}, |
| 577 |
{"proxy-authorization": "Basic Zm9vOmJhcg=="}, |
| 578 |
), |
| 579 |
({"disable_cache": True}, {"cache-control": "no-cache"}), |
| 580 |
], |
| 581 |
) |
| 582 |
def test_make_headers( |
| 583 |
self, kwargs: dict[str, bool | str], expected: dict[str, str] |
| 584 |
) -> None: |
| 585 |
assert make_headers(**kwargs) == expected # type: ignore[arg-type] |
| 586 |
|
| 587 |
def test_rewind_body(self) -> None: |
| 588 |
body = io.BytesIO(b"test data") |
| 589 |
assert body.read() == b"test data" |
| 590 |
|
| 591 |
# Assert the file object has been consumed |
| 592 |
assert body.read() == b"" |
| 593 |
|
| 594 |
# Rewind it back to just be b'data' |
| 595 |
rewind_body(body, 5) |
| 596 |
assert body.read() == b"data" |
| 597 |
|
| 598 |
def test_rewind_body_failed_tell(self) -> None: |
| 599 |
body = io.BytesIO(b"test data") |
| 600 |
body.read() # Consume body |
| 601 |
|
| 602 |
# Simulate failed tell() |
| 603 |
body_pos = _FAILEDTELL |
| 604 |
with pytest.raises(UnrewindableBodyError): |
| 605 |
rewind_body(body, body_pos) |
| 606 |
|
| 607 |
def test_rewind_body_bad_position(self) -> None: |
| 608 |
body = io.BytesIO(b"test data") |
| 609 |
body.read() # Consume body |
| 610 |
|
| 611 |
# Pass non-integer position |
| 612 |
with pytest.raises(ValueError): |
| 613 |
rewind_body(body, body_pos=None) # type: ignore[arg-type] |
| 614 |
with pytest.raises(ValueError): |
| 615 |
rewind_body(body, body_pos=object()) # type: ignore[arg-type] |
| 616 |
|
| 617 |
def test_rewind_body_failed_seek(self) -> None: |
| 618 |
class BadSeek(io.StringIO): |
| 619 |
def seek(self, offset: int, whence: int = 0) -> typing.NoReturn: |
| 620 |
raise OSError |
| 621 |
|
| 622 |
with pytest.raises(UnrewindableBodyError): |
| 623 |
rewind_body(BadSeek(), body_pos=2) |
| 624 |
|
| 625 |
def test_add_stderr_logger(self) -> None: |
| 626 |
handler = add_stderr_logger(level=logging.INFO) # Don't actually print debug |
| 627 |
logger = logging.getLogger("urllib3") |
| 628 |
assert handler in logger.handlers |
| 629 |
|
| 630 |
logger.debug("Testing add_stderr_logger") |
| 631 |
logger.removeHandler(handler) |
| 632 |
|
| 633 |
def test_disable_warnings(self) -> None: |
| 634 |
with warnings.catch_warnings(record=True) as w: |
| 635 |
clear_warnings() |
| 636 |
warnings.simplefilter("default", InsecureRequestWarning) |
| 637 |
warnings.warn("This is a test.", InsecureRequestWarning) |
| 638 |
assert len(w) == 1 |
| 639 |
disable_warnings() |
| 640 |
warnings.warn("This is a test.", InsecureRequestWarning) |
| 641 |
assert len(w) == 1 |
| 642 |
|
| 643 |
def _make_time_pass( |
| 644 |
self, seconds: int, timeout: Timeout, time_mock: Mock |
| 645 |
) -> Timeout: |
| 646 |
"""Make some time pass for the timeout object""" |
| 647 |
time_mock.return_value = TIMEOUT_EPOCH |
| 648 |
timeout.start_connect() |
| 649 |
time_mock.return_value = TIMEOUT_EPOCH + seconds |
| 650 |
return timeout |
| 651 |
|
| 652 |
@pytest.mark.parametrize( |
| 653 |
"kwargs, message", |
| 654 |
[ |
| 655 |
({"total": -1}, "less than"), |
| 656 |
({"connect": 2, "total": -1}, "less than"), |
| 657 |
({"read": -1}, "less than"), |
| 658 |
({"connect": False}, "cannot be a boolean"), |
| 659 |
({"read": True}, "cannot be a boolean"), |
| 660 |
({"connect": 0}, "less than or equal"), |
| 661 |
({"read": "foo"}, "int, float or None"), |
| 662 |
({"read": "1.0"}, "int, float or None"), |
| 663 |
], |
| 664 |
) |
| 665 |
def test_invalid_timeouts( |
| 666 |
self, kwargs: dict[str, int | bool], message: str |
| 667 |
) -> None: |
| 668 |
with pytest.raises(ValueError, match=message): |
| 669 |
Timeout(**kwargs) |
| 670 |
|
| 671 |
@patch("time.monotonic") |
| 672 |
def test_timeout(self, time_monotonic: MagicMock) -> None: |
| 673 |
timeout = Timeout(total=3) |
| 674 |
|
| 675 |
# make 'no time' elapse |
| 676 |
timeout = self._make_time_pass( |
| 677 |
seconds=0, timeout=timeout, time_mock=time_monotonic |
| 678 |
) |
| 679 |
assert timeout.read_timeout == 3 |
| 680 |
assert timeout.connect_timeout == 3 |
| 681 |
|
| 682 |
timeout = Timeout(total=3, connect=2) |
| 683 |
assert timeout.connect_timeout == 2 |
| 684 |
|
| 685 |
timeout = Timeout() |
| 686 |
assert timeout.connect_timeout == _DEFAULT_TIMEOUT |
| 687 |
|
| 688 |
# Connect takes 5 seconds, leaving 5 seconds for read |
| 689 |
timeout = Timeout(total=10, read=7) |
| 690 |
timeout = self._make_time_pass( |
| 691 |
seconds=5, timeout=timeout, time_mock=time_monotonic |
| 692 |
) |
| 693 |
assert timeout.read_timeout == 5 |
| 694 |
|
| 695 |
# Connect takes 2 seconds, read timeout still 7 seconds |
| 696 |
timeout = Timeout(total=10, read=7) |
| 697 |
timeout = self._make_time_pass( |
| 698 |
seconds=2, timeout=timeout, time_mock=time_monotonic |
| 699 |
) |
| 700 |
assert timeout.read_timeout == 7 |
| 701 |
|
| 702 |
timeout = Timeout(total=10, read=7) |
| 703 |
assert timeout.read_timeout == 7 |
| 704 |
|
| 705 |
timeout = Timeout(total=None, read=None, connect=None) |
| 706 |
assert timeout.connect_timeout is None |
| 707 |
assert timeout.read_timeout is None |
| 708 |
assert timeout.total is None |
| 709 |
|
| 710 |
timeout = Timeout(5) |
| 711 |
assert timeout.total == 5 |
| 712 |
|
| 713 |
def test_timeout_default_resolve(self) -> None: |
| 714 |
"""The timeout default is resolved when read_timeout is accessed.""" |
| 715 |
timeout = Timeout() |
| 716 |
with patch("urllib3.util.timeout.getdefaulttimeout", return_value=2): |
| 717 |
assert timeout.read_timeout == 2 |
| 718 |
|
| 719 |
with patch("urllib3.util.timeout.getdefaulttimeout", return_value=3): |
| 720 |
assert timeout.read_timeout == 3 |
| 721 |
|
| 722 |
def test_timeout_str(self) -> None: |
| 723 |
timeout = Timeout(connect=1, read=2, total=3) |
| 724 |
assert str(timeout) == "Timeout(connect=1, read=2, total=3)" |
| 725 |
timeout = Timeout(connect=1, read=None, total=3) |
| 726 |
assert str(timeout) == "Timeout(connect=1, read=None, total=3)" |
| 727 |
|
| 728 |
@patch("time.monotonic") |
| 729 |
def test_timeout_elapsed(self, time_monotonic: MagicMock) -> None: |
| 730 |
time_monotonic.return_value = TIMEOUT_EPOCH |
| 731 |
timeout = Timeout(total=3) |
| 732 |
with pytest.raises(TimeoutStateError): |
| 733 |
timeout.get_connect_duration() |
| 734 |
|
| 735 |
timeout.start_connect() |
| 736 |
with pytest.raises(TimeoutStateError): |
| 737 |
timeout.start_connect() |
| 738 |
|
| 739 |
time_monotonic.return_value = TIMEOUT_EPOCH + 2 |
| 740 |
assert timeout.get_connect_duration() == 2 |
| 741 |
time_monotonic.return_value = TIMEOUT_EPOCH + 37 |
| 742 |
assert timeout.get_connect_duration() == 37 |
| 743 |
|
| 744 |
def test_is_fp_closed_object_supports_closed(self) -> None: |
| 745 |
class ClosedFile: |
| 746 |
@property |
| 747 |
def closed(self) -> typing.Literal[True]: |
| 748 |
return True |
| 749 |
|
| 750 |
assert is_fp_closed(ClosedFile()) |
| 751 |
|
| 752 |
def test_is_fp_closed_object_has_none_fp(self) -> None: |
| 753 |
class NoneFpFile: |
| 754 |
@property |
| 755 |
def fp(self) -> None: |
| 756 |
return None |
| 757 |
|
| 758 |
assert is_fp_closed(NoneFpFile()) |
| 759 |
|
| 760 |
def test_is_fp_closed_object_has_fp(self) -> None: |
| 761 |
class FpFile: |
| 762 |
@property |
| 763 |
def fp(self) -> typing.Literal[True]: |
| 764 |
return True |
| 765 |
|
| 766 |
assert not is_fp_closed(FpFile()) |
| 767 |
|
| 768 |
def test_is_fp_closed_object_has_neither_fp_nor_closed(self) -> None: |
| 769 |
class NotReallyAFile: |
| 770 |
pass |
| 771 |
|
| 772 |
with pytest.raises(ValueError): |
| 773 |
is_fp_closed(NotReallyAFile()) |
| 774 |
|
| 775 |
def test_has_ipv6_disabled_on_compile(self) -> None: |
| 776 |
with patch("socket.has_ipv6", False): |
| 777 |
assert not _has_ipv6("::1") |
| 778 |
|
| 779 |
def test_has_ipv6_enabled_but_fails(self) -> None: |
| 780 |
with patch("socket.has_ipv6", True): |
| 781 |
with patch("socket.socket") as mock: |
| 782 |
instance = mock.return_value |
| 783 |
instance.bind = Mock(side_effect=Exception("No IPv6 here!")) |
| 784 |
assert not _has_ipv6("::1") |
| 785 |
|
| 786 |
def test_has_ipv6_enabled_and_working(self) -> None: |
| 787 |
with patch("socket.has_ipv6", True): |
| 788 |
with patch("socket.socket") as mock: |
| 789 |
instance = mock.return_value |
| 790 |
instance.bind.return_value = True |
| 791 |
assert _has_ipv6("::1") |
| 792 |
|
| 793 |
def test_ip_family_ipv6_enabled(self) -> None: |
| 794 |
with patch("urllib3.util.connection.HAS_IPV6", True): |
| 795 |
assert allowed_gai_family() == socket.AF_UNSPEC |
| 796 |
|
| 797 |
def test_ip_family_ipv6_disabled(self) -> None: |
| 798 |
with patch("urllib3.util.connection.HAS_IPV6", False): |
| 799 |
assert allowed_gai_family() == socket.AF_INET |
| 800 |
|
| 801 |
@pytest.mark.parametrize("headers", [b"foo", None, object]) |
| 802 |
def test_assert_header_parsing_throws_typeerror_with_non_headers( |
| 803 |
self, headers: bytes | object | None |
| 804 |
) -> None: |
| 805 |
with pytest.raises(TypeError): |
| 806 |
assert_header_parsing(headers) # type: ignore[arg-type] |
| 807 |
|
| 808 |
def test_connection_requires_http_tunnel_no_proxy(self) -> None: |
| 809 |
assert not connection_requires_http_tunnel( |
| 810 |
proxy_url=None, proxy_config=None, destination_scheme=None |
| 811 |
) |
| 812 |
|
| 813 |
def test_connection_requires_http_tunnel_http_proxy(self) -> None: |
| 814 |
proxy = parse_url("http://proxy:8080") |
| 815 |
proxy_config = ProxyConfig( |
| 816 |
ssl_context=None, |
| 817 |
use_forwarding_for_https=False, |
| 818 |
assert_hostname=None, |
| 819 |
assert_fingerprint=None, |
| 820 |
) |
| 821 |
destination_scheme = "http" |
| 822 |
assert not connection_requires_http_tunnel( |
| 823 |
proxy, proxy_config, destination_scheme |
| 824 |
) |
| 825 |
|
| 826 |
destination_scheme = "https" |
| 827 |
assert connection_requires_http_tunnel(proxy, proxy_config, destination_scheme) |
| 828 |
|
| 829 |
def test_connection_requires_http_tunnel_https_proxy(self) -> None: |
| 830 |
proxy = parse_url("https://proxy:8443") |
| 831 |
proxy_config = ProxyConfig( |
| 832 |
ssl_context=None, |
| 833 |
use_forwarding_for_https=False, |
| 834 |
assert_hostname=None, |
| 835 |
assert_fingerprint=None, |
| 836 |
) |
| 837 |
destination_scheme = "http" |
| 838 |
assert not connection_requires_http_tunnel( |
| 839 |
proxy, proxy_config, destination_scheme |
| 840 |
) |
| 841 |
|
| 842 |
def test_assert_header_parsing_no_error_on_multipart(self) -> None: |
| 843 |
from http import client |
| 844 |
|
| 845 |
header_msg = io.BytesIO() |
| 846 |
header_msg.write( |
| 847 |
b'Content-Type: multipart/encrypted;protocol="application/' |
| 848 |
b'HTTP-SPNEGO-session-encrypted";boundary="Encrypted Boundary"' |
| 849 |
b"\nServer: Microsoft-HTTPAPI/2.0\nDate: Fri, 16 Aug 2019 19:28:01 GMT" |
| 850 |
b"\nContent-Length: 1895\n\n\n" |
| 851 |
) |
| 852 |
header_msg.seek(0) |
| 853 |
assert_header_parsing(client.parse_headers(header_msg)) |
| 854 |
|
| 855 |
@pytest.mark.parametrize("host", [".localhost", "...", "t" * 64]) |
| 856 |
def test_create_connection_with_invalid_idna_labels(self, host: str) -> None: |
| 857 |
with pytest.raises( |
| 858 |
LocationParseError, |
| 859 |
match=f"Failed to parse: '{host}', label empty or too long", |
| 860 |
): |
| 861 |
create_connection((host, 80)) |
| 862 |
|
| 863 |
@pytest.mark.parametrize( |
| 864 |
"host", |
| 865 |
[ |
| 866 |
"a.example.com", |
| 867 |
"localhost.", |
| 868 |
"[dead::beef]", |
| 869 |
"[dead::beef%en5]", |
| 870 |
"[dead::beef%en5.]", |
| 871 |
], |
| 872 |
) |
| 873 |
@patch("socket.getaddrinfo") |
| 874 |
@patch("socket.socket") |
| 875 |
def test_create_connection_with_valid_idna_labels( |
| 876 |
self, socket: MagicMock, getaddrinfo: MagicMock, host: str |
| 877 |
) -> None: |
| 878 |
getaddrinfo.return_value = [(None, None, None, None, None)] |
| 879 |
socket.return_value = Mock() |
| 880 |
create_connection((host, 80)) |
| 881 |
|
| 882 |
@patch("socket.getaddrinfo") |
| 883 |
def test_create_connection_error(self, getaddrinfo: MagicMock) -> None: |
| 884 |
getaddrinfo.return_value = [] |
| 885 |
with pytest.raises(OSError, match="getaddrinfo returns an empty list"): |
| 886 |
create_connection(("example.com", 80)) |
| 887 |
|
| 888 |
@patch("socket.getaddrinfo") |
| 889 |
def test_dnsresolver_forced_error(self, getaddrinfo: MagicMock) -> None: |
| 890 |
getaddrinfo.side_effect = socket.gaierror() |
| 891 |
with pytest.raises(socket.gaierror): |
| 892 |
# dns is valid but we force the error just for the sake of the test |
| 893 |
create_connection(("example.com", 80)) |
| 894 |
|
| 895 |
def test_dnsresolver_expected_error(self) -> None: |
| 896 |
with pytest.raises(socket.gaierror): |
| 897 |
# windows: [Errno 11001] getaddrinfo failed in windows |
| 898 |
# linux: [Errno -2] Name or service not known |
| 899 |
# macos: [Errno 8] nodename nor servname provided, or not known |
| 900 |
create_connection(("badhost.invalid", 80)) |
| 901 |
|
| 902 |
@patch("socket.getaddrinfo") |
| 903 |
@patch("socket.socket") |
| 904 |
def test_create_connection_with_scoped_ipv6( |
| 905 |
self, socket: MagicMock, getaddrinfo: MagicMock |
| 906 |
) -> None: |
| 907 |
# Check that providing create_connection with a scoped IPv6 address |
| 908 |
# properly propagates the scope to getaddrinfo, and that the returned |
| 909 |
# scoped ID makes it to the socket creation call. |
| 910 |
fake_scoped_sa6 = ("a::b", 80, 0, 42) |
| 911 |
getaddrinfo.return_value = [ |
| 912 |
( |
| 913 |
socket.AF_INET6, |
| 914 |
socket.SOCK_STREAM, |
| 915 |
socket.IPPROTO_TCP, |
| 916 |
"", |
| 917 |
fake_scoped_sa6, |
| 918 |
) |
| 919 |
] |
| 920 |
socket.return_value = fake_sock = MagicMock() |
| 921 |
|
| 922 |
create_connection(("a::b%iface", 80)) |
| 923 |
assert getaddrinfo.call_args[0][0] == "a::b%iface" |
| 924 |
fake_sock.connect.assert_called_once_with(fake_scoped_sa6) |
| 925 |
|
| 926 |
@pytest.mark.parametrize( |
| 927 |
"input,params,expected", |
| 928 |
( |
| 929 |
("test", {}, "test"), # str input |
| 930 |
(b"test", {}, "test"), # bytes input |
| 931 |
(b"test", {"encoding": "utf-8"}, "test"), # bytes input with utf-8 |
| 932 |
(b"test", {"encoding": "ascii"}, "test"), # bytes input with ascii |
| 933 |
), |
| 934 |
) |
| 935 |
def test_to_str( |
| 936 |
self, input: bytes | str, params: dict[str, str], expected: str |
| 937 |
) -> None: |
| 938 |
assert to_str(input, **params) == expected |
| 939 |
|
| 940 |
def test_to_str_error(self) -> None: |
| 941 |
with pytest.raises(TypeError, match="not expecting type int"): |
| 942 |
to_str(1) # type: ignore[arg-type] |
| 943 |
|
| 944 |
@pytest.mark.parametrize( |
| 945 |
"input,params,expected", |
| 946 |
( |
| 947 |
(b"test", {}, b"test"), # str input |
| 948 |
("test", {}, b"test"), # bytes input |
| 949 |
("é", {}, b"\xc3\xa9"), # bytes input |
| 950 |
("test", {"encoding": "utf-8"}, b"test"), # bytes input with utf-8 |
| 951 |
("test", {"encoding": "ascii"}, b"test"), # bytes input with ascii |
| 952 |
), |
| 953 |
) |
| 954 |
def test_to_bytes( |
| 955 |
self, input: bytes | str, params: dict[str, str], expected: bytes |
| 956 |
) -> None: |
| 957 |
assert to_bytes(input, **params) == expected |
| 958 |
|
| 959 |
def test_to_bytes_error(self) -> None: |
| 960 |
with pytest.raises(TypeError, match="not expecting type int"): |
| 961 |
to_bytes(1) # type: ignore[arg-type] |
| 962 |
|
| 963 |
|
| 964 |
class TestUtilSSL: |
| 965 |
"""Test utils that use an SSL backend.""" |
| 966 |
|
| 967 |
@pytest.mark.parametrize( |
| 968 |
"candidate, requirements", |
| 969 |
[ |
| 970 |
(None, ssl.CERT_REQUIRED), |
| 971 |
(ssl.CERT_NONE, ssl.CERT_NONE), |
| 972 |
(ssl.CERT_REQUIRED, ssl.CERT_REQUIRED), |
| 973 |
("REQUIRED", ssl.CERT_REQUIRED), |
| 974 |
("CERT_REQUIRED", ssl.CERT_REQUIRED), |
| 975 |
], |
| 976 |
) |
| 977 |
def test_resolve_cert_reqs( |
| 978 |
self, candidate: int | str | None, requirements: int |
| 979 |
) -> None: |
| 980 |
assert resolve_cert_reqs(candidate) == requirements |
| 981 |
|
| 982 |
@pytest.mark.parametrize( |
| 983 |
"candidate, version", |
| 984 |
[ |
| 985 |
(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLSv1), |
| 986 |
("PROTOCOL_TLSv1", ssl.PROTOCOL_TLSv1), |
| 987 |
("TLSv1", ssl.PROTOCOL_TLSv1), |
| 988 |
(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv23), |
| 989 |
], |
| 990 |
) |
| 991 |
def test_resolve_ssl_version(self, candidate: int | str, version: int) -> None: |
| 992 |
assert resolve_ssl_version(candidate) == version |
| 993 |
|
| 994 |
def test_ssl_wrap_socket_loads_the_cert_chain(self) -> None: |
| 995 |
socket = Mock() |
| 996 |
mock_context = Mock() |
| 997 |
ssl_wrap_socket( |
| 998 |
ssl_context=mock_context, sock=socket, certfile="/path/to/certfile" |
| 999 |
) |
| 1000 |
|
| 1001 |
mock_context.load_cert_chain.assert_called_once_with("/path/to/certfile", None) |
| 1002 |
|
| 1003 |
@patch("urllib3.util.ssl_.create_urllib3_context") |
| 1004 |
def test_ssl_wrap_socket_creates_new_context( |
| 1005 |
self, create_urllib3_context: mock.MagicMock |
| 1006 |
) -> None: |
| 1007 |
socket = Mock() |
| 1008 |
ssl_wrap_socket(socket, cert_reqs=ssl.CERT_REQUIRED) |
| 1009 |
|
| 1010 |
create_urllib3_context.assert_called_once_with(None, 2, ciphers=None) |
| 1011 |
|
| 1012 |
def test_ssl_wrap_socket_loads_verify_locations(self) -> None: |
| 1013 |
socket = Mock() |
| 1014 |
mock_context = Mock() |
| 1015 |
ssl_wrap_socket(ssl_context=mock_context, ca_certs="/path/to/pem", sock=socket) |
| 1016 |
mock_context.load_verify_locations.assert_called_once_with( |
| 1017 |
"/path/to/pem", None, None |
| 1018 |
) |
| 1019 |
|
| 1020 |
def test_ssl_wrap_socket_loads_certificate_directories(self) -> None: |
| 1021 |
socket = Mock() |
| 1022 |
mock_context = Mock() |
| 1023 |
ssl_wrap_socket( |
| 1024 |
ssl_context=mock_context, ca_cert_dir="/path/to/pems", sock=socket |
| 1025 |
) |
| 1026 |
mock_context.load_verify_locations.assert_called_once_with( |
| 1027 |
None, "/path/to/pems", None |
| 1028 |
) |
| 1029 |
|
| 1030 |
def test_ssl_wrap_socket_loads_certificate_data(self) -> None: |
| 1031 |
socket = Mock() |
| 1032 |
mock_context = Mock() |
| 1033 |
ssl_wrap_socket( |
| 1034 |
ssl_context=mock_context, ca_cert_data="TOTALLY PEM DATA", sock=socket |
| 1035 |
) |
| 1036 |
mock_context.load_verify_locations.assert_called_once_with( |
| 1037 |
None, None, "TOTALLY PEM DATA" |
| 1038 |
) |
| 1039 |
|
| 1040 |
def _wrap_socket_and_mock_warn( |
| 1041 |
self, sock: socket.socket, server_hostname: str | None |
| 1042 |
) -> tuple[Mock, MagicMock]: |
| 1043 |
mock_context = Mock() |
| 1044 |
with patch("warnings.warn") as warn: |
| 1045 |
ssl_wrap_socket( |
| 1046 |
ssl_context=mock_context, |
| 1047 |
sock=sock, |
| 1048 |
server_hostname=server_hostname, |
| 1049 |
) |
| 1050 |
return mock_context, warn |
| 1051 |
|
| 1052 |
def test_ssl_wrap_socket_sni_ip_address_no_warn(self) -> None: |
| 1053 |
"""Test that a warning is not made if server_hostname is an IP address.""" |
| 1054 |
sock = Mock() |
| 1055 |
context, warn = self._wrap_socket_and_mock_warn(sock, "8.8.8.8") |
| 1056 |
context.wrap_socket.assert_called_once_with(sock, server_hostname="8.8.8.8") |
| 1057 |
warn.assert_not_called() |
| 1058 |
|
| 1059 |
def test_ssl_wrap_socket_sni_none_no_warn(self) -> None: |
| 1060 |
"""Test that a warning is not made if server_hostname is not given.""" |
| 1061 |
sock = Mock() |
| 1062 |
context, warn = self._wrap_socket_and_mock_warn(sock, None) |
| 1063 |
context.wrap_socket.assert_called_once_with(sock, server_hostname=None) |
| 1064 |
warn.assert_not_called() |
| 1065 |
|
| 1066 |
@pytest.mark.parametrize( |
| 1067 |
"openssl_version, reliable", |
| 1068 |
[ |
| 1069 |
# any OpenSSL 1.1.1+ -> reliable since Python 3.10.0b1 according to |
| 1070 |
# https://github.com/python/cpython/issues/87688#issuecomment-1093906646 |
| 1071 |
("OpenSSL 1.1.1", True), |
| 1072 |
# not OpenSSSL -> unreliable |
| 1073 |
("LibreSSL 2.8.3", False), |
| 1074 |
], |
| 1075 |
) |
| 1076 |
def test_is_has_never_check_common_name_reliable( |
| 1077 |
self, |
| 1078 |
openssl_version: str, |
| 1079 |
reliable: bool, |
| 1080 |
) -> None: |
| 1081 |
assert ( |
| 1082 |
_is_has_never_check_common_name_reliable( |
| 1083 |
openssl_version, |
| 1084 |
) |
| 1085 |
== reliable |
| 1086 |
) |
| 1087 |
|
| 1088 |
|
| 1089 |
idna_blocker = ImportBlocker("idna") |
| 1090 |
module_stash = ModuleStash("urllib3") |
| 1091 |
|
| 1092 |
|
| 1093 |
class TestUtilWithoutIdna: |
| 1094 |
@classmethod |
| 1095 |
def setup_class(cls) -> None: |
| 1096 |
sys.modules.pop("idna", None) |
| 1097 |
|
| 1098 |
module_stash.stash() |
| 1099 |
sys.meta_path.insert(0, idna_blocker) |
| 1100 |
|
| 1101 |
@classmethod |
| 1102 |
def teardown_class(cls) -> None: |
| 1103 |
sys.meta_path.remove(idna_blocker) |
| 1104 |
module_stash.pop() |
| 1105 |
|
| 1106 |
def test_parse_url_without_idna(self) -> None: |
| 1107 |
url = "http://\ud7ff.com" |
| 1108 |
with pytest.raises(LocationParseError, match=f"Failed to parse: {url}"): |
| 1109 |
parse_url(url) |