| 1 |
"""Proxy tests. |
| 2 |
|
| 3 |
Tests do modify `os.environ` global states. Each test must be run in separate |
| 4 |
process. Must use `pytest --forked` or similar technique. |
| 5 |
""" |
| 6 |
|
| 7 |
import ipaddress |
| 8 |
import os |
| 9 |
import pytest |
| 10 |
import random |
| 11 |
import socket |
| 12 |
import socks |
| 13 |
from unittest import mock |
| 14 |
import urllib |
| 15 |
|
| 16 |
import httplib2 |
| 17 |
import tests |
| 18 |
from tests import socks5 |
| 19 |
|
| 20 |
|
| 21 |
def _raise_name_not_known_error(*args, **kwargs): |
| 22 |
raise socket.gaierror(socket.EAI_NONAME, "Name or service not known") |
| 23 |
|
| 24 |
|
| 25 |
@pytest.mark.parametrize( |
| 26 |
"url,kind,host,port,user,password", |
| 27 |
[ |
| 28 |
# ("noscheme.means.http", socks.PROXY_TYPE_HTTP, "noscheme.means.http", 80, None, None), |
| 29 |
("http://myproxy.example.com", socks.PROXY_TYPE_HTTP, "myproxy.example.com", 80, None, None), |
| 30 |
("http://zoidberg:fish@someproxy:99", socks.PROXY_TYPE_HTTP, "someproxy", 99, "zoidberg", "fish"), |
| 31 |
("http://[email protected]:1032", socks.PROXY_TYPE_HTTP, "fro.xy", 1032, "leila", None), |
| 32 |
("http://[::1]:8888", socks.PROXY_TYPE_HTTP, "::1", 8888, None, None), |
| 33 |
("socks4://myproxy.example.com", socks.PROXY_TYPE_SOCKS4, "myproxy.example.com", 80, None, None), |
| 34 |
("socks4://zoidberg:fish@someproxy:99", socks.PROXY_TYPE_SOCKS4, "someproxy", 99, "zoidberg", "fish"), |
| 35 |
("socks4://[email protected]:1032", socks.PROXY_TYPE_SOCKS4, "fro.xy", 1032, "leila", None), |
| 36 |
("socks4://[::1]:8888", socks.PROXY_TYPE_SOCKS4, "::1", 8888, None, None), |
| 37 |
("socks5://myproxy.example.com", socks.PROXY_TYPE_SOCKS5, "myproxy.example.com", 80, None, None), |
| 38 |
("socks5://zoidberg:fish@someproxy:99", socks.PROXY_TYPE_SOCKS5, "someproxy", 99, "zoidberg", "fish"), |
| 39 |
("socks5://[email protected]:1032", socks.PROXY_TYPE_SOCKS5, "fro.xy", 1032, "leila", None), |
| 40 |
("socks5://[::1]:8888", socks.PROXY_TYPE_SOCKS5, "::1", 8888, None, None), |
| 41 |
], |
| 42 |
) |
| 43 |
def test_from_url(url, kind, host, port, user, password): |
| 44 |
pi = httplib2.proxy_info_from_url(url) |
| 45 |
assert pi.proxy_type == kind, f"proxy_type expected={kind} invalid={pi.proxy_type}" |
| 46 |
assert pi.proxy_host == host, f"proxy_host expected={host} invalid={pi.proxy_host}" |
| 47 |
assert pi.proxy_port == port, f"proxy_port expected={port} invalid={pi.proxy_port}" |
| 48 |
assert pi.proxy_user == user, f"proxy_user expected={user} invalid={pi.proxy_user}" |
| 49 |
assert pi.proxy_pass == password, f"proxy_pass expected={password} invalid={pi.proxy_pass}" |
| 50 |
|
| 51 |
|
| 52 |
@pytest.mark.forked |
| 53 |
def test_from_env(monkeypatch): |
| 54 |
assert os.environ.get("http_proxy") is None |
| 55 |
monkeypatch.setenv("http_proxy", "http://myproxy.example.com:8080") |
| 56 |
pi = httplib2.proxy_info_from_environment() |
| 57 |
assert pi.proxy_host == "myproxy.example.com" |
| 58 |
assert pi.proxy_port == 8080 |
| 59 |
|
| 60 |
|
| 61 |
@pytest.mark.forked |
| 62 |
def test_from_env_https(monkeypatch): |
| 63 |
assert os.environ.get("http_proxy") is None |
| 64 |
monkeypatch.setenv("http_proxy", "http://myproxy.example.com:80") |
| 65 |
monkeypatch.setenv("https_proxy", "http://myproxy.example.com:81") |
| 66 |
pi = httplib2.proxy_info_from_environment("https") |
| 67 |
assert pi.proxy_host == "myproxy.example.com" |
| 68 |
assert pi.proxy_port == 81 |
| 69 |
|
| 70 |
|
| 71 |
@pytest.mark.forked |
| 72 |
def test_from_env_none(): |
| 73 |
os.environ.clear() |
| 74 |
pi = httplib2.proxy_info_from_environment() |
| 75 |
assert pi is None |
| 76 |
|
| 77 |
|
| 78 |
def test_from_env_other(): |
| 79 |
pi = httplib2.proxy_info_from_environment("foobar") |
| 80 |
assert pi is None |
| 81 |
|
| 82 |
|
| 83 |
def test_proxy_info_repr(): |
| 84 |
pi = httplib2.ProxyInfo(3, "pseudorandom", 8123, proxy_pass="secret") |
| 85 |
r = repr(pi) |
| 86 |
assert "pseudorandom" in r |
| 87 |
assert "8123" in r |
| 88 |
assert "secret" not in r |
| 89 |
|
| 90 |
|
| 91 |
@pytest.mark.forked |
| 92 |
def test_applies_to(monkeypatch): |
| 93 |
monkeypatch.setenv("http_proxy", "http://myproxy.example.com:80") |
| 94 |
monkeypatch.setenv("https_proxy", "http://myproxy.example.com:81") |
| 95 |
monkeypatch.setenv("no_proxy", "localhost,example.com,.wildcard") |
| 96 |
pi = httplib2.proxy_info_from_environment() |
| 97 |
assert not pi.applies_to("localhost") |
| 98 |
assert pi.applies_to("www.google.com") |
| 99 |
assert pi.applies_to("prefixlocalhost") |
| 100 |
assert pi.applies_to("www.example.com") |
| 101 |
assert pi.applies_to("sub.example.com") |
| 102 |
assert not pi.applies_to("sub.wildcard") |
| 103 |
assert not pi.applies_to("pub.sub.wildcard") |
| 104 |
|
| 105 |
|
| 106 |
@pytest.mark.forked |
| 107 |
def test_noproxy_trailing_comma(monkeypatch): |
| 108 |
monkeypatch.setenv("http_proxy", "http://myproxy.example.com:80") |
| 109 |
monkeypatch.setenv("no_proxy", "localhost,other.host,") |
| 110 |
pi = httplib2.proxy_info_from_environment() |
| 111 |
assert not pi.applies_to("localhost") |
| 112 |
assert not pi.applies_to("other.host") |
| 113 |
assert pi.applies_to("example.domain") |
| 114 |
|
| 115 |
|
| 116 |
@pytest.mark.forked |
| 117 |
def test_noproxy_star(monkeypatch): |
| 118 |
monkeypatch.setenv("http_proxy", "http://myproxy.example.com:80") |
| 119 |
monkeypatch.setenv("NO_PROXY", "*") |
| 120 |
pi = httplib2.proxy_info_from_environment() |
| 121 |
for host in ("localhost", "169.254.38.192", "www.google.com"): |
| 122 |
assert not pi.applies_to(host) |
| 123 |
|
| 124 |
|
| 125 |
def test_headers(): |
| 126 |
headers = {"key0": "val0", "key1": "val1"} |
| 127 |
pi = httplib2.ProxyInfo(httplib2.socks.PROXY_TYPE_HTTP, "localhost", 1234, proxy_headers=headers) |
| 128 |
assert pi.proxy_headers == headers |
| 129 |
|
| 130 |
|
| 131 |
@mock.patch("socket.socket.connect", spec=True) |
| 132 |
def test_server_not_found_error_is_raised_for_invalid_hostname(mock_socket_connect): |
| 133 |
"""Invalidates https://github.com/httplib2/httplib2/pull/100.""" |
| 134 |
mock_socket_connect.side_effect = _raise_name_not_known_error |
| 135 |
http = httplib2.Http(proxy_info=httplib2.ProxyInfo(httplib2.socks.PROXY_TYPE_HTTP, "255.255.255.255", 8001)) |
| 136 |
try: |
| 137 |
http.request("http://invalid.hostname.foo.bar/", "GET") |
| 138 |
except httplib2.ServerNotFoundError: |
| 139 |
pass |
| 140 |
except Exception as e: |
| 141 |
assert "name or service not known" in str(e).lower() |
| 142 |
|
| 143 |
|
| 144 |
def test_auth_str_bytes(): |
| 145 |
# https://github.com/httplib2/httplib2/pull/115 |
| 146 |
# Proxy-Authorization b64encode() TypeError: a bytes-like object is required, not 'str' |
| 147 |
with tests.server_const_http(request_count=2) as uri: |
| 148 |
uri_parsed = urllib.parse.urlparse(uri) |
| 149 |
http = httplib2.Http( |
| 150 |
proxy_info=httplib2.ProxyInfo( |
| 151 |
httplib2.socks.PROXY_TYPE_HTTP, |
| 152 |
proxy_host=uri_parsed.hostname, |
| 153 |
proxy_port=uri_parsed.port, |
| 154 |
proxy_rdns=True, |
| 155 |
proxy_user="user_str", |
| 156 |
proxy_pass="pass_str", |
| 157 |
) |
| 158 |
) |
| 159 |
response, _ = http.request(uri, "GET") |
| 160 |
assert response.status == 200 |
| 161 |
|
| 162 |
with tests.server_const_http(request_count=2) as uri: |
| 163 |
uri_parsed = urllib.parse.urlparse(uri) |
| 164 |
http = httplib2.Http( |
| 165 |
proxy_info=httplib2.ProxyInfo( |
| 166 |
httplib2.socks.PROXY_TYPE_HTTP, |
| 167 |
proxy_host=uri_parsed.hostname, |
| 168 |
proxy_port=uri_parsed.port, |
| 169 |
proxy_rdns=True, |
| 170 |
proxy_user=b"user_bytes", |
| 171 |
proxy_pass=b"pass_bytes", |
| 172 |
) |
| 173 |
) |
| 174 |
response, _ = http.request(uri, "GET") |
| 175 |
assert response.status == 200 |
| 176 |
|
| 177 |
|
| 178 |
def test_socks5_auth(): |
| 179 |
def proxy_conn(client, tick): |
| 180 |
data = client.recv(64) |
| 181 |
assert data == bytes( |
| 182 |
[socks5.VERSION, 0x02, socks5.AUTH_NO_AUTHENTICATION_REQUIRED, socks5.AUTH_USERNAME_PASSWORD] |
| 183 |
) |
| 184 |
client.send(socks5.SERVER_GREETING_USER_PASS) |
| 185 |
data = client.recv(64) |
| 186 |
assert data == b"\x01\x08user_str\x08pass_str" |
| 187 |
client.send(socks5.AUTH_FAILURE) |
| 188 |
tick(None) |
| 189 |
|
| 190 |
with tests.server_socket(proxy_conn) as uri: |
| 191 |
uri_parsed = urllib.parse.urlparse(uri) |
| 192 |
proxy_info = httplib2.ProxyInfo( |
| 193 |
httplib2.socks.PROXY_TYPE_SOCKS5, |
| 194 |
proxy_host=uri_parsed.hostname, |
| 195 |
proxy_port=uri_parsed.port, |
| 196 |
proxy_rdns=True, |
| 197 |
proxy_user="user_str", |
| 198 |
proxy_pass="pass_str", |
| 199 |
) |
| 200 |
http = httplib2.Http(proxy_info=proxy_info) |
| 201 |
try: |
| 202 |
http.request(uri, "GET") |
| 203 |
assert False, "expected socks authentication error" |
| 204 |
except httplib2.socks.SOCKS5AuthError: |
| 205 |
pass |
| 206 |
except Exception as e: |
| 207 |
assert "authentication failed" in str(e) |
| 208 |
|
| 209 |
|
| 210 |
@pytest.mark.forked |
| 211 |
def test_functional_socks5(monkeypatch): |
| 212 |
expect_body = "unique-{}".format(random.randint(1, 100)).encode("utf-8") |
| 213 |
gserver = [None, b""] |
| 214 |
glog = [] |
| 215 |
|
| 216 |
def proxy_conn(client, tick): |
| 217 |
assert gserver[0] is not None |
| 218 |
assert gserver[1] |
| 219 |
|
| 220 |
data_hello = client.recv(64) |
| 221 |
assert data_hello == bytes([socks5.VERSION, 1, socks5.AUTH_NO_AUTHENTICATION_REQUIRED]) |
| 222 |
client.send(socks5.SERVER_GREETING_NO_AUTH) |
| 223 |
|
| 224 |
data_connect = client.recv(64) |
| 225 |
assert data_connect == bytes([socks5.VERSION, socks5.CMD_CONNECT, 0x00]) + gserver[1] |
| 226 |
http_endpoint = gserver[0] # TODO parse data_connect |
| 227 |
backend = socket.create_connection(http_endpoint, timeout=5) |
| 228 |
client.send(b"\x05\x00\x00\x01\x00\x00\x00\x00\x00\x00") |
| 229 |
|
| 230 |
request_buf = tests.BufferedReader(client) |
| 231 |
request = tests.HttpRequest.from_buffered(request_buf) |
| 232 |
assert request is not None |
| 233 |
glog.append(request) |
| 234 |
backend.sendall(request.raw) |
| 235 |
response_buf = tests.BufferedReader(backend) |
| 236 |
backend_response = tests.HttpResponse.from_buffered(response_buf) |
| 237 |
client.sendall(backend_response.raw) |
| 238 |
|
| 239 |
tick(request) |
| 240 |
|
| 241 |
with tests.server_socket(proxy_conn, scheme=None) as proxy_endpoint, tests.server_const_http( |
| 242 |
body=expect_body, scheme=None |
| 243 |
) as http_endpoint: |
| 244 |
http_host, http_port = http_endpoint |
| 245 |
http_ip_version = check_ip_version(http_host) |
| 246 |
http_endpoint_socks_format = b"" |
| 247 |
if http_ip_version == 4: |
| 248 |
http_endpoint_socks_format = b"\x01" + bytes(map(int, http_host.split("."))) |
| 249 |
elif http_ip_version == 6: |
| 250 |
pass # TODO |
| 251 |
else: |
| 252 |
http_endpoint_socks_format = b"\x03" + bytes([len(http_host)]) + http_host.encode("ascii") |
| 253 |
assert http_endpoint_socks_format |
| 254 |
http_endpoint_socks_format += http_port.to_bytes(2, byteorder="big") |
| 255 |
gserver[0] = http_endpoint |
| 256 |
gserver[1] = http_endpoint_socks_format |
| 257 |
|
| 258 |
proxy_uri = "socks5://{}:{}".format(*proxy_endpoint) |
| 259 |
monkeypatch.setenv("http_proxy", proxy_uri) |
| 260 |
uri = "http://{}:{}/".format(*http_endpoint) |
| 261 |
http = httplib2.Http() |
| 262 |
response, body = http.request(uri, "GET") |
| 263 |
assert response.status == 200 |
| 264 |
assert body == expect_body |
| 265 |
|
| 266 |
|
| 267 |
def check_ip_version(s: str): |
| 268 |
try: |
| 269 |
ip = ipaddress.ip_address(s) |
| 270 |
if isinstance(ip, ipaddress.IPv4Address): |
| 271 |
return 4 |
| 272 |
elif isinstance(ip, ipaddress.IPv6Address): |
| 273 |
return 6 |
| 274 |
else: |
| 275 |
raise NotImplementedError |
| 276 |
except ValueError: |
| 277 |
return None |
| 278 |
|
| 279 |
|
| 280 |
@pytest.mark.forked |
| 281 |
def test_functional_noproxy_star_http(monkeypatch): |
| 282 |
def handler(request): |
| 283 |
if request.method == "CONNECT": |
| 284 |
return tests.http_response_bytes( |
| 285 |
status="400 Expected direct", |
| 286 |
headers={"connection": "close"}, |
| 287 |
) |
| 288 |
return tests.http_response_bytes() |
| 289 |
|
| 290 |
with tests.server_request(handler) as uri: |
| 291 |
monkeypatch.setenv("http_proxy", uri) |
| 292 |
monkeypatch.setenv("no_proxy", "*") |
| 293 |
http = httplib2.Http() |
| 294 |
response, _ = http.request(uri, "GET") |
| 295 |
assert response.status == 200 |
| 296 |
|
| 297 |
|
| 298 |
@pytest.mark.forked |
| 299 |
def test_functional_noproxy_star_https(monkeypatch): |
| 300 |
def handler(request): |
| 301 |
if request.method == "CONNECT": |
| 302 |
return tests.http_response_bytes( |
| 303 |
status="400 Expected direct", |
| 304 |
headers={"connection": "close"}, |
| 305 |
) |
| 306 |
return tests.http_response_bytes() |
| 307 |
|
| 308 |
with tests.server_request(handler, tls=True) as uri: |
| 309 |
monkeypatch.setenv("https_proxy", uri) |
| 310 |
monkeypatch.setenv("no_proxy", "*") |
| 311 |
http = httplib2.Http(ca_certs=tests.CA_CERTS) |
| 312 |
response, _ = http.request(uri, "GET") |
| 313 |
assert response.status == 200 |