-
Notifications
You must be signed in to change notification settings - Fork 160
Expand file tree
/
Copy pathtest_http_proxy.py
More file actions
320 lines (278 loc) · 9.99 KB
/
test_http_proxy.py
File metadata and controls
320 lines (278 loc) · 9.99 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
import ssl
import typing
import hpack
import hyperframe.frame
import pytest
from httpcore import (
SOCKET_OPTION,
ConnectionPool,
MockBackend,
MockStream,
NetworkStream,
Origin,
Proxy,
ProxyError,
)
def test_proxy_forwarding():
"""
Send an HTTP request via a proxy.
"""
network_backend = MockBackend(
[
b"HTTP/1.1 200 OK\r\n",
b"Content-Type: plain/text\r\n",
b"Content-Length: 13\r\n",
b"\r\n",
b"Hello, world!",
]
)
with ConnectionPool(
proxy=Proxy("http://localhost:8080/"),
max_connections=10,
network_backend=network_backend,
) as proxy:
# Sending an intial request, which once complete will return to the pool, IDLE.
with proxy.stream("GET", "http://example.com/") as response:
info = [repr(c) for c in proxy.connections]
assert info == [
"<ForwardHTTPConnection ['http://localhost:8080', HTTP/1.1, ACTIVE, Request Count: 1]>"
]
response.read()
assert response.status == 200
assert response.content == b"Hello, world!"
info = [repr(c) for c in proxy.connections]
assert info == [
"<ForwardHTTPConnection ['http://localhost:8080', HTTP/1.1, IDLE, Request Count: 1]>"
]
assert proxy.connections[0].is_idle()
assert proxy.connections[0].is_available()
assert not proxy.connections[0].is_closed()
# A connection on a forwarding proxy can only handle HTTP requests to the same origin.
assert proxy.connections[0].can_handle_request(
Origin(b"http", b"example.com", 80)
)
assert not proxy.connections[0].can_handle_request(
Origin(b"http", b"other.com", 80)
)
assert not proxy.connections[0].can_handle_request(
Origin(b"https", b"example.com", 443)
)
assert not proxy.connections[0].can_handle_request(
Origin(b"https", b"other.com", 443)
)
def test_proxy_tunneling():
"""
Send an HTTPS request via a proxy.
"""
network_backend = MockBackend(
[
# The initial response to the proxy CONNECT
b"HTTP/1.1 200 OK\r\n\r\n",
# The actual response from the remote server
b"HTTP/1.1 200 OK\r\n",
b"Content-Type: plain/text\r\n",
b"Content-Length: 13\r\n",
b"\r\n",
b"Hello, world!",
]
)
with ConnectionPool(
proxy=Proxy("http://localhost:8080/"),
network_backend=network_backend,
) as proxy:
# Sending an intial request, which once complete will return to the pool, IDLE.
with proxy.stream("GET", "https://example.com/") as response:
info = [repr(c) for c in proxy.connections]
assert info == [
"<TunnelHTTPConnection ['https://example.com:443', HTTP/1.1, ACTIVE, Request Count: 1]>"
]
response.read()
assert response.status == 200
assert response.content == b"Hello, world!"
info = [repr(c) for c in proxy.connections]
assert info == [
"<TunnelHTTPConnection ['https://example.com:443', HTTP/1.1, IDLE, Request Count: 1]>"
]
assert proxy.connections[0].is_idle()
assert proxy.connections[0].is_available()
assert not proxy.connections[0].is_closed()
# A connection on a tunneled proxy can only handle HTTPS requests to the same origin.
assert not proxy.connections[0].can_handle_request(
Origin(b"http", b"example.com", 80)
)
assert not proxy.connections[0].can_handle_request(
Origin(b"http", b"other.com", 80)
)
assert proxy.connections[0].can_handle_request(
Origin(b"https", b"example.com", 443)
)
assert not proxy.connections[0].can_handle_request(
Origin(b"https", b"other.com", 443)
)
# We need to adapt the mock backend here slightly in order to deal
# with the proxy case. We do not want the initial connection to the proxy
# to indicate an HTTP/2 connection, but we do want it to indicate HTTP/2
# once the SSL upgrade has taken place.
class HTTP1ThenHTTP2Stream(MockStream):
def start_tls(
self,
ssl_context: ssl.SSLContext,
server_hostname: typing.Optional[str] = None,
timeout: typing.Optional[float] = None,
) -> NetworkStream:
self._http2 = True
return self
class HTTP1ThenHTTP2Backend(MockBackend):
def connect_tcp(
self,
host: str,
port: int,
timeout: typing.Optional[float] = None,
local_address: typing.Optional[str] = None,
socket_options: typing.Optional[typing.Iterable[SOCKET_OPTION]] = None,
) -> NetworkStream:
return HTTP1ThenHTTP2Stream(list(self._buffer))
def test_proxy_tunneling_http2():
"""
Send an HTTP/2 request via a proxy.
"""
network_backend = HTTP1ThenHTTP2Backend(
[
# The initial response to the proxy CONNECT
b"HTTP/1.1 200 OK\r\n\r\n",
# The actual response from the remote server
hyperframe.frame.SettingsFrame().serialize(),
hyperframe.frame.HeadersFrame(
stream_id=1,
data=hpack.Encoder().encode(
[
(b":status", b"200"),
(b"content-type", b"plain/text"),
]
),
flags=["END_HEADERS"],
).serialize(),
hyperframe.frame.DataFrame(
stream_id=1, data=b"Hello, world!", flags=["END_STREAM"]
).serialize(),
],
)
with ConnectionPool(
proxy=Proxy("http://localhost:8080/"),
network_backend=network_backend,
http2=True,
) as proxy:
# Sending an intial request, which once complete will return to the pool, IDLE.
with proxy.stream("GET", "https://example.com/") as response:
info = [repr(c) for c in proxy.connections]
assert info == [
"<TunnelHTTPConnection ['https://example.com:443', HTTP/2, ACTIVE, Request Count: 1]>"
]
response.read()
assert response.status == 200
assert response.content == b"Hello, world!"
info = [repr(c) for c in proxy.connections]
assert info == [
"<TunnelHTTPConnection ['https://example.com:443', HTTP/2, IDLE, Request Count: 1]>"
]
assert proxy.connections[0].is_idle()
assert proxy.connections[0].is_available()
assert not proxy.connections[0].is_closed()
# A connection on a tunneled proxy can only handle HTTPS requests to the same origin.
assert not proxy.connections[0].can_handle_request(
Origin(b"http", b"example.com", 80)
)
assert not proxy.connections[0].can_handle_request(
Origin(b"http", b"other.com", 80)
)
assert proxy.connections[0].can_handle_request(
Origin(b"https", b"example.com", 443)
)
assert not proxy.connections[0].can_handle_request(
Origin(b"https", b"other.com", 443)
)
def test_proxy_tunneling_with_403():
"""
Send an HTTPS request via a proxy.
"""
network_backend = MockBackend(
[
b"HTTP/1.1 403 Permission Denied\r\n\r\n",
]
)
with ConnectionPool(
proxy=Proxy("http://localhost:8080/"),
network_backend=network_backend,
) as proxy:
with pytest.raises(ProxyError) as exc_info:
proxy.request("GET", "https://example.com/")
assert str(exc_info.value) == "403 Permission Denied"
assert not proxy.connections
def test_proxy_tunneling_with_auth():
"""
Send an authenticated HTTPS request via a proxy.
"""
network_backend = MockBackend(
[
# The initial response to the proxy CONNECT
b"HTTP/1.1 200 OK\r\n\r\n",
# The actual response from the remote server
b"HTTP/1.1 200 OK\r\n",
b"Content-Type: plain/text\r\n",
b"Content-Length: 13\r\n",
b"\r\n",
b"Hello, world!",
]
)
with ConnectionPool(
proxy=Proxy(
url="http://localhost:8080/",
auth=("username", "password"),
),
network_backend=network_backend,
) as proxy:
response = proxy.request("GET", "https://example.com/")
assert response.status == 200
assert response.content == b"Hello, world!"
def test_proxy_headers():
proxy = Proxy(
url="http://localhost:8080/",
auth=("username", "password"),
)
assert proxy.headers == [
(b"Proxy-Authorization", b"Basic dXNlcm5hbWU6cGFzc3dvcmQ=")
]
def test_proxy_tunneling_tls_error():
"""
Send an HTTPS request via a proxy, but the TLS handshake fails.
"""
class BrokenTLSStream(MockStream):
def start_tls(
self,
ssl_context: ssl.SSLContext,
server_hostname: typing.Optional[str] = None,
timeout: typing.Optional[float] = None,
) -> NetworkStream:
raise OSError("TLS Failure")
class BrokenTLSBackend(MockBackend):
def connect_tcp(
self,
host: str,
port: int,
timeout: typing.Optional[float] = None,
local_address: typing.Optional[str] = None,
socket_options: typing.Optional[typing.Iterable[SOCKET_OPTION]] = None,
) -> NetworkStream:
return BrokenTLSStream(list(self._buffer))
network_backend = BrokenTLSBackend(
[
b"HTTP/1.1 200 OK\r\n\r\n",
]
)
with ConnectionPool(
proxy=Proxy("http://localhost:8080/"),
network_backend=network_backend,
) as proxy:
with pytest.raises(OSError, match="TLS Failure"):
proxy.request("GET", "https://example.com/")
assert not proxy.connections