Debian Codegraph @

tests/test_https.py

raw
1 import socket
2 import ssl
3 import urllib
4 import warnings
5
6 import pytest
7
8 import httplib2
9 import tests
10
11
12 def test_get_via_https():
13 # Test that we can handle HTTPS
14 http = httplib2.Http(ca_certs=tests.CA_CERTS)
15 with tests.server_const_http(tls=True) as uri:
16 response, _ = http.request(uri, "GET")
17 assert response.status == 200
18
19
20 def test_get_301_via_https():
21 http = httplib2.Http(ca_certs=tests.CA_CERTS)
22 glocation = [""] # nonlocal kind of trick, maybe redundant
23
24 def handler(request):
25 if request.uri == "/final":
26 return tests.http_response_bytes(body=b"final")
27 return tests.http_response_bytes(status="301 goto", headers={"location": glocation[0]})
28
29 with tests.server_request(handler, request_count=2, tls=True) as uri:
30 glocation[0] = urllib.parse.urljoin(uri, "/final")
31 response, content = http.request(uri, "GET")
32 assert response.status == 200
33 assert content == b"final"
34 assert response.previous.status == 301
35 assert response.previous["location"] == glocation[0]
36
37
38 def test_get_301_via_https_spec_violation_on_location():
39 # Test that we follow redirects through HTTPS
40 # even if they violate the spec by including
41 # a relative Location: header instead of an absolute one.
42 http = httplib2.Http(ca_certs=tests.CA_CERTS)
43
44 def handler(request):
45 if request.uri == "/final":
46 return tests.http_response_bytes(body=b"final")
47 return tests.http_response_bytes(status="301 goto", headers={"location": "/final"})
48
49 with tests.server_request(handler, request_count=2, tls=True) as uri:
50 response, content = http.request(uri, "GET")
51 assert response.status == 200
52 assert content == b"final"
53 assert response.previous.status == 301
54
55
56 def test_invalid_ca_certs_path():
57 http = httplib2.Http(ca_certs="/nosuchfile")
58 with tests.server_const_http(request_count=0, tls=True) as uri:
59 with tests.assert_raises(IOError):
60 http.request(uri, "GET")
61
62
63 def test_not_trusted_ca():
64 # Test that we get a SSLHandshakeError if we try to access
65 # server using a CA cert file that doesn't contain server's CA.
66 http = httplib2.Http(ca_certs=tests.CA_UNUSED_CERTS)
67 with tests.server_const_http(tls=True) as uri:
68 try:
69 http.request(uri, "GET")
70 assert False, "expected CERTIFICATE_VERIFY_FAILED"
71 except ssl.SSLError as e:
72 assert e.reason == "CERTIFICATE_VERIFY_FAILED"
73 except httplib2.SSLHandshakeError: # Python2
74 pass
75
76
77 # Python >= 3.7
78 ssl_context_accept_version = (
79 hasattr(ssl.SSLContext(), "maximum_version")
80 and hasattr(ssl.SSLContext(), "minimum_version")
81 )
82 tls_minmax_versions = (
83 (None, "TLSv1_2", ssl.TLSVersion.TLSv1_2)
84 if ssl_context_accept_version else (None,)
85 )
86
87
88 @pytest.mark.skipif(not ssl_context_accept_version, reason="ssl doesn't support TLS min/max")
89 @pytest.mark.parametrize("attr", ("maximum_version", "minimum_version"))
90 @pytest.mark.parametrize("version", tls_minmax_versions)
91 def test_set_tls_version(attr, version):
92 ctx = ssl.SSLContext()
93 # We expect failure on Python < 3.7 or OpenSSL < 1.1
94 expect_success = hasattr(ctx, attr)
95 kwargs = {"tls_" + attr: version}
96 http = httplib2.Http(**kwargs)
97 try:
98 http.request(tests.DUMMY_HTTPS_URL)
99 except RuntimeError:
100 assert not expect_success
101 except socket.error:
102 assert expect_success
103
104
105 @pytest.mark.skipif(not ssl_context_accept_version, reason="ssl doesn't support TLS min/max")
106 def test_max_tls_version():
107 http = httplib2.Http(ca_certs=tests.CA_CERTS, tls_maximum_version="TLSv1_2")
108 with tests.server_const_http(tls=True) as uri:
109 http.request(uri)
110 _, tls_ver, _ = http.connections.popitem()[1].sock.cipher()
111 if tls_ver == "TLSv1/SSLv3":
112 warnings.warn(DeprecationWarning("outdated ssl module"))
113 return
114 assert "TLSv1.0" <= tls_ver <= "TLSv1.2"
115
116
117 def test_client_cert_verified():
118 cert_log = []
119
120 def setup_tls(context, server, skip_errors):
121 context.load_verify_locations(cafile=tests.CA_CERTS)
122 context.verify_mode = ssl.CERT_REQUIRED
123 return context.wrap_socket(server, server_side=True)
124
125 def handler(request):
126 cert_log.append(request.client_sock.getpeercert())
127 return tests.http_response_bytes()
128
129 http = httplib2.Http(ca_certs=tests.CA_CERTS)
130 with tests.server_request(handler, tls=setup_tls) as uri:
131 uri_parsed = urllib.parse.urlparse(uri)
132 http.add_certificate(tests.CLIENT_PEM, tests.CLIENT_PEM, uri_parsed.netloc)
133 http.request(uri)
134
135 assert len(cert_log) == 1
136 expect_serial = tests.x509_serial(tests.CLIENT_PEM)
137 assert int(cert_log[0]["serialNumber"], base=16) == expect_serial
138
139
140 def test_client_cert_password_verified():
141 cert_log = []
142
143 def setup_tls(context, server, skip_errors):
144 context.load_verify_locations(cafile=tests.CA_CERTS)
145 context.verify_mode = ssl.CERT_REQUIRED
146 return context.wrap_socket(server, server_side=True)
147
148 def handler(request):
149 cert_log.append(request.client_sock.getpeercert())
150 return tests.http_response_bytes()
151
152 http = httplib2.Http(ca_certs=tests.CA_CERTS)
153 with tests.server_request(handler, tls=setup_tls) as uri:
154 uri_parsed = urllib.parse.urlparse(uri)
155 http.add_certificate(tests.CLIENT_ENCRYPTED_PEM, tests.CLIENT_ENCRYPTED_PEM, uri_parsed.netloc, password="12345")
156 http.request(uri)
157
158 assert len(cert_log) == 1
159 expect_serial = tests.x509_serial(tests.CLIENT_ENCRYPTED_PEM)
160 assert int(cert_log[0]["serialNumber"], base=16) == expect_serial
161
162
163 # Python >= 3.6
164 def test_sni_set_servername_callback():
165 sni_log = []
166
167 def setup_tls(context, server, skip_errors):
168 context.set_servername_callback(lambda _sock, hostname, _context: sni_log.append(hostname))
169 return context.wrap_socket(server, server_side=True)
170
171 http = httplib2.Http(ca_certs=tests.CA_CERTS)
172 with tests.server_const_http(tls=setup_tls) as uri:
173 uri_parsed = urllib.parse.urlparse(uri)
174 http.request(uri)
175 assert sni_log == [uri_parsed.hostname]
176
177
178 def test_http_redirect_https():
179 http = httplib2.Http(ca_certs=tests.CA_CERTS)
180 with tests.server_const_http(tls=True) as uri_https:
181 with tests.server_const_http(status=301, headers={"location": uri_https}) as uri_http:
182 response, _ = http.request(uri_http, "GET")
183 assert response.status == 200
184 assert response["content-location"] == uri_https
185 assert response.previous.status == 301
186 assert response.previous["content-location"] == uri_http
187
188
189 def test_https_redirect_http():
190 http = httplib2.Http(ca_certs=tests.CA_CERTS)
191 with tests.server_const_http() as uri_http:
192 with tests.server_const_http(tls=True, status=301, headers={"location": uri_http}) as uri_https:
193 response, _ = http.request(uri_https, "GET")
194 assert response.status == 200
195 assert response["content-location"] == uri_http
196 assert response.previous.status == 301
197 assert response.previous["content-location"] == uri_https
198
199
200 def test_disable_ssl_certificate_validation():
201 http = httplib2.Http(disable_ssl_certificate_validation=True)
202 with tests.server_const_http(tls=True) as uri:
203 response, _ = http.request(uri, "GET")
204 assert response.status == 200