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
|
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0.
import awscrt.exceptions
from awscrt.http import HttpClientConnection, HttpClientStream, HttpHeaders, HttpProxyOptions, HttpRequest, HttpVersion
from awscrt.io import ClientBootstrap, ClientTlsContext, DefaultHostResolver, EventLoopGroup, TlsConnectionOptions, TlsContextOptions, TlsCipherPref
from concurrent.futures import Future
from http.server import HTTPServer, SimpleHTTPRequestHandler
from io import BytesIO
import os
import ssl
from test import NativeResourceTest
import threading
import unittest
from urllib.parse import urlparse
class Response:
"""Holds contents of incoming response"""
def __init__(self):
self.status_code = None
self.headers = None
self.body = bytearray()
def on_response(self, http_stream, status_code, headers, **kwargs):
self.status_code = status_code
self.headers = HttpHeaders(headers)
def on_body(self, http_stream, chunk, **kwargs):
self.body.extend(chunk)
class TestRequestHandler(SimpleHTTPRequestHandler):
"""Request handler for test server"""
def do_PUT(self):
content_length = int(self.headers['Content-Length'])
# store put request on the server object
incoming_body_bytes = self.rfile.read(content_length)
self.server.put_requests[self.path] = incoming_body_bytes
self.send_response(200, 'OK')
self.end_headers()
class TestClient(NativeResourceTest):
hostname = 'localhost'
timeout = 10 # seconds
def _start_server(self, secure, http_1_0=False):
# HTTP/1.0 closes the connection at the end of each request
# HTTP/1.1 will keep the connection alive
if http_1_0:
TestRequestHandler.protocol_version = "HTTP/1.0"
else:
TestRequestHandler.protocol_version = "HTTP/1.1"
self.server = HTTPServer((self.hostname, 0), TestRequestHandler)
if secure:
context = ssl.SSLContext()
context.load_cert_chain(certfile='test/resources/unittest.crt', keyfile="test/resources/unittest.key")
self.server.socket = context.wrap_socket(self.server.socket, server_side=True)
self.port = self.server.server_address[1]
# put requests are stored in this dict
self.server.put_requests = {}
self.server_thread = threading.Thread(target=self.server.serve_forever, name='test_server')
self.server_thread.start()
def _stop_server(self):
self.server.shutdown()
self.server.server_close()
self.server_thread.join()
def _new_client_connection(self, secure, proxy_options=None, cipher_pref=TlsCipherPref.DEFAULT):
if secure:
tls_ctx_opt = TlsContextOptions()
tls_ctx_opt.cipher_pref = cipher_pref
tls_ctx_opt.verify_peer = False
tls_ctx = ClientTlsContext(tls_ctx_opt)
tls_conn_opt = tls_ctx.new_connection_options()
tls_conn_opt.set_server_name(self.hostname)
else:
tls_conn_opt = None
event_loop_group = EventLoopGroup()
host_resolver = DefaultHostResolver(event_loop_group)
bootstrap = ClientBootstrap(event_loop_group, host_resolver)
connection_future = HttpClientConnection.new(host_name=self.hostname,
port=self.port,
bootstrap=bootstrap,
tls_connection_options=tls_conn_opt,
proxy_options=proxy_options)
return connection_future.result(self.timeout)
def _test_connect(self, secure, cipher_pref=TlsCipherPref.DEFAULT):
self._start_server(secure)
try:
connection = self._new_client_connection(secure, cipher_pref=cipher_pref)
# close connection
shutdown_error_from_close_future = connection.close().exception(self.timeout)
# assert that error was reported via close_future and shutdown callback
# error should be None (normal shutdown)
self.assertEqual(None, shutdown_error_from_close_future)
self.assertFalse(connection.is_open())
finally:
self._stop_server()
def test_connect_http(self):
self._test_connect(secure=False)
def test_connect_https(self):
self._test_connect(secure=True)
def _test_connection_closes_on_zero_refcount(self, secure):
# The connection should shut itself down cleanly when the GC collects the HttpClientConnection Python object.
self._start_server(secure)
try:
connection = self._new_client_connection(secure)
# referencing the shutdown_future does not keep the connection alive
close_future = connection.shutdown_future
# This should cause the GC to collect the HttpClientConnection
del connection
close_error = close_future.exception(self.timeout)
self.assertEqual(None, close_error)
finally:
self._stop_server()
def test_connection_closes_on_zero_refcount_http(self):
self._test_connection_closes_on_zero_refcount(secure=False)
def test_connection_closes_on_zero_refcount_https(self):
self._test_connection_closes_on_zero_refcount(secure=True)
def _test_get(self, secure, proxy_options=None):
# GET request receives this very file from the server. Super meta.
# Use HTTP/1.0 in proxy tests or server will keep connection with proxy alive
# and refuse to shut down for 1 minute at the end of each proxy test
http_1_0 = proxy_options is not None
self._start_server(secure, http_1_0)
try:
connection = self._new_client_connection(secure, proxy_options)
test_asset_path = 'test/test_http_client.py'
request = HttpRequest('GET', '/' + test_asset_path)
response = Response()
stream = connection.request(request, response.on_response, response.on_body)
stream.activate()
# wait for stream to complete
stream_completion_result = stream.completion_future.result(self.timeout)
self.assertEqual(200, response.status_code)
self.assertEqual(200, stream_completion_result)
with open(test_asset_path, 'rb') as test_asset:
test_asset_bytes = test_asset.read()
self.assertEqual(test_asset_bytes, response.body)
self.assertEqual(None, connection.close().exception(self.timeout))
finally:
self._stop_server()
def test_get_http(self):
self._test_get(secure=False)
def test_get_https(self):
self._test_get(secure=True)
def _test_shutdown_error(self, secure):
# Use HTTP/1.0 connection to force a SOCKET_CLOSED error after request completes
self._start_server(secure, http_1_0=True)
try:
connection = self._new_client_connection(secure)
# Send request, don't care what happens
request = HttpRequest('GET', '/')
response = Response()
stream = connection.request(request, response.on_response, response.on_body)
stream.activate()
stream.completion_future.result(self.timeout)
# Wait for server to hang up, which should be immediate since it's using HTTP/1.0
shutdown_error = connection.shutdown_future.exception(self.timeout)
self.assertIsInstance(shutdown_error, awscrt.exceptions.AwsCrtError)
finally:
self._stop_server()
def test_shutdown_error_http(self):
return self._test_shutdown_error(secure=False)
def test_shutdown_error_https(self):
return self._test_shutdown_error(secure=True)
def _test_put(self, secure):
# PUT request sends this very file to the server.
self._start_server(secure)
try:
connection = self._new_client_connection(secure)
test_asset_path = 'test/test_http_client.py'
with open(test_asset_path, 'rb') as outgoing_body_stream:
outgoing_body_bytes = outgoing_body_stream.read()
headers = HttpHeaders([
('Content-Length', str(len(outgoing_body_bytes))),
])
# seek back to start of stream before trying to send it
outgoing_body_stream.seek(0)
request = HttpRequest('PUT', '/' + test_asset_path, headers, outgoing_body_stream)
response = Response()
http_stream = connection.request(request, response.on_response, response.on_body)
http_stream.activate()
# wait for stream to complete
stream_completion_result = http_stream.completion_future.result(self.timeout)
self.assertEqual(200, response.status_code)
self.assertEqual(200, stream_completion_result)
# compare what we sent against what the server received
server_received = self.server.put_requests.get('/' + test_asset_path)
self.assertIsNotNone(server_received)
self.assertEqual(server_received, outgoing_body_bytes)
self.assertEqual(None, connection.close().result(self.timeout))
finally:
self._stop_server()
def test_put_http(self):
self._test_put(secure=False)
def test_put_https(self):
self._test_put(secure=True)
def _test_stream_lives_until_complete(self, secure):
# Ensure that stream and connection classes stay alive until work is complete
self._start_server(secure)
try:
connection = self._new_client_connection(secure)
request = HttpRequest('GET', '/test/test_http_client.py')
stream = connection.request(request)
stream.activate()
completion_future = stream.completion_future
# delete all local references
del stream
del connection
# stream should still complete successfully
completion_future.result(self.timeout)
finally:
self._stop_server()
def test_stream_lives_until_complete_http(self):
self._test_stream_lives_until_complete(secure=False)
def test_stream_lives_until_complete_https(self):
self._test_stream_lives_until_complete(secure=True)
def _test_request_lives_until_stream_complete(self, secure):
# Ensure HttpRequest and body InputStream stay alive until HttpClientStream completes (regression test)
self._start_server(secure)
try:
connection = self._new_client_connection(secure)
request = HttpRequest(
method='PUT',
path='/test/test_request_refcounts.txt',
headers=HttpHeaders([('Host', self.hostname), ('Content-Length', '5')]),
body_stream=BytesIO(b'hello'))
response = Response()
http_stream = connection.request(request, response.on_response, response.on_body)
# HttpClientStream should keep the dependencies (HttpRequest, HttpHeaders, InputStream)
# alive as long as it needs them
del request
http_stream.activate()
http_stream.completion_future.result(self.timeout)
self.assertEqual(None, connection.close().result(self.timeout))
finally:
self._stop_server()
def test_request_lives_until_stream_complete_http(self):
return self._test_request_lives_until_stream_complete(secure=False)
def test_request_lives_until_stream_complete_https(self):
return self._test_request_lives_until_stream_complete(secure=True)
def _test_stream_cleans_up_if_never_activated(self, secure):
# If a stream is never activated, it should just clean itself up
self._start_server(secure)
try:
connection = self._new_client_connection(secure)
stream = connection.request(HttpRequest('GET', '/test/test_http_client.py'))
# note we do NOT activate the stream
# delete local references, stream should clean itself up, connection should shut itself down
del stream
del connection
finally:
self._stop_server()
def test_stream_cleans_up_if_never_activated_http(self):
self._test_stream_cleans_up_if_never_activated(secure=False)
def test_stream_cleans_up_if_never_activated_https(self):
self._test_stream_cleans_up_if_never_activated(secure=True)
def _new_h2_client_connection(self, url):
event_loop_group = EventLoopGroup()
host_resolver = DefaultHostResolver(event_loop_group)
bootstrap = ClientBootstrap(event_loop_group, host_resolver)
port = 443
scheme = 'https'
tls_ctx_options = TlsContextOptions()
tls_ctx = ClientTlsContext(tls_ctx_options)
tls_conn_opt = tls_ctx.new_connection_options()
tls_conn_opt.set_server_name(url.hostname)
tls_conn_opt.set_alpn_list(["h2"])
connection_future = HttpClientConnection.new(host_name=url.hostname,
port=port,
bootstrap=bootstrap,
tls_connection_options=tls_conn_opt)
return connection_future.result(self.timeout)
def test_h2_client(self):
url = urlparse("https://d1cz66xoahf9cl.cloudfront.net/http_test_doc.txt")
connection = self._new_h2_client_connection(url)
# check we set an h2 connection
self.assertEqual(connection.version, HttpVersion.Http2)
request = HttpRequest('GET', url.path)
request.headers.add('host', url.hostname)
response = Response()
stream = connection.request(request, response.on_response, response.on_body)
stream.activate()
# wait for stream to complete (use long timeout, it's a big file)
stream_completion_result = stream.completion_future.result(80)
# check result
self.assertEqual(200, response.status_code)
self.assertEqual(200, stream_completion_result)
self.assertEqual(14428801, len(response.body))
self.assertEqual(None, connection.close().exception(self.timeout))
@unittest.skipIf(not TlsCipherPref.PQ_TLSv1_0_2021_05.is_supported(), "Cipher pref not supported")
def test_connect_pq_tlsv1_0_2021_05(self):
self._test_connect(secure=True, cipher_pref=TlsCipherPref.PQ_TLSv1_0_2021_05)
if __name__ == '__main__':
unittest.main()
|