1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929
|
# TODO: Break this module up into pieces. Maybe group by functionality tested
# rather than the socket level-ness of it.
from dummyserver.server import (
DEFAULT_CA,
DEFAULT_CERTS,
encrypt_key_pem,
get_unreachable_address,
)
from dummyserver.testcase import SocketDummyServerTestCase, consume_socket
from urllib3 import HTTPConnectionPool, HTTPSConnectionPool, util
from urllib3._collections import HTTPHeaderDict
from urllib3.connection import HTTPConnection, _get_default_user_agent
from urllib3.exceptions import (
MaxRetryError,
ProtocolError,
ProxyError,
ReadTimeoutError,
SSLError,
)
from six.moves import http_client as httplib
from urllib3.poolmanager import proxy_from_url
from urllib3.util import ssl_, ssl_wrap_socket
from urllib3.util.retry import Retry
from urllib3.util.timeout import Timeout
from .. import LogRecorder, has_alpn, onlyPy3
try:
from mimetools import Message as MimeToolMessage
except ImportError:
class MimeToolMessage(object):
pass
import os
import os.path
import select
import shutil
import socket
import ssl
import tempfile
from collections import OrderedDict
from test import (
LONG_TIMEOUT,
SHORT_TIMEOUT,
notPyPy2,
notSecureTransport,
notWindows,
requires_ssl_context_keyfile_password,
resolvesLocalhostFQDN,
)
from threading import Event
import mock
import pytest
import trustme
# Retry failed tests
pytestmark = pytest.mark.flaky
class TestCookies(SocketDummyServerTestCase):
def test_multi_setcookie(self):
def multicookie_response_handler(listener):
sock = listener.accept()[0]
buf = b""
while not buf.endswith(b"\r\n\r\n"):
buf += sock.recv(65536)
sock.send(
b"HTTP/1.1 200 OK\r\n"
b"Set-Cookie: foo=1\r\n"
b"Set-Cookie: bar=1\r\n"
b"\r\n"
)
sock.close()
self._start_server(multicookie_response_handler)
with HTTPConnectionPool(self.host, self.port) as pool:
r = pool.request("GET", "/", retries=0)
assert r.headers == {"set-cookie": "foo=1, bar=1"}
assert r.headers.getlist("set-cookie") == ["foo=1", "bar=1"]
class TestSNI(SocketDummyServerTestCase):
def test_hostname_in_first_request_packet(self):
if not util.HAS_SNI:
pytest.skip("SNI-support not available")
done_receiving = Event()
self.buf = b""
def socket_handler(listener):
sock = listener.accept()[0]
self.buf = sock.recv(65536) # We only accept one packet
done_receiving.set() # let the test know it can proceed
sock.close()
self._start_server(socket_handler)
with HTTPSConnectionPool(self.host, self.port) as pool:
try:
pool.request("GET", "/", retries=0)
except MaxRetryError: # We are violating the protocol
pass
successful = done_receiving.wait(LONG_TIMEOUT)
assert successful, "Timed out waiting for connection accept"
assert (
self.host.encode("ascii") in self.buf
), "missing hostname in SSL handshake"
class TestALPN(SocketDummyServerTestCase):
def test_alpn_protocol_in_first_request_packet(self):
if not has_alpn():
pytest.skip("ALPN-support not available")
done_receiving = Event()
self.buf = b""
def socket_handler(listener):
sock = listener.accept()[0]
self.buf = sock.recv(65536) # We only accept one packet
done_receiving.set() # let the test know it can proceed
sock.close()
self._start_server(socket_handler)
with HTTPSConnectionPool(self.host, self.port) as pool:
try:
pool.request("GET", "/", retries=0)
except MaxRetryError: # We are violating the protocol
pass
successful = done_receiving.wait(LONG_TIMEOUT)
assert successful, "Timed out waiting for connection accept"
for protocol in util.ALPN_PROTOCOLS:
assert (
protocol.encode("ascii") in self.buf
), "missing ALPN protocol in SSL handshake"
class TestClientCerts(SocketDummyServerTestCase):
"""
Tests for client certificate support.
"""
@classmethod
def setup_class(cls):
cls.tmpdir = tempfile.mkdtemp()
ca = trustme.CA()
cert = ca.issue_cert(u"localhost")
encrypted_key = encrypt_key_pem(cert.private_key_pem, b"letmein")
cls.ca_path = os.path.join(cls.tmpdir, "ca.pem")
cls.cert_combined_path = os.path.join(cls.tmpdir, "server.combined.pem")
cls.cert_path = os.path.join(cls.tmpdir, "server.pem")
cls.key_path = os.path.join(cls.tmpdir, "key.pem")
cls.password_key_path = os.path.join(cls.tmpdir, "password_key.pem")
ca.cert_pem.write_to_path(cls.ca_path)
cert.private_key_and_cert_chain_pem.write_to_path(cls.cert_combined_path)
cert.cert_chain_pems[0].write_to_path(cls.cert_path)
cert.private_key_pem.write_to_path(cls.key_path)
encrypted_key.write_to_path(cls.password_key_path)
def teardown_class(cls):
shutil.rmtree(cls.tmpdir)
def _wrap_in_ssl(self, sock):
"""
Given a single socket, wraps it in TLS.
"""
return ssl.wrap_socket(
sock,
ssl_version=ssl.PROTOCOL_SSLv23,
cert_reqs=ssl.CERT_REQUIRED,
ca_certs=self.ca_path,
certfile=self.cert_path,
keyfile=self.key_path,
server_side=True,
)
def test_client_certs_two_files(self):
"""
Having a client cert in a separate file to its associated key works
properly.
"""
done_receiving = Event()
client_certs = []
def socket_handler(listener):
sock = listener.accept()[0]
sock = self._wrap_in_ssl(sock)
client_certs.append(sock.getpeercert())
data = b""
while not data.endswith(b"\r\n\r\n"):
data += sock.recv(8192)
sock.sendall(
b"HTTP/1.1 200 OK\r\n"
b"Server: testsocket\r\n"
b"Connection: close\r\n"
b"Content-Length: 6\r\n"
b"\r\n"
b"Valid!"
)
done_receiving.wait(5)
sock.close()
self._start_server(socket_handler)
with HTTPSConnectionPool(
self.host,
self.port,
cert_file=self.cert_path,
key_file=self.key_path,
cert_reqs="REQUIRED",
ca_certs=self.ca_path,
) as pool:
pool.request("GET", "/", retries=0)
done_receiving.set()
assert len(client_certs) == 1
def test_client_certs_one_file(self):
"""
Having a client cert and its associated private key in just one file
works properly.
"""
done_receiving = Event()
client_certs = []
def socket_handler(listener):
sock = listener.accept()[0]
sock = self._wrap_in_ssl(sock)
client_certs.append(sock.getpeercert())
data = b""
while not data.endswith(b"\r\n\r\n"):
data += sock.recv(8192)
sock.sendall(
b"HTTP/1.1 200 OK\r\n"
b"Server: testsocket\r\n"
b"Connection: close\r\n"
b"Content-Length: 6\r\n"
b"\r\n"
b"Valid!"
)
done_receiving.wait(5)
sock.close()
self._start_server(socket_handler)
with HTTPSConnectionPool(
self.host,
self.port,
cert_file=self.cert_combined_path,
cert_reqs="REQUIRED",
ca_certs=self.ca_path,
) as pool:
pool.request("GET", "/", retries=0)
done_receiving.set()
assert len(client_certs) == 1
def test_missing_client_certs_raises_error(self):
"""
Having client certs not be present causes an error.
"""
done_receiving = Event()
def socket_handler(listener):
sock = listener.accept()[0]
try:
self._wrap_in_ssl(sock)
except ssl.SSLError:
pass
done_receiving.wait(5)
sock.close()
self._start_server(socket_handler)
with HTTPSConnectionPool(
self.host, self.port, cert_reqs="REQUIRED", ca_certs=self.ca_path
) as pool:
with pytest.raises(MaxRetryError):
pool.request("GET", "/", retries=0)
done_receiving.set()
done_receiving.set()
@requires_ssl_context_keyfile_password
def test_client_cert_with_string_password(self):
self.run_client_cert_with_password_test(u"letmein")
@requires_ssl_context_keyfile_password
def test_client_cert_with_bytes_password(self):
self.run_client_cert_with_password_test(b"letmein")
def run_client_cert_with_password_test(self, password):
"""
Tests client certificate password functionality
"""
done_receiving = Event()
client_certs = []
def socket_handler(listener):
sock = listener.accept()[0]
sock = self._wrap_in_ssl(sock)
client_certs.append(sock.getpeercert())
data = b""
while not data.endswith(b"\r\n\r\n"):
data += sock.recv(8192)
sock.sendall(
b"HTTP/1.1 200 OK\r\n"
b"Server: testsocket\r\n"
b"Connection: close\r\n"
b"Content-Length: 6\r\n"
b"\r\n"
b"Valid!"
)
done_receiving.wait(5)
sock.close()
self._start_server(socket_handler)
ssl_context = ssl_.SSLContext(ssl_.PROTOCOL_SSLv23)
ssl_context.load_cert_chain(
certfile=self.cert_path, keyfile=self.password_key_path, password=password
)
with HTTPSConnectionPool(
self.host,
self.port,
ssl_context=ssl_context,
cert_reqs="REQUIRED",
ca_certs=self.ca_path,
) as pool:
pool.request("GET", "/", retries=0)
done_receiving.set()
assert len(client_certs) == 1
@requires_ssl_context_keyfile_password
def test_load_keyfile_with_invalid_password(self):
context = ssl_.SSLContext(ssl_.PROTOCOL_SSLv23)
# Different error is raised depending on context.
if ssl_.IS_PYOPENSSL:
from OpenSSL.SSL import Error
expected_error = Error
else:
expected_error = ssl.SSLError
with pytest.raises(expected_error):
context.load_cert_chain(
certfile=self.cert_path,
keyfile=self.password_key_path,
password=b"letmei",
)
class TestSocketClosing(SocketDummyServerTestCase):
def test_recovery_when_server_closes_connection(self):
# Does the pool work seamlessly if an open connection in the
# connection pool gets hung up on by the server, then reaches
# the front of the queue again?
done_closing = Event()
def socket_handler(listener):
for i in 0, 1:
sock = listener.accept()[0]
buf = b""
while not buf.endswith(b"\r\n\r\n"):
buf = sock.recv(65536)
body = "Response %d" % i
sock.send(
(
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/plain\r\n"
"Content-Length: %d\r\n"
"\r\n"
"%s" % (len(body), body)
).encode("utf-8")
)
sock.close() # simulate a server timing out, closing socket
done_closing.set() # let the test know it can proceed
self._start_server(socket_handler)
with HTTPConnectionPool(self.host, self.port) as pool:
response = pool.request("GET", "/", retries=0)
assert response.status == 200
assert response.data == b"Response 0"
done_closing.wait() # wait until the socket in our pool gets closed
response = pool.request("GET", "/", retries=0)
assert response.status == 200
assert response.data == b"Response 1"
def test_connection_refused(self):
# Does the pool retry if there is no listener on the port?
host, port = get_unreachable_address()
with HTTPConnectionPool(host, port, maxsize=3, block=True) as http:
with pytest.raises(MaxRetryError):
http.request("GET", "/", retries=0, release_conn=False)
assert http.pool.qsize() == http.pool.maxsize
def test_connection_read_timeout(self):
timed_out = Event()
def socket_handler(listener):
sock = listener.accept()[0]
while not sock.recv(65536).endswith(b"\r\n\r\n"):
pass
timed_out.wait()
sock.close()
self._start_server(socket_handler)
with HTTPConnectionPool(
self.host,
self.port,
timeout=SHORT_TIMEOUT,
retries=False,
maxsize=3,
block=True,
) as http:
try:
with pytest.raises(ReadTimeoutError):
http.request("GET", "/", release_conn=False)
finally:
timed_out.set()
assert http.pool.qsize() == http.pool.maxsize
def test_read_timeout_dont_retry_method_not_in_allowlist(self):
timed_out = Event()
def socket_handler(listener):
sock = listener.accept()[0]
sock.recv(65536)
timed_out.wait()
sock.close()
self._start_server(socket_handler)
with HTTPConnectionPool(
self.host, self.port, timeout=LONG_TIMEOUT, retries=True
) as pool:
try:
with pytest.raises(ReadTimeoutError):
pool.request("POST", "/")
finally:
timed_out.set()
def test_https_connection_read_timeout(self):
"""Handshake timeouts should fail with a Timeout"""
timed_out = Event()
def socket_handler(listener):
sock = listener.accept()[0]
while not sock.recv(65536):
pass
timed_out.wait()
sock.close()
self._start_server(socket_handler)
with HTTPSConnectionPool(
self.host, self.port, timeout=LONG_TIMEOUT, retries=False
) as pool:
try:
with pytest.raises(ReadTimeoutError):
pool.request("GET", "/")
finally:
timed_out.set()
def test_timeout_errors_cause_retries(self):
def socket_handler(listener):
sock_timeout = listener.accept()[0]
# Wait for a second request before closing the first socket.
sock = listener.accept()[0]
sock_timeout.close()
# Second request.
buf = b""
while not buf.endswith(b"\r\n\r\n"):
buf += sock.recv(65536)
# Now respond immediately.
body = "Response 2"
sock.send(
(
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/plain\r\n"
"Content-Length: %d\r\n"
"\r\n"
"%s" % (len(body), body)
).encode("utf-8")
)
sock.close()
# In situations where the main thread throws an exception, the server
# thread can hang on an accept() call. This ensures everything times
# out within 1 second. This should be long enough for any socket
# operations in the test suite to complete
default_timeout = socket.getdefaulttimeout()
socket.setdefaulttimeout(1)
try:
self._start_server(socket_handler)
t = Timeout(connect=LONG_TIMEOUT, read=LONG_TIMEOUT)
with HTTPConnectionPool(self.host, self.port, timeout=t) as pool:
response = pool.request("GET", "/", retries=1)
assert response.status == 200
assert response.data == b"Response 2"
finally:
socket.setdefaulttimeout(default_timeout)
def test_delayed_body_read_timeout(self):
timed_out = Event()
def socket_handler(listener):
sock = listener.accept()[0]
buf = b""
body = "Hi"
while not buf.endswith(b"\r\n\r\n"):
buf = sock.recv(65536)
sock.send(
(
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/plain\r\n"
"Content-Length: %d\r\n"
"\r\n" % len(body)
).encode("utf-8")
)
timed_out.wait()
sock.send(body.encode("utf-8"))
sock.close()
self._start_server(socket_handler)
with HTTPConnectionPool(self.host, self.port) as pool:
response = pool.urlopen(
"GET",
"/",
retries=0,
preload_content=False,
timeout=Timeout(connect=1, read=LONG_TIMEOUT),
)
try:
with pytest.raises(ReadTimeoutError):
response.read()
finally:
timed_out.set()
def test_delayed_body_read_timeout_with_preload(self):
timed_out = Event()
def socket_handler(listener):
sock = listener.accept()[0]
buf = b""
body = "Hi"
while not buf.endswith(b"\r\n\r\n"):
buf += sock.recv(65536)
sock.send(
(
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/plain\r\n"
"Content-Length: %d\r\n"
"\r\n" % len(body)
).encode("utf-8")
)
timed_out.wait(5)
sock.close()
self._start_server(socket_handler)
with HTTPConnectionPool(self.host, self.port) as pool:
try:
with pytest.raises(ReadTimeoutError):
timeout = Timeout(connect=LONG_TIMEOUT, read=SHORT_TIMEOUT)
pool.urlopen("GET", "/", retries=False, timeout=timeout)
finally:
timed_out.set()
def test_incomplete_response(self):
body = "Response"
partial_body = body[:2]
def socket_handler(listener):
sock = listener.accept()[0]
# Consume request
buf = b""
while not buf.endswith(b"\r\n\r\n"):
buf = sock.recv(65536)
# Send partial response and close socket.
sock.send(
(
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/plain\r\n"
"Content-Length: %d\r\n"
"\r\n"
"%s" % (len(body), partial_body)
).encode("utf-8")
)
sock.close()
self._start_server(socket_handler)
with HTTPConnectionPool(self.host, self.port) as pool:
response = pool.request("GET", "/", retries=0, preload_content=False)
with pytest.raises(ProtocolError):
response.read()
def test_retry_weird_http_version(self):
"""Retry class should handle httplib.BadStatusLine errors properly"""
def socket_handler(listener):
sock = listener.accept()[0]
# First request.
# Pause before responding so the first request times out.
buf = b""
while not buf.endswith(b"\r\n\r\n"):
buf += sock.recv(65536)
# send unknown http protocol
body = "bad http 0.5 response"
sock.send(
(
"HTTP/0.5 200 OK\r\n"
"Content-Type: text/plain\r\n"
"Content-Length: %d\r\n"
"\r\n"
"%s" % (len(body), body)
).encode("utf-8")
)
sock.close()
# Second request.
sock = listener.accept()[0]
buf = b""
while not buf.endswith(b"\r\n\r\n"):
buf += sock.recv(65536)
# Now respond immediately.
sock.send(
(
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/plain\r\n"
"Content-Length: %d\r\n"
"\r\n"
"foo" % (len("foo"))
).encode("utf-8")
)
sock.close() # Close the socket.
self._start_server(socket_handler)
with HTTPConnectionPool(self.host, self.port) as pool:
retry = Retry(read=1)
response = pool.request("GET", "/", retries=retry)
assert response.status == 200
assert response.data == b"foo"
def test_connection_cleanup_on_read_timeout(self):
timed_out = Event()
def socket_handler(listener):
sock = listener.accept()[0]
buf = b""
body = "Hi"
while not buf.endswith(b"\r\n\r\n"):
buf = sock.recv(65536)
sock.send(
(
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/plain\r\n"
"Content-Length: %d\r\n"
"\r\n" % len(body)
).encode("utf-8")
)
timed_out.wait()
sock.close()
self._start_server(socket_handler)
with HTTPConnectionPool(self.host, self.port) as pool:
poolsize = pool.pool.qsize()
response = pool.urlopen(
"GET", "/", retries=0, preload_content=False, timeout=LONG_TIMEOUT
)
try:
with pytest.raises(ReadTimeoutError):
response.read()
assert poolsize == pool.pool.qsize()
finally:
timed_out.set()
def test_connection_cleanup_on_protocol_error_during_read(self):
body = "Response"
partial_body = body[:2]
def socket_handler(listener):
sock = listener.accept()[0]
# Consume request
buf = b""
while not buf.endswith(b"\r\n\r\n"):
buf = sock.recv(65536)
# Send partial response and close socket.
sock.send(
(
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/plain\r\n"
"Content-Length: %d\r\n"
"\r\n"
"%s" % (len(body), partial_body)
).encode("utf-8")
)
sock.close()
self._start_server(socket_handler)
with HTTPConnectionPool(self.host, self.port) as pool:
poolsize = pool.pool.qsize()
response = pool.request("GET", "/", retries=0, preload_content=False)
with pytest.raises(ProtocolError):
response.read()
assert poolsize == pool.pool.qsize()
def test_connection_closed_on_read_timeout_preload_false(self):
timed_out = Event()
def socket_handler(listener):
sock = listener.accept()[0]
# Consume request
buf = b""
while not buf.endswith(b"\r\n\r\n"):
buf = sock.recv(65535)
# Send partial chunked response and then hang.
sock.send(
(
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/plain\r\n"
"Transfer-Encoding: chunked\r\n"
"\r\n"
"8\r\n"
"12345678\r\n"
).encode("utf-8")
)
timed_out.wait(5)
# Expect a new request, but keep hold of the old socket to avoid
# leaking it. Because we don't want to hang this thread, we
# actually use select.select to confirm that a new request is
# coming in: this lets us time the thread out.
rlist, _, _ = select.select([listener], [], [], 1)
assert rlist
new_sock = listener.accept()[0]
# Consume request
buf = b""
while not buf.endswith(b"\r\n\r\n"):
buf = new_sock.recv(65535)
# Send complete chunked response.
new_sock.send(
(
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/plain\r\n"
"Transfer-Encoding: chunked\r\n"
"\r\n"
"8\r\n"
"12345678\r\n"
"0\r\n\r\n"
).encode("utf-8")
)
new_sock.close()
sock.close()
self._start_server(socket_handler)
with HTTPConnectionPool(self.host, self.port) as pool:
# First request should fail.
response = pool.urlopen(
"GET", "/", retries=0, preload_content=False, timeout=LONG_TIMEOUT
)
try:
with pytest.raises(ReadTimeoutError):
response.read()
finally:
timed_out.set()
# Second should succeed.
response = pool.urlopen(
"GET", "/", retries=0, preload_content=False, timeout=LONG_TIMEOUT
)
assert len(response.read()) == 8
def test_closing_response_actually_closes_connection(self):
done_closing = Event()
complete = Event()
def socket_handler(listener):
sock = listener.accept()[0]
buf = b""
while not buf.endswith(b"\r\n\r\n"):
buf = sock.recv(65536)
sock.send(
(
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/plain\r\n"
"Content-Length: 0\r\n"
"\r\n"
).encode("utf-8")
)
# Wait for the socket to close.
done_closing.wait(timeout=LONG_TIMEOUT)
# Look for the empty string to show that the connection got closed.
# Don't get stuck in a timeout.
sock.settimeout(LONG_TIMEOUT)
new_data = sock.recv(65536)
assert not new_data
sock.close()
complete.set()
self._start_server(socket_handler)
with HTTPConnectionPool(self.host, self.port) as pool:
response = pool.request("GET", "/", retries=0, preload_content=False)
assert response.status == 200
response.close()
done_closing.set() # wait until the socket in our pool gets closed
successful = complete.wait(timeout=LONG_TIMEOUT)
assert successful, "Timed out waiting for connection close"
def test_release_conn_param_is_respected_after_timeout_retry(self):
"""For successful ```urlopen(release_conn=False)```,
the connection isn't released, even after a retry.
This test allows a retry: one request fails, the next request succeeds.
This is a regression test for issue #651 [1], where the connection
would be released if the initial request failed, even if a retry
succeeded.
[1] <https://github.com/urllib3/urllib3/issues/651>
"""
def socket_handler(listener):
sock = listener.accept()[0]
consume_socket(sock)
# Close the connection, without sending any response (not even the
# HTTP status line). This will trigger a `Timeout` on the client,
# inside `urlopen()`.
sock.close()
# Expect a new request. Because we don't want to hang this thread,
# we actually use select.select to confirm that a new request is
# coming in: this lets us time the thread out.
rlist, _, _ = select.select([listener], [], [], 5)
assert rlist
sock = listener.accept()[0]
consume_socket(sock)
# Send complete chunked response.
sock.send(
(
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/plain\r\n"
"Transfer-Encoding: chunked\r\n"
"\r\n"
"8\r\n"
"12345678\r\n"
"0\r\n\r\n"
).encode("utf-8")
)
sock.close()
self._start_server(socket_handler)
with HTTPConnectionPool(self.host, self.port, maxsize=1) as pool:
# First request should fail, but the timeout and `retries=1` should
# save it.
response = pool.urlopen(
"GET",
"/",
retries=1,
release_conn=False,
preload_content=False,
timeout=LONG_TIMEOUT,
)
# The connection should still be on the response object, and none
# should be in the pool. We opened two though.
assert pool.num_connections == 2
assert pool.pool.qsize() == 0
assert response.connection is not None
# Consume the data. This should put the connection back.
response.read()
assert pool.pool.qsize() == 1
assert response.connection is None
class TestProxyManager(SocketDummyServerTestCase):
def test_simple(self):
def echo_socket_handler(listener):
sock = listener.accept()[0]
buf = b""
while not buf.endswith(b"\r\n\r\n"):
buf += sock.recv(65536)
sock.send(
(
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/plain\r\n"
"Content-Length: %d\r\n"
"\r\n"
"%s" % (len(buf), buf.decode("utf-8"))
).encode("utf-8")
)
sock.close()
self._start_server(echo_socket_handler)
base_url = "http://%s:%d" % (self.host, self.port)
with proxy_from_url(base_url) as proxy:
r = proxy.request("GET", "http://google.com/")
assert r.status == 200
# FIXME: The order of the headers is not predictable right now. We
# should fix that someday (maybe when we migrate to
# OrderedDict/MultiDict).
assert sorted(r.data.split(b"\r\n")) == sorted(
[
b"GET http://google.com/ HTTP/1.1",
b"Host: google.com",
b"Accept-Encoding: identity",
b"Accept: */*",
b"User-Agent: " + _get_default_user_agent().encode("utf-8"),
b"",
b"",
]
)
def test_headers(self):
def echo_socket_handler(listener):
sock = listener.accept()[0]
buf = b""
while not buf.endswith(b"\r\n\r\n"):
buf += sock.recv(65536)
sock.send(
(
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/plain\r\n"
"Content-Length: %d\r\n"
"\r\n"
"%s" % (len(buf), buf.decode("utf-8"))
).encode("utf-8")
)
sock.close()
self._start_server(echo_socket_handler)
base_url = "http://%s:%d" % (self.host, self.port)
# Define some proxy headers.
proxy_headers = HTTPHeaderDict({"For The Proxy": "YEAH!"})
with proxy_from_url(base_url, proxy_headers=proxy_headers) as proxy:
conn = proxy.connection_from_url("http://www.google.com/")
r = conn.urlopen("GET", "http://www.google.com/", assert_same_host=False)
assert r.status == 200
# FIXME: The order of the headers is not predictable right now. We
# should fix that someday (maybe when we migrate to
# OrderedDict/MultiDict).
assert b"For The Proxy: YEAH!\r\n" in r.data
def test_retries(self):
close_event = Event()
def echo_socket_handler(listener):
sock = listener.accept()[0]
# First request, which should fail
sock.close()
# Second request
sock = listener.accept()[0]
buf = b""
while not buf.endswith(b"\r\n\r\n"):
buf += sock.recv(65536)
sock.send(
(
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/plain\r\n"
"Content-Length: %d\r\n"
"\r\n"
"%s" % (len(buf), buf.decode("utf-8"))
).encode("utf-8")
)
sock.close()
close_event.set()
self._start_server(echo_socket_handler)
base_url = "http://%s:%d" % (self.host, self.port)
with proxy_from_url(base_url) as proxy:
conn = proxy.connection_from_url("http://www.google.com")
r = conn.urlopen(
"GET", "http://www.google.com", assert_same_host=False, retries=1
)
assert r.status == 200
close_event.wait(timeout=LONG_TIMEOUT)
with pytest.raises(ProxyError):
conn.urlopen(
"GET",
"http://www.google.com",
assert_same_host=False,
retries=False,
)
def test_connect_reconn(self):
def proxy_ssl_one(listener):
sock = listener.accept()[0]
buf = b""
while not buf.endswith(b"\r\n\r\n"):
buf += sock.recv(65536)
s = buf.decode("utf-8")
if not s.startswith("CONNECT "):
sock.send(
(
"HTTP/1.1 405 Method not allowed\r\nAllow: CONNECT\r\n\r\n"
).encode("utf-8")
)
sock.close()
return
if not s.startswith("CONNECT %s:443" % (self.host,)):
sock.send(("HTTP/1.1 403 Forbidden\r\n\r\n").encode("utf-8"))
sock.close()
return
sock.send(("HTTP/1.1 200 Connection Established\r\n\r\n").encode("utf-8"))
ssl_sock = ssl.wrap_socket(
sock,
server_side=True,
keyfile=DEFAULT_CERTS["keyfile"],
certfile=DEFAULT_CERTS["certfile"],
ca_certs=DEFAULT_CA,
)
buf = b""
while not buf.endswith(b"\r\n\r\n"):
buf += ssl_sock.recv(65536)
ssl_sock.send(
(
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/plain\r\n"
"Content-Length: 2\r\n"
"Connection: close\r\n"
"\r\n"
"Hi"
).encode("utf-8")
)
ssl_sock.close()
def echo_socket_handler(listener):
proxy_ssl_one(listener)
proxy_ssl_one(listener)
self._start_server(echo_socket_handler)
base_url = "http://%s:%d" % (self.host, self.port)
with proxy_from_url(base_url, ca_certs=DEFAULT_CA) as proxy:
url = "https://{0}".format(self.host)
conn = proxy.connection_from_url(url)
r = conn.urlopen("GET", url, retries=0)
assert r.status == 200
r = conn.urlopen("GET", url, retries=0)
assert r.status == 200
def test_connect_ipv6_addr(self):
ipv6_addr = "2001:4998:c:a06::2:4008"
def echo_socket_handler(listener):
sock = listener.accept()[0]
buf = b""
while not buf.endswith(b"\r\n\r\n"):
buf += sock.recv(65536)
s = buf.decode("utf-8")
if s.startswith("CONNECT [%s]:443" % (ipv6_addr,)):
sock.send(b"HTTP/1.1 200 Connection Established\r\n\r\n")
ssl_sock = ssl.wrap_socket(
sock,
server_side=True,
keyfile=DEFAULT_CERTS["keyfile"],
certfile=DEFAULT_CERTS["certfile"],
)
buf = b""
while not buf.endswith(b"\r\n\r\n"):
buf += ssl_sock.recv(65536)
ssl_sock.send(
b"HTTP/1.1 200 OK\r\n"
b"Content-Type: text/plain\r\n"
b"Content-Length: 2\r\n"
b"Connection: close\r\n"
b"\r\n"
b"Hi"
)
ssl_sock.close()
else:
sock.close()
self._start_server(echo_socket_handler)
base_url = "http://%s:%d" % (self.host, self.port)
with proxy_from_url(base_url, cert_reqs="NONE") as proxy:
url = "https://[{0}]".format(ipv6_addr)
conn = proxy.connection_from_url(url)
try:
r = conn.urlopen("GET", url, retries=0)
assert r.status == 200
except MaxRetryError:
self.fail("Invalid IPv6 format in HTTP CONNECT request")
class TestSSL(SocketDummyServerTestCase):
def test_ssl_failure_midway_through_conn(self):
def socket_handler(listener):
sock = listener.accept()[0]
sock2 = sock.dup()
ssl_sock = ssl.wrap_socket(
sock,
server_side=True,
keyfile=DEFAULT_CERTS["keyfile"],
certfile=DEFAULT_CERTS["certfile"],
ca_certs=DEFAULT_CA,
)
buf = b""
while not buf.endswith(b"\r\n\r\n"):
buf += ssl_sock.recv(65536)
# Deliberately send from the non-SSL socket.
sock2.send(
(
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/plain\r\n"
"Content-Length: 2\r\n"
"\r\n"
"Hi"
).encode("utf-8")
)
sock2.close()
ssl_sock.close()
self._start_server(socket_handler)
with HTTPSConnectionPool(self.host, self.port) as pool:
with pytest.raises(MaxRetryError) as cm:
pool.request("GET", "/", retries=0)
assert isinstance(cm.value.reason, SSLError)
@notSecureTransport
def test_ssl_read_timeout(self):
timed_out = Event()
def socket_handler(listener):
sock = listener.accept()[0]
ssl_sock = ssl.wrap_socket(
sock,
server_side=True,
keyfile=DEFAULT_CERTS["keyfile"],
certfile=DEFAULT_CERTS["certfile"],
)
buf = b""
while not buf.endswith(b"\r\n\r\n"):
buf += ssl_sock.recv(65536)
# Send incomplete message (note Content-Length)
ssl_sock.send(
(
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/plain\r\n"
"Content-Length: 10\r\n"
"\r\n"
"Hi-"
).encode("utf-8")
)
timed_out.wait()
sock.close()
ssl_sock.close()
self._start_server(socket_handler)
with HTTPSConnectionPool(self.host, self.port, ca_certs=DEFAULT_CA) as pool:
response = pool.urlopen(
"GET", "/", retries=0, preload_content=False, timeout=LONG_TIMEOUT
)
try:
with pytest.raises(ReadTimeoutError):
response.read()
finally:
timed_out.set()
def test_ssl_failed_fingerprint_verification(self):
def socket_handler(listener):
for i in range(2):
sock = listener.accept()[0]
ssl_sock = ssl.wrap_socket(
sock,
server_side=True,
keyfile=DEFAULT_CERTS["keyfile"],
certfile=DEFAULT_CERTS["certfile"],
ca_certs=DEFAULT_CA,
)
ssl_sock.send(
b"HTTP/1.1 200 OK\r\n"
b"Content-Type: text/plain\r\n"
b"Content-Length: 5\r\n\r\n"
b"Hello"
)
ssl_sock.close()
sock.close()
self._start_server(socket_handler)
# GitHub's fingerprint. Valid, but not matching.
fingerprint = "A0:C4:A7:46:00:ED:A7:2D:C0:BE:CB:9A:8C:B6:07:CA:58:EE:74:5E"
def request():
pool = HTTPSConnectionPool(
self.host, self.port, assert_fingerprint=fingerprint
)
try:
timeout = Timeout(connect=LONG_TIMEOUT, read=SHORT_TIMEOUT)
response = pool.urlopen(
"GET", "/", preload_content=False, retries=0, timeout=timeout
)
response.read()
finally:
pool.close()
with pytest.raises(MaxRetryError) as cm:
request()
assert isinstance(cm.value.reason, SSLError)
# Should not hang, see https://github.com/urllib3/urllib3/issues/529
with pytest.raises(MaxRetryError):
request()
def test_retry_ssl_error(self):
def socket_handler(listener):
# first request, trigger an SSLError
sock = listener.accept()[0]
sock2 = sock.dup()
ssl_sock = ssl.wrap_socket(
sock,
server_side=True,
keyfile=DEFAULT_CERTS["keyfile"],
certfile=DEFAULT_CERTS["certfile"],
)
buf = b""
while not buf.endswith(b"\r\n\r\n"):
buf += ssl_sock.recv(65536)
# Deliberately send from the non-SSL socket to trigger an SSLError
sock2.send(
(
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/plain\r\n"
"Content-Length: 4\r\n"
"\r\n"
"Fail"
).encode("utf-8")
)
sock2.close()
ssl_sock.close()
# retried request
sock = listener.accept()[0]
ssl_sock = ssl.wrap_socket(
sock,
server_side=True,
keyfile=DEFAULT_CERTS["keyfile"],
certfile=DEFAULT_CERTS["certfile"],
)
buf = b""
while not buf.endswith(b"\r\n\r\n"):
buf += ssl_sock.recv(65536)
ssl_sock.send(
b"HTTP/1.1 200 OK\r\n"
b"Content-Type: text/plain\r\n"
b"Content-Length: 7\r\n\r\n"
b"Success"
)
ssl_sock.close()
self._start_server(socket_handler)
with HTTPSConnectionPool(self.host, self.port, ca_certs=DEFAULT_CA) as pool:
response = pool.urlopen("GET", "/", retries=1)
assert response.data == b"Success"
def test_ssl_load_default_certs_when_empty(self):
def socket_handler(listener):
sock = listener.accept()[0]
ssl_sock = ssl.wrap_socket(
sock,
server_side=True,
keyfile=DEFAULT_CERTS["keyfile"],
certfile=DEFAULT_CERTS["certfile"],
ca_certs=DEFAULT_CA,
)
buf = b""
while not buf.endswith(b"\r\n\r\n"):
buf += ssl_sock.recv(65536)
ssl_sock.send(
b"HTTP/1.1 200 OK\r\n"
b"Content-Type: text/plain\r\n"
b"Content-Length: 5\r\n\r\n"
b"Hello"
)
ssl_sock.close()
sock.close()
context = mock.create_autospec(ssl_.SSLContext)
context.load_default_certs = mock.Mock()
context.options = 0
with mock.patch("urllib3.util.ssl_.SSLContext", lambda *_, **__: context):
self._start_server(socket_handler)
with HTTPSConnectionPool(self.host, self.port) as pool:
with pytest.raises(MaxRetryError):
pool.request("GET", "/", timeout=SHORT_TIMEOUT)
context.load_default_certs.assert_called_with()
@notPyPy2
def test_ssl_dont_load_default_certs_when_given(self):
def socket_handler(listener):
sock = listener.accept()[0]
ssl_sock = ssl.wrap_socket(
sock,
server_side=True,
keyfile=DEFAULT_CERTS["keyfile"],
certfile=DEFAULT_CERTS["certfile"],
ca_certs=DEFAULT_CA,
)
buf = b""
while not buf.endswith(b"\r\n\r\n"):
buf += ssl_sock.recv(65536)
ssl_sock.send(
b"HTTP/1.1 200 OK\r\n"
b"Content-Type: text/plain\r\n"
b"Content-Length: 5\r\n\r\n"
b"Hello"
)
ssl_sock.close()
sock.close()
context = mock.create_autospec(ssl_.SSLContext)
context.load_default_certs = mock.Mock()
context.options = 0
with mock.patch("urllib3.util.ssl_.SSLContext", lambda *_, **__: context):
for kwargs in [
{"ca_certs": "/a"},
{"ca_cert_dir": "/a"},
{"ca_certs": "a", "ca_cert_dir": "a"},
{"ssl_context": context},
]:
self._start_server(socket_handler)
with HTTPSConnectionPool(self.host, self.port, **kwargs) as pool:
with pytest.raises(MaxRetryError):
pool.request("GET", "/", timeout=SHORT_TIMEOUT)
context.load_default_certs.assert_not_called()
def test_load_verify_locations_exception(self):
"""
Ensure that load_verify_locations raises SSLError for all backends
"""
with pytest.raises(SSLError):
ssl_wrap_socket(None, ca_certs="/tmp/fake-file")
def test_ssl_custom_validation_failure_terminates(self, tmpdir):
"""
Ensure that the underlying socket is terminated if custom validation fails.
"""
server_closed = Event()
def is_closed_socket(sock):
try:
sock.settimeout(SHORT_TIMEOUT) # Python 3
sock.recv(1) # Python 2
except (OSError, socket.error):
return True
return False
def socket_handler(listener):
sock = listener.accept()[0]
try:
_ = ssl.wrap_socket(
sock,
server_side=True,
keyfile=DEFAULT_CERTS["keyfile"],
certfile=DEFAULT_CERTS["certfile"],
ca_certs=DEFAULT_CA,
)
except ssl.SSLError as e:
assert "alert unknown ca" in str(e)
if is_closed_socket(sock):
server_closed.set()
self._start_server(socket_handler)
# client uses a different ca
other_ca = trustme.CA()
other_ca_path = str(tmpdir / "ca.pem")
other_ca.cert_pem.write_to_path(other_ca_path)
with HTTPSConnectionPool(
self.host, self.port, cert_reqs="REQUIRED", ca_certs=other_ca_path
) as pool:
with pytest.raises(SSLError):
pool.request("GET", "/", retries=False, timeout=LONG_TIMEOUT)
assert server_closed.wait(LONG_TIMEOUT), "The socket was not terminated"
class TestErrorWrapping(SocketDummyServerTestCase):
def test_bad_statusline(self):
self.start_response_handler(
b"HTTP/1.1 Omg What Is This?\r\n" b"Content-Length: 0\r\n" b"\r\n"
)
with HTTPConnectionPool(self.host, self.port, retries=False) as pool:
with pytest.raises(ProtocolError):
pool.request("GET", "/")
def test_unknown_protocol(self):
self.start_response_handler(
b"HTTP/1000 200 OK\r\n" b"Content-Length: 0\r\n" b"\r\n"
)
with HTTPConnectionPool(self.host, self.port, retries=False) as pool:
with pytest.raises(ProtocolError):
pool.request("GET", "/")
class TestHeaders(SocketDummyServerTestCase):
@onlyPy3
def test_httplib_headers_case_insensitive(self):
self.start_response_handler(
b"HTTP/1.1 200 OK\r\n"
b"Content-Length: 0\r\n"
b"Content-type: text/plain\r\n"
b"\r\n"
)
with HTTPConnectionPool(self.host, self.port, retries=False) as pool:
HEADERS = {"Content-Length": "0", "Content-type": "text/plain"}
r = pool.request("GET", "/")
assert HEADERS == dict(r.headers.items()) # to preserve case sensitivity
def start_parsing_handler(self):
self.parsed_headers = OrderedDict()
self.received_headers = []
def socket_handler(listener):
sock = listener.accept()[0]
buf = b""
while not buf.endswith(b"\r\n\r\n"):
buf += sock.recv(65536)
self.received_headers = [
header for header in buf.split(b"\r\n")[1:] if header
]
for header in self.received_headers:
(key, value) = header.split(b": ")
self.parsed_headers[key.decode("ascii")] = value.decode("ascii")
sock.send(
("HTTP/1.1 204 No Content\r\nContent-Length: 0\r\n\r\n").encode("utf-8")
)
sock.close()
self._start_server(socket_handler)
def test_headers_are_sent_with_the_original_case(self):
headers = {"foo": "bar", "bAz": "quux"}
self.start_parsing_handler()
expected_headers = {
"Accept-Encoding": "identity",
"Host": "{0}:{1}".format(self.host, self.port),
"User-Agent": _get_default_user_agent(),
}
expected_headers.update(headers)
with HTTPConnectionPool(self.host, self.port, retries=False) as pool:
pool.request("GET", "/", headers=HTTPHeaderDict(headers))
assert expected_headers == self.parsed_headers
def test_ua_header_can_be_overridden(self):
headers = {"uSeR-AgENt": "Definitely not urllib3!"}
self.start_parsing_handler()
expected_headers = {
"Accept-Encoding": "identity",
"Host": "{0}:{1}".format(self.host, self.port),
}
expected_headers.update(headers)
with HTTPConnectionPool(self.host, self.port, retries=False) as pool:
pool.request("GET", "/", headers=HTTPHeaderDict(headers))
assert expected_headers == self.parsed_headers
def test_request_headers_are_sent_in_the_original_order(self):
# NOTE: Probability this test gives a false negative is 1/(K!)
K = 16
# NOTE: Provide headers in non-sorted order (i.e. reversed)
# so that if the internal implementation tries to sort them,
# a change will be detected.
expected_request_headers = [
(u"X-Header-%d" % i, str(i)) for i in reversed(range(K))
]
def filter_non_x_headers(d):
return [(k, v) for (k, v) in d.items() if k.startswith("X-Header-")]
request_headers = OrderedDict()
self.start_parsing_handler()
with HTTPConnectionPool(self.host, self.port, retries=False) as pool:
pool.request("GET", "/", headers=OrderedDict(expected_request_headers))
request_headers = filter_non_x_headers(self.parsed_headers)
assert expected_request_headers == request_headers
@resolvesLocalhostFQDN
def test_request_host_header_ignores_fqdn_dot(self):
self.start_parsing_handler()
with HTTPConnectionPool(self.host + ".", self.port, retries=False) as pool:
pool.request("GET", "/")
self.assert_header_received(
self.received_headers, "Host", "%s:%s" % (self.host, self.port)
)
def test_response_headers_are_returned_in_the_original_order(self):
# NOTE: Probability this test gives a false negative is 1/(K!)
K = 16
# NOTE: Provide headers in non-sorted order (i.e. reversed)
# so that if the internal implementation tries to sort them,
# a change will be detected.
expected_response_headers = [
("X-Header-%d" % i, str(i)) for i in reversed(range(K))
]
def socket_handler(listener):
sock = listener.accept()[0]
buf = b""
while not buf.endswith(b"\r\n\r\n"):
buf += sock.recv(65536)
sock.send(
b"HTTP/1.1 200 OK\r\n"
+ b"\r\n".join(
[
(k.encode("utf8") + b": " + v.encode("utf8"))
for (k, v) in expected_response_headers
]
)
+ b"\r\n"
)
sock.close()
self._start_server(socket_handler)
with HTTPConnectionPool(self.host, self.port) as pool:
r = pool.request("GET", "/", retries=0)
actual_response_headers = [
(k, v) for (k, v) in r.headers.items() if k.startswith("X-Header-")
]
assert expected_response_headers == actual_response_headers
@pytest.mark.skipif(
issubclass(httplib.HTTPMessage, MimeToolMessage),
reason="Header parsing errors not available",
)
class TestBrokenHeaders(SocketDummyServerTestCase):
def _test_broken_header_parsing(self, headers, unparsed_data_check=None):
self.start_response_handler(
(
b"HTTP/1.1 200 OK\r\n"
b"Content-Length: 0\r\n"
b"Content-type: text/plain\r\n"
)
+ b"\r\n".join(headers)
+ b"\r\n\r\n"
)
with HTTPConnectionPool(self.host, self.port, retries=False) as pool:
with LogRecorder() as logs:
pool.request("GET", "/")
for record in logs:
if (
"Failed to parse headers" in record.msg
and pool._absolute_url("/") == record.args[0]
):
if (
unparsed_data_check is None
or unparsed_data_check in record.getMessage()
):
return
self.fail("Missing log about unparsed headers")
def test_header_without_name(self):
self._test_broken_header_parsing([b": Value", b"Another: Header"])
def test_header_without_name_or_value(self):
self._test_broken_header_parsing([b":", b"Another: Header"])
def test_header_without_colon_or_value(self):
self._test_broken_header_parsing(
[b"Broken Header", b"Another: Header"], "Broken Header"
)
class TestHeaderParsingContentType(SocketDummyServerTestCase):
def _test_okay_header_parsing(self, header):
self.start_response_handler(
(b"HTTP/1.1 200 OK\r\n" b"Content-Length: 0\r\n") + header + b"\r\n\r\n"
)
with HTTPConnectionPool(self.host, self.port, retries=False) as pool:
with LogRecorder() as logs:
pool.request("GET", "/")
for record in logs:
assert "Failed to parse headers" not in record.msg
def test_header_text_plain(self):
self._test_okay_header_parsing(b"Content-type: text/plain")
def test_header_message_rfc822(self):
self._test_okay_header_parsing(b"Content-type: message/rfc822")
class TestHEAD(SocketDummyServerTestCase):
def test_chunked_head_response_does_not_hang(self):
self.start_response_handler(
b"HTTP/1.1 200 OK\r\n"
b"Transfer-Encoding: chunked\r\n"
b"Content-type: text/plain\r\n"
b"\r\n"
)
with HTTPConnectionPool(self.host, self.port, retries=False) as pool:
r = pool.request("HEAD", "/", timeout=LONG_TIMEOUT, preload_content=False)
# stream will use the read_chunked method here.
assert [] == list(r.stream())
def test_empty_head_response_does_not_hang(self):
self.start_response_handler(
b"HTTP/1.1 200 OK\r\n"
b"Content-Length: 256\r\n"
b"Content-type: text/plain\r\n"
b"\r\n"
)
with HTTPConnectionPool(self.host, self.port, retries=False) as pool:
r = pool.request("HEAD", "/", timeout=LONG_TIMEOUT, preload_content=False)
# stream will use the read method here.
assert [] == list(r.stream())
class TestStream(SocketDummyServerTestCase):
def test_stream_none_unchunked_response_does_not_hang(self):
done_event = Event()
def socket_handler(listener):
sock = listener.accept()[0]
buf = b""
while not buf.endswith(b"\r\n\r\n"):
buf += sock.recv(65536)
sock.send(
b"HTTP/1.1 200 OK\r\n"
b"Content-Length: 12\r\n"
b"Content-type: text/plain\r\n"
b"\r\n"
b"hello, world"
)
done_event.wait(5)
sock.close()
self._start_server(socket_handler)
with HTTPConnectionPool(self.host, self.port, retries=False) as pool:
r = pool.request("GET", "/", timeout=LONG_TIMEOUT, preload_content=False)
# Stream should read to the end.
assert [b"hello, world"] == list(r.stream(None))
done_event.set()
class TestBadContentLength(SocketDummyServerTestCase):
def test_enforce_content_length_get(self):
done_event = Event()
def socket_handler(listener):
sock = listener.accept()[0]
buf = b""
while not buf.endswith(b"\r\n\r\n"):
buf += sock.recv(65536)
sock.send(
b"HTTP/1.1 200 OK\r\n"
b"Content-Length: 22\r\n"
b"Content-type: text/plain\r\n"
b"\r\n"
b"hello, world"
)
done_event.wait(LONG_TIMEOUT)
sock.close()
self._start_server(socket_handler)
with HTTPConnectionPool(self.host, self.port, maxsize=1) as conn:
# Test stream read when content length less than headers claim
get_response = conn.request(
"GET", url="/", preload_content=False, enforce_content_length=True
)
data = get_response.stream(100)
# Read "good" data before we try to read again.
# This won't trigger till generator is exhausted.
next(data)
try:
next(data)
assert False
except ProtocolError as e:
assert "12 bytes read, 10 more expected" in str(e)
done_event.set()
def test_enforce_content_length_no_body(self):
done_event = Event()
def socket_handler(listener):
sock = listener.accept()[0]
buf = b""
while not buf.endswith(b"\r\n\r\n"):
buf += sock.recv(65536)
sock.send(
b"HTTP/1.1 200 OK\r\n"
b"Content-Length: 22\r\n"
b"Content-type: text/plain\r\n"
b"\r\n"
)
done_event.wait(1)
sock.close()
self._start_server(socket_handler)
with HTTPConnectionPool(self.host, self.port, maxsize=1) as conn:
# Test stream on 0 length body
head_response = conn.request(
"HEAD", url="/", preload_content=False, enforce_content_length=True
)
data = [chunk for chunk in head_response.stream(1)]
assert len(data) == 0
done_event.set()
class TestRetryPoolSizeDrainFail(SocketDummyServerTestCase):
def test_pool_size_retry_drain_fail(self):
def socket_handler(listener):
for _ in range(2):
sock = listener.accept()[0]
while not sock.recv(65536).endswith(b"\r\n\r\n"):
pass
# send a response with an invalid content length -- this causes
# a ProtocolError to raise when trying to drain the connection
sock.send(
b"HTTP/1.1 404 NOT FOUND\r\n"
b"Content-Length: 1000\r\n"
b"Content-Type: text/plain\r\n"
b"\r\n"
)
sock.close()
self._start_server(socket_handler)
retries = Retry(total=1, raise_on_status=False, status_forcelist=[404])
with HTTPConnectionPool(
self.host, self.port, maxsize=10, retries=retries, block=True
) as pool:
pool.urlopen("GET", "/not_found", preload_content=False)
assert pool.num_connections == 1
class TestBrokenPipe(SocketDummyServerTestCase):
@notWindows
def test_ignore_broken_pipe_errors(self, monkeypatch):
# On Windows an aborted connection raises an error on
# attempts to read data out of a socket that's been closed.
sock_shut = Event()
orig_connect = HTTPConnection.connect
# a buffer that will cause two sendall calls
buf = "a" * 1024 * 1024 * 4
def connect_and_wait(*args, **kw):
ret = orig_connect(*args, **kw)
assert sock_shut.wait(5)
return ret
def socket_handler(listener):
for i in range(2):
sock = listener.accept()[0]
sock.send(
b"HTTP/1.1 404 Not Found\r\n"
b"Connection: close\r\n"
b"Content-Length: 10\r\n"
b"\r\n"
b"xxxxxxxxxx"
)
sock.shutdown(socket.SHUT_RDWR)
sock_shut.set()
sock.close()
monkeypatch.setattr(HTTPConnection, "connect", connect_and_wait)
self._start_server(socket_handler)
with HTTPConnectionPool(self.host, self.port) as pool:
r = pool.request("POST", "/", body=buf)
assert r.status == 404
assert r.headers["content-length"] == "10"
assert r.data == b"xxxxxxxxxx"
r = pool.request("POST", "/admin", chunked=True, body=buf)
assert r.status == 404
assert r.headers["content-length"] == "10"
assert r.data == b"xxxxxxxxxx"
class TestMultipartResponse(SocketDummyServerTestCase):
def test_multipart_assert_header_parsing_no_defects(self):
def socket_handler(listener):
for _ in range(2):
sock = listener.accept()[0]
while not sock.recv(65536).endswith(b"\r\n\r\n"):
pass
sock.sendall(
b"HTTP/1.1 404 Not Found\r\n"
b"Server: example.com\r\n"
b"Content-Type: multipart/mixed; boundary=36eeb8c4e26d842a\r\n"
b"Content-Length: 73\r\n"
b"\r\n"
b"--36eeb8c4e26d842a\r\n"
b"Content-Type: text/plain\r\n"
b"\r\n"
b"1\r\n"
b"--36eeb8c4e26d842a--\r\n",
)
sock.close()
self._start_server(socket_handler)
from urllib3.connectionpool import log
with mock.patch.object(log, "warning") as log_warning:
with HTTPConnectionPool(self.host, self.port, timeout=3) as pool:
resp = pool.urlopen("GET", "/")
assert resp.status == 404
assert (
resp.headers["content-type"]
== "multipart/mixed; boundary=36eeb8c4e26d842a"
)
assert len(resp.data) == 73
log_warning.assert_not_called()
|