Debian Codegraph @

test/test_mqtt.py

raw symbols SCIP
1 # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2 # SPDX-License-Identifier: Apache-2.0.
3
4 from awscrt.io import ClientBootstrap, ClientTlsContext, DefaultHostResolver, EventLoopGroup, Pkcs11Lib, TlsContextOptions
5 from awscrt import http
6 from awscrt.mqtt import Client, Connection, QoS, Will, OnConnectionClosedData, OnConnectionFailureData, OnConnectionSuccessData, ConnectReturnCode
7 from test import test_retry_wrapper, NativeResourceTest
8 from concurrent.futures import Future
9 import os
10 import unittest
11 import uuid
12 import time
13
14 TIMEOUT = 100.0
15
16
17 def _get_env_variable(env_name):
18 env_data = os.environ.get(env_name)
19 if not env_data:
20 raise unittest.SkipTest(f"test requires env var: {env_name}")
21 return env_data
22
23
24 def create_client_id():
25 return 'aws-crt-python-unit-test-{0}'.format(uuid.uuid4())
26
27
28 class MqttConnectionTest(NativeResourceTest):
29 TEST_TOPIC = '/test/me/senpai/' + str(uuid.uuid4())
30 TEST_MSG = 'NOTICE ME!'.encode('utf8')
31
32 def _create_connection(
33 self,
34 endpoint,
35 tls_context,
36 port=8883,
37 use_static_singletons=False,
38 client_id=None,
39 on_connection_success_callback=None,
40 on_connection_failure_callback=None,
41 on_connection_closed_callback=None,
42 on_connection_resumed_callback=None):
43 if use_static_singletons:
44 client = Client(tls_ctx=tls_context)
45 else:
46 elg = EventLoopGroup()
47 resolver = DefaultHostResolver(elg)
48 bootstrap = ClientBootstrap(elg, resolver)
49 client = Client(bootstrap, tls_context)
50
51 connection = Connection(
52 client=client,
53 client_id=client_id if client_id else create_client_id(),
54 host_name=endpoint,
55 port=port,
56 on_connection_closed=on_connection_closed_callback,
57 on_connection_failure=on_connection_failure_callback,
58 on_connection_success=on_connection_success_callback,
59 on_connection_resumed=on_connection_resumed_callback)
60 return connection
61
62 def _test_connect_disconnect(self):
63 test_input_endpoint = _get_env_variable("AWS_TEST_MQTT311_IOT_CORE_HOST")
64 test_input_cert = _get_env_variable("AWS_TEST_MQTT311_IOT_CORE_RSA_CERT")
65 test_input_key = _get_env_variable("AWS_TEST_MQTT311_IOT_CORE_RSA_KEY")
66
67 test_tls_opts = TlsContextOptions.create_client_with_mtls_from_path(test_input_cert, test_input_key)
68 test_tls = ClientTlsContext(test_tls_opts)
69
70 connection = self._create_connection(test_input_endpoint, test_tls)
71 connection.connect().result(TIMEOUT)
72 connection.disconnect().result(TIMEOUT)
73
74 def test_connect_disconnect(self):
75 test_retry_wrapper(self._test_connect_disconnect)
76
77 def _test_ecc_connect_disconnect(self):
78 test_input_endpoint = _get_env_variable("AWS_TEST_MQTT311_IOT_CORE_HOST")
79 test_input_cert = _get_env_variable("AWS_TEST_MQTT311_IOT_CORE_ECC_CERT")
80 test_input_key = _get_env_variable("AWS_TEST_MQTT311_IOT_CORE_ECC_KEY")
81
82 test_tls_opts = TlsContextOptions.create_client_with_mtls_from_path(test_input_cert, test_input_key)
83 test_tls = ClientTlsContext(test_tls_opts)
84
85 connection = self._create_connection(test_input_endpoint, test_tls)
86 connection.connect().result(TIMEOUT)
87 connection.disconnect().result(TIMEOUT)
88
89 def test_ecc_connect_disconnect(self):
90 test_retry_wrapper(self._test_ecc_connect_disconnect)
91
92 def _test_pkcs11(self):
93 test_input_endpoint = _get_env_variable("AWS_TEST_MQTT311_IOT_CORE_HOST")
94 test_input_pkcs11_lib = _get_env_variable("AWS_TEST_PKCS11_LIB")
95 test_input_pkcs11_pin = _get_env_variable("AWS_TEST_PKCS11_PIN")
96 test_input_pkcs11_token_label = _get_env_variable("AWS_TEST_PKCS11_TOKEN_LABEL")
97 test_input_pkcs11_private_key = _get_env_variable("AWS_TEST_PKCS11_PKEY_LABEL")
98 test_input_pkcs11_cert = _get_env_variable("AWS_TEST_PKCS11_CERT_FILE")
99
100 test_pkcs11_lib = Pkcs11Lib(file=test_input_pkcs11_lib, behavior=Pkcs11Lib.InitializeFinalizeBehavior.STRICT)
101 test_tls_opts = TlsContextOptions.create_client_with_mtls_pkcs11(
102 pkcs11_lib=test_pkcs11_lib,
103 user_pin=test_input_pkcs11_pin,
104 token_label=test_input_pkcs11_token_label,
105 private_key_label=test_input_pkcs11_private_key,
106 cert_file_path=test_input_pkcs11_cert
107 )
108 test_tls = ClientTlsContext(test_tls_opts)
109
110 connection = self._create_connection(test_input_endpoint, test_tls)
111 connection.connect().result(TIMEOUT)
112 connection.disconnect().result(TIMEOUT)
113
114 def test_pkcs11(self):
115 test_retry_wrapper(self._test_pkcs11)
116
117 def _test_pub_sub(self):
118 self.TEST_TOPIC = '/test/me/senpai/' + str(uuid.uuid4())
119 test_input_endpoint = _get_env_variable("AWS_TEST_MQTT311_IOT_CORE_HOST")
120 test_input_cert = _get_env_variable("AWS_TEST_MQTT311_IOT_CORE_RSA_CERT")
121 test_input_key = _get_env_variable("AWS_TEST_MQTT311_IOT_CORE_RSA_KEY")
122 test_tls_opts = TlsContextOptions.create_client_with_mtls_from_path(test_input_cert, test_input_key)
123 test_tls = ClientTlsContext(test_tls_opts)
124 connection = self._create_connection(test_input_endpoint, test_tls)
125
126 connection.connect().result(TIMEOUT)
127 received = Future()
128
129 def on_message(**kwargs):
130 received.set_result(kwargs)
131
132 # subscribe
133 subscribed, packet_id = connection.subscribe(self.TEST_TOPIC, QoS.AT_LEAST_ONCE, on_message)
134 suback = subscribed.result(TIMEOUT)
135 self.assertEqual(packet_id, suback['packet_id'])
136 self.assertEqual(self.TEST_TOPIC, suback['topic'])
137 self.assertIs(QoS.AT_LEAST_ONCE, suback['qos'])
138
139 # publish
140 published, packet_id = connection.publish(self.TEST_TOPIC, self.TEST_MSG, QoS.AT_LEAST_ONCE)
141 puback = published.result(TIMEOUT)
142 self.assertEqual(packet_id, puback['packet_id'])
143
144 # receive message
145 rcv = received.result(TIMEOUT)
146 self.assertEqual(self.TEST_TOPIC, rcv['topic'])
147 self.assertEqual(self.TEST_MSG, rcv['payload'])
148 self.assertFalse(rcv['dup'])
149 self.assertEqual(QoS.AT_LEAST_ONCE, rcv['qos'])
150 self.assertFalse(rcv['retain'])
151
152 # unsubscribe
153 unsubscribed, packet_id = connection.unsubscribe(self.TEST_TOPIC)
154 unsuback = unsubscribed.result(TIMEOUT)
155 self.assertEqual(packet_id, unsuback['packet_id'])
156
157 # disconnect
158 connection.disconnect().result(TIMEOUT)
159
160 def test_pub_sub(self):
161 test_retry_wrapper(self._test_pub_sub)
162
163 def _test_will(self):
164 self.TEST_TOPIC = '/test/me/senpai/' + str(uuid.uuid4())
165 test_input_endpoint = _get_env_variable("AWS_TEST_MQTT311_IOT_CORE_HOST")
166 test_input_cert = _get_env_variable("AWS_TEST_MQTT311_IOT_CORE_RSA_CERT")
167 test_input_key = _get_env_variable("AWS_TEST_MQTT311_IOT_CORE_RSA_KEY")
168 test_tls_opts = TlsContextOptions.create_client_with_mtls_from_path(test_input_cert, test_input_key)
169 test_tls = ClientTlsContext(test_tls_opts)
170
171 elg = EventLoopGroup()
172 resolver = DefaultHostResolver(elg)
173 bootstrap = ClientBootstrap(elg, resolver)
174 client = Client(bootstrap, test_tls)
175
176 will_client_id = create_client_id()
177 connection = Connection(
178 client=client,
179 client_id=will_client_id,
180 host_name=test_input_endpoint,
181 port=8883,
182 will=Will(self.TEST_TOPIC, QoS.AT_LEAST_ONCE, self.TEST_MSG, False),
183 ping_timeout_ms=10000,
184 keep_alive_secs=30
185 )
186 connection.connect().result(TIMEOUT)
187
188 subscriber = Connection(
189 client=client,
190 client_id=create_client_id(),
191 host_name=test_input_endpoint,
192 port=8883,
193 ping_timeout_ms=10000,
194 keep_alive_secs=30
195 )
196 subscriber.connect().result(TIMEOUT)
197
198 received = Future()
199
200 def on_message(**kwargs):
201 received.set_result(kwargs)
202
203 # subscribe
204 subscribed, packet_id = subscriber.subscribe(self.TEST_TOPIC, QoS.AT_LEAST_ONCE, on_message)
205 suback = subscribed.result(TIMEOUT)
206 self.assertEqual(packet_id, suback['packet_id'])
207 self.assertEqual(self.TEST_TOPIC, suback['topic'])
208 self.assertIs(QoS.AT_LEAST_ONCE, suback['qos'])
209
210 # wait a few seconds to ensure we can make another client ID connect (don't trigger IoT Core limit)
211 time.sleep(2)
212
213 # Disconnect the will client to send the will by making another connection with the same client id
214 disconnecter = Connection(
215 client=client,
216 client_id=will_client_id,
217 host_name=test_input_endpoint,
218 port=8883,
219 will=Will(self.TEST_TOPIC, QoS.AT_LEAST_ONCE, self.TEST_MSG, False),
220 ping_timeout_ms=10000,
221 keep_alive_secs=30
222 )
223
224 # A race condition exists in IoT Core where the interrupter may get refused rather than the existing
225 # connection getting dropped. Loop until we successfully connect.
226 continue_connecting = True
227 while continue_connecting:
228 try:
229 disconnecter.connect().result(TIMEOUT)
230 continue_connecting = False
231 except BaseException:
232 pass
233
234 # Receive message
235 rcv = received.result(TIMEOUT)
236 self.assertEqual(self.TEST_TOPIC, rcv['topic'])
237 self.assertEqual(self.TEST_MSG, rcv['payload'])
238 self.assertFalse(rcv['dup'])
239 self.assertEqual(QoS.AT_LEAST_ONCE, rcv['qos'])
240 self.assertFalse(rcv['retain'])
241
242 # Disconnect the other clients
243 connection.disconnect().result(TIMEOUT)
244 disconnecter.disconnect().result(TIMEOUT)
245
246 # unsubscribe
247 unsubscribed, packet_id = subscriber.unsubscribe(self.TEST_TOPIC)
248 unsuback = unsubscribed.result(TIMEOUT)
249 self.assertEqual(packet_id, unsuback['packet_id'])
250
251 # disconnect
252 subscriber.disconnect().result(TIMEOUT)
253
254 def test_will(self):
255 test_retry_wrapper(self._test_will)
256
257 def _test_on_message(self):
258 test_input_endpoint = _get_env_variable("AWS_TEST_MQTT311_IOT_CORE_HOST")
259 test_input_cert = _get_env_variable("AWS_TEST_MQTT311_IOT_CORE_RSA_CERT")
260 test_input_key = _get_env_variable("AWS_TEST_MQTT311_IOT_CORE_RSA_KEY")
261 test_tls_opts = TlsContextOptions.create_client_with_mtls_from_path(test_input_cert, test_input_key)
262 test_tls = ClientTlsContext(test_tls_opts)
263 connection = self._create_connection(test_input_endpoint, test_tls)
264
265 received = Future()
266
267 def on_message(**kwargs):
268 received.set_result(kwargs)
269
270 # on_message for connection has to be set before connect, or possible race will happen
271 connection.on_message(on_message)
272
273 connection.connect().result(TIMEOUT)
274 # subscribe without callback
275 subscribed, packet_id = connection.subscribe(self.TEST_TOPIC, QoS.AT_LEAST_ONCE)
276 subscribed.result(TIMEOUT)
277
278 # publish
279 published, packet_id = connection.publish(self.TEST_TOPIC, self.TEST_MSG, QoS.AT_LEAST_ONCE)
280 puback = published.result(TIMEOUT)
281
282 # receive message
283 rcv = received.result(TIMEOUT)
284 self.assertEqual(self.TEST_TOPIC, rcv['topic'])
285 self.assertEqual(self.TEST_MSG, rcv['payload'])
286 self.assertFalse(rcv['dup'])
287 self.assertEqual(QoS.AT_LEAST_ONCE, rcv['qos'])
288 self.assertFalse(rcv['retain'])
289
290 # disconnect
291 connection.disconnect().result(TIMEOUT)
292
293 def test_on_message(self):
294 test_retry_wrapper(self._test_on_message)
295
296 def _test_on_message_old_fn_signature(self):
297 # ensure that message-received callbacks with the old function signature still work
298
299 test_input_endpoint = _get_env_variable("AWS_TEST_MQTT311_IOT_CORE_HOST")
300 test_input_cert = _get_env_variable("AWS_TEST_MQTT311_IOT_CORE_RSA_CERT")
301 test_input_key = _get_env_variable("AWS_TEST_MQTT311_IOT_CORE_RSA_KEY")
302 test_tls_opts = TlsContextOptions.create_client_with_mtls_from_path(test_input_cert, test_input_key)
303 test_tls = ClientTlsContext(test_tls_opts)
304 connection = self._create_connection(test_input_endpoint, test_tls)
305
306 any_received = Future()
307 sub_received = Future()
308
309 # Note: Testing degenerate callback signature that failed to take
310 # forward-compatibility **kwargs.
311 def on_any_message(topic, payload):
312 any_received.set_result({'topic': topic, 'payload': payload})
313
314 def on_sub_message(topic, payload):
315 sub_received.set_result({'topic': topic, 'payload': payload})
316
317 # on_message for connection has to be set before connect, or possible race will happen
318 connection.on_message(on_any_message)
319
320 connection.connect().result(TIMEOUT)
321 # subscribe without callback
322 subscribed, packet_id = connection.subscribe(self.TEST_TOPIC, QoS.AT_LEAST_ONCE, on_sub_message)
323 subscribed.result(TIMEOUT)
324
325 # publish
326 published, packet_id = connection.publish(self.TEST_TOPIC, self.TEST_MSG, QoS.AT_LEAST_ONCE)
327 puback = published.result(TIMEOUT)
328
329 # receive message
330 rcv = any_received.result(TIMEOUT)
331 self.assertEqual(self.TEST_TOPIC, rcv['topic'])
332 self.assertEqual(self.TEST_MSG, rcv['payload'])
333
334 rcv = sub_received.result(TIMEOUT)
335 self.assertEqual(self.TEST_TOPIC, rcv['topic'])
336 self.assertEqual(self.TEST_MSG, rcv['payload'])
337
338 # disconnect
339 connection.disconnect().result(TIMEOUT)
340
341 def test_on_message_old_fn_signature(self):
342 test_retry_wrapper(self._test_on_message_old_fn_signature)
343
344 def _test_connect_disconnect_with_default_singletons(self):
345 test_input_endpoint = _get_env_variable("AWS_TEST_MQTT311_IOT_CORE_HOST")
346 test_input_cert = _get_env_variable("AWS_TEST_MQTT311_IOT_CORE_RSA_CERT")
347 test_input_key = _get_env_variable("AWS_TEST_MQTT311_IOT_CORE_RSA_KEY")
348
349 test_tls_opts = TlsContextOptions.create_client_with_mtls_from_path(test_input_cert, test_input_key)
350 test_tls = ClientTlsContext(test_tls_opts)
351
352 connection = self._create_connection(test_input_endpoint, test_tls, use_static_singletons=True)
353 connection.connect().result(TIMEOUT)
354 connection.disconnect().result(TIMEOUT)
355
356 # free singletons
357 ClientBootstrap.release_static_default()
358 EventLoopGroup.release_static_default()
359 DefaultHostResolver.release_static_default()
360
361 def test_connect_disconnect_with_default_singletons(self):
362 test_retry_wrapper(self._test_connect_disconnect_with_default_singletons)
363
364 def _test_connect_publish_wait_statistics_disconnect(self):
365 test_input_endpoint = _get_env_variable("AWS_TEST_MQTT311_IOT_CORE_HOST")
366 test_input_cert = _get_env_variable("AWS_TEST_MQTT311_IOT_CORE_RSA_CERT")
367 test_input_key = _get_env_variable("AWS_TEST_MQTT311_IOT_CORE_RSA_KEY")
368 test_tls_opts = TlsContextOptions.create_client_with_mtls_from_path(test_input_cert, test_input_key)
369 test_tls = ClientTlsContext(test_tls_opts)
370 connection = self._create_connection(test_input_endpoint, test_tls)
371
372 connection.connect().result(TIMEOUT)
373
374 # check operation statistics
375 statistics = connection.get_stats()
376 self.assertEqual(statistics.incomplete_operation_count, 0)
377 self.assertEqual(statistics.incomplete_operation_size, 0)
378 self.assertEqual(statistics.unacked_operation_count, 0)
379 self.assertEqual(statistics.unacked_operation_size, 0)
380
381 # publish
382 published, packet_id = connection.publish(self.TEST_TOPIC, self.TEST_MSG, QoS.AT_LEAST_ONCE)
383 puback = published.result(TIMEOUT)
384 self.assertEqual(packet_id, puback['packet_id'])
385
386 # check operation statistics
387 statistics = connection.get_stats()
388 self.assertEqual(statistics.incomplete_operation_count, 0)
389 self.assertEqual(statistics.incomplete_operation_size, 0)
390 self.assertEqual(statistics.unacked_operation_count, 0)
391 self.assertEqual(statistics.unacked_operation_size, 0)
392
393 # disconnect
394 connection.disconnect().result(TIMEOUT)
395
396 def test_connect_publish_wait_statistics_disconnect(self):
397 test_retry_wrapper(self._test_connect_publish_wait_statistics_disconnect)
398
399 def _test_connect_publish_statistics_wait_disconnect(self):
400 test_input_endpoint = _get_env_variable("AWS_TEST_MQTT311_IOT_CORE_HOST")
401 test_input_cert = _get_env_variable("AWS_TEST_MQTT311_IOT_CORE_RSA_CERT")
402 test_input_key = _get_env_variable("AWS_TEST_MQTT311_IOT_CORE_RSA_KEY")
403 test_tls_opts = TlsContextOptions.create_client_with_mtls_from_path(test_input_cert, test_input_key)
404 test_tls = ClientTlsContext(test_tls_opts)
405 connection = self._create_connection(test_input_endpoint, test_tls)
406
407 connection.connect().result(TIMEOUT)
408
409 # publish
410 published, packet_id = connection.publish(self.TEST_TOPIC, self.TEST_MSG, QoS.AT_LEAST_ONCE)
411 # Per packet: (The size of the topic, the size of the payload, 2 for the header and 2 for the packet ID)
412 expected_size = len(self.TEST_TOPIC) + len(self.TEST_MSG) + 4
413
414 # check operation statistics
415 statistics = connection.get_stats()
416 self.assertEqual(statistics.incomplete_operation_count, 1)
417 self.assertEqual(statistics.incomplete_operation_size, expected_size)
418 # NOTE: Unacked MAY be zero because we have not invoked the future yet
419 # and so it has not had time to move to the socket. With Python especially, it seems to heavily depend on how fast
420 # the test is executed, which makes it sometimes rarely get into the unacked operation and then it is non-zero.
421 # To fix this, we just make sure it is within expected bounds (0 or within packet size).
422 self.assertTrue(statistics.unacked_operation_count <= 1)
423 self.assertTrue(statistics.unacked_operation_count <= expected_size)
424
425 # wait for PubAck
426 puback = published.result(TIMEOUT)
427 self.assertEqual(packet_id, puback['packet_id'])
428
429 # check operation statistics
430 statistics = connection.get_stats()
431 self.assertEqual(statistics.incomplete_operation_count, 0)
432 self.assertEqual(statistics.incomplete_operation_size, 0)
433 self.assertEqual(statistics.unacked_operation_count, 0)
434 self.assertEqual(statistics.unacked_operation_size, 0)
435
436 # disconnect
437 connection.disconnect().result(TIMEOUT)
438
439 def test_connect_publish_statistics_wait_disconnect(self):
440 test_retry_wrapper(self._test_connect_publish_statistics_wait_disconnect)
441
442 def _test_connect_disconnect_with_callbacks_happy(self):
443 test_input_endpoint = _get_env_variable("AWS_TEST_MQTT311_IOT_CORE_HOST")
444 test_input_cert = _get_env_variable("AWS_TEST_MQTT311_IOT_CORE_RSA_CERT")
445 test_input_key = _get_env_variable("AWS_TEST_MQTT311_IOT_CORE_RSA_KEY")
446 test_tls_opts = TlsContextOptions.create_client_with_mtls_from_path(test_input_cert, test_input_key)
447 test_tls = ClientTlsContext(test_tls_opts)
448
449 on_connection_success_future = Future()
450 on_connection_closed_future = Future()
451
452 def on_connection_success_callback(connection, callback_data: OnConnectionSuccessData):
453 on_connection_success_future.set_result(
454 {'return_code': callback_data.return_code, "session_present": callback_data.session_present})
455
456 def on_connection_failure_callback(connection, callback_data: OnConnectionFailureData):
457 pass
458
459 def on_connection_closed_callback(connection, callback_data: OnConnectionClosedData):
460 on_connection_closed_future.set_result({})
461
462 connection = self._create_connection(
463 endpoint=test_input_endpoint,
464 tls_context=test_tls,
465 on_connection_success_callback=on_connection_success_callback,
466 on_connection_failure_callback=on_connection_failure_callback,
467 on_connection_closed_callback=on_connection_closed_callback)
468 connection.connect().result(TIMEOUT)
469 success_data = on_connection_success_future.result(TIMEOUT)
470 self.assertEqual(success_data['return_code'], ConnectReturnCode.ACCEPTED)
471 self.assertEqual(success_data['session_present'], False)
472 connection.disconnect().result(TIMEOUT)
473 on_connection_closed_future.result(TIMEOUT)
474
475 def test_connect_disconnect_with_callbacks_happy(self):
476 test_retry_wrapper(self._test_connect_disconnect_with_callbacks_happy)
477
478 def _test_connect_disconnect_with_callbacks_unhappy(self):
479 test_input_endpoint = _get_env_variable("AWS_TEST_MQTT311_IOT_CORE_HOST")
480 test_input_cert = _get_env_variable("AWS_TEST_MQTT311_IOT_CORE_RSA_CERT")
481 test_input_key = _get_env_variable("AWS_TEST_MQTT311_IOT_CORE_RSA_KEY")
482 test_tls_opts = TlsContextOptions.create_client_with_mtls_from_path(test_input_cert, test_input_key)
483 test_tls = ClientTlsContext(test_tls_opts)
484
485 on_onnection_failure_future = Future()
486
487 def on_connection_success_callback(connection, callback_data: OnConnectionSuccessData):
488 pass
489
490 def on_connection_failure_callback(connection, callback_data: OnConnectionFailureData):
491 on_onnection_failure_future.set_result({'error': callback_data.error})
492
493 def on_connection_closed_callback(connection, callback_data: OnConnectionClosedData):
494 pass
495
496 connection = self._create_connection(
497 endpoint=test_input_endpoint,
498 tls_context=test_tls,
499 port=1234,
500 on_connection_success_callback=on_connection_success_callback,
501 on_connection_failure_callback=on_connection_failure_callback,
502 on_connection_closed_callback=on_connection_closed_callback)
503
504 exception_occurred = False
505 try:
506 connection.connect().result(TIMEOUT)
507 except Exception:
508 exception_occurred = True
509 self.assertTrue(exception_occurred, "Exception did not occur when connecting with invalid arguments!")
510
511 failure_data = on_onnection_failure_future.result(TIMEOUT)
512 self.assertTrue(failure_data['error'] is not None)
513
514 def test_connect_disconnect_with_callbacks_unhappy(self):
515 test_retry_wrapper(self._test_connect_disconnect_with_callbacks_unhappy)
516
517 def _test_connect_disconnect_with_callbacks_happy_on_resume(self):
518 # Check that an on_connection_success callback fires on a resumed connection.
519
520 # NOTE Since there is no mocked server available on this abstraction level, the only sensible approach
521 # is to interrupt a connection, and wait for it to be resumed automatically. For that, another client
522 # with the same client_id connects to the server and then immediately disconnects.
523
524 test_input_endpoint = _get_env_variable("AWS_TEST_MQTT311_IOT_CORE_HOST")
525 test_input_cert = _get_env_variable("AWS_TEST_MQTT311_IOT_CORE_RSA_CERT")
526 test_input_key = _get_env_variable("AWS_TEST_MQTT311_IOT_CORE_RSA_KEY")
527 test_tls_opts = TlsContextOptions.create_client_with_mtls_from_path(test_input_cert, test_input_key)
528 test_tls = ClientTlsContext(test_tls_opts)
529
530 on_connection_success_future = Future()
531 on_connection_closed_future = Future()
532 on_connection_resumed_future = Future()
533
534 def on_connection_success_callback(connection, callback_data: OnConnectionSuccessData):
535 on_connection_success_future.set_result(
536 {'return_code': callback_data.return_code, "session_present": callback_data.session_present})
537
538 def on_connection_closed_callback(connection, callback_data: OnConnectionClosedData):
539 on_connection_closed_future.set_result({})
540
541 def on_connection_resumed_callback(connection, return_code: ConnectReturnCode, session_present):
542 on_connection_resumed_future.set_result(
543 {'return_code': return_code, "session_present": session_present})
544
545 connection = self._create_connection(
546 endpoint=test_input_endpoint,
547 tls_context=test_tls,
548 on_connection_success_callback=on_connection_success_callback,
549 on_connection_closed_callback=on_connection_closed_callback,
550 on_connection_resumed_callback=on_connection_resumed_callback)
551 connection.connect().result(TIMEOUT)
552 success_data = on_connection_success_future.result(TIMEOUT)
553 self.assertEqual(success_data['return_code'], ConnectReturnCode.ACCEPTED)
554 self.assertEqual(success_data['session_present'], False)
555
556 # Putting a sleep here helps prevent a "race" condition in IoT Core where the second connection can get
557 # rejected rather than the first disconnected.
558 time.sleep(5)
559
560 # Reset the future for the reconnect attempt.
561 on_connection_success_future = Future()
562
563 on_connection_success_future_dup = Future()
564
565 def on_connection_success_callback_dup(connection, callback_data: OnConnectionSuccessData):
566 on_connection_success_future_dup.set_result({})
567
568 # Reuse the same client_id to displace the first client.
569 connection_dup = self._create_connection(
570 endpoint=test_input_endpoint,
571 tls_context=test_tls,
572 client_id=connection.client_id,
573 on_connection_success_callback=on_connection_success_callback_dup)
574
575 connection_dup.connect().result(TIMEOUT)
576 on_connection_success_future_dup.result(TIMEOUT)
577 connection_dup.disconnect().result(TIMEOUT)
578
579 # After the second client disconnects, the first one should reconnect,
580 # and on_connection_success callback should be fired once again.
581 on_connection_resumed_future.result(TIMEOUT)
582 success_data = on_connection_success_future.result(TIMEOUT)
583
584 self.assertEqual(success_data['return_code'], ConnectReturnCode.ACCEPTED)
585 self.assertEqual(success_data['session_present'], False)
586
587 connection.disconnect().result(TIMEOUT)
588 on_connection_closed_future.result(TIMEOUT)
589
590 def test_connect_disconnect_with_callbacks_happy_on_resume(self):
591 test_retry_wrapper(self._test_connect_disconnect_with_callbacks_happy_on_resume)
592
593 # ==============================================================
594 # MOSQUITTO CONNECTION TESTS
595 # ==============================================================
596
597 def _test_mqtt311_direct_connect_minimum(self):
598 input_host_name = _get_env_variable("AWS_TEST_MQTT311_DIRECT_MQTT_HOST")
599 input_port = int(_get_env_variable("AWS_TEST_MQTT311_DIRECT_MQTT_PORT"))
600
601 elg = EventLoopGroup()
602 resolver = DefaultHostResolver(elg)
603 bootstrap = ClientBootstrap(elg, resolver)
604 client = Client(bootstrap, None)
605 connection = Connection(
606 client=client,
607 client_id=create_client_id(),
608 host_name=input_host_name,
609 port=input_port)
610 connection.connect().result(TIMEOUT)
611 connection.disconnect().result(TIMEOUT)
612
613 def test_mqtt311_direct_connect_minimum(self):
614 test_retry_wrapper(self._test_mqtt311_direct_connect_minimum)
615
616 def _test_mqtt311_direct_connect_basic_auth(self):
617 input_host_name = _get_env_variable("AWS_TEST_MQTT311_DIRECT_MQTT_BASIC_AUTH_HOST")
618 input_port = int(_get_env_variable("AWS_TEST_MQTT311_DIRECT_MQTT_BASIC_AUTH_PORT"))
619 input_username = _get_env_variable("AWS_TEST_MQTT311_BASIC_AUTH_USERNAME")
620 input_password = _get_env_variable("AWS_TEST_MQTT311_BASIC_AUTH_PASSWORD")
621
622 elg = EventLoopGroup()
623 resolver = DefaultHostResolver(elg)
624 bootstrap = ClientBootstrap(elg, resolver)
625 client = Client(bootstrap, None)
626 connection = Connection(
627 client=client,
628 client_id=create_client_id(),
629 host_name=input_host_name,
630 port=input_port,
631 username=input_username,
632 password=input_password,
633 disable_metrics=True)
634 connection.connect().result(TIMEOUT)
635 connection.disconnect().result(TIMEOUT)
636
637 def test_mqtt311_direct_connect_basic_auth(self):
638 test_retry_wrapper(self._test_mqtt311_direct_connect_basic_auth)
639
640 def _test_mqtt311_direct_connect_tls(self):
641 input_host_name = _get_env_variable("AWS_TEST_MQTT311_DIRECT_MQTT_TLS_HOST")
642 input_port = int(_get_env_variable("AWS_TEST_MQTT311_DIRECT_MQTT_TLS_PORT"))
643
644 tls_ctx_options = TlsContextOptions()
645 tls_ctx_options.verify_peer = False
646 elg = EventLoopGroup()
647 resolver = DefaultHostResolver(elg)
648 bootstrap = ClientBootstrap(elg, resolver)
649 client = Client(bootstrap, ClientTlsContext(tls_ctx_options))
650 connection = Connection(
651 client=client,
652 client_id=create_client_id(),
653 host_name=input_host_name,
654 port=input_port)
655 connection.connect().result(TIMEOUT)
656 connection.disconnect().result(TIMEOUT)
657
658 def test_mqtt311_direct_connect_tls(self):
659 test_retry_wrapper(self._test_mqtt311_direct_connect_tls)
660
661 def _test_mqtt311_direct_connect_mutual_tls(self):
662 input_cert = _get_env_variable("AWS_TEST_MQTT311_IOT_CORE_RSA_CERT")
663 input_key = _get_env_variable("AWS_TEST_MQTT311_IOT_CORE_RSA_KEY")
664 input_host = _get_env_variable("AWS_TEST_MQTT311_IOT_CORE_HOST")
665
666 tls_ctx_options = TlsContextOptions.create_client_with_mtls_from_path(
667 input_cert,
668 input_key
669 )
670 elg = EventLoopGroup()
671 resolver = DefaultHostResolver(elg)
672 bootstrap = ClientBootstrap(elg, resolver)
673 client = Client(bootstrap, ClientTlsContext(tls_ctx_options))
674 connection = Connection(
675 client=client,
676 client_id=create_client_id(),
677 host_name=input_host,
678 port=8883)
679 connection.connect().result(TIMEOUT)
680 connection.disconnect().result(TIMEOUT)
681
682 def test_mqtt311_direct_connect_mutual_tls(self):
683 test_retry_wrapper(self._test_mqtt311_direct_connect_mutual_tls)
684
685 def _test_mqtt311_direct_connect_http_proxy_tls(self):
686 input_proxy_host = _get_env_variable("AWS_TEST_MQTT311_PROXY_HOST")
687 input_proxy_port = int(_get_env_variable("AWS_TEST_MQTT311_PROXY_PORT"))
688 input_host_name = _get_env_variable("AWS_TEST_MQTT311_DIRECT_MQTT_TLS_HOST")
689 input_port = int(_get_env_variable("AWS_TEST_MQTT311_DIRECT_MQTT_TLS_PORT"))
690
691 tls_ctx_options = TlsContextOptions()
692 tls_ctx_options.verify_peer = False
693 elg = EventLoopGroup()
694 resolver = DefaultHostResolver(elg)
695 bootstrap = ClientBootstrap(elg, resolver)
696 client = Client(bootstrap, ClientTlsContext(tls_ctx_options))
697
698 http_proxy_options = http.HttpProxyOptions(
699 host_name=input_proxy_host,
700 port=input_proxy_port
701 )
702 http_proxy_options.connection_type = http.HttpProxyConnectionType.Tunneling
703 http_proxy_options.auth_type = http.HttpProxyAuthenticationType.Nothing
704
705 connection = Connection(
706 client=client,
707 client_id=create_client_id(),
708 host_name=input_host_name,
709 port=input_port,
710 proxy_options=http_proxy_options)
711 connection.connect().result(TIMEOUT)
712 connection.disconnect().result(TIMEOUT)
713
714 def test_mqtt311_direct_connect_http_proxy_tls(self):
715 test_retry_wrapper(self._test_mqtt311_direct_connect_http_proxy_tls)
716
717 def _test_mqtt311_websocket_connect_minimum(self):
718 input_host_name = _get_env_variable("AWS_TEST_MQTT311_WS_MQTT_HOST")
719 input_port = int(_get_env_variable("AWS_TEST_MQTT311_WS_MQTT_PORT"))
720
721 elg = EventLoopGroup()
722 resolver = DefaultHostResolver(elg)
723 bootstrap = ClientBootstrap(elg, resolver)
724
725 def sign_function(transform_args, **kwargs):
726 transform_args.set_done()
727
728 client = Client(bootstrap, None)
729 connection = Connection(
730 client=client,
731 client_id=create_client_id(),
732 host_name=input_host_name,
733 port=input_port,
734 use_websockets=True,
735 websocket_handshake_transform=sign_function)
736 connection.connect().result(TIMEOUT)
737 connection.disconnect().result(TIMEOUT)
738
739 def test_mqtt311_websocket_connect_minimum(self):
740 test_retry_wrapper(self._test_mqtt311_websocket_connect_minimum)
741
742 def _test_mqtt311_websocket_connect_basic_auth(self):
743 input_host_name = _get_env_variable("AWS_TEST_MQTT311_WS_MQTT_BASIC_AUTH_HOST")
744 input_port = int(_get_env_variable("AWS_TEST_MQTT311_WS_MQTT_BASIC_AUTH_PORT"))
745 input_username = _get_env_variable("AWS_TEST_MQTT311_BASIC_AUTH_USERNAME")
746 input_password = _get_env_variable("AWS_TEST_MQTT311_BASIC_AUTH_PASSWORD")
747
748 elg = EventLoopGroup()
749 resolver = DefaultHostResolver(elg)
750 bootstrap = ClientBootstrap(elg, resolver)
751
752 def sign_function(transform_args, **kwargs):
753 transform_args.set_done()
754
755 client = Client(bootstrap, None)
756 connection = Connection(
757 client=client,
758 client_id=create_client_id(),
759 host_name=input_host_name,
760 port=input_port,
761 username=input_username,
762 password=input_password,
763 use_websockets=True,
764 websocket_handshake_transform=sign_function,
765 disable_metrics=True)
766 connection.connect().result(TIMEOUT)
767 connection.disconnect().result(TIMEOUT)
768
769 def test_mqtt311_websocket_connect_basic_auth(self):
770 test_retry_wrapper(self._test_mqtt311_websocket_connect_basic_auth)
771
772 def _test_mqtt311_websocket_connect_tls(self):
773 input_host_name = _get_env_variable("AWS_TEST_MQTT311_WS_MQTT_TLS_HOST")
774 input_port = int(_get_env_variable("AWS_TEST_MQTT311_WS_MQTT_TLS_PORT"))
775
776 tls_ctx_options = TlsContextOptions()
777 tls_ctx_options.verify_peer = False
778 elg = EventLoopGroup()
779 resolver = DefaultHostResolver(elg)
780 bootstrap = ClientBootstrap(elg, resolver)
781
782 def sign_function(transform_args, **kwargs):
783 transform_args.set_done()
784
785 client = Client(bootstrap, ClientTlsContext(tls_ctx_options))
786 connection = Connection(
787 client=client,
788 client_id=create_client_id(),
789 host_name=input_host_name,
790 port=input_port,
791 use_websockets=True,
792 websocket_handshake_transform=sign_function)
793 connection.connect().result(TIMEOUT)
794 connection.disconnect().result(TIMEOUT)
795
796 def test_mqtt311_websocket_connect_tls(self):
797 test_retry_wrapper(self._test_mqtt311_websocket_connect_tls)
798
799 def _test_mqtt311_websocket_connect_http_proxy_tls(self):
800 input_proxy_host = _get_env_variable("AWS_TEST_MQTT311_PROXY_HOST")
801 input_proxy_port = int(_get_env_variable("AWS_TEST_MQTT311_PROXY_PORT"))
802 input_host_name = _get_env_variable("AWS_TEST_MQTT311_WS_MQTT_TLS_HOST")
803 input_port = int(_get_env_variable("AWS_TEST_MQTT311_WS_MQTT_TLS_PORT"))
804
805 tls_ctx_options = TlsContextOptions()
806 tls_ctx_options.verify_peer = False
807 elg = EventLoopGroup()
808 resolver = DefaultHostResolver(elg)
809 bootstrap = ClientBootstrap(elg, resolver)
810
811 http_proxy_options = http.HttpProxyOptions(
812 host_name=input_proxy_host,
813 port=input_proxy_port
814 )
815 http_proxy_options.connection_type = http.HttpProxyConnectionType.Tunneling
816 http_proxy_options.auth_type = http.HttpProxyAuthenticationType.Nothing
817
818 def sign_function(transform_args, **kwargs):
819 transform_args.set_done()
820
821 client = Client(bootstrap, ClientTlsContext(tls_ctx_options))
822 connection = Connection(
823 client=client,
824 client_id=create_client_id(),
825 host_name=input_host_name,
826 port=input_port,
827 use_websockets=True,
828 websocket_handshake_transform=sign_function,
829 proxy_options=http_proxy_options)
830 connection.connect().result(TIMEOUT)
831 connection.disconnect().result(TIMEOUT)
832
833 def test_mqtt311_websocket_connect_http_proxy_tls(self):
834 test_retry_wrapper(self._test_mqtt311_websocket_connect_http_proxy_tls)
835
836 # ==============================================================
837 # METRICS TEST CASES
838 # ==============================================================
839
840 def _test_mqtt311_direct_connect_basic_auth_metrics_enabled(self):
841 """Test that connection fails with basic auth when metrics are enabled.
842
843 When metrics are enabled, the SDK appends metrics information to the username field,
844 which corrupts the basic authentication and causes the connection to fail.
845 """
846 input_host_name = _get_env_variable("AWS_TEST_MQTT311_DIRECT_MQTT_BASIC_AUTH_HOST")
847 input_port = int(_get_env_variable("AWS_TEST_MQTT311_DIRECT_MQTT_BASIC_AUTH_PORT"))
848 input_username = _get_env_variable("AWS_TEST_MQTT311_BASIC_AUTH_USERNAME")
849 input_password = _get_env_variable("AWS_TEST_MQTT311_BASIC_AUTH_PASSWORD")
850
851 elg = EventLoopGroup()
852 resolver = DefaultHostResolver(elg)
853 bootstrap = ClientBootstrap(elg, resolver)
854 client = Client(bootstrap, None)
855
856 # Create connection with disable_metrics=False explicitly
857 # This should fail because metrics appends to username, corrupting basic auth
858 connection = Connection(
859 client=client,
860 client_id=create_client_id(),
861 host_name=input_host_name,
862 port=input_port,
863 username=input_username,
864 password=input_password,
865 disable_metrics=False)
866
867 # Connection should fail because metrics corrupts the username for basic auth
868 exception_occurred = False
869 try:
870 connection.connect().result(TIMEOUT)
871 except Exception:
872 exception_occurred = True
873 self.assertTrue(exception_occurred, "Connection should fail when metrics are enabled with basic auth!")
874
875 def test_mqtt311_direct_connect_basic_auth_metrics_enabled(self):
876 test_retry_wrapper(self._test_mqtt311_direct_connect_basic_auth_metrics_enabled)
877
878
879 if __name__ == 'main':
880 unittest.main()