-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathadapter.py
More file actions
359 lines (287 loc) · 12.2 KB
/
adapter.py
File metadata and controls
359 lines (287 loc) · 12.2 KB
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
from __future__ import unicode_literals
from logging_helper import setup_logging
import urllib3
from urllib3.util.url import parse_url
import requests
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.timeout import Timeout
from ._rules import https_url_rewrite, _get_rulesets
from ._chrome_preload_hsts import _preload_including_subdomains
from ._mozilla_preload_hsts import _preload_remove_negative
from ._util import _check_in
PY2 = str != "".__class__
if PY2:
str = "".__class__
_REASON = "HTTPS Everywhere"
_HTTP_BLOCK_CODE = 406
logger = setup_logging()
def _generate_response(code=200, reason=None, headers=None):
r = requests.Response()
r.encoding = "utf8"
r.status_code = code
r.reason = reason or _REASON
r._content = ""
if headers:
r.headers.update(headers)
return r
def _generate_redirect(location, code=302):
return _generate_response(code=code, headers={"Location": location})
class BlockAdapter(HTTPAdapter):
block_code = 500
def send_block(self, request, status_code=None, *args, **kwargs):
response = _generate_response(status_code or self.block_code)
response.url = request.url
response.request = request
return response
class BlockCodeAdapter(BlockAdapter):
block_code = _HTTP_BLOCK_CODE
class HTTPBlockAdapter(BlockCodeAdapter):
def send(self, request, *args, **kwargs):
if request.url.startswith("http:"):
return self.send_block(request, *args, **kwargs)
return super(HTTPBlockAdapter, self).send(request, *args, **kwargs)
class HTTPRedirectBlockAdapter(BlockCodeAdapter):
def send(self, request, *args, **kwargs):
response = super(HTTPRedirectBlockAdapter, self).send(request, *args, **kwargs)
if response.is_redirect:
target = response.headers["location"]
if target.startswith("http:"):
return self.send_block(request, *args, **kwargs)
return response
class RedirectAdapter(HTTPAdapter):
redirect_code = 302
@staticmethod
def _generate_redirect(location, code=None):
return _generate_response(
code=RedirectAdapter.redirect_code, headers={"Location": location}
)
def get_redirect(self, url):
logger.debug("No implementation for get_redirect({!r})".format(url))
def send(self, request, *args, **kwargs):
code = self.redirect_code
rv = self.get_redirect(request.url)
if rv is None:
url = None
elif isinstance(rv, requests.Response):
logger.info(
"adapter responding to {} with {}: {!r}".format(
request.url, rv.url, rv.headers
)
)
rv.request = request
rv.url = request.url
return rv
elif isinstance(rv, tuple):
url, code = rv
else:
url = rv
if url and url != request.url:
# need to prevent redirecting to https when https has already downgraded to http
response = self._generate_redirect(url)
response.request = request
response.url = request.url
response._redirected = True
logger.info("adapter redirecting {} to {}".format(request.url, url))
return response
try:
logger.debug("no redirection of {} occurred".format(request.url))
resp = super(RedirectAdapter, self).send(request, *args, **kwargs)
except Exception as e:
resp = self.handle_error(e, request)
return resp
def handle_error(self, exc, request=None):
logger.error(
"handle_error {}.{}: {}".format(
exc.__class__.__module__, exc.__class__.__name__, exc
)
)
raise exc
class HTTPSEverywhereOnlyAdapter(RedirectAdapter):
def __init__(self, *args, **kwargs):
super(HTTPSEverywhereOnlyAdapter, self).__init__(*args, **kwargs)
# prime cache
_get_rulesets()
def get_redirect(self, url):
if url.startswith("http://"):
if PY2:
url = str(url)
new_url = https_url_rewrite(url)
if new_url.startswith("https://"):
return new_url
return super(HTTPSEverywhereOnlyAdapter, self).get_redirect(url)
class PreloadHSTSAdapter(RedirectAdapter):
def __init__(self, *args, **kwargs):
super(PreloadHSTSAdapter, self).__init__(*args, **kwargs)
# prime cache
self._domains = self._get_preload()
def get_redirect(self, url):
if url.startswith("http://"):
p = parse_url(url)
if _check_in(self._domains, p.host):
new_url = "https:" + url[5:]
return new_url
return super(PreloadHSTSAdapter, self).get_redirect(url)
class ChromePreloadHSTSAdapter(PreloadHSTSAdapter):
_get_preload = _preload_including_subdomains
class MozillaPreloadHSTSAdapter(PreloadHSTSAdapter):
_get_preload = _preload_remove_negative
class HTTPSEverywhereAdapter(ChromePreloadHSTSAdapter, HTTPSEverywhereOnlyAdapter):
pass
class ForceHTTPSAdapter(RedirectAdapter):
def __init__(self, *args, **kwargs):
https_exclusions = kwargs.pop("https_exclusions", [])
super(ForceHTTPSAdapter, self).__init__(*args, **kwargs)
self._https_exclusions = https_exclusions
def _prevent_https(self, tail):
for rule in self._https_exclusions:
if tail.startswith(rule):
return True
return False
def get_redirect(self, url):
if url.startswith("https://"):
tail = url[8:]
if self._prevent_https(tail):
return "http://" + tail
elif url.startswith("http://"):
tail = url[7:]
if not self._prevent_https(tail):
return "https://" + tail
return super(ForceHTTPSAdapter, self).get_redirect(url)
# Rename to CheckHTTPRedirectAdapter ?
# Allows for scenarios where https is broken, and http redirects to
# a different host, such as www.modwsgi.org
class PreferHTTPSAdapter(ForceHTTPSAdapter):
_head_timeout = Timeout(connect=10, read=5)
def _follow_redirects_on_http(self, url):
previous_url = None
while True:
current_url = url
# TODO: use same session
# TODO: if http is a timeout, use a shorter timeout/retry for https
# as it is likely to also not work
try:
response = None
try:
response = requests.head(
current_url, allow_redirects=False, timeout=self._head_timeout
)
response.raise_for_status()
except Exception: # pragma: no cover
# Add test case for this, possibly from code.google.com
if response and response.status_code == 403:
response = requests.get(
current_url,
allow_redirects=False,
timeout=self._head_timeout,
)
response.raise_for_status()
else:
raise
except Exception as e:
logger.info("head failed for {}: {!r}".format(current_url, e))
return previous_url
else:
logger.debug(
"head",
current_url,
response.url,
response,
response.headers,
response.content,
)
location = response.headers.get("location")
if not location or location == current_url:
return previous_url
else: # pragma: no cover
# modwsgi scenario
if location.startswith("https:"):
tail = location[8:]
if self._prevent_https(tail):
return "http://" + tail
return response
elif location.startswith("http://"):
previous_url = current_url
url = location
else:
raise RuntimeError(
"{} redirected to {}".format(current_url, location)
)
def send(self, request, *args, **kwargs):
url = request.url
if url.startswith("https://"):
tail = url[8:]
if self._prevent_https(tail):
logger.info("downgraded {} to http".format(url))
response = self._generate_redirect("http://" + tail)
response.request = request
response.url = url
return response
elif url.startswith("http://"):
tail = url[7:]
if not self._prevent_https(tail):
logger.debug("checking {} for redirects".format(url))
redirect = self._follow_redirects_on_http(url)
if redirect: # pragma: no cover
if not isinstance(redirect, str):
# Following redirects may provide a redirect response object
# This was the modwsgi scenario
logger.info(
"upgrading {} to https with {}".format(url, redirect.url)
)
return redirect
elif redirect != url:
if redirect.startswith("http://"):
tail = url[7:]
else:
raise RuntimeError(
"Unexpectedly {} redirected to {}".format(url, redirect)
)
logger.info("upgrading {} to https".format(url))
response = self._generate_redirect("https://" + tail)
response.request = request
response.url = request.url
return response
return super(PreferHTTPSAdapter, self).send(request, *args, **kwargs)
class UpgradeHTTPSAdapter(ForceHTTPSAdapter):
_https_downgrade_exceptions = (
requests.exceptions.ConnectionError,
urllib3.exceptions.MaxRetryError,
requests.exceptions.SSLError,
)
def send(self, request, *args, **kwargs):
url = request.url
if not url.startswith("https://"):
response = super(UpgradeHTTPSAdapter, self).send(request, *args, **kwargs)
logger.debug("http response reason: {}".format(response.reason))
return response
try:
return super(UpgradeHTTPSAdapter, self).send(request, *args, **kwargs)
except self._https_downgrade_exceptions as e:
logger.info("downgrading {} to http due to {}".format(url, e))
request.url = "http://" + url[8:]
# Note: skipping base classes including ForceHTTPSAdapter
return super(RedirectAdapter, self).send(request, *args, **kwargs)
class SafeUpgradeHTTPSAdapter(ForceHTTPSAdapter):
_https_downgrade_exceptions = UpgradeHTTPSAdapter._https_downgrade_exceptions
def send(self, request, *args, **kwargs):
url = request.url
if not url.startswith("https://"):
response = super(SafeUpgradeHTTPSAdapter, self).send(
request, *args, **kwargs
)
logger.debug("http response reason: {}".format(response.reason))
if response.reason != _REASON: # pragma: no cover
return response
request.url = response.headers["location"]
try:
response = super(SafeUpgradeHTTPSAdapter, self).send(
request, *args, **kwargs
)
redirect = response.headers.get("location")
if not redirect or redirect != url:
return response
except self._https_downgrade_exceptions as e:
logger.info("downgrading {} to http due to {}".format(url, e))
request.url = "http://" + request.url[8:]
# Note: skipping base classes including ForceHTTPSAdapter
return super(RedirectAdapter, self).send(request, *args, **kwargs)