| 1 |
# TODO: Break this module up into pieces. Maybe group by functionality tested |
| 2 |
# rather than the socket level-ness of it. |
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
import contextlib |
| 6 |
import errno |
| 7 |
import http.client |
| 8 |
import io |
| 9 |
import os |
| 10 |
import os.path |
| 11 |
import select |
| 12 |
import shutil |
| 13 |
import socket |
| 14 |
import ssl |
| 15 |
import tempfile |
| 16 |
import threading |
| 17 |
import time |
| 18 |
import typing |
| 19 |
import zlib |
| 20 |
from collections import OrderedDict |
| 21 |
from pathlib import Path |
| 22 |
from test import LONG_TIMEOUT, SHORT_TIMEOUT, notWindows, resolvesLocalhostFQDN |
| 23 |
from threading import Event |
| 24 |
from unittest import mock |
| 25 |
from urllib.parse import urlparse |
| 26 |
|
| 27 |
import pytest |
| 28 |
import trustme |
| 29 |
|
| 30 |
from dummyserver.socketserver import ( |
| 31 |
DEFAULT_CA, |
| 32 |
DEFAULT_CERTS, |
| 33 |
encrypt_key_pem, |
| 34 |
get_unreachable_address, |
| 35 |
) |
| 36 |
from dummyserver.testcase import SocketDummyServerTestCase, consume_socket |
| 37 |
from urllib3 import ( |
| 38 |
BaseHTTPResponse, |
| 39 |
HTTPConnectionPool, |
| 40 |
HTTPSConnectionPool, |
| 41 |
ProxyManager, |
| 42 |
util, |
| 43 |
) |
| 44 |
from urllib3._collections import HTTPHeaderDict |
| 45 |
from urllib3.connection import HTTPConnection, _get_default_user_agent |
| 46 |
from urllib3.connectionpool import _url_from_pool |
| 47 |
from urllib3.exceptions import ( |
| 48 |
InsecureRequestWarning, |
| 49 |
MaxRetryError, |
| 50 |
ProtocolError, |
| 51 |
ProxyError, |
| 52 |
ReadTimeoutError, |
| 53 |
SSLError, |
| 54 |
) |
| 55 |
from urllib3.poolmanager import proxy_from_url |
| 56 |
from urllib3.util import ssl_, ssl_wrap_socket |
| 57 |
from urllib3.util.retry import Retry |
| 58 |
from urllib3.util.timeout import Timeout |
| 59 |
|
| 60 |
from .. import LogRecorder |
| 61 |
|
| 62 |
if typing.TYPE_CHECKING: |
| 63 |
from _typeshed import StrOrBytesPath |
| 64 |
else: |
| 65 |
StrOrBytesPath = object |
| 66 |
|
| 67 |
|
| 68 |
class TestCookies(SocketDummyServerTestCase): |
| 69 |
def test_multi_setcookie(self) -> None: |
| 70 |
def multicookie_response_handler(listener: socket.socket) -> None: |
| 71 |
sock = listener.accept()[0] |
| 72 |
|
| 73 |
buf = b"" |
| 74 |
while not buf.endswith(b"\r\n\r\n"): |
| 75 |
buf += sock.recv(65536) |
| 76 |
|
| 77 |
sock.send( |
| 78 |
b"HTTP/1.1 200 OK\r\n" |
| 79 |
b"Set-Cookie: foo=1\r\n" |
| 80 |
b"Set-Cookie: bar=1\r\n" |
| 81 |
b"\r\n" |
| 82 |
) |
| 83 |
sock.close() |
| 84 |
|
| 85 |
self._start_server(multicookie_response_handler) |
| 86 |
with HTTPConnectionPool(self.host, self.port) as pool: |
| 87 |
r = pool.request("GET", "/", retries=0) |
| 88 |
assert r.headers == {"set-cookie": "foo=1, bar=1"} |
| 89 |
assert r.headers.getlist("set-cookie") == ["foo=1", "bar=1"] |
| 90 |
|
| 91 |
|
| 92 |
class TestSNI(SocketDummyServerTestCase): |
| 93 |
def test_hostname_in_first_request_packet(self) -> None: |
| 94 |
done_receiving = Event() |
| 95 |
self.buf = b"" |
| 96 |
|
| 97 |
def socket_handler(listener: socket.socket) -> None: |
| 98 |
sock = listener.accept()[0] |
| 99 |
|
| 100 |
self.buf = sock.recv(65536) # We only accept one packet |
| 101 |
done_receiving.set() # let the test know it can proceed |
| 102 |
sock.close() |
| 103 |
|
| 104 |
self._start_server(socket_handler) |
| 105 |
with HTTPSConnectionPool(self.host, self.port) as pool: |
| 106 |
try: |
| 107 |
pool.request("GET", "/", retries=0) |
| 108 |
except MaxRetryError: # We are violating the protocol |
| 109 |
pass |
| 110 |
successful = done_receiving.wait(LONG_TIMEOUT) |
| 111 |
assert successful, "Timed out waiting for connection accept" |
| 112 |
assert ( |
| 113 |
self.host.encode("ascii") in self.buf |
| 114 |
), "missing hostname in SSL handshake" |
| 115 |
|
| 116 |
|
| 117 |
class TestALPN(SocketDummyServerTestCase): |
| 118 |
def test_alpn_protocol_in_first_request_packet(self) -> None: |
| 119 |
done_receiving = Event() |
| 120 |
self.buf = b"" |
| 121 |
|
| 122 |
def socket_handler(listener: socket.socket) -> None: |
| 123 |
sock = listener.accept()[0] |
| 124 |
|
| 125 |
self.buf = sock.recv(65536) # We only accept one packet |
| 126 |
done_receiving.set() # let the test know it can proceed |
| 127 |
sock.close() |
| 128 |
|
| 129 |
self._start_server(socket_handler) |
| 130 |
with HTTPSConnectionPool(self.host, self.port) as pool: |
| 131 |
try: |
| 132 |
pool.request("GET", "/", retries=0) |
| 133 |
except MaxRetryError: # We are violating the protocol |
| 134 |
pass |
| 135 |
successful = done_receiving.wait(LONG_TIMEOUT) |
| 136 |
assert successful, "Timed out waiting for connection accept" |
| 137 |
for protocol in util.ALPN_PROTOCOLS: |
| 138 |
assert ( |
| 139 |
protocol.encode("ascii") in self.buf |
| 140 |
), "missing ALPN protocol in SSL handshake" |
| 141 |
|
| 142 |
|
| 143 |
def original_ssl_wrap_socket( |
| 144 |
sock: socket.socket, |
| 145 |
keyfile: StrOrBytesPath | None = None, |
| 146 |
certfile: StrOrBytesPath | None = None, |
| 147 |
server_side: bool = False, |
| 148 |
cert_reqs: ssl.VerifyMode = ssl.CERT_NONE, |
| 149 |
ssl_version: int = ssl.PROTOCOL_TLS, |
| 150 |
ca_certs: str | None = None, |
| 151 |
do_handshake_on_connect: bool = True, |
| 152 |
suppress_ragged_eofs: bool = True, |
| 153 |
ciphers: str | None = None, |
| 154 |
) -> ssl.SSLSocket: |
| 155 |
if server_side and not certfile: |
| 156 |
raise ValueError("certfile must be specified for server-side operations") |
| 157 |
if keyfile and not certfile: |
| 158 |
raise ValueError("certfile must be specified") |
| 159 |
context = ssl.SSLContext(ssl_version) |
| 160 |
context.verify_mode = cert_reqs |
| 161 |
if ca_certs: |
| 162 |
context.load_verify_locations(ca_certs) |
| 163 |
if certfile: |
| 164 |
context.load_cert_chain(certfile, keyfile) |
| 165 |
if ciphers: |
| 166 |
context.set_ciphers(ciphers) |
| 167 |
return context.wrap_socket( |
| 168 |
sock=sock, |
| 169 |
server_side=server_side, |
| 170 |
do_handshake_on_connect=do_handshake_on_connect, |
| 171 |
suppress_ragged_eofs=suppress_ragged_eofs, |
| 172 |
) |
| 173 |
|
| 174 |
|
| 175 |
class TestClientCerts(SocketDummyServerTestCase): |
| 176 |
""" |
| 177 |
Tests for client certificate support. |
| 178 |
""" |
| 179 |
|
| 180 |
@classmethod |
| 181 |
def setup_class(cls) -> None: |
| 182 |
cls.tmpdir = tempfile.mkdtemp() |
| 183 |
ca = trustme.CA() |
| 184 |
cert = ca.issue_cert("localhost") |
| 185 |
encrypted_key = encrypt_key_pem(cert.private_key_pem, b"letmein") |
| 186 |
|
| 187 |
cls.ca_path = os.path.join(cls.tmpdir, "ca.pem") |
| 188 |
cls.cert_combined_path = os.path.join(cls.tmpdir, "server.combined.pem") |
| 189 |
cls.cert_path = os.path.join(cls.tmpdir, "server.pem") |
| 190 |
cls.key_path = os.path.join(cls.tmpdir, "key.pem") |
| 191 |
cls.password_key_path = os.path.join(cls.tmpdir, "password_key.pem") |
| 192 |
|
| 193 |
ca.cert_pem.write_to_path(cls.ca_path) |
| 194 |
cert.private_key_and_cert_chain_pem.write_to_path(cls.cert_combined_path) |
| 195 |
cert.cert_chain_pems[0].write_to_path(cls.cert_path) |
| 196 |
cert.private_key_pem.write_to_path(cls.key_path) |
| 197 |
encrypted_key.write_to_path(cls.password_key_path) |
| 198 |
|
| 199 |
@classmethod |
| 200 |
def teardown_class(cls) -> None: |
| 201 |
shutil.rmtree(cls.tmpdir) |
| 202 |
|
| 203 |
def _wrap_in_ssl(self, sock: socket.socket) -> ssl.SSLSocket: |
| 204 |
""" |
| 205 |
Given a single socket, wraps it in TLS. |
| 206 |
""" |
| 207 |
return original_ssl_wrap_socket( |
| 208 |
sock, |
| 209 |
ssl_version=ssl.PROTOCOL_SSLv23, |
| 210 |
cert_reqs=ssl.CERT_REQUIRED, |
| 211 |
ca_certs=self.ca_path, |
| 212 |
certfile=self.cert_path, |
| 213 |
keyfile=self.key_path, |
| 214 |
server_side=True, |
| 215 |
) |
| 216 |
|
| 217 |
def test_client_certs_two_files(self) -> None: |
| 218 |
""" |
| 219 |
Having a client cert in a separate file to its associated key works |
| 220 |
properly. |
| 221 |
""" |
| 222 |
done_receiving = Event() |
| 223 |
client_certs = [] |
| 224 |
|
| 225 |
def socket_handler(listener: socket.socket) -> None: |
| 226 |
sock = listener.accept()[0] |
| 227 |
sock = self._wrap_in_ssl(sock) |
| 228 |
|
| 229 |
client_certs.append(sock.getpeercert()) |
| 230 |
|
| 231 |
data = b"" |
| 232 |
while not data.endswith(b"\r\n\r\n"): |
| 233 |
data += sock.recv(8192) |
| 234 |
|
| 235 |
sock.sendall( |
| 236 |
b"HTTP/1.1 200 OK\r\n" |
| 237 |
b"Server: testsocket\r\n" |
| 238 |
b"Connection: close\r\n" |
| 239 |
b"Content-Length: 6\r\n" |
| 240 |
b"\r\n" |
| 241 |
b"Valid!" |
| 242 |
) |
| 243 |
|
| 244 |
done_receiving.wait(5) |
| 245 |
sock.close() |
| 246 |
|
| 247 |
self._start_server(socket_handler) |
| 248 |
with HTTPSConnectionPool( |
| 249 |
self.host, |
| 250 |
self.port, |
| 251 |
cert_file=self.cert_path, |
| 252 |
key_file=self.key_path, |
| 253 |
cert_reqs="REQUIRED", |
| 254 |
ca_certs=self.ca_path, |
| 255 |
) as pool: |
| 256 |
pool.request("GET", "/", retries=0) |
| 257 |
done_receiving.set() |
| 258 |
|
| 259 |
assert len(client_certs) == 1 |
| 260 |
|
| 261 |
def test_client_certs_one_file(self) -> None: |
| 262 |
""" |
| 263 |
Having a client cert and its associated private key in just one file |
| 264 |
works properly. |
| 265 |
""" |
| 266 |
done_receiving = Event() |
| 267 |
client_certs = [] |
| 268 |
|
| 269 |
def socket_handler(listener: socket.socket) -> None: |
| 270 |
sock = listener.accept()[0] |
| 271 |
sock = self._wrap_in_ssl(sock) |
| 272 |
|
| 273 |
client_certs.append(sock.getpeercert()) |
| 274 |
|
| 275 |
data = b"" |
| 276 |
while not data.endswith(b"\r\n\r\n"): |
| 277 |
data += sock.recv(8192) |
| 278 |
|
| 279 |
sock.sendall( |
| 280 |
b"HTTP/1.1 200 OK\r\n" |
| 281 |
b"Server: testsocket\r\n" |
| 282 |
b"Connection: close\r\n" |
| 283 |
b"Content-Length: 6\r\n" |
| 284 |
b"\r\n" |
| 285 |
b"Valid!" |
| 286 |
) |
| 287 |
|
| 288 |
done_receiving.wait(5) |
| 289 |
sock.close() |
| 290 |
|
| 291 |
self._start_server(socket_handler) |
| 292 |
with HTTPSConnectionPool( |
| 293 |
self.host, |
| 294 |
self.port, |
| 295 |
cert_file=self.cert_combined_path, |
| 296 |
cert_reqs="REQUIRED", |
| 297 |
ca_certs=self.ca_path, |
| 298 |
) as pool: |
| 299 |
pool.request("GET", "/", retries=0) |
| 300 |
done_receiving.set() |
| 301 |
|
| 302 |
assert len(client_certs) == 1 |
| 303 |
|
| 304 |
def test_missing_client_certs_raises_error(self) -> None: |
| 305 |
""" |
| 306 |
Having client certs not be present causes an error. |
| 307 |
""" |
| 308 |
done_receiving = Event() |
| 309 |
|
| 310 |
def socket_handler(listener: socket.socket) -> None: |
| 311 |
sock = listener.accept()[0] |
| 312 |
|
| 313 |
try: |
| 314 |
self._wrap_in_ssl(sock) |
| 315 |
except ssl.SSLError: |
| 316 |
pass |
| 317 |
|
| 318 |
done_receiving.wait(5) |
| 319 |
sock.close() |
| 320 |
|
| 321 |
self._start_server(socket_handler) |
| 322 |
with HTTPSConnectionPool( |
| 323 |
self.host, self.port, cert_reqs="REQUIRED", ca_certs=self.ca_path |
| 324 |
) as pool: |
| 325 |
with pytest.raises(MaxRetryError): |
| 326 |
pool.request("GET", "/", retries=0) |
| 327 |
done_receiving.set() |
| 328 |
done_receiving.set() |
| 329 |
|
| 330 |
def test_client_cert_with_string_password(self) -> None: |
| 331 |
self.run_client_cert_with_password_test("letmein") |
| 332 |
|
| 333 |
def test_client_cert_with_bytes_password(self) -> None: |
| 334 |
self.run_client_cert_with_password_test(b"letmein") |
| 335 |
|
| 336 |
def run_client_cert_with_password_test(self, password: bytes | str) -> None: |
| 337 |
""" |
| 338 |
Tests client certificate password functionality |
| 339 |
""" |
| 340 |
done_receiving = Event() |
| 341 |
client_certs = [] |
| 342 |
|
| 343 |
def socket_handler(listener: socket.socket) -> None: |
| 344 |
sock = listener.accept()[0] |
| 345 |
sock = self._wrap_in_ssl(sock) |
| 346 |
|
| 347 |
client_certs.append(sock.getpeercert()) |
| 348 |
|
| 349 |
data = b"" |
| 350 |
while not data.endswith(b"\r\n\r\n"): |
| 351 |
data += sock.recv(8192) |
| 352 |
|
| 353 |
sock.sendall( |
| 354 |
b"HTTP/1.1 200 OK\r\n" |
| 355 |
b"Server: testsocket\r\n" |
| 356 |
b"Connection: close\r\n" |
| 357 |
b"Content-Length: 6\r\n" |
| 358 |
b"\r\n" |
| 359 |
b"Valid!" |
| 360 |
) |
| 361 |
|
| 362 |
done_receiving.wait(5) |
| 363 |
sock.close() |
| 364 |
|
| 365 |
self._start_server(socket_handler) |
| 366 |
assert ssl_.SSLContext is not None |
| 367 |
ssl_context = ssl_.SSLContext(ssl_.PROTOCOL_SSLv23) |
| 368 |
ssl_context.load_cert_chain( |
| 369 |
certfile=self.cert_path, keyfile=self.password_key_path, password=password |
| 370 |
) |
| 371 |
|
| 372 |
with HTTPSConnectionPool( |
| 373 |
self.host, |
| 374 |
self.port, |
| 375 |
ssl_context=ssl_context, |
| 376 |
cert_reqs="REQUIRED", |
| 377 |
ca_certs=self.ca_path, |
| 378 |
) as pool: |
| 379 |
pool.request("GET", "/", retries=0) |
| 380 |
done_receiving.set() |
| 381 |
|
| 382 |
assert len(client_certs) == 1 |
| 383 |
|
| 384 |
def test_load_keyfile_with_invalid_password(self) -> None: |
| 385 |
assert ssl_.SSLContext is not None |
| 386 |
context = ssl_.SSLContext(ssl_.PROTOCOL_SSLv23) |
| 387 |
with pytest.raises(ssl.SSLError): |
| 388 |
context.load_cert_chain( |
| 389 |
certfile=self.cert_path, |
| 390 |
keyfile=self.password_key_path, |
| 391 |
password=b"letmei", |
| 392 |
) |
| 393 |
|
| 394 |
def test_load_invalid_cert_file(self) -> None: |
| 395 |
assert ssl_.SSLContext is not None |
| 396 |
context = ssl_.SSLContext(ssl_.PROTOCOL_SSLv23) |
| 397 |
with pytest.raises(ssl.SSLError): |
| 398 |
context.load_cert_chain(certfile=self.password_key_path) |
| 399 |
|
| 400 |
|
| 401 |
class TestSocketClosing(SocketDummyServerTestCase): |
| 402 |
def test_recovery_when_server_closes_connection(self) -> None: |
| 403 |
# Does the pool work seamlessly if an open connection in the |
| 404 |
# connection pool gets hung up on by the server, then reaches |
| 405 |
# the front of the queue again? |
| 406 |
|
| 407 |
done_closing = Event() |
| 408 |
|
| 409 |
def socket_handler(listener: socket.socket) -> None: |
| 410 |
for i in 0, 1: |
| 411 |
sock = listener.accept()[0] |
| 412 |
|
| 413 |
buf = b"" |
| 414 |
while not buf.endswith(b"\r\n\r\n"): |
| 415 |
buf = sock.recv(65536) |
| 416 |
|
| 417 |
body = f"Response {int(i)}" |
| 418 |
sock.send( |
| 419 |
( |
| 420 |
"HTTP/1.1 200 OK\r\n" |
| 421 |
"Content-Type: text/plain\r\n" |
| 422 |
"Content-Length: %d\r\n" |
| 423 |
"\r\n" |
| 424 |
"%s" % (len(body), body) |
| 425 |
).encode("utf-8") |
| 426 |
) |
| 427 |
|
| 428 |
sock.close() # simulate a server timing out, closing socket |
| 429 |
done_closing.set() # let the test know it can proceed |
| 430 |
|
| 431 |
self._start_server(socket_handler) |
| 432 |
with HTTPConnectionPool(self.host, self.port) as pool: |
| 433 |
response = pool.request("GET", "/", retries=0) |
| 434 |
assert response.status == 200 |
| 435 |
assert response.data == b"Response 0" |
| 436 |
|
| 437 |
done_closing.wait() # wait until the socket in our pool gets closed |
| 438 |
|
| 439 |
response = pool.request("GET", "/", retries=0) |
| 440 |
assert response.status == 200 |
| 441 |
assert response.data == b"Response 1" |
| 442 |
|
| 443 |
def test_connection_refused(self) -> None: |
| 444 |
# Does the pool retry if there is no listener on the port? |
| 445 |
host, port = get_unreachable_address() |
| 446 |
with HTTPConnectionPool(host, port, maxsize=3, block=True) as http: |
| 447 |
with pytest.raises(MaxRetryError): |
| 448 |
http.request("GET", "/", retries=0, release_conn=False) |
| 449 |
assert http.pool is not None |
| 450 |
assert http.pool.qsize() == http.pool.maxsize |
| 451 |
|
| 452 |
def test_connection_read_timeout(self) -> None: |
| 453 |
timed_out = Event() |
| 454 |
|
| 455 |
def socket_handler(listener: socket.socket) -> None: |
| 456 |
sock = listener.accept()[0] |
| 457 |
while not sock.recv(65536).endswith(b"\r\n\r\n"): |
| 458 |
pass |
| 459 |
|
| 460 |
timed_out.wait() |
| 461 |
sock.close() |
| 462 |
|
| 463 |
self._start_server(socket_handler) |
| 464 |
with HTTPConnectionPool( |
| 465 |
self.host, |
| 466 |
self.port, |
| 467 |
timeout=SHORT_TIMEOUT, |
| 468 |
retries=False, |
| 469 |
maxsize=3, |
| 470 |
block=True, |
| 471 |
) as http: |
| 472 |
try: |
| 473 |
with pytest.raises(ReadTimeoutError): |
| 474 |
http.request("GET", "/", release_conn=False) |
| 475 |
finally: |
| 476 |
timed_out.set() |
| 477 |
|
| 478 |
assert http.pool is not None |
| 479 |
assert http.pool.qsize() == http.pool.maxsize |
| 480 |
|
| 481 |
def test_read_timeout_dont_retry_method_not_in_allowlist(self) -> None: |
| 482 |
timed_out = Event() |
| 483 |
|
| 484 |
def socket_handler(listener: socket.socket) -> None: |
| 485 |
sock = listener.accept()[0] |
| 486 |
sock.recv(65536) |
| 487 |
timed_out.wait() |
| 488 |
sock.close() |
| 489 |
|
| 490 |
self._start_server(socket_handler) |
| 491 |
with HTTPConnectionPool( |
| 492 |
self.host, self.port, timeout=LONG_TIMEOUT, retries=True |
| 493 |
) as pool: |
| 494 |
try: |
| 495 |
with pytest.raises(ReadTimeoutError): |
| 496 |
pool.request("POST", "/") |
| 497 |
finally: |
| 498 |
timed_out.set() |
| 499 |
|
| 500 |
def test_https_connection_read_timeout(self) -> None: |
| 501 |
"""Handshake timeouts should fail with a Timeout""" |
| 502 |
timed_out = Event() |
| 503 |
|
| 504 |
def socket_handler(listener: socket.socket) -> None: |
| 505 |
sock = listener.accept()[0] |
| 506 |
while not sock.recv(65536): |
| 507 |
pass |
| 508 |
|
| 509 |
timed_out.wait() |
| 510 |
sock.close() |
| 511 |
|
| 512 |
# first ReadTimeoutError due to SocketTimeout |
| 513 |
self._start_server(socket_handler) |
| 514 |
with HTTPSConnectionPool( |
| 515 |
self.host, self.port, timeout=LONG_TIMEOUT, retries=False |
| 516 |
) as pool: |
| 517 |
try: |
| 518 |
with pytest.raises(ReadTimeoutError): |
| 519 |
pool.request("GET", "/") |
| 520 |
finally: |
| 521 |
timed_out.set() |
| 522 |
|
| 523 |
# second ReadTimeoutError due to errno |
| 524 |
with HTTPSConnectionPool(host=self.host): |
| 525 |
err = OSError() |
| 526 |
err.errno = errno.EAGAIN |
| 527 |
with pytest.raises(ReadTimeoutError): |
| 528 |
pool._raise_timeout(err, "", 0) |
| 529 |
|
| 530 |
def test_timeout_errors_cause_retries(self) -> None: |
| 531 |
def socket_handler(listener: socket.socket) -> None: |
| 532 |
sock_timeout = listener.accept()[0] |
| 533 |
|
| 534 |
# Wait for a second request before closing the first socket. |
| 535 |
sock = listener.accept()[0] |
| 536 |
sock_timeout.close() |
| 537 |
|
| 538 |
# Second request. |
| 539 |
buf = b"" |
| 540 |
while not buf.endswith(b"\r\n\r\n"): |
| 541 |
buf += sock.recv(65536) |
| 542 |
|
| 543 |
# Now respond immediately. |
| 544 |
body = "Response 2" |
| 545 |
sock.send( |
| 546 |
( |
| 547 |
"HTTP/1.1 200 OK\r\n" |
| 548 |
"Content-Type: text/plain\r\n" |
| 549 |
"Content-Length: %d\r\n" |
| 550 |
"\r\n" |
| 551 |
"%s" % (len(body), body) |
| 552 |
).encode("utf-8") |
| 553 |
) |
| 554 |
|
| 555 |
sock.close() |
| 556 |
|
| 557 |
# In situations where the main thread throws an exception, the server |
| 558 |
# thread can hang on an accept() call. This ensures everything times |
| 559 |
# out within 1 second. This should be long enough for any socket |
| 560 |
# operations in the test suite to complete |
| 561 |
default_timeout = socket.getdefaulttimeout() |
| 562 |
socket.setdefaulttimeout(1) |
| 563 |
|
| 564 |
try: |
| 565 |
self._start_server(socket_handler) |
| 566 |
t = Timeout(connect=LONG_TIMEOUT, read=LONG_TIMEOUT) |
| 567 |
with HTTPConnectionPool(self.host, self.port, timeout=t) as pool: |
| 568 |
response = pool.request("GET", "/", retries=1) |
| 569 |
assert response.status == 200 |
| 570 |
assert response.data == b"Response 2" |
| 571 |
finally: |
| 572 |
socket.setdefaulttimeout(default_timeout) |
| 573 |
|
| 574 |
def test_delayed_body_read_timeout(self) -> None: |
| 575 |
timed_out = Event() |
| 576 |
|
| 577 |
def socket_handler(listener: socket.socket) -> None: |
| 578 |
sock = listener.accept()[0] |
| 579 |
buf = b"" |
| 580 |
body = "Hi" |
| 581 |
while not buf.endswith(b"\r\n\r\n"): |
| 582 |
buf = sock.recv(65536) |
| 583 |
sock.send( |
| 584 |
( |
| 585 |
"HTTP/1.1 200 OK\r\n" |
| 586 |
"Content-Type: text/plain\r\n" |
| 587 |
"Content-Length: %d\r\n" |
| 588 |
"\r\n" % len(body) |
| 589 |
).encode("utf-8") |
| 590 |
) |
| 591 |
|
| 592 |
timed_out.wait() |
| 593 |
sock.send(body.encode("utf-8")) |
| 594 |
sock.close() |
| 595 |
|
| 596 |
self._start_server(socket_handler) |
| 597 |
with HTTPConnectionPool(self.host, self.port) as pool: |
| 598 |
response = pool.urlopen( |
| 599 |
"GET", |
| 600 |
"/", |
| 601 |
retries=0, |
| 602 |
preload_content=False, |
| 603 |
timeout=Timeout(connect=1, read=LONG_TIMEOUT), |
| 604 |
) |
| 605 |
try: |
| 606 |
with pytest.raises(ReadTimeoutError): |
| 607 |
response.read() |
| 608 |
finally: |
| 609 |
timed_out.set() |
| 610 |
|
| 611 |
def test_delayed_body_read_timeout_with_preload(self) -> None: |
| 612 |
timed_out = Event() |
| 613 |
|
| 614 |
def socket_handler(listener: socket.socket) -> None: |
| 615 |
sock = listener.accept()[0] |
| 616 |
buf = b"" |
| 617 |
body = "Hi" |
| 618 |
while not buf.endswith(b"\r\n\r\n"): |
| 619 |
buf += sock.recv(65536) |
| 620 |
sock.send( |
| 621 |
( |
| 622 |
"HTTP/1.1 200 OK\r\n" |
| 623 |
"Content-Type: text/plain\r\n" |
| 624 |
"Content-Length: %d\r\n" |
| 625 |
"\r\n" % len(body) |
| 626 |
).encode("utf-8") |
| 627 |
) |
| 628 |
|
| 629 |
timed_out.wait(5) |
| 630 |
sock.close() |
| 631 |
|
| 632 |
self._start_server(socket_handler) |
| 633 |
with HTTPConnectionPool(self.host, self.port) as pool: |
| 634 |
try: |
| 635 |
with pytest.raises(ReadTimeoutError): |
| 636 |
timeout = Timeout(connect=LONG_TIMEOUT, read=SHORT_TIMEOUT) |
| 637 |
pool.urlopen("GET", "/", retries=False, timeout=timeout) |
| 638 |
finally: |
| 639 |
timed_out.set() |
| 640 |
|
| 641 |
def test_incomplete_response(self) -> None: |
| 642 |
body = "Response" |
| 643 |
partial_body = body[:2] |
| 644 |
|
| 645 |
def socket_handler(listener: socket.socket) -> None: |
| 646 |
sock = listener.accept()[0] |
| 647 |
|
| 648 |
# Consume request |
| 649 |
buf = b"" |
| 650 |
while not buf.endswith(b"\r\n\r\n"): |
| 651 |
buf = sock.recv(65536) |
| 652 |
|
| 653 |
# Send partial response and close socket. |
| 654 |
sock.send( |
| 655 |
( |
| 656 |
"HTTP/1.1 200 OK\r\n" |
| 657 |
"Content-Type: text/plain\r\n" |
| 658 |
"Content-Length: %d\r\n" |
| 659 |
"\r\n" |
| 660 |
"%s" % (len(body), partial_body) |
| 661 |
).encode("utf-8") |
| 662 |
) |
| 663 |
sock.close() |
| 664 |
|
| 665 |
self._start_server(socket_handler) |
| 666 |
with HTTPConnectionPool(self.host, self.port) as pool: |
| 667 |
response = pool.request("GET", "/", retries=0, preload_content=False) |
| 668 |
with pytest.raises(ProtocolError): |
| 669 |
response.read() |
| 670 |
|
| 671 |
def test_retry_weird_http_version(self) -> None: |
| 672 |
"""Retry class should handle httplib.BadStatusLine errors properly""" |
| 673 |
|
| 674 |
def socket_handler(listener: socket.socket) -> None: |
| 675 |
sock = listener.accept()[0] |
| 676 |
# First request. |
| 677 |
# Pause before responding so the first request times out. |
| 678 |
buf = b"" |
| 679 |
while not buf.endswith(b"\r\n\r\n"): |
| 680 |
buf += sock.recv(65536) |
| 681 |
|
| 682 |
# send unknown http protocol |
| 683 |
body = "bad http 0.5 response" |
| 684 |
sock.send( |
| 685 |
( |
| 686 |
"HTTP/0.5 200 OK\r\n" |
| 687 |
"Content-Type: text/plain\r\n" |
| 688 |
"Content-Length: %d\r\n" |
| 689 |
"\r\n" |
| 690 |
"%s" % (len(body), body) |
| 691 |
).encode("utf-8") |
| 692 |
) |
| 693 |
sock.close() |
| 694 |
|
| 695 |
# Second request. |
| 696 |
sock = listener.accept()[0] |
| 697 |
buf = b"" |
| 698 |
while not buf.endswith(b"\r\n\r\n"): |
| 699 |
buf += sock.recv(65536) |
| 700 |
|
| 701 |
# Now respond immediately. |
| 702 |
sock.send( |
| 703 |
( |
| 704 |
"HTTP/1.1 200 OK\r\n" |
| 705 |
"Content-Type: text/plain\r\n" |
| 706 |
"Content-Length: %d\r\n" |
| 707 |
"\r\n" |
| 708 |
"foo" % (len("foo")) |
| 709 |
).encode("utf-8") |
| 710 |
) |
| 711 |
|
| 712 |
sock.close() # Close the socket. |
| 713 |
|
| 714 |
self._start_server(socket_handler) |
| 715 |
with HTTPConnectionPool(self.host, self.port) as pool: |
| 716 |
retry = Retry(read=1) |
| 717 |
response = pool.request("GET", "/", retries=retry) |
| 718 |
assert response.status == 200 |
| 719 |
assert response.data == b"foo" |
| 720 |
|
| 721 |
def test_connection_cleanup_on_read_timeout(self) -> None: |
| 722 |
timed_out = Event() |
| 723 |
|
| 724 |
def socket_handler(listener: socket.socket) -> None: |
| 725 |
sock = listener.accept()[0] |
| 726 |
buf = b"" |
| 727 |
body = "Hi" |
| 728 |
while not buf.endswith(b"\r\n\r\n"): |
| 729 |
buf = sock.recv(65536) |
| 730 |
sock.send( |
| 731 |
( |
| 732 |
"HTTP/1.1 200 OK\r\n" |
| 733 |
"Content-Type: text/plain\r\n" |
| 734 |
"Content-Length: %d\r\n" |
| 735 |
"\r\n" % len(body) |
| 736 |
).encode("utf-8") |
| 737 |
) |
| 738 |
|
| 739 |
timed_out.wait() |
| 740 |
sock.close() |
| 741 |
|
| 742 |
self._start_server(socket_handler) |
| 743 |
with HTTPConnectionPool(self.host, self.port) as pool: |
| 744 |
assert pool.pool is not None |
| 745 |
poolsize = pool.pool.qsize() |
| 746 |
response = pool.urlopen( |
| 747 |
"GET", "/", retries=0, preload_content=False, timeout=LONG_TIMEOUT |
| 748 |
) |
| 749 |
try: |
| 750 |
with pytest.raises(ReadTimeoutError): |
| 751 |
response.read() |
| 752 |
assert poolsize == pool.pool.qsize() |
| 753 |
finally: |
| 754 |
timed_out.set() |
| 755 |
|
| 756 |
def test_connection_cleanup_on_protocol_error_during_read(self) -> None: |
| 757 |
body = "Response" |
| 758 |
partial_body = body[:2] |
| 759 |
|
| 760 |
def socket_handler(listener: socket.socket) -> None: |
| 761 |
sock = listener.accept()[0] |
| 762 |
|
| 763 |
# Consume request |
| 764 |
buf = b"" |
| 765 |
while not buf.endswith(b"\r\n\r\n"): |
| 766 |
buf = sock.recv(65536) |
| 767 |
|
| 768 |
# Send partial response and close socket. |
| 769 |
sock.send( |
| 770 |
( |
| 771 |
"HTTP/1.1 200 OK\r\n" |
| 772 |
"Content-Type: text/plain\r\n" |
| 773 |
"Content-Length: %d\r\n" |
| 774 |
"\r\n" |
| 775 |
"%s" % (len(body), partial_body) |
| 776 |
).encode("utf-8") |
| 777 |
) |
| 778 |
sock.close() |
| 779 |
|
| 780 |
self._start_server(socket_handler) |
| 781 |
with HTTPConnectionPool(self.host, self.port) as pool: |
| 782 |
assert pool.pool is not None |
| 783 |
poolsize = pool.pool.qsize() |
| 784 |
response = pool.request("GET", "/", retries=0, preload_content=False) |
| 785 |
|
| 786 |
with pytest.raises(ProtocolError): |
| 787 |
response.read() |
| 788 |
assert poolsize == pool.pool.qsize() |
| 789 |
|
| 790 |
def test_connection_closed_on_read_timeout_preload_false(self) -> None: |
| 791 |
timed_out = Event() |
| 792 |
|
| 793 |
def socket_handler(listener: socket.socket) -> None: |
| 794 |
sock = listener.accept()[0] |
| 795 |
|
| 796 |
# Consume request |
| 797 |
buf = b"" |
| 798 |
while not buf.endswith(b"\r\n\r\n"): |
| 799 |
buf = sock.recv(65535) |
| 800 |
|
| 801 |
# Send partial chunked response and then hang. |
| 802 |
sock.send( |
| 803 |
b"HTTP/1.1 200 OK\r\n" |
| 804 |
b"Content-Type: text/plain\r\n" |
| 805 |
b"Transfer-Encoding: chunked\r\n" |
| 806 |
b"\r\n" |
| 807 |
b"8\r\n" |
| 808 |
b"12345678\r\n" |
| 809 |
) |
| 810 |
timed_out.wait(5) |
| 811 |
|
| 812 |
# Expect a new request, but keep hold of the old socket to avoid |
| 813 |
# leaking it. Because we don't want to hang this thread, we |
| 814 |
# actually use select.select to confirm that a new request is |
| 815 |
# coming in: this lets us time the thread out. |
| 816 |
rlist, _, _ = select.select([listener], [], [], 1) |
| 817 |
assert rlist |
| 818 |
new_sock = listener.accept()[0] |
| 819 |
|
| 820 |
# Consume request |
| 821 |
buf = b"" |
| 822 |
while not buf.endswith(b"\r\n\r\n"): |
| 823 |
buf = new_sock.recv(65535) |
| 824 |
|
| 825 |
# Send complete chunked response. |
| 826 |
new_sock.send( |
| 827 |
b"HTTP/1.1 200 OK\r\n" |
| 828 |
b"Content-Type: text/plain\r\n" |
| 829 |
b"Transfer-Encoding: chunked\r\n" |
| 830 |
b"\r\n" |
| 831 |
b"8\r\n" |
| 832 |
b"12345678\r\n" |
| 833 |
b"0\r\n\r\n" |
| 834 |
) |
| 835 |
|
| 836 |
new_sock.close() |
| 837 |
sock.close() |
| 838 |
|
| 839 |
self._start_server(socket_handler) |
| 840 |
with HTTPConnectionPool(self.host, self.port) as pool: |
| 841 |
# First request should fail. |
| 842 |
response = pool.urlopen( |
| 843 |
"GET", "/", retries=0, preload_content=False, timeout=LONG_TIMEOUT |
| 844 |
) |
| 845 |
try: |
| 846 |
with pytest.raises(ReadTimeoutError): |
| 847 |
response.read() |
| 848 |
finally: |
| 849 |
timed_out.set() |
| 850 |
|
| 851 |
# Second should succeed. |
| 852 |
response = pool.urlopen( |
| 853 |
"GET", "/", retries=0, preload_content=False, timeout=LONG_TIMEOUT |
| 854 |
) |
| 855 |
assert len(response.read()) == 8 |
| 856 |
|
| 857 |
def test_closing_response_actually_closes_connection(self) -> None: |
| 858 |
done_closing = Event() |
| 859 |
complete = Event() |
| 860 |
|
| 861 |
def socket_handler(listener: socket.socket) -> None: |
| 862 |
sock = listener.accept()[0] |
| 863 |
|
| 864 |
buf = b"" |
| 865 |
while not buf.endswith(b"\r\n\r\n"): |
| 866 |
buf = sock.recv(65536) |
| 867 |
|
| 868 |
sock.send( |
| 869 |
b"HTTP/1.1 200 OK\r\n" |
| 870 |
b"Content-Type: text/plain\r\n" |
| 871 |
b"Content-Length: 0\r\n" |
| 872 |
b"\r\n" |
| 873 |
) |
| 874 |
|
| 875 |
# Wait for the socket to close. |
| 876 |
done_closing.wait(timeout=LONG_TIMEOUT) |
| 877 |
|
| 878 |
# Look for the empty string to show that the connection got closed. |
| 879 |
# Don't get stuck in a timeout. |
| 880 |
sock.settimeout(LONG_TIMEOUT) |
| 881 |
new_data = sock.recv(65536) |
| 882 |
assert not new_data |
| 883 |
sock.close() |
| 884 |
complete.set() |
| 885 |
|
| 886 |
self._start_server(socket_handler) |
| 887 |
with HTTPConnectionPool(self.host, self.port) as pool: |
| 888 |
response = pool.request("GET", "/", retries=0, preload_content=False) |
| 889 |
assert response.status == 200 |
| 890 |
response.close() |
| 891 |
|
| 892 |
done_closing.set() # wait until the socket in our pool gets closed |
| 893 |
successful = complete.wait(timeout=LONG_TIMEOUT) |
| 894 |
assert successful, "Timed out waiting for connection close" |
| 895 |
|
| 896 |
def test_release_conn_param_is_respected_after_timeout_retry(self) -> None: |
| 897 |
"""For successful ```urlopen(release_conn=False)```, |
| 898 |
the connection isn't released, even after a retry. |
| 899 |
|
| 900 |
This test allows a retry: one request fails, the next request succeeds. |
| 901 |
|
| 902 |
This is a regression test for issue #651 [1], where the connection |
| 903 |
would be released if the initial request failed, even if a retry |
| 904 |
succeeded. |
| 905 |
|
| 906 |
[1] <https://github.com/urllib3/urllib3/issues/651> |
| 907 |
""" |
| 908 |
|
| 909 |
def socket_handler(listener: socket.socket) -> None: |
| 910 |
sock = listener.accept()[0] |
| 911 |
consume_socket(sock) |
| 912 |
|
| 913 |
# Close the connection, without sending any response (not even the |
| 914 |
# HTTP status line). This will trigger a `Timeout` on the client, |
| 915 |
# inside `urlopen()`. |
| 916 |
sock.close() |
| 917 |
|
| 918 |
# Expect a new request. Because we don't want to hang this thread, |
| 919 |
# we actually use select.select to confirm that a new request is |
| 920 |
# coming in: this lets us time the thread out. |
| 921 |
rlist, _, _ = select.select([listener], [], [], 5) |
| 922 |
assert rlist |
| 923 |
sock = listener.accept()[0] |
| 924 |
consume_socket(sock) |
| 925 |
|
| 926 |
# Send complete chunked response. |
| 927 |
sock.send( |
| 928 |
b"HTTP/1.1 200 OK\r\n" |
| 929 |
b"Content-Type: text/plain\r\n" |
| 930 |
b"Transfer-Encoding: chunked\r\n" |
| 931 |
b"\r\n" |
| 932 |
b"8\r\n" |
| 933 |
b"12345678\r\n" |
| 934 |
b"0\r\n\r\n" |
| 935 |
) |
| 936 |
|
| 937 |
sock.close() |
| 938 |
|
| 939 |
self._start_server(socket_handler) |
| 940 |
with HTTPConnectionPool(self.host, self.port, maxsize=1) as pool: |
| 941 |
# First request should fail, but the timeout and `retries=1` should |
| 942 |
# save it. |
| 943 |
response = pool.urlopen( |
| 944 |
"GET", |
| 945 |
"/", |
| 946 |
retries=1, |
| 947 |
release_conn=False, |
| 948 |
preload_content=False, |
| 949 |
timeout=LONG_TIMEOUT, |
| 950 |
) |
| 951 |
|
| 952 |
# The connection should still be on the response object, and none |
| 953 |
# should be in the pool. We opened two though. |
| 954 |
assert pool.num_connections == 2 |
| 955 |
assert pool.pool is not None |
| 956 |
assert pool.pool.qsize() == 0 |
| 957 |
assert response.connection is not None |
| 958 |
|
| 959 |
# Consume the data. This should put the connection back. |
| 960 |
response.read() |
| 961 |
assert pool.pool.qsize() == 1 |
| 962 |
assert response.connection is None |
| 963 |
|
| 964 |
def test_socket_close_socket_then_file(self) -> None: |
| 965 |
quit_event = threading.Event() |
| 966 |
|
| 967 |
def consume_ssl_socket( |
| 968 |
listener: socket.socket, |
| 969 |
) -> None: |
| 970 |
try: |
| 971 |
with ( |
| 972 |
listener.accept()[0] as sock, |
| 973 |
original_ssl_wrap_socket( |
| 974 |
sock, |
| 975 |
server_side=True, |
| 976 |
keyfile=DEFAULT_CERTS["keyfile"], |
| 977 |
certfile=DEFAULT_CERTS["certfile"], |
| 978 |
ca_certs=DEFAULT_CA, |
| 979 |
) as ssl_sock, |
| 980 |
): |
| 981 |
consume_socket(ssl_sock, quit_event=quit_event) |
| 982 |
except (ConnectionResetError, ConnectionAbortedError, OSError): |
| 983 |
pass |
| 984 |
|
| 985 |
self._start_server(consume_ssl_socket, quit_event=quit_event) |
| 986 |
with ( |
| 987 |
socket.create_connection((self.host, self.port)) as sock, |
| 988 |
contextlib.closing( |
| 989 |
ssl_wrap_socket(sock, server_hostname=self.host, ca_certs=DEFAULT_CA) |
| 990 |
) as ssl_sock, |
| 991 |
ssl_sock.makefile("rb") as f, |
| 992 |
): |
| 993 |
ssl_sock.close() |
| 994 |
f.close() |
| 995 |
with pytest.raises(OSError): |
| 996 |
ssl_sock.sendall(b"hello") |
| 997 |
assert ssl_sock.fileno() == -1 |
| 998 |
|
| 999 |
def test_socket_close_stays_open_with_makefile_open(self) -> None: |
| 1000 |
quit_event = threading.Event() |
| 1001 |
|
| 1002 |
def consume_ssl_socket(listener: socket.socket) -> None: |
| 1003 |
try: |
| 1004 |
with ( |
| 1005 |
listener.accept()[0] as sock, |
| 1006 |
original_ssl_wrap_socket( |
| 1007 |
sock, |
| 1008 |
server_side=True, |
| 1009 |
keyfile=DEFAULT_CERTS["keyfile"], |
| 1010 |
certfile=DEFAULT_CERTS["certfile"], |
| 1011 |
ca_certs=DEFAULT_CA, |
| 1012 |
) as ssl_sock, |
| 1013 |
): |
| 1014 |
consume_socket(ssl_sock, quit_event=quit_event) |
| 1015 |
except (ConnectionResetError, ConnectionAbortedError, OSError): |
| 1016 |
pass |
| 1017 |
|
| 1018 |
self._start_server(consume_ssl_socket, quit_event=quit_event) |
| 1019 |
with ( |
| 1020 |
socket.create_connection((self.host, self.port)) as sock, |
| 1021 |
contextlib.closing( |
| 1022 |
ssl_wrap_socket(sock, server_hostname=self.host, ca_certs=DEFAULT_CA) |
| 1023 |
) as ssl_sock, |
| 1024 |
ssl_sock.makefile("rb"), |
| 1025 |
): |
| 1026 |
ssl_sock.close() |
| 1027 |
ssl_sock.close() |
| 1028 |
ssl_sock.sendall(b"hello") |
| 1029 |
assert ssl_sock.fileno() > 0 |
| 1030 |
|
| 1031 |
def test_socket_shutdown_stops_recv(self) -> None: |
| 1032 |
timed_out, starting_read = Event(), Event() |
| 1033 |
|
| 1034 |
def socket_handler(listener: socket.socket) -> None: |
| 1035 |
sock = listener.accept()[0] |
| 1036 |
|
| 1037 |
ssl_sock = original_ssl_wrap_socket( |
| 1038 |
sock, |
| 1039 |
server_side=True, |
| 1040 |
keyfile=DEFAULT_CERTS["keyfile"], |
| 1041 |
certfile=DEFAULT_CERTS["certfile"], |
| 1042 |
ca_certs=DEFAULT_CA, |
| 1043 |
) |
| 1044 |
|
| 1045 |
# Consume request |
| 1046 |
buf = b"" |
| 1047 |
while not buf.endswith(b"\r\n\r\n"): |
| 1048 |
buf = ssl_sock.recv(65535) |
| 1049 |
|
| 1050 |
# Send incomplete message (note Content-Length) |
| 1051 |
ssl_sock.send( |
| 1052 |
b"HTTP/1.1 200 OK\r\n" |
| 1053 |
b"Content-Type: text/plain\r\n" |
| 1054 |
b"Content-Length: 10\r\n" |
| 1055 |
b"\r\n" |
| 1056 |
b"Hi-" |
| 1057 |
) |
| 1058 |
timed_out.wait(5) |
| 1059 |
ssl_sock.close() |
| 1060 |
|
| 1061 |
self._start_server(socket_handler) |
| 1062 |
|
| 1063 |
class TestClient(threading.Thread): |
| 1064 |
def __init__(self, host: str, port: int) -> None: |
| 1065 |
super().__init__() |
| 1066 |
self.host, self.port = host, port |
| 1067 |
self.response: BaseHTTPResponse | None = None |
| 1068 |
|
| 1069 |
def run(self) -> None: |
| 1070 |
with HTTPSConnectionPool( |
| 1071 |
self.host, self.port, ca_certs=DEFAULT_CA |
| 1072 |
) as pool: |
| 1073 |
self.response = pool.urlopen( |
| 1074 |
"GET", "/", preload_content=False, retries=0 |
| 1075 |
) |
| 1076 |
with pytest.raises(ProtocolError, match="Connection broken"): |
| 1077 |
starting_read.set() |
| 1078 |
self.response.read() |
| 1079 |
|
| 1080 |
test_client = TestClient(self.host, self.port) |
| 1081 |
test_client.start() |
| 1082 |
# First, wait to make sure the client is really stuck reading |
| 1083 |
starting_read.wait(5) |
| 1084 |
time.sleep(LONG_TIMEOUT) |
| 1085 |
# Calling shutdown here calls shutdown() on the underlying socket, |
| 1086 |
# so that the remaining read will fail instead of blocking |
| 1087 |
# indefinitely |
| 1088 |
assert test_client.response is not None |
| 1089 |
test_client.response.shutdown() |
| 1090 |
timed_out.set() |
| 1091 |
|
| 1092 |
|
| 1093 |
class TestProxyManager(SocketDummyServerTestCase): |
| 1094 |
def test_simple(self) -> None: |
| 1095 |
def echo_socket_handler(listener: socket.socket) -> None: |
| 1096 |
sock = listener.accept()[0] |
| 1097 |
|
| 1098 |
buf = b"" |
| 1099 |
while not buf.endswith(b"\r\n\r\n"): |
| 1100 |
buf += sock.recv(65536) |
| 1101 |
|
| 1102 |
sock.send( |
| 1103 |
( |
| 1104 |
"HTTP/1.1 200 OK\r\n" |
| 1105 |
"Content-Type: text/plain\r\n" |
| 1106 |
"Content-Length: %d\r\n" |
| 1107 |
"\r\n" |
| 1108 |
"%s" % (len(buf), buf.decode("utf-8")) |
| 1109 |
).encode("utf-8") |
| 1110 |
) |
| 1111 |
sock.close() |
| 1112 |
|
| 1113 |
self._start_server(echo_socket_handler) |
| 1114 |
base_url = f"http://{self.host}:{self.port}" |
| 1115 |
with proxy_from_url(base_url) as proxy: |
| 1116 |
r = proxy.request("GET", "http://google.com/") |
| 1117 |
|
| 1118 |
assert r.status == 200 |
| 1119 |
# FIXME: The order of the headers is not predictable right now. We |
| 1120 |
# should fix that someday (maybe when we migrate to |
| 1121 |
# OrderedDict/MultiDict). |
| 1122 |
assert sorted(r.data.split(b"\r\n")) == sorted( |
| 1123 |
[ |
| 1124 |
b"GET http://google.com/ HTTP/1.1", |
| 1125 |
b"Host: google.com", |
| 1126 |
b"Accept-Encoding: identity", |
| 1127 |
b"Accept: */*", |
| 1128 |
b"User-Agent: " + _get_default_user_agent().encode("utf-8"), |
| 1129 |
b"", |
| 1130 |
b"", |
| 1131 |
] |
| 1132 |
) |
| 1133 |
|
| 1134 |
def test_headers(self) -> None: |
| 1135 |
def echo_socket_handler(listener: socket.socket) -> None: |
| 1136 |
sock = listener.accept()[0] |
| 1137 |
|
| 1138 |
buf = b"" |
| 1139 |
while not buf.endswith(b"\r\n\r\n"): |
| 1140 |
buf += sock.recv(65536) |
| 1141 |
|
| 1142 |
sock.send( |
| 1143 |
( |
| 1144 |
"HTTP/1.1 200 OK\r\n" |
| 1145 |
"Content-Type: text/plain\r\n" |
| 1146 |
"Content-Length: %d\r\n" |
| 1147 |
"\r\n" |
| 1148 |
"%s" % (len(buf), buf.decode("utf-8")) |
| 1149 |
).encode("utf-8") |
| 1150 |
) |
| 1151 |
sock.close() |
| 1152 |
|
| 1153 |
self._start_server(echo_socket_handler) |
| 1154 |
base_url = f"http://{self.host}:{self.port}" |
| 1155 |
|
| 1156 |
# Define some proxy headers. |
| 1157 |
proxy_headers = HTTPHeaderDict({"For The Proxy": "YEAH!"}) |
| 1158 |
with proxy_from_url(base_url, proxy_headers=proxy_headers) as proxy: |
| 1159 |
conn = proxy.connection_from_url("http://www.google.com/") |
| 1160 |
|
| 1161 |
r = conn.urlopen("GET", "http://www.google.com/", assert_same_host=False) |
| 1162 |
|
| 1163 |
assert r.status == 200 |
| 1164 |
# FIXME: The order of the headers is not predictable right now. We |
| 1165 |
# should fix that someday (maybe when we migrate to |
| 1166 |
# OrderedDict/MultiDict). |
| 1167 |
assert b"For The Proxy: YEAH!\r\n" in r.data |
| 1168 |
|
| 1169 |
def test_retries(self) -> None: |
| 1170 |
close_event = Event() |
| 1171 |
|
| 1172 |
def echo_socket_handler(listener: socket.socket) -> None: |
| 1173 |
sock = listener.accept()[0] |
| 1174 |
# First request, which should fail |
| 1175 |
sock.close() |
| 1176 |
|
| 1177 |
# Second request |
| 1178 |
sock = listener.accept()[0] |
| 1179 |
|
| 1180 |
buf = b"" |
| 1181 |
while not buf.endswith(b"\r\n\r\n"): |
| 1182 |
buf += sock.recv(65536) |
| 1183 |
|
| 1184 |
sock.send( |
| 1185 |
( |
| 1186 |
"HTTP/1.1 200 OK\r\n" |
| 1187 |
"Content-Type: text/plain\r\n" |
| 1188 |
"Content-Length: %d\r\n" |
| 1189 |
"\r\n" |
| 1190 |
"%s" % (len(buf), buf.decode("utf-8")) |
| 1191 |
).encode("utf-8") |
| 1192 |
) |
| 1193 |
sock.close() |
| 1194 |
close_event.set() |
| 1195 |
|
| 1196 |
self._start_server(echo_socket_handler) |
| 1197 |
base_url = f"http://{self.host}:{self.port}" |
| 1198 |
|
| 1199 |
with proxy_from_url(base_url) as proxy: |
| 1200 |
conn = proxy.connection_from_url("http://www.google.com") |
| 1201 |
|
| 1202 |
r = conn.urlopen( |
| 1203 |
"GET", "http://www.google.com", assert_same_host=False, retries=1 |
| 1204 |
) |
| 1205 |
assert r.status == 200 |
| 1206 |
|
| 1207 |
close_event.wait(timeout=LONG_TIMEOUT) |
| 1208 |
with pytest.raises(ProxyError): |
| 1209 |
conn.urlopen( |
| 1210 |
"GET", |
| 1211 |
"http://www.google.com", |
| 1212 |
assert_same_host=False, |
| 1213 |
retries=False, |
| 1214 |
) |
| 1215 |
|
| 1216 |
def test_tunnel_sets_http_11_alpn(self) -> None: |
| 1217 |
done_receiving = Event() |
| 1218 |
self.buf = b"" |
| 1219 |
|
| 1220 |
def socket_handler(listener: socket.socket) -> None: |
| 1221 |
sock = listener.accept()[0] |
| 1222 |
|
| 1223 |
self.buf = sock.recv(65536) # We only accept one packet |
| 1224 |
done_receiving.set() # let the test know it can proceed |
| 1225 |
sock.close() |
| 1226 |
|
| 1227 |
self._start_server(socket_handler) |
| 1228 |
base_url = f"https://{self.host}:{self.port}" |
| 1229 |
with proxy_from_url(base_url) as proxy: |
| 1230 |
with pytest.raises(MaxRetryError): |
| 1231 |
proxy.request("GET", "https://localhost/") |
| 1232 |
|
| 1233 |
done_receiving.wait() |
| 1234 |
assert b"http/1.1" in self.buf |
| 1235 |
assert b"h2" not in self.buf |
| 1236 |
|
| 1237 |
def test_connect_reconn(self) -> None: |
| 1238 |
def proxy_ssl_one(listener: socket.socket) -> None: |
| 1239 |
sock = listener.accept()[0] |
| 1240 |
|
| 1241 |
buf = b"" |
| 1242 |
while not buf.endswith(b"\r\n\r\n"): |
| 1243 |
buf += sock.recv(65536) |
| 1244 |
s = buf.decode("utf-8") |
| 1245 |
if not s.startswith("CONNECT "): |
| 1246 |
sock.send(b"HTTP/1.1 405 Method not allowed\r\nAllow: CONNECT\r\n\r\n") |
| 1247 |
sock.close() |
| 1248 |
return |
| 1249 |
|
| 1250 |
if not s.startswith(f"CONNECT {self.host}:443"): |
| 1251 |
sock.send(b"HTTP/1.1 403 Forbidden\r\n\r\n") |
| 1252 |
sock.close() |
| 1253 |
return |
| 1254 |
|
| 1255 |
sock.send(b"HTTP/1.1 200 Connection Established\r\n\r\n") |
| 1256 |
ssl_sock = original_ssl_wrap_socket( |
| 1257 |
sock, |
| 1258 |
server_side=True, |
| 1259 |
keyfile=DEFAULT_CERTS["keyfile"], |
| 1260 |
certfile=DEFAULT_CERTS["certfile"], |
| 1261 |
ca_certs=DEFAULT_CA, |
| 1262 |
) |
| 1263 |
|
| 1264 |
buf = b"" |
| 1265 |
while not buf.endswith(b"\r\n\r\n"): |
| 1266 |
buf += ssl_sock.recv(65536) |
| 1267 |
|
| 1268 |
ssl_sock.send( |
| 1269 |
b"HTTP/1.1 200 OK\r\n" |
| 1270 |
b"Content-Type: text/plain\r\n" |
| 1271 |
b"Content-Length: 2\r\n" |
| 1272 |
b"Connection: close\r\n" |
| 1273 |
b"\r\n" |
| 1274 |
b"Hi" |
| 1275 |
) |
| 1276 |
ssl_sock.close() |
| 1277 |
|
| 1278 |
def echo_socket_handler(listener: socket.socket) -> None: |
| 1279 |
proxy_ssl_one(listener) |
| 1280 |
proxy_ssl_one(listener) |
| 1281 |
|
| 1282 |
self._start_server(echo_socket_handler) |
| 1283 |
base_url = f"http://{self.host}:{self.port}" |
| 1284 |
|
| 1285 |
with proxy_from_url(base_url, ca_certs=DEFAULT_CA) as proxy: |
| 1286 |
url = f"https://{self.host}" |
| 1287 |
conn = proxy.connection_from_url(url) |
| 1288 |
r = conn.urlopen("GET", url, retries=0) |
| 1289 |
assert r.status == 200 |
| 1290 |
r = conn.urlopen("GET", url, retries=0) |
| 1291 |
assert r.status == 200 |
| 1292 |
|
| 1293 |
def test_connect_ipv6_addr_from_host(self) -> None: |
| 1294 |
ipv6_addr = "2001:4998:c:a06::2:4008" |
| 1295 |
|
| 1296 |
def echo_socket_handler(listener: socket.socket) -> None: |
| 1297 |
sock = listener.accept()[0] |
| 1298 |
|
| 1299 |
buf = b"" |
| 1300 |
while not buf.endswith(b"\r\n\r\n"): |
| 1301 |
buf += sock.recv(65536) |
| 1302 |
s = buf.decode("utf-8") |
| 1303 |
|
| 1304 |
if s.startswith(f"CONNECT [{ipv6_addr}]:443"): |
| 1305 |
sock.send(b"HTTP/1.1 200 Connection Established\r\n\r\n") |
| 1306 |
ssl_sock = original_ssl_wrap_socket( |
| 1307 |
sock, |
| 1308 |
server_side=True, |
| 1309 |
keyfile=DEFAULT_CERTS["keyfile"], |
| 1310 |
certfile=DEFAULT_CERTS["certfile"], |
| 1311 |
) |
| 1312 |
buf = b"" |
| 1313 |
while not buf.endswith(b"\r\n\r\n"): |
| 1314 |
buf += ssl_sock.recv(65536) |
| 1315 |
|
| 1316 |
ssl_sock.send( |
| 1317 |
b"HTTP/1.1 200 OK\r\n" |
| 1318 |
b"Content-Type: text/plain\r\n" |
| 1319 |
b"Content-Length: 2\r\n" |
| 1320 |
b"Connection: close\r\n" |
| 1321 |
b"\r\n" |
| 1322 |
b"Hi" |
| 1323 |
) |
| 1324 |
ssl_sock.close() |
| 1325 |
else: |
| 1326 |
sock.close() |
| 1327 |
|
| 1328 |
self._start_server(echo_socket_handler) |
| 1329 |
base_url = f"http://{self.host}:{self.port}" |
| 1330 |
|
| 1331 |
with proxy_from_url(base_url, cert_reqs="NONE") as proxy: |
| 1332 |
url = f"https://[{ipv6_addr}]" |
| 1333 |
|
| 1334 |
# Try with connection_from_host |
| 1335 |
parsed_request_url = urlparse(url) |
| 1336 |
|
| 1337 |
conn = proxy.connection_from_host( |
| 1338 |
scheme=parsed_request_url.scheme.lower(), |
| 1339 |
host=parsed_request_url.hostname, |
| 1340 |
port=parsed_request_url.port, |
| 1341 |
) |
| 1342 |
try: |
| 1343 |
with pytest.warns(InsecureRequestWarning): |
| 1344 |
r = conn.urlopen("GET", url, retries=0) |
| 1345 |
assert r.status == 200 |
| 1346 |
except MaxRetryError: |
| 1347 |
pytest.fail( |
| 1348 |
"Invalid IPv6 format in HTTP CONNECT request when using connection_from_host" |
| 1349 |
) |
| 1350 |
|
| 1351 |
def test_connect_ipv6_addr_from_url(self) -> None: |
| 1352 |
ipv6_addr = "2001:4998:c:a06::2:4008" |
| 1353 |
|
| 1354 |
def echo_socket_handler(listener: socket.socket) -> None: |
| 1355 |
sock = listener.accept()[0] |
| 1356 |
|
| 1357 |
buf = b"" |
| 1358 |
while not buf.endswith(b"\r\n\r\n"): |
| 1359 |
buf += sock.recv(65536) |
| 1360 |
s = buf.decode("utf-8") |
| 1361 |
|
| 1362 |
if s.startswith(f"CONNECT [{ipv6_addr}]:443"): |
| 1363 |
sock.send(b"HTTP/1.1 200 Connection Established\r\n\r\n") |
| 1364 |
ssl_sock = original_ssl_wrap_socket( |
| 1365 |
sock, |
| 1366 |
server_side=True, |
| 1367 |
keyfile=DEFAULT_CERTS["keyfile"], |
| 1368 |
certfile=DEFAULT_CERTS["certfile"], |
| 1369 |
) |
| 1370 |
buf = b"" |
| 1371 |
while not buf.endswith(b"\r\n\r\n"): |
| 1372 |
buf += ssl_sock.recv(65536) |
| 1373 |
|
| 1374 |
ssl_sock.send( |
| 1375 |
b"HTTP/1.1 200 OK\r\n" |
| 1376 |
b"Content-Type: text/plain\r\n" |
| 1377 |
b"Content-Length: 2\r\n" |
| 1378 |
b"Connection: close\r\n" |
| 1379 |
b"\r\n" |
| 1380 |
b"Hi" |
| 1381 |
) |
| 1382 |
ssl_sock.close() |
| 1383 |
else: |
| 1384 |
sock.close() |
| 1385 |
|
| 1386 |
self._start_server(echo_socket_handler) |
| 1387 |
base_url = f"http://{self.host}:{self.port}" |
| 1388 |
|
| 1389 |
with proxy_from_url(base_url, cert_reqs="NONE") as proxy: |
| 1390 |
url = f"https://[{ipv6_addr}]" |
| 1391 |
|
| 1392 |
# Try with connection_from_url |
| 1393 |
conn = proxy.connection_from_url(url) |
| 1394 |
try: |
| 1395 |
with pytest.warns(InsecureRequestWarning): |
| 1396 |
r = conn.urlopen("GET", url, retries=0) |
| 1397 |
assert r.status == 200 |
| 1398 |
except MaxRetryError: |
| 1399 |
pytest.fail( |
| 1400 |
"Invalid IPv6 format in HTTP CONNECT request when using connection_from_url" |
| 1401 |
) |
| 1402 |
|
| 1403 |
@pytest.mark.parametrize("target_scheme", ["http", "https"]) |
| 1404 |
def test_https_proxymanager_connected_to_http_proxy( |
| 1405 |
self, target_scheme: str |
| 1406 |
) -> None: |
| 1407 |
errored = Event() |
| 1408 |
|
| 1409 |
def http_socket_handler(listener: socket.socket) -> None: |
| 1410 |
sock = listener.accept()[0] |
| 1411 |
sock.send(b"HTTP/1.0 501 Not Implemented\r\nConnection: close\r\n\r\n") |
| 1412 |
errored.wait() |
| 1413 |
sock.close() |
| 1414 |
|
| 1415 |
self._start_server(http_socket_handler) |
| 1416 |
base_url = f"https://{self.host}:{self.port}" |
| 1417 |
|
| 1418 |
with ProxyManager(base_url, cert_reqs="NONE") as proxy: |
| 1419 |
with pytest.raises(MaxRetryError) as e: |
| 1420 |
proxy.request("GET", f"{target_scheme}://example.com", retries=0) |
| 1421 |
|
| 1422 |
errored.set() # Avoid a ConnectionAbortedError on Windows. |
| 1423 |
|
| 1424 |
assert type(e.value.reason) is ProxyError |
| 1425 |
assert "Your proxy appears to only use HTTP and not HTTPS" in str( |
| 1426 |
e.value.reason |
| 1427 |
) |
| 1428 |
|
| 1429 |
def test_proxy_status_not_ok(self) -> None: |
| 1430 |
def http_socket_handler(listener: socket.socket) -> None: |
| 1431 |
sock = listener.accept()[0] |
| 1432 |
consume_socket(sock) |
| 1433 |
sock.send(b"HTTP/1.0 501 Not Implemented\r\nConnection: close\r\n\r\n") |
| 1434 |
sock.close() |
| 1435 |
|
| 1436 |
self._start_server(http_socket_handler) |
| 1437 |
base_url = f"http://{self.host}:{self.port}" |
| 1438 |
|
| 1439 |
with ProxyManager(base_url) as proxy: |
| 1440 |
with pytest.raises(MaxRetryError) as e: |
| 1441 |
proxy.request("GET", "https://example.com", retries=0) |
| 1442 |
|
| 1443 |
assert type(e.value.reason) is ProxyError |
| 1444 |
assert e.value.reason.args[0] == "Unable to connect to proxy" |
| 1445 |
assert type(e.value.reason.args[1]) is OSError |
| 1446 |
assert ( |
| 1447 |
str(e.value.reason.args[1]) |
| 1448 |
== "Tunnel connection failed: 501 Not Implemented" |
| 1449 |
) |
| 1450 |
|
| 1451 |
def test_early_eof_doesnt_cause_infinite_loop(self) -> None: |
| 1452 |
def http_socket_handler(listener: socket.socket) -> None: |
| 1453 |
sock = listener.accept()[0] |
| 1454 |
consume_socket(sock) |
| 1455 |
sock.send(b"HTTP/1.0 200 OK\r\n") |
| 1456 |
sock.close() |
| 1457 |
|
| 1458 |
self._start_server(http_socket_handler) |
| 1459 |
base_url = f"http://{self.host}:{self.port}" |
| 1460 |
|
| 1461 |
with ProxyManager(base_url) as proxy: |
| 1462 |
with pytest.raises(MaxRetryError): |
| 1463 |
proxy.request("GET", "https://example.com", retries=0) |
| 1464 |
|
| 1465 |
def test_header_longer_than_maxline(self) -> None: |
| 1466 |
def http_socket_handler(listener: socket.socket) -> None: |
| 1467 |
sock = listener.accept()[0] |
| 1468 |
consume_socket(sock) |
| 1469 |
sock.send( |
| 1470 |
b"HTTP/1.0 200 OK\r\nThis-Header-Is-Too-Long: Way-Too-Long\r\n\r\n" |
| 1471 |
) |
| 1472 |
sock.close() |
| 1473 |
|
| 1474 |
self._start_server(http_socket_handler) |
| 1475 |
base_url = f"http://{self.host}:{self.port}" |
| 1476 |
|
| 1477 |
with mock.patch("http.client._MAXLINE", 17): |
| 1478 |
with ProxyManager(base_url) as proxy: |
| 1479 |
with pytest.raises(MaxRetryError) as e: |
| 1480 |
proxy.request("GET", "https://example.com", retries=0) |
| 1481 |
|
| 1482 |
assert type(e.value.reason) is ProtocolError |
| 1483 |
assert e.value.reason.args[0] == "Connection aborted." |
| 1484 |
assert type(e.value.reason.args[1]) is http.client.LineTooLong |
| 1485 |
assert ( |
| 1486 |
str(e.value.reason.args[1]) |
| 1487 |
== "got more than 17 bytes when reading header line" |
| 1488 |
) |
| 1489 |
|
| 1490 |
def test_debuglevel(self, capsys: pytest.CaptureFixture[str]) -> None: |
| 1491 |
def http_socket_handler(listener: socket.socket) -> None: |
| 1492 |
sock = listener.accept()[0] |
| 1493 |
consume_socket(sock) |
| 1494 |
sock.send(b"HTTP/1.0 200 OK\r\nExample-Header: Example-Value\r\n\r\n") |
| 1495 |
sock.close() |
| 1496 |
|
| 1497 |
self._start_server(http_socket_handler) |
| 1498 |
base_url = f"http://{self.host}:{self.port}" |
| 1499 |
|
| 1500 |
with mock.patch("http.client.HTTPConnection.debuglevel", 1): |
| 1501 |
with ProxyManager(base_url) as proxy: |
| 1502 |
with pytest.raises(MaxRetryError): |
| 1503 |
proxy.request("GET", "https://example.com", retries=0) |
| 1504 |
|
| 1505 |
assert "header: Example-Header: Example-Value\r\n\n" in capsys.readouterr().out |
| 1506 |
|
| 1507 |
|
| 1508 |
class TestSSL(SocketDummyServerTestCase): |
| 1509 |
def test_ssl_failure_midway_through_conn(self) -> None: |
| 1510 |
def socket_handler(listener: socket.socket) -> None: |
| 1511 |
with listener.accept()[0] as sock, sock.dup() as sock2: |
| 1512 |
ssl_sock = original_ssl_wrap_socket( |
| 1513 |
sock, |
| 1514 |
server_side=True, |
| 1515 |
keyfile=DEFAULT_CERTS["keyfile"], |
| 1516 |
certfile=DEFAULT_CERTS["certfile"], |
| 1517 |
ca_certs=DEFAULT_CA, |
| 1518 |
) |
| 1519 |
|
| 1520 |
buf = b"" |
| 1521 |
while not buf.endswith(b"\r\n\r\n"): |
| 1522 |
buf += ssl_sock.recv(65536) |
| 1523 |
|
| 1524 |
# Deliberately send from the non-SSL socket. |
| 1525 |
sock2.send( |
| 1526 |
b"HTTP/1.1 200 OK\r\n" |
| 1527 |
b"Content-Type: text/plain\r\n" |
| 1528 |
b"Content-Length: 2\r\n" |
| 1529 |
b"\r\n" |
| 1530 |
b"Hi" |
| 1531 |
) |
| 1532 |
ssl_sock.close() |
| 1533 |
|
| 1534 |
self._start_server(socket_handler) |
| 1535 |
with HTTPSConnectionPool(self.host, self.port, ca_certs=DEFAULT_CA) as pool: |
| 1536 |
with pytest.raises( |
| 1537 |
SSLError, |
| 1538 |
match=r"(wrong version number|record overflow|record layer failure)", |
| 1539 |
): |
| 1540 |
pool.request("GET", "/", retries=False) |
| 1541 |
|
| 1542 |
def test_ssl_read_timeout(self) -> None: |
| 1543 |
timed_out = Event() |
| 1544 |
|
| 1545 |
def socket_handler(listener: socket.socket) -> None: |
| 1546 |
sock = listener.accept()[0] |
| 1547 |
# disable Nagle's algorithm so there's no delay in sending a partial body |
| 1548 |
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, True) |
| 1549 |
ssl_sock = original_ssl_wrap_socket( |
| 1550 |
sock, |
| 1551 |
server_side=True, |
| 1552 |
keyfile=DEFAULT_CERTS["keyfile"], |
| 1553 |
certfile=DEFAULT_CERTS["certfile"], |
| 1554 |
) |
| 1555 |
|
| 1556 |
buf = b"" |
| 1557 |
while not buf.endswith(b"\r\n\r\n"): |
| 1558 |
buf += ssl_sock.recv(65536) |
| 1559 |
|
| 1560 |
# Send incomplete message (note Content-Length) |
| 1561 |
ssl_sock.send( |
| 1562 |
b"HTTP/1.1 200 OK\r\n" |
| 1563 |
b"Content-Type: text/plain\r\n" |
| 1564 |
b"Content-Length: 10\r\n" |
| 1565 |
b"\r\n" |
| 1566 |
b"Hi-" |
| 1567 |
) |
| 1568 |
timed_out.wait() |
| 1569 |
|
| 1570 |
sock.close() |
| 1571 |
ssl_sock.close() |
| 1572 |
|
| 1573 |
self._start_server(socket_handler) |
| 1574 |
with HTTPSConnectionPool(self.host, self.port, ca_certs=DEFAULT_CA) as pool: |
| 1575 |
response = pool.urlopen( |
| 1576 |
"GET", "/", retries=0, preload_content=False, timeout=LONG_TIMEOUT |
| 1577 |
) |
| 1578 |
try: |
| 1579 |
with pytest.raises(ReadTimeoutError): |
| 1580 |
response.read() |
| 1581 |
finally: |
| 1582 |
timed_out.set() |
| 1583 |
|
| 1584 |
def test_ssl_failed_fingerprint_verification(self) -> None: |
| 1585 |
def socket_handler(listener: socket.socket) -> None: |
| 1586 |
for i in range(2): |
| 1587 |
sock = listener.accept()[0] |
| 1588 |
try: |
| 1589 |
ssl_sock = original_ssl_wrap_socket( |
| 1590 |
sock, |
| 1591 |
server_side=True, |
| 1592 |
keyfile=DEFAULT_CERTS["keyfile"], |
| 1593 |
certfile=DEFAULT_CERTS["certfile"], |
| 1594 |
ca_certs=DEFAULT_CA, |
| 1595 |
) |
| 1596 |
except (ssl.SSLError, ConnectionResetError, ConnectionAbortedError): |
| 1597 |
pass |
| 1598 |
|
| 1599 |
else: |
| 1600 |
with ssl_sock: |
| 1601 |
try: |
| 1602 |
ssl_sock.send( |
| 1603 |
b"HTTP/1.1 200 OK\r\n" |
| 1604 |
b"Content-Type: text/plain\r\n" |
| 1605 |
b"Content-Length: 5\r\n\r\n" |
| 1606 |
b"Hello" |
| 1607 |
) |
| 1608 |
except (ssl.SSLEOFError, ConnectionResetError, BrokenPipeError): |
| 1609 |
pass |
| 1610 |
|
| 1611 |
sock.close() |
| 1612 |
|
| 1613 |
self._start_server(socket_handler) |
| 1614 |
# GitHub's fingerprint. Valid, but not matching. |
| 1615 |
fingerprint = "A0:C4:A7:46:00:ED:A7:2D:C0:BE:CB:9A:8C:B6:07:CA:58:EE:74:5E" |
| 1616 |
|
| 1617 |
def request() -> None: |
| 1618 |
pool = HTTPSConnectionPool( |
| 1619 |
self.host, |
| 1620 |
self.port, |
| 1621 |
assert_fingerprint=fingerprint, |
| 1622 |
cert_reqs="CERT_NONE", |
| 1623 |
) |
| 1624 |
try: |
| 1625 |
timeout = Timeout(connect=LONG_TIMEOUT, read=SHORT_TIMEOUT) |
| 1626 |
response = pool.urlopen( |
| 1627 |
"GET", "/", preload_content=False, retries=0, timeout=timeout |
| 1628 |
) |
| 1629 |
response.read() |
| 1630 |
finally: |
| 1631 |
pool.close() |
| 1632 |
|
| 1633 |
with pytest.raises(MaxRetryError) as cm: |
| 1634 |
request() |
| 1635 |
assert type(cm.value.reason) is SSLError |
| 1636 |
assert str(cm.value.reason) == ( |
| 1637 |
"Fingerprints did not match. Expected " |
| 1638 |
'"a0c4a74600eda72dc0becb9a8cb607ca58ee745e", got ' |
| 1639 |
'"728b554c9afc1e88a11cad1bb2e7cc3edbc8f98a"' |
| 1640 |
) |
| 1641 |
# Should not hang, see https://github.com/urllib3/urllib3/issues/529 |
| 1642 |
with pytest.raises(MaxRetryError) as cm2: |
| 1643 |
request() |
| 1644 |
assert type(cm2.value.reason) is SSLError |
| 1645 |
assert str(cm2.value.reason) == ( |
| 1646 |
"Fingerprints did not match. Expected " |
| 1647 |
'"a0c4a74600eda72dc0becb9a8cb607ca58ee745e", got ' |
| 1648 |
'"728b554c9afc1e88a11cad1bb2e7cc3edbc8f98a"' |
| 1649 |
) |
| 1650 |
|
| 1651 |
def test_retry_ssl_error(self) -> None: |
| 1652 |
def socket_handler(listener: socket.socket) -> None: |
| 1653 |
# first request, trigger an SSLError |
| 1654 |
sock = listener.accept()[0] |
| 1655 |
sock2 = sock.dup() |
| 1656 |
ssl_sock = original_ssl_wrap_socket( |
| 1657 |
sock, |
| 1658 |
server_side=True, |
| 1659 |
keyfile=DEFAULT_CERTS["keyfile"], |
| 1660 |
certfile=DEFAULT_CERTS["certfile"], |
| 1661 |
) |
| 1662 |
buf = b"" |
| 1663 |
while not buf.endswith(b"\r\n\r\n"): |
| 1664 |
buf += ssl_sock.recv(65536) |
| 1665 |
|
| 1666 |
# Deliberately send from the non-SSL socket to trigger an SSLError |
| 1667 |
sock2.send( |
| 1668 |
b"HTTP/1.1 200 OK\r\n" |
| 1669 |
b"Content-Type: text/plain\r\n" |
| 1670 |
b"Content-Length: 4\r\n" |
| 1671 |
b"\r\n" |
| 1672 |
b"Fail" |
| 1673 |
) |
| 1674 |
sock2.close() |
| 1675 |
ssl_sock.close() |
| 1676 |
|
| 1677 |
# retried request |
| 1678 |
sock = listener.accept()[0] |
| 1679 |
ssl_sock = original_ssl_wrap_socket( |
| 1680 |
sock, |
| 1681 |
server_side=True, |
| 1682 |
keyfile=DEFAULT_CERTS["keyfile"], |
| 1683 |
certfile=DEFAULT_CERTS["certfile"], |
| 1684 |
) |
| 1685 |
buf = b"" |
| 1686 |
while not buf.endswith(b"\r\n\r\n"): |
| 1687 |
buf += ssl_sock.recv(65536) |
| 1688 |
ssl_sock.send( |
| 1689 |
b"HTTP/1.1 200 OK\r\n" |
| 1690 |
b"Content-Type: text/plain\r\n" |
| 1691 |
b"Content-Length: 7\r\n\r\n" |
| 1692 |
b"Success" |
| 1693 |
) |
| 1694 |
ssl_sock.close() |
| 1695 |
|
| 1696 |
self._start_server(socket_handler) |
| 1697 |
|
| 1698 |
with HTTPSConnectionPool(self.host, self.port, ca_certs=DEFAULT_CA) as pool: |
| 1699 |
response = pool.urlopen("GET", "/", retries=1) |
| 1700 |
assert response.data == b"Success" |
| 1701 |
|
| 1702 |
def test_ssl_load_default_certs_when_empty(self) -> None: |
| 1703 |
def socket_handler(listener: socket.socket) -> None: |
| 1704 |
sock = listener.accept()[0] |
| 1705 |
try: |
| 1706 |
ssl_sock = original_ssl_wrap_socket( |
| 1707 |
sock, |
| 1708 |
server_side=True, |
| 1709 |
keyfile=DEFAULT_CERTS["keyfile"], |
| 1710 |
certfile=DEFAULT_CERTS["certfile"], |
| 1711 |
ca_certs=DEFAULT_CA, |
| 1712 |
) |
| 1713 |
except (ssl.SSLError, OSError): |
| 1714 |
return |
| 1715 |
|
| 1716 |
buf = b"" |
| 1717 |
while not buf.endswith(b"\r\n\r\n"): |
| 1718 |
buf += ssl_sock.recv(65536) |
| 1719 |
|
| 1720 |
ssl_sock.send( |
| 1721 |
b"HTTP/1.1 200 OK\r\n" |
| 1722 |
b"Content-Type: text/plain\r\n" |
| 1723 |
b"Content-Length: 5\r\n\r\n" |
| 1724 |
b"Hello" |
| 1725 |
) |
| 1726 |
|
| 1727 |
ssl_sock.close() |
| 1728 |
sock.close() |
| 1729 |
|
| 1730 |
context = mock.create_autospec(ssl_.SSLContext) |
| 1731 |
context.load_default_certs = mock.Mock() |
| 1732 |
context.options = 0 |
| 1733 |
|
| 1734 |
class MockSSLSocket: |
| 1735 |
def __init__( |
| 1736 |
self, sock: socket.socket, *args: object, **kwargs: object |
| 1737 |
) -> None: |
| 1738 |
self._sock = sock |
| 1739 |
|
| 1740 |
def close(self) -> None: |
| 1741 |
self._sock.close() |
| 1742 |
|
| 1743 |
context.wrap_socket = MockSSLSocket |
| 1744 |
|
| 1745 |
with mock.patch("urllib3.util.ssl_.SSLContext", lambda *_, **__: context): |
| 1746 |
self._start_server(socket_handler) |
| 1747 |
with HTTPSConnectionPool(self.host, self.port) as pool: |
| 1748 |
# Without a proper `SSLContext`, this request will fail in some |
| 1749 |
# arbitrary way, but we only want to know if load_default_certs() was |
| 1750 |
# called, which is why we accept any `Exception` here. |
| 1751 |
with pytest.raises(Exception): |
| 1752 |
pool.request("GET", "/", timeout=SHORT_TIMEOUT) |
| 1753 |
context.load_default_certs.assert_called_with() |
| 1754 |
|
| 1755 |
def test_ssl_dont_load_default_certs_when_given(self) -> None: |
| 1756 |
def socket_handler(listener: socket.socket) -> None: |
| 1757 |
sock = listener.accept()[0] |
| 1758 |
try: |
| 1759 |
ssl_sock = original_ssl_wrap_socket( |
| 1760 |
sock, |
| 1761 |
server_side=True, |
| 1762 |
keyfile=DEFAULT_CERTS["keyfile"], |
| 1763 |
certfile=DEFAULT_CERTS["certfile"], |
| 1764 |
ca_certs=DEFAULT_CA, |
| 1765 |
) |
| 1766 |
except (ssl.SSLError, OSError): |
| 1767 |
return |
| 1768 |
|
| 1769 |
buf = b"" |
| 1770 |
while not buf.endswith(b"\r\n\r\n"): |
| 1771 |
buf += ssl_sock.recv(65536) |
| 1772 |
|
| 1773 |
ssl_sock.send( |
| 1774 |
b"HTTP/1.1 200 OK\r\n" |
| 1775 |
b"Content-Type: text/plain\r\n" |
| 1776 |
b"Content-Length: 5\r\n\r\n" |
| 1777 |
b"Hello" |
| 1778 |
) |
| 1779 |
|
| 1780 |
ssl_sock.close() |
| 1781 |
sock.close() |
| 1782 |
|
| 1783 |
context = mock.create_autospec(ssl_.SSLContext) |
| 1784 |
context.load_default_certs = mock.Mock() |
| 1785 |
context.options = 0 |
| 1786 |
|
| 1787 |
class MockSSLSocket: |
| 1788 |
def __init__( |
| 1789 |
self, sock: socket.socket, *args: object, **kwargs: object |
| 1790 |
) -> None: |
| 1791 |
self._sock = sock |
| 1792 |
|
| 1793 |
def close(self) -> None: |
| 1794 |
self._sock.close() |
| 1795 |
|
| 1796 |
context.wrap_socket = MockSSLSocket |
| 1797 |
|
| 1798 |
with mock.patch("urllib3.util.ssl_.SSLContext", lambda *_, **__: context): |
| 1799 |
for kwargs in [ |
| 1800 |
{"ca_certs": "/a"}, |
| 1801 |
{"ca_cert_dir": "/a"}, |
| 1802 |
{"ca_certs": "a", "ca_cert_dir": "a"}, |
| 1803 |
{"ssl_context": context}, |
| 1804 |
]: |
| 1805 |
self._start_server(socket_handler) |
| 1806 |
|
| 1807 |
with HTTPSConnectionPool(self.host, self.port, **kwargs) as pool: |
| 1808 |
with pytest.raises(Exception): |
| 1809 |
pool.request("GET", "/", timeout=SHORT_TIMEOUT) |
| 1810 |
context.load_default_certs.assert_not_called() |
| 1811 |
|
| 1812 |
def test_load_verify_locations_exception(self) -> None: |
| 1813 |
""" |
| 1814 |
Ensure that load_verify_locations raises SSLError for all backends |
| 1815 |
""" |
| 1816 |
with pytest.raises(SSLError): |
| 1817 |
ssl_wrap_socket(None, ca_certs="/tmp/fake-file") # type: ignore[call-overload] |
| 1818 |
|
| 1819 |
def test_ssl_custom_validation_failure_terminates(self, tmpdir: Path) -> None: |
| 1820 |
""" |
| 1821 |
Ensure that the underlying socket is terminated if custom validation fails. |
| 1822 |
""" |
| 1823 |
server_closed = Event() |
| 1824 |
|
| 1825 |
def is_closed_socket(sock: socket.socket) -> bool: |
| 1826 |
try: |
| 1827 |
sock.settimeout(SHORT_TIMEOUT) |
| 1828 |
except OSError: |
| 1829 |
return True |
| 1830 |
return False |
| 1831 |
|
| 1832 |
def socket_handler(listener: socket.socket) -> None: |
| 1833 |
sock = listener.accept()[0] |
| 1834 |
try: |
| 1835 |
_ = original_ssl_wrap_socket( |
| 1836 |
sock, |
| 1837 |
server_side=True, |
| 1838 |
keyfile=DEFAULT_CERTS["keyfile"], |
| 1839 |
certfile=DEFAULT_CERTS["certfile"], |
| 1840 |
ca_certs=DEFAULT_CA, |
| 1841 |
) |
| 1842 |
except ConnectionResetError: |
| 1843 |
return |
| 1844 |
except ssl.SSLError as e: |
| 1845 |
assert "alert unknown ca" in str(e) |
| 1846 |
if is_closed_socket(sock): |
| 1847 |
server_closed.set() |
| 1848 |
|
| 1849 |
self._start_server(socket_handler) |
| 1850 |
|
| 1851 |
# client uses a different ca |
| 1852 |
other_ca = trustme.CA() |
| 1853 |
other_ca_path = str(tmpdir / "ca.pem") |
| 1854 |
other_ca.cert_pem.write_to_path(other_ca_path) |
| 1855 |
|
| 1856 |
with HTTPSConnectionPool( |
| 1857 |
self.host, self.port, cert_reqs="REQUIRED", ca_certs=other_ca_path |
| 1858 |
) as pool: |
| 1859 |
with pytest.raises(SSLError): |
| 1860 |
pool.request("GET", "/", retries=False, timeout=LONG_TIMEOUT) |
| 1861 |
assert server_closed.wait(LONG_TIMEOUT), "The socket was not terminated" |
| 1862 |
|
| 1863 |
def _run_preload(self, pool: HTTPSConnectionPool, content_length: int) -> None: |
| 1864 |
response = pool.request("GET", "/") |
| 1865 |
assert len(response.data) == content_length |
| 1866 |
|
| 1867 |
def _run_read_None(self, pool: HTTPSConnectionPool, content_length: int) -> None: |
| 1868 |
response = pool.request("GET", "/", preload_content=False) |
| 1869 |
assert len(response.read(None)) == content_length |
| 1870 |
assert response.read(None) == b"" |
| 1871 |
|
| 1872 |
def _run_read_amt(self, pool: HTTPSConnectionPool, content_length: int) -> None: |
| 1873 |
response = pool.request("GET", "/", preload_content=False) |
| 1874 |
assert len(response.read(content_length)) == content_length |
| 1875 |
assert response.read(5) == b"" |
| 1876 |
|
| 1877 |
def _run_read1_None(self, pool: HTTPSConnectionPool, content_length: int) -> None: |
| 1878 |
response = pool.request("GET", "/", preload_content=False) |
| 1879 |
remaining = content_length |
| 1880 |
while True: |
| 1881 |
chunk = response.read1(None) |
| 1882 |
if not chunk: |
| 1883 |
break |
| 1884 |
remaining -= len(chunk) |
| 1885 |
assert remaining == 0 |
| 1886 |
|
| 1887 |
def _run_read1_amt(self, pool: HTTPSConnectionPool, content_length: int) -> None: |
| 1888 |
response = pool.request("GET", "/", preload_content=False) |
| 1889 |
remaining = content_length |
| 1890 |
while True: |
| 1891 |
chunk = response.read1(content_length) |
| 1892 |
if not chunk: |
| 1893 |
break |
| 1894 |
remaining -= len(chunk) |
| 1895 |
assert remaining == 0 |
| 1896 |
|
| 1897 |
@pytest.mark.integration |
| 1898 |
@pytest.mark.parametrize( |
| 1899 |
"method", |
| 1900 |
[_run_preload, _run_read_None, _run_read_amt, _run_read1_None, _run_read1_amt], |
| 1901 |
) |
| 1902 |
def test_requesting_large_resources_via_ssl( |
| 1903 |
self, method: typing.Callable[[typing.Any, HTTPSConnectionPool, int], None] |
| 1904 |
) -> None: |
| 1905 |
""" |
| 1906 |
Ensure that it is possible to read 2 GiB or more via an SSL |
| 1907 |
socket. |
| 1908 |
https://github.com/urllib3/urllib3/issues/2513 |
| 1909 |
""" |
| 1910 |
content_length = 2**31 # (`int` max value in C) + 1. |
| 1911 |
ssl_ready = Event() |
| 1912 |
|
| 1913 |
def socket_handler(listener: socket.socket) -> None: |
| 1914 |
sock = listener.accept()[0] |
| 1915 |
ssl_sock = original_ssl_wrap_socket( |
| 1916 |
sock, |
| 1917 |
server_side=True, |
| 1918 |
keyfile=DEFAULT_CERTS["keyfile"], |
| 1919 |
certfile=DEFAULT_CERTS["certfile"], |
| 1920 |
ca_certs=DEFAULT_CA, |
| 1921 |
) |
| 1922 |
ssl_ready.set() |
| 1923 |
|
| 1924 |
while not ssl_sock.recv(65536).endswith(b"\r\n\r\n"): |
| 1925 |
continue |
| 1926 |
|
| 1927 |
ssl_sock.send( |
| 1928 |
b"HTTP/1.1 200 OK\r\n" |
| 1929 |
b"Content-Type: text/plain\r\n" |
| 1930 |
b"Content-Length: %d\r\n\r\n" % content_length |
| 1931 |
) |
| 1932 |
|
| 1933 |
chunks = 2 |
| 1934 |
for i in range(chunks): |
| 1935 |
ssl_sock.sendall(bytes(content_length // chunks)) |
| 1936 |
|
| 1937 |
ssl_sock.close() |
| 1938 |
sock.close() |
| 1939 |
|
| 1940 |
self._start_server(socket_handler) |
| 1941 |
ssl_ready.wait(5) |
| 1942 |
with HTTPSConnectionPool( |
| 1943 |
self.host, self.port, ca_certs=DEFAULT_CA, retries=False |
| 1944 |
) as pool: |
| 1945 |
method(self, pool, content_length) |
| 1946 |
|
| 1947 |
|
| 1948 |
class TestErrorWrapping(SocketDummyServerTestCase): |
| 1949 |
def test_bad_statusline(self) -> None: |
| 1950 |
self.start_response_handler( |
| 1951 |
b"HTTP/1.1 Omg What Is This?\r\n" b"Content-Length: 0\r\n" b"\r\n" |
| 1952 |
) |
| 1953 |
with HTTPConnectionPool(self.host, self.port, retries=False) as pool: |
| 1954 |
with pytest.raises(ProtocolError): |
| 1955 |
pool.request("GET", "/") |
| 1956 |
|
| 1957 |
def test_unknown_protocol(self) -> None: |
| 1958 |
self.start_response_handler( |
| 1959 |
b"HTTP/1000 200 OK\r\n" b"Content-Length: 0\r\n" b"\r\n" |
| 1960 |
) |
| 1961 |
with HTTPConnectionPool(self.host, self.port, retries=False) as pool: |
| 1962 |
with pytest.raises(ProtocolError): |
| 1963 |
pool.request("GET", "/") |
| 1964 |
|
| 1965 |
|
| 1966 |
class TestHeaders(SocketDummyServerTestCase): |
| 1967 |
def test_httplib_headers_case_insensitive(self) -> None: |
| 1968 |
self.start_response_handler( |
| 1969 |
b"HTTP/1.1 200 OK\r\n" |
| 1970 |
b"Content-Length: 0\r\n" |
| 1971 |
b"Content-type: text/plain\r\n" |
| 1972 |
b"\r\n" |
| 1973 |
) |
| 1974 |
with HTTPConnectionPool(self.host, self.port, retries=False) as pool: |
| 1975 |
HEADERS = {"Content-Length": "0", "Content-type": "text/plain"} |
| 1976 |
r = pool.request("GET", "/") |
| 1977 |
assert HEADERS == dict(r.headers.items()) # to preserve case sensitivity |
| 1978 |
|
| 1979 |
def start_parsing_handler(self) -> None: |
| 1980 |
self.parsed_headers: typing.OrderedDict[str, str] = OrderedDict() |
| 1981 |
self.received_headers: list[bytes] = [] |
| 1982 |
|
| 1983 |
def socket_handler(listener: socket.socket) -> None: |
| 1984 |
sock = listener.accept()[0] |
| 1985 |
|
| 1986 |
buf = b"" |
| 1987 |
while not buf.endswith(b"\r\n\r\n"): |
| 1988 |
buf += sock.recv(65536) |
| 1989 |
|
| 1990 |
self.received_headers = [ |
| 1991 |
header for header in buf.split(b"\r\n")[1:] if header |
| 1992 |
] |
| 1993 |
|
| 1994 |
for header in self.received_headers: |
| 1995 |
(key, value) = header.split(b": ") |
| 1996 |
self.parsed_headers[key.decode("ascii")] = value.decode("ascii") |
| 1997 |
|
| 1998 |
sock.send(b"HTTP/1.1 204 No Content\r\nContent-Length: 0\r\n\r\n") |
| 1999 |
|
| 2000 |
sock.close() |
| 2001 |
|
| 2002 |
self._start_server(socket_handler) |
| 2003 |
|
| 2004 |
def test_headers_are_sent_with_the_original_case(self) -> None: |
| 2005 |
headers = {"foo": "bar", "bAz": "quux"} |
| 2006 |
|
| 2007 |
self.start_parsing_handler() |
| 2008 |
expected_headers = { |
| 2009 |
"Accept-Encoding": "identity", |
| 2010 |
"Host": f"{self.host}:{self.port}", |
| 2011 |
"User-Agent": _get_default_user_agent(), |
| 2012 |
} |
| 2013 |
expected_headers.update(headers) |
| 2014 |
|
| 2015 |
with HTTPConnectionPool(self.host, self.port, retries=False) as pool: |
| 2016 |
pool.request("GET", "/", headers=HTTPHeaderDict(headers)) |
| 2017 |
assert expected_headers == self.parsed_headers |
| 2018 |
|
| 2019 |
def test_ua_header_can_be_overridden(self) -> None: |
| 2020 |
headers = {"uSeR-AgENt": "Definitely not urllib3!"} |
| 2021 |
|
| 2022 |
self.start_parsing_handler() |
| 2023 |
expected_headers = { |
| 2024 |
"Accept-Encoding": "identity", |
| 2025 |
"Host": f"{self.host}:{self.port}", |
| 2026 |
} |
| 2027 |
expected_headers.update(headers) |
| 2028 |
|
| 2029 |
with HTTPConnectionPool(self.host, self.port, retries=False) as pool: |
| 2030 |
pool.request("GET", "/", headers=HTTPHeaderDict(headers)) |
| 2031 |
assert expected_headers == self.parsed_headers |
| 2032 |
|
| 2033 |
def test_request_headers_are_sent_in_the_original_order(self) -> None: |
| 2034 |
# NOTE: Probability this test gives a false negative is 1/(K!) |
| 2035 |
K = 16 |
| 2036 |
# NOTE: Provide headers in non-sorted order (i.e. reversed) |
| 2037 |
# so that if the internal implementation tries to sort them, |
| 2038 |
# a change will be detected. |
| 2039 |
expected_request_headers = [ |
| 2040 |
(f"X-Header-{int(i)}", str(i)) for i in reversed(range(K)) |
| 2041 |
] |
| 2042 |
|
| 2043 |
def filter_non_x_headers( |
| 2044 |
d: typing.OrderedDict[str, str], |
| 2045 |
) -> list[tuple[str, str]]: |
| 2046 |
return [(k, v) for (k, v) in d.items() if k.startswith("X-Header-")] |
| 2047 |
|
| 2048 |
self.start_parsing_handler() |
| 2049 |
|
| 2050 |
with HTTPConnectionPool(self.host, self.port, retries=False) as pool: |
| 2051 |
pool.request("GET", "/", headers=OrderedDict(expected_request_headers)) |
| 2052 |
assert expected_request_headers == filter_non_x_headers(self.parsed_headers) |
| 2053 |
|
| 2054 |
@resolvesLocalhostFQDN() |
| 2055 |
def test_request_host_header_ignores_fqdn_dot(self) -> None: |
| 2056 |
self.start_parsing_handler() |
| 2057 |
|
| 2058 |
with HTTPConnectionPool(self.host + ".", self.port, retries=False) as pool: |
| 2059 |
pool.request("GET", "/") |
| 2060 |
self.assert_header_received( |
| 2061 |
self.received_headers, "Host", f"{self.host}:{self.port}" |
| 2062 |
) |
| 2063 |
|
| 2064 |
def test_response_headers_are_returned_in_the_original_order(self) -> None: |
| 2065 |
# NOTE: Probability this test gives a false negative is 1/(K!) |
| 2066 |
K = 16 |
| 2067 |
# NOTE: Provide headers in non-sorted order (i.e. reversed) |
| 2068 |
# so that if the internal implementation tries to sort them, |
| 2069 |
# a change will be detected. |
| 2070 |
expected_response_headers = [ |
| 2071 |
(f"X-Header-{int(i)}", str(i)) for i in reversed(range(K)) |
| 2072 |
] |
| 2073 |
|
| 2074 |
def socket_handler(listener: socket.socket) -> None: |
| 2075 |
sock = listener.accept()[0] |
| 2076 |
|
| 2077 |
buf = b"" |
| 2078 |
while not buf.endswith(b"\r\n\r\n"): |
| 2079 |
buf += sock.recv(65536) |
| 2080 |
|
| 2081 |
sock.send( |
| 2082 |
b"HTTP/1.1 200 OK\r\n" |
| 2083 |
+ b"\r\n".join( |
| 2084 |
[ |
| 2085 |
(k.encode("utf8") + b": " + v.encode("utf8")) |
| 2086 |
for (k, v) in expected_response_headers |
| 2087 |
] |
| 2088 |
) |
| 2089 |
+ b"\r\n" |
| 2090 |
) |
| 2091 |
sock.close() |
| 2092 |
|
| 2093 |
self._start_server(socket_handler) |
| 2094 |
with HTTPConnectionPool(self.host, self.port) as pool: |
| 2095 |
r = pool.request("GET", "/", retries=0) |
| 2096 |
actual_response_headers = [ |
| 2097 |
(k, v) for (k, v) in r.headers.items() if k.startswith("X-Header-") |
| 2098 |
] |
| 2099 |
assert expected_response_headers == actual_response_headers |
| 2100 |
|
| 2101 |
@pytest.mark.parametrize( |
| 2102 |
"method_type, body_type", |
| 2103 |
[ |
| 2104 |
("GET", None), |
| 2105 |
("POST", None), |
| 2106 |
("POST", "bytes"), |
| 2107 |
("POST", "bytes-io"), |
| 2108 |
], |
| 2109 |
) |
| 2110 |
def test_headers_sent_with_add( |
| 2111 |
self, method_type: str, body_type: str | None |
| 2112 |
) -> None: |
| 2113 |
""" |
| 2114 |
Confirm that when adding headers with combine=True that we simply append to the |
| 2115 |
most recent value, rather than create a new header line. |
| 2116 |
""" |
| 2117 |
body: None | bytes | io.BytesIO |
| 2118 |
if body_type is None: |
| 2119 |
body = None |
| 2120 |
expected = b"\r\n\r\n" |
| 2121 |
elif body_type == "bytes": |
| 2122 |
body = b"my-body" |
| 2123 |
expected = b"\r\n\r\nmy-body" |
| 2124 |
elif body_type == "bytes-io": |
| 2125 |
body = io.BytesIO(b"bytes-io-body") |
| 2126 |
body.seek(0, 0) |
| 2127 |
expected = b"bytes-io-body\r\n0\r\n\r\n" |
| 2128 |
else: |
| 2129 |
raise ValueError("Unknown body type") |
| 2130 |
|
| 2131 |
buffer: bytes = b"" |
| 2132 |
|
| 2133 |
def socket_handler(listener: socket.socket) -> None: |
| 2134 |
nonlocal buffer |
| 2135 |
sock = listener.accept()[0] |
| 2136 |
sock.settimeout(0) |
| 2137 |
|
| 2138 |
while expected not in buffer: |
| 2139 |
with contextlib.suppress(BlockingIOError): |
| 2140 |
buffer += sock.recv(65536) |
| 2141 |
|
| 2142 |
sock.sendall( |
| 2143 |
b"HTTP/1.1 200 OK\r\n" |
| 2144 |
b"Server: example.com\r\n" |
| 2145 |
b"Content-Length: 0\r\n\r\n" |
| 2146 |
) |
| 2147 |
sock.close() |
| 2148 |
|
| 2149 |
self._start_server(socket_handler) |
| 2150 |
|
| 2151 |
headers = HTTPHeaderDict() |
| 2152 |
headers.add("A", "1") |
| 2153 |
headers.add("C", "3") |
| 2154 |
headers.add("B", "2") |
| 2155 |
headers.add("B", "3") |
| 2156 |
headers.add("A", "4", combine=False) |
| 2157 |
headers.add("C", "5", combine=True) |
| 2158 |
headers.add("C", "6") |
| 2159 |
|
| 2160 |
with HTTPConnectionPool(self.host, self.port, retries=False) as pool: |
| 2161 |
r = pool.request( |
| 2162 |
method_type, |
| 2163 |
"/", |
| 2164 |
body=body, |
| 2165 |
headers=headers, |
| 2166 |
) |
| 2167 |
assert r.status == 200 |
| 2168 |
assert b"A: 1\r\nA: 4\r\nC: 3, 5\r\nC: 6\r\nB: 2\r\nB: 3" in buffer |
| 2169 |
|
| 2170 |
|
| 2171 |
class TestBrokenHeaders(SocketDummyServerTestCase): |
| 2172 |
def _test_broken_header_parsing( |
| 2173 |
self, headers: list[bytes], unparsed_data_check: str | None = None |
| 2174 |
) -> None: |
| 2175 |
self.start_response_handler( |
| 2176 |
( |
| 2177 |
b"HTTP/1.1 200 OK\r\n" |
| 2178 |
b"Content-Length: 0\r\n" |
| 2179 |
b"Content-type: text/plain\r\n" |
| 2180 |
) |
| 2181 |
+ b"\r\n".join(headers) |
| 2182 |
+ b"\r\n\r\n" |
| 2183 |
) |
| 2184 |
|
| 2185 |
with HTTPConnectionPool(self.host, self.port, retries=False) as pool: |
| 2186 |
with LogRecorder() as logs: |
| 2187 |
pool.request("GET", "/") |
| 2188 |
|
| 2189 |
for record in logs: |
| 2190 |
if ( |
| 2191 |
"Failed to parse headers" in record.msg |
| 2192 |
and type(record.args) is tuple |
| 2193 |
and _url_from_pool(pool, "/") == record.args[0] |
| 2194 |
): |
| 2195 |
if ( |
| 2196 |
unparsed_data_check is None |
| 2197 |
or unparsed_data_check in record.getMessage() |
| 2198 |
): |
| 2199 |
return |
| 2200 |
pytest.fail("Missing log about unparsed headers") |
| 2201 |
|
| 2202 |
def test_header_without_name(self) -> None: |
| 2203 |
self._test_broken_header_parsing([b": Value", b"Another: Header"]) |
| 2204 |
|
| 2205 |
def test_header_without_name_or_value(self) -> None: |
| 2206 |
self._test_broken_header_parsing([b":", b"Another: Header"]) |
| 2207 |
|
| 2208 |
def test_header_without_colon_or_value(self) -> None: |
| 2209 |
self._test_broken_header_parsing( |
| 2210 |
[b"Broken Header", b"Another: Header"], "Broken Header" |
| 2211 |
) |
| 2212 |
|
| 2213 |
|
| 2214 |
class TestHeaderParsingContentType(SocketDummyServerTestCase): |
| 2215 |
def _test_okay_header_parsing(self, header: bytes) -> None: |
| 2216 |
self.start_response_handler( |
| 2217 |
(b"HTTP/1.1 200 OK\r\n" b"Content-Length: 0\r\n") + header + b"\r\n\r\n" |
| 2218 |
) |
| 2219 |
|
| 2220 |
with HTTPConnectionPool(self.host, self.port, retries=False) as pool: |
| 2221 |
with LogRecorder() as logs: |
| 2222 |
pool.request("GET", "/") |
| 2223 |
|
| 2224 |
for record in logs: |
| 2225 |
assert "Failed to parse headers" not in record.msg |
| 2226 |
|
| 2227 |
def test_header_text_plain(self) -> None: |
| 2228 |
self._test_okay_header_parsing(b"Content-type: text/plain") |
| 2229 |
|
| 2230 |
def test_header_message_rfc822(self) -> None: |
| 2231 |
self._test_okay_header_parsing(b"Content-type: message/rfc822") |
| 2232 |
|
| 2233 |
|
| 2234 |
class TestHEAD(SocketDummyServerTestCase): |
| 2235 |
def test_chunked_head_response_does_not_hang(self) -> None: |
| 2236 |
self.start_response_handler( |
| 2237 |
b"HTTP/1.1 200 OK\r\n" |
| 2238 |
b"Transfer-Encoding: chunked\r\n" |
| 2239 |
b"Content-type: text/plain\r\n" |
| 2240 |
b"\r\n" |
| 2241 |
) |
| 2242 |
with HTTPConnectionPool(self.host, self.port, retries=False) as pool: |
| 2243 |
r = pool.request("HEAD", "/", timeout=LONG_TIMEOUT, preload_content=False) |
| 2244 |
|
| 2245 |
# stream will use the read_chunked method here. |
| 2246 |
assert [] == list(r.stream()) |
| 2247 |
|
| 2248 |
def test_empty_head_response_does_not_hang(self) -> None: |
| 2249 |
self.start_response_handler( |
| 2250 |
b"HTTP/1.1 200 OK\r\n" |
| 2251 |
b"Content-Length: 256\r\n" |
| 2252 |
b"Content-type: text/plain\r\n" |
| 2253 |
b"\r\n" |
| 2254 |
) |
| 2255 |
with HTTPConnectionPool(self.host, self.port, retries=False) as pool: |
| 2256 |
r = pool.request("HEAD", "/", timeout=LONG_TIMEOUT, preload_content=False) |
| 2257 |
|
| 2258 |
# stream will use the read method here. |
| 2259 |
assert [] == list(r.stream()) |
| 2260 |
|
| 2261 |
|
| 2262 |
class TestStream(SocketDummyServerTestCase): |
| 2263 |
def test_stream_none_unchunked_response_does_not_hang(self) -> None: |
| 2264 |
done_event = Event() |
| 2265 |
|
| 2266 |
def socket_handler(listener: socket.socket) -> None: |
| 2267 |
sock = listener.accept()[0] |
| 2268 |
|
| 2269 |
buf = b"" |
| 2270 |
while not buf.endswith(b"\r\n\r\n"): |
| 2271 |
buf += sock.recv(65536) |
| 2272 |
|
| 2273 |
sock.send( |
| 2274 |
b"HTTP/1.1 200 OK\r\n" |
| 2275 |
b"Content-Length: 12\r\n" |
| 2276 |
b"Content-type: text/plain\r\n" |
| 2277 |
b"\r\n" |
| 2278 |
b"hello, world" |
| 2279 |
) |
| 2280 |
done_event.wait(5) |
| 2281 |
sock.close() |
| 2282 |
|
| 2283 |
self._start_server(socket_handler) |
| 2284 |
with HTTPConnectionPool(self.host, self.port, retries=False) as pool: |
| 2285 |
r = pool.request("GET", "/", timeout=LONG_TIMEOUT, preload_content=False) |
| 2286 |
|
| 2287 |
# Stream should read to the end. |
| 2288 |
assert [b"hello, world"] == list(r.stream(None)) |
| 2289 |
|
| 2290 |
done_event.set() |
| 2291 |
|
| 2292 |
def test_large_compressed_stream(self) -> None: |
| 2293 |
done_event = Event() |
| 2294 |
expected_total_length = 296085 |
| 2295 |
|
| 2296 |
def socket_handler(listener: socket.socket) -> None: |
| 2297 |
compress = zlib.compressobj(6, zlib.DEFLATED, 16 + zlib.MAX_WBITS) |
| 2298 |
data = compress.compress(b"x" * expected_total_length) |
| 2299 |
data += compress.flush() |
| 2300 |
|
| 2301 |
sock = listener.accept()[0] |
| 2302 |
|
| 2303 |
buf = b"" |
| 2304 |
while not buf.endswith(b"\r\n\r\n"): |
| 2305 |
buf += sock.recv(65536) |
| 2306 |
|
| 2307 |
sock.sendall( |
| 2308 |
b"HTTP/1.1 200 OK\r\n" |
| 2309 |
b"Content-Length: %d\r\n" |
| 2310 |
b"Content-Encoding: gzip\r\n" |
| 2311 |
b"\r\n" % (len(data),) + data |
| 2312 |
) |
| 2313 |
|
| 2314 |
done_event.wait(5) |
| 2315 |
sock.close() |
| 2316 |
|
| 2317 |
self._start_server(socket_handler) |
| 2318 |
|
| 2319 |
with HTTPConnectionPool(self.host, self.port, retries=False) as pool: |
| 2320 |
r = pool.request("GET", "/", timeout=LONG_TIMEOUT, preload_content=False) |
| 2321 |
|
| 2322 |
# Chunks must all be equal or less than 10240 |
| 2323 |
# and only the last chunk is allowed to be smaller |
| 2324 |
# than 10240. |
| 2325 |
total_length = 0 |
| 2326 |
chunks_smaller_than_10240 = 0 |
| 2327 |
for chunk in r.stream(10240, decode_content=True): |
| 2328 |
assert 0 < len(chunk) <= 10240 |
| 2329 |
if len(chunk) < 10240: |
| 2330 |
chunks_smaller_than_10240 += 1 |
| 2331 |
else: |
| 2332 |
assert chunks_smaller_than_10240 == 0 |
| 2333 |
total_length += len(chunk) |
| 2334 |
|
| 2335 |
assert chunks_smaller_than_10240 == 1 |
| 2336 |
assert expected_total_length == total_length |
| 2337 |
|
| 2338 |
done_event.set() |
| 2339 |
|
| 2340 |
|
| 2341 |
class TestBadContentLength(SocketDummyServerTestCase): |
| 2342 |
def test_enforce_content_length_get(self) -> None: |
| 2343 |
done_event = Event() |
| 2344 |
|
| 2345 |
def socket_handler(listener: socket.socket) -> None: |
| 2346 |
sock = listener.accept()[0] |
| 2347 |
|
| 2348 |
buf = b"" |
| 2349 |
while not buf.endswith(b"\r\n\r\n"): |
| 2350 |
buf += sock.recv(65536) |
| 2351 |
|
| 2352 |
sock.send( |
| 2353 |
b"HTTP/1.1 200 OK\r\n" |
| 2354 |
b"Content-Length: 22\r\n" |
| 2355 |
b"Content-type: text/plain\r\n" |
| 2356 |
b"\r\n" |
| 2357 |
b"hello, world" |
| 2358 |
) |
| 2359 |
done_event.wait(LONG_TIMEOUT) |
| 2360 |
sock.close() |
| 2361 |
|
| 2362 |
self._start_server(socket_handler) |
| 2363 |
with HTTPConnectionPool(self.host, self.port, maxsize=1) as conn: |
| 2364 |
# Test stream read when content length less than headers claim |
| 2365 |
get_response = conn.request( |
| 2366 |
"GET", url="/", preload_content=False, enforce_content_length=True |
| 2367 |
) |
| 2368 |
data = get_response.stream(100) |
| 2369 |
with pytest.raises(ProtocolError, match="12 bytes read, 10 more expected"): |
| 2370 |
next(data) |
| 2371 |
done_event.set() |
| 2372 |
|
| 2373 |
def test_enforce_content_length_no_body(self) -> None: |
| 2374 |
done_event = Event() |
| 2375 |
|
| 2376 |
def socket_handler(listener: socket.socket) -> None: |
| 2377 |
sock = listener.accept()[0] |
| 2378 |
|
| 2379 |
buf = b"" |
| 2380 |
while not buf.endswith(b"\r\n\r\n"): |
| 2381 |
buf += sock.recv(65536) |
| 2382 |
|
| 2383 |
sock.send( |
| 2384 |
b"HTTP/1.1 200 OK\r\n" |
| 2385 |
b"Content-Length: 22\r\n" |
| 2386 |
b"Content-type: text/plain\r\n" |
| 2387 |
b"\r\n" |
| 2388 |
) |
| 2389 |
done_event.wait(1) |
| 2390 |
sock.close() |
| 2391 |
|
| 2392 |
self._start_server(socket_handler) |
| 2393 |
with HTTPConnectionPool(self.host, self.port, maxsize=1) as conn: |
| 2394 |
# Test stream on 0 length body |
| 2395 |
head_response = conn.request( |
| 2396 |
"HEAD", url="/", preload_content=False, enforce_content_length=True |
| 2397 |
) |
| 2398 |
data = [chunk for chunk in head_response.stream(1)] |
| 2399 |
assert len(data) == 0 |
| 2400 |
|
| 2401 |
done_event.set() |
| 2402 |
|
| 2403 |
|
| 2404 |
class TestRetryPoolSizeDrainFail(SocketDummyServerTestCase): |
| 2405 |
def test_pool_size_retry_drain_fail(self) -> None: |
| 2406 |
def socket_handler(listener: socket.socket) -> None: |
| 2407 |
for _ in range(2): |
| 2408 |
sock = listener.accept()[0] |
| 2409 |
while not sock.recv(65536).endswith(b"\r\n\r\n"): |
| 2410 |
pass |
| 2411 |
|
| 2412 |
# send a response with an invalid content length -- this causes |
| 2413 |
# a ProtocolError to raise when trying to drain the connection |
| 2414 |
sock.send( |
| 2415 |
b"HTTP/1.1 404 NOT FOUND\r\n" |
| 2416 |
b"Content-Length: 1000\r\n" |
| 2417 |
b"Content-Type: text/plain\r\n" |
| 2418 |
b"\r\n" |
| 2419 |
) |
| 2420 |
sock.close() |
| 2421 |
|
| 2422 |
self._start_server(socket_handler) |
| 2423 |
retries = Retry(total=1, raise_on_status=False, status_forcelist=[404]) |
| 2424 |
with HTTPConnectionPool( |
| 2425 |
self.host, self.port, maxsize=10, retries=retries, block=True |
| 2426 |
) as pool: |
| 2427 |
pool.urlopen("GET", "/not_found", preload_content=False) |
| 2428 |
assert pool.num_connections == 1 |
| 2429 |
|
| 2430 |
|
| 2431 |
class TestBrokenPipe(SocketDummyServerTestCase): |
| 2432 |
@notWindows() |
| 2433 |
def test_ignore_broken_pipe_errors(self, monkeypatch: pytest.MonkeyPatch) -> None: |
| 2434 |
# On Windows an aborted connection raises an error on |
| 2435 |
# attempts to read data out of a socket that's been closed. |
| 2436 |
sock_shut = Event() |
| 2437 |
orig_connect = HTTPConnection.connect |
| 2438 |
# a buffer that will cause two sendall calls |
| 2439 |
buf = "a" * 1024 * 1024 * 4 |
| 2440 |
|
| 2441 |
def connect_and_wait(*args: typing.Any, **kw: typing.Any) -> None: |
| 2442 |
ret = orig_connect(*args, **kw) |
| 2443 |
assert sock_shut.wait(5) |
| 2444 |
return ret |
| 2445 |
|
| 2446 |
def socket_handler(listener: socket.socket) -> None: |
| 2447 |
for i in range(2): |
| 2448 |
sock = listener.accept()[0] |
| 2449 |
sock.send( |
| 2450 |
b"HTTP/1.1 404 Not Found\r\n" |
| 2451 |
b"Connection: close\r\n" |
| 2452 |
b"Content-Length: 10\r\n" |
| 2453 |
b"\r\n" |
| 2454 |
b"xxxxxxxxxx" |
| 2455 |
) |
| 2456 |
sock.shutdown(socket.SHUT_RDWR) |
| 2457 |
sock_shut.set() |
| 2458 |
sock.close() |
| 2459 |
|
| 2460 |
monkeypatch.setattr(HTTPConnection, "connect", connect_and_wait) |
| 2461 |
self._start_server(socket_handler) |
| 2462 |
with HTTPConnectionPool(self.host, self.port) as pool: |
| 2463 |
r = pool.request("POST", "/", body=buf) |
| 2464 |
assert r.status == 404 |
| 2465 |
assert r.headers["content-length"] == "10" |
| 2466 |
assert r.data == b"xxxxxxxxxx" |
| 2467 |
|
| 2468 |
r = pool.request("POST", "/admin", chunked=True, body=buf) |
| 2469 |
assert r.status == 404 |
| 2470 |
assert r.headers["content-length"] == "10" |
| 2471 |
assert r.data == b"xxxxxxxxxx" |
| 2472 |
|
| 2473 |
|
| 2474 |
class TestMultipartResponse(SocketDummyServerTestCase): |
| 2475 |
def test_multipart_assert_header_parsing_no_defects(self) -> None: |
| 2476 |
quit_event = threading.Event() |
| 2477 |
|
| 2478 |
def socket_handler(listener: socket.socket) -> None: |
| 2479 |
for _ in range(2): |
| 2480 |
listener.settimeout(LONG_TIMEOUT) |
| 2481 |
|
| 2482 |
while True: |
| 2483 |
if quit_event and quit_event.is_set(): |
| 2484 |
return |
| 2485 |
try: |
| 2486 |
sock = listener.accept()[0] |
| 2487 |
break |
| 2488 |
except TimeoutError: |
| 2489 |
continue |
| 2490 |
|
| 2491 |
sock.settimeout(LONG_TIMEOUT) |
| 2492 |
while True: |
| 2493 |
if quit_event and quit_event.is_set(): |
| 2494 |
sock.close() |
| 2495 |
return |
| 2496 |
if sock.recv(65536).endswith(b"\r\n\r\n"): |
| 2497 |
break |
| 2498 |
|
| 2499 |
sock.sendall( |
| 2500 |
b"HTTP/1.1 404 Not Found\r\n" |
| 2501 |
b"Server: example.com\r\n" |
| 2502 |
b"Content-Type: multipart/mixed; boundary=36eeb8c4e26d842a\r\n" |
| 2503 |
b"Content-Length: 73\r\n" |
| 2504 |
b"\r\n" |
| 2505 |
b"--36eeb8c4e26d842a\r\n" |
| 2506 |
b"Content-Type: text/plain\r\n" |
| 2507 |
b"\r\n" |
| 2508 |
b"1\r\n" |
| 2509 |
b"--36eeb8c4e26d842a--\r\n", |
| 2510 |
) |
| 2511 |
sock.close() |
| 2512 |
|
| 2513 |
self._start_server(socket_handler, quit_event=quit_event) |
| 2514 |
from urllib3.connectionpool import log |
| 2515 |
|
| 2516 |
with mock.patch.object(log, "warning") as log_warning: |
| 2517 |
with HTTPConnectionPool(self.host, self.port, timeout=LONG_TIMEOUT) as pool: |
| 2518 |
resp = pool.urlopen("GET", "/") |
| 2519 |
assert resp.status == 404 |
| 2520 |
assert ( |
| 2521 |
resp.headers["content-type"] |
| 2522 |
== "multipart/mixed; boundary=36eeb8c4e26d842a" |
| 2523 |
) |
| 2524 |
assert len(resp.data) == 73 |
| 2525 |
log_warning.assert_not_called() |
| 2526 |
|
| 2527 |
|
| 2528 |
class TestContentFraming(SocketDummyServerTestCase): |
| 2529 |
@pytest.mark.parametrize("content_length", [None, 0]) |
| 2530 |
@pytest.mark.parametrize("method", ["POST", "PUT", "PATCH"]) |
| 2531 |
def test_content_length_0_by_default( |
| 2532 |
self, method: str, content_length: int | None |
| 2533 |
) -> None: |
| 2534 |
buffer = bytearray() |
| 2535 |
|
| 2536 |
def socket_handler(listener: socket.socket) -> None: |
| 2537 |
nonlocal buffer |
| 2538 |
sock = listener.accept()[0] |
| 2539 |
while not buffer.endswith(b"\r\n\r\n"): |
| 2540 |
buffer += sock.recv(65536) |
| 2541 |
sock.sendall( |
| 2542 |
b"HTTP/1.1 200 OK\r\n" |
| 2543 |
b"Server: example.com\r\n" |
| 2544 |
b"Content-Length: 0\r\n\r\n" |
| 2545 |
) |
| 2546 |
sock.close() |
| 2547 |
|
| 2548 |
self._start_server(socket_handler) |
| 2549 |
|
| 2550 |
headers = {} |
| 2551 |
if content_length is not None: |
| 2552 |
headers["Content-Length"] = str(content_length) |
| 2553 |
|
| 2554 |
with HTTPConnectionPool(self.host, self.port, timeout=3) as pool: |
| 2555 |
resp = pool.request(method, "/") |
| 2556 |
assert resp.status == 200 |
| 2557 |
|
| 2558 |
sent_bytes = bytes(buffer) |
| 2559 |
assert b"Accept-Encoding: identity\r\n" in sent_bytes |
| 2560 |
assert b"Content-Length: 0\r\n" in sent_bytes |
| 2561 |
assert b"transfer-encoding" not in sent_bytes.lower() |
| 2562 |
|
| 2563 |
@pytest.mark.parametrize("chunked", [True, False]) |
| 2564 |
@pytest.mark.parametrize("method", ["POST", "PUT", "PATCH"]) |
| 2565 |
@pytest.mark.parametrize("body_type", ["file", "generator", "bytes"]) |
| 2566 |
def test_chunked_specified( |
| 2567 |
self, method: str, chunked: bool, body_type: str |
| 2568 |
) -> None: |
| 2569 |
quit_event = threading.Event() |
| 2570 |
buffer = bytearray() |
| 2571 |
expected_bytes = b"\r\n\r\na\r\nxxxxxxxxxx\r\n0\r\n\r\n" |
| 2572 |
|
| 2573 |
def socket_handler(listener: socket.socket) -> None: |
| 2574 |
nonlocal buffer |
| 2575 |
listener.settimeout(LONG_TIMEOUT) |
| 2576 |
while True: |
| 2577 |
if quit_event.is_set(): |
| 2578 |
return |
| 2579 |
try: |
| 2580 |
sock = listener.accept()[0] |
| 2581 |
break |
| 2582 |
except TimeoutError: |
| 2583 |
continue |
| 2584 |
sock.settimeout(LONG_TIMEOUT) |
| 2585 |
|
| 2586 |
while expected_bytes not in buffer: |
| 2587 |
if quit_event.is_set(): |
| 2588 |
return |
| 2589 |
with contextlib.suppress(BlockingIOError): |
| 2590 |
buffer += sock.recv(65536) |
| 2591 |
|
| 2592 |
sock.sendall( |
| 2593 |
b"HTTP/1.1 200 OK\r\n" |
| 2594 |
b"Server: example.com\r\n" |
| 2595 |
b"Content-Length: 0\r\n\r\n" |
| 2596 |
) |
| 2597 |
sock.close() |
| 2598 |
|
| 2599 |
self._start_server(socket_handler, quit_event=quit_event) |
| 2600 |
|
| 2601 |
body: typing.Any |
| 2602 |
if body_type == "generator": |
| 2603 |
|
| 2604 |
def body_generator() -> typing.Generator[bytes]: |
| 2605 |
yield b"x" * 10 |
| 2606 |
|
| 2607 |
body = body_generator() |
| 2608 |
elif body_type == "file": |
| 2609 |
body = io.BytesIO(b"x" * 10) |
| 2610 |
body.seek(0, 0) |
| 2611 |
else: |
| 2612 |
if chunked is False: |
| 2613 |
pytest.skip("urllib3 uses Content-Length in this case") |
| 2614 |
body = b"x" * 10 |
| 2615 |
|
| 2616 |
with HTTPConnectionPool( |
| 2617 |
self.host, self.port, timeout=LONG_TIMEOUT, retries=False |
| 2618 |
) as pool: |
| 2619 |
resp = pool.request(method, "/", chunked=chunked, body=body) |
| 2620 |
assert resp.status == 200 |
| 2621 |
|
| 2622 |
sent_bytes = bytes(buffer) |
| 2623 |
assert sent_bytes.count(b":") == 5 |
| 2624 |
assert b"Host: localhost:" in sent_bytes |
| 2625 |
assert b"Accept-Encoding: identity\r\n" in sent_bytes |
| 2626 |
assert b"Transfer-Encoding: chunked\r\n" in sent_bytes |
| 2627 |
assert b"User-Agent: python-urllib3/" in sent_bytes |
| 2628 |
assert b"content-length" not in sent_bytes.lower() |
| 2629 |
assert expected_bytes in sent_bytes |
| 2630 |
|
| 2631 |
@pytest.mark.parametrize("method", ["POST", "PUT", "PATCH"]) |
| 2632 |
@pytest.mark.parametrize( |
| 2633 |
"body_type", ["file", "generator", "bytes", "bytearray", "file_text"] |
| 2634 |
) |
| 2635 |
def test_chunked_not_specified(self, method: str, body_type: str) -> None: |
| 2636 |
buffer = bytearray() |
| 2637 |
expected_bytes: bytes |
| 2638 |
body: typing.Any |
| 2639 |
|
| 2640 |
if body_type == "generator": |
| 2641 |
|
| 2642 |
def body_generator() -> typing.Generator[bytes]: |
| 2643 |
yield b"x" * 10 |
| 2644 |
|
| 2645 |
body = body_generator() |
| 2646 |
should_be_chunked = True |
| 2647 |
elif body_type == "file": |
| 2648 |
body = io.BytesIO(b"x" * 10) |
| 2649 |
body.seek(0, 0) |
| 2650 |
should_be_chunked = True |
| 2651 |
elif body_type == "file_text": |
| 2652 |
body = io.StringIO("x" * 10) |
| 2653 |
body.seek(0, 0) |
| 2654 |
should_be_chunked = True |
| 2655 |
elif body_type == "bytearray": |
| 2656 |
body = bytearray(b"x" * 10) |
| 2657 |
should_be_chunked = False |
| 2658 |
else: |
| 2659 |
body = b"x" * 10 |
| 2660 |
should_be_chunked = False |
| 2661 |
|
| 2662 |
if should_be_chunked: |
| 2663 |
expected_bytes = b"\r\n\r\na\r\nxxxxxxxxxx\r\n0\r\n\r\n" |
| 2664 |
else: |
| 2665 |
expected_bytes = b"\r\n\r\nxxxxxxxxxx" |
| 2666 |
|
| 2667 |
def socket_handler(listener: socket.socket) -> None: |
| 2668 |
nonlocal buffer |
| 2669 |
sock = listener.accept()[0] |
| 2670 |
sock.settimeout(0) |
| 2671 |
|
| 2672 |
while expected_bytes not in buffer: |
| 2673 |
with contextlib.suppress(BlockingIOError): |
| 2674 |
buffer += sock.recv(65536) |
| 2675 |
|
| 2676 |
sock.sendall( |
| 2677 |
b"HTTP/1.1 200 OK\r\n" |
| 2678 |
b"Server: example.com\r\n" |
| 2679 |
b"Content-Length: 0\r\n\r\n" |
| 2680 |
) |
| 2681 |
sock.close() |
| 2682 |
|
| 2683 |
self._start_server(socket_handler) |
| 2684 |
|
| 2685 |
with HTTPConnectionPool( |
| 2686 |
self.host, self.port, timeout=LONG_TIMEOUT, retries=False |
| 2687 |
) as pool: |
| 2688 |
resp = pool.request(method, "/", body=body) |
| 2689 |
assert resp.status == 200 |
| 2690 |
|
| 2691 |
sent_bytes = bytes(buffer) |
| 2692 |
assert sent_bytes.count(b":") == 5 |
| 2693 |
assert b"Host: localhost:" in sent_bytes |
| 2694 |
assert b"Accept-Encoding: identity\r\n" in sent_bytes |
| 2695 |
assert b"User-Agent: python-urllib3/" in sent_bytes |
| 2696 |
|
| 2697 |
if should_be_chunked: |
| 2698 |
assert b"content-length" not in sent_bytes.lower() |
| 2699 |
assert b"Transfer-Encoding: chunked\r\n" in sent_bytes |
| 2700 |
assert expected_bytes in sent_bytes |
| 2701 |
|
| 2702 |
else: |
| 2703 |
assert b"Content-Length: 10\r\n" in sent_bytes |
| 2704 |
assert b"transfer-encoding" not in sent_bytes.lower() |
| 2705 |
assert sent_bytes.endswith(expected_bytes) |
| 2706 |
|
| 2707 |
@pytest.mark.parametrize( |
| 2708 |
"header_transform", |
| 2709 |
[str.lower, str.title, str.upper], |
| 2710 |
) |
| 2711 |
@pytest.mark.parametrize( |
| 2712 |
["header", "header_value", "expected"], |
| 2713 |
[ |
| 2714 |
("content-length", "10", b": 10\r\n\r\nxxxxxxxx"), |
| 2715 |
( |
| 2716 |
"transfer-encoding", |
| 2717 |
"chunked", |
| 2718 |
b": chunked\r\n\r\n8\r\nxxxxxxxx\r\n0\r\n\r\n", |
| 2719 |
), |
| 2720 |
], |
| 2721 |
) |
| 2722 |
def test_framing_set_via_headers( |
| 2723 |
self, |
| 2724 |
header_transform: typing.Callable[[str], str], |
| 2725 |
header: str, |
| 2726 |
header_value: str, |
| 2727 |
expected: bytes, |
| 2728 |
) -> None: |
| 2729 |
buffer = bytearray() |
| 2730 |
|
| 2731 |
def socket_handler(listener: socket.socket) -> None: |
| 2732 |
nonlocal buffer |
| 2733 |
sock = listener.accept()[0] |
| 2734 |
sock.settimeout(0) |
| 2735 |
|
| 2736 |
while expected not in buffer: |
| 2737 |
with contextlib.suppress(BlockingIOError): |
| 2738 |
buffer += sock.recv(65536) |
| 2739 |
|
| 2740 |
sock.sendall( |
| 2741 |
b"HTTP/1.1 200 OK\r\n" |
| 2742 |
b"Server: example.com\r\n" |
| 2743 |
b"Content-Length: 0\r\n\r\n" |
| 2744 |
) |
| 2745 |
sock.close() |
| 2746 |
|
| 2747 |
self._start_server(socket_handler) |
| 2748 |
|
| 2749 |
with HTTPConnectionPool( |
| 2750 |
self.host, self.port, timeout=LONG_TIMEOUT, retries=False |
| 2751 |
) as pool: |
| 2752 |
resp = pool.request( |
| 2753 |
"POST", |
| 2754 |
"/", |
| 2755 |
body=b"xxxxxxxx", |
| 2756 |
headers={header_transform(header): header_value}, |
| 2757 |
) |
| 2758 |
assert resp.status == 200 |
| 2759 |
|
| 2760 |
sent_bytes = bytes(buffer) |
| 2761 |
assert sent_bytes.endswith(expected) |