Debian Codegraph @

test/test_mqtt5_credentials.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 concurrent.futures import Future
5 from awscrt import mqtt5, io, auth
6 from test import test_retry_wrapper, NativeResourceTest
7 import os
8 import unittest
9 import uuid
10
11 TIMEOUT = 100.0
12
13
14 def _get_env_variable(env_name):
15 env_data = os.environ.get(env_name)
16 if not env_data:
17 raise unittest.SkipTest(f"test requires env var: {env_name}")
18 return env_data
19
20
21 def create_client_id():
22 return 'aws-crt-python-unit-test-{0}'.format(uuid.uuid4())
23
24
25 class Mqtt5TestCallbacks():
26 def __init__(self):
27 self.on_publish_receive_expected = 0
28 self.on_publish_received_counter = 0
29 self.last_exception = None
30
31 self.negotiated_settings = None
32 self.connack_packet = None
33 self.publish_packet = None
34
35 self.future_connection_success = Future()
36 self.future_stopped = Future()
37 self.future_connection_failure = Future()
38 self.future_disconnection = Future()
39 self.future_publish_received = Future()
40 self.future_expected_publishes_received = Future()
41
42 self.signing_config = None
43
44 def ws_handshake_transform(self, transform_args):
45 signing_future = auth.aws_sign_request(
46 http_request=transform_args.http_request,
47 signing_config=self.signing_config)
48 signing_future.add_done_callback(lambda x: transform_args.set_done(x.exception()))
49
50 def on_publish_received(self, publish_received_data: mqtt5.PublishReceivedData):
51 self.on_publish_received_counter += 1
52 if self.future_publish_received and not self.future_publish_received.done():
53 self.future_publish_received.set_result(publish_received_data.publish_packet)
54
55 if self.on_publish_receive_expected > 0 and self.on_publish_received_counter == self.on_publish_receive_expected and not self.future_expected_publishes_received.done():
56 self.future_expected_publishes_received.set_result(True)
57
58 def on_lifecycle_stopped(self, lifecycle_stopped: mqtt5.LifecycleStoppedData):
59 if self.future_stopped:
60 self.future_stopped.set_result(None)
61
62 def on_lifecycle_attempting_connect(self, lifecycle_attempting_connect: mqtt5.LifecycleAttemptingConnectData):
63 pass
64
65 def on_lifecycle_connection_success(self, lifecycle_connection_success: mqtt5.LifecycleConnectSuccessData):
66 self.negotiated_settings = lifecycle_connection_success.negotiated_settings
67 self.connack_packet = lifecycle_connection_success.connack_packet
68 if self.future_connection_success:
69 self.future_connection_success.set_result(lifecycle_connection_success)
70
71 def on_lifecycle_connection_failure(self, lifecycle_connection_failure: mqtt5.LifecycleConnectFailureData):
72 self.last_exception = lifecycle_connection_failure.exception
73 if self.future_connection_failure:
74 if self.future_connection_failure.done():
75 pass
76 else:
77 self.future_connection_failure.set_result(lifecycle_connection_failure)
78
79 def on_lifecycle_disconnection(self, lifecycle_disconnect_data: mqtt5.LifecycleDisconnectData):
80 if self.future_disconnection:
81 self.future_disconnection.set_result(lifecycle_disconnect_data)
82
83
84 class MqttConnectionTest(NativeResourceTest):
85 def _create_client(
86 self,
87 client_options: mqtt5.ClientOptions = None,
88 callbacks: Mqtt5TestCallbacks = None):
89
90 default_host = _get_env_variable("AWS_TEST_MQTT5_IOT_CORE_HOST")
91 if client_options is None:
92 client_options = mqtt5.ClientOptions(
93 host_name=default_host,
94 port=8883
95 )
96 if client_options.connect_options is None:
97 client_options.connect_options = mqtt5.ConnectPacket()
98 client_options.connect_options.client_id = create_client_id()
99
100 if callbacks is not None:
101 client_options.on_publish_callback_fn = callbacks.on_publish_received
102 client_options.on_lifecycle_event_stopped_fn = callbacks.on_lifecycle_stopped
103 client_options.on_lifecycle_event_attempting_connect_fn = callbacks.on_lifecycle_attempting_connect
104 client_options.on_lifecycle_event_connection_success_fn = callbacks.on_lifecycle_connection_success
105 client_options.on_lifecycle_event_connection_failure_fn = callbacks.on_lifecycle_connection_failure
106 client_options.on_lifecycle_event_disconnection_fn = callbacks.on_lifecycle_disconnection
107
108 client = mqtt5.Client(client_options)
109 return client
110
111 def _test_mqtt5_cred_pkcs12(self):
112 input_host_name = _get_env_variable("AWS_TEST_MQTT5_IOT_CORE_HOST")
113 input_key = _get_env_variable("AWS_TEST_MQTT5_IOT_CORE_PKCS12_KEY")
114 input_key_password = _get_env_variable("AWS_TEST_MQTT5_IOT_CORE_PKCS12_KEY_PASSWORD")
115
116 client_options = mqtt5.ClientOptions(
117 host_name=input_host_name,
118 port=8883
119 )
120 tls_ctx_options = io.TlsContextOptions.create_client_with_mtls_pkcs12(
121 input_key,
122 input_key_password
123 )
124 client_options.tls_ctx = io.ClientTlsContext(tls_ctx_options)
125
126 callbacks = Mqtt5TestCallbacks()
127 client = self._create_client(client_options=client_options, callbacks=callbacks)
128 client.start()
129 callbacks.future_connection_success.result(TIMEOUT)
130 client.stop()
131 callbacks.future_stopped.result(TIMEOUT)
132
133 # When AWS_CRT_USE_NON_FIPS_TLS_13 is set, the TLS backend on macOS switches from
134 # Secure Transport to s2n-tls, which doesn't support PKCS#12.
135 @unittest.skipIf(os.environ.get('AWS_CRT_USE_NON_FIPS_TLS_13'), "PKCS12 not supported with non-FIPS TLS 1.3")
136 def test_mqtt5_cred_pkcs12(self):
137 test_retry_wrapper(self._test_mqtt5_cred_pkcs12)
138
139 def _test_mqtt5_cred_windows_cert(self):
140 input_host_name = _get_env_variable("AWS_TEST_MQTT5_IOT_CORE_HOST")
141 input_windows = _get_env_variable("AWS_TEST_MQTT5_IOT_CORE_WINDOWS_CERT_STORE")
142
143 client_options = mqtt5.ClientOptions(
144 host_name=input_host_name,
145 port=8883
146 )
147 tls_ctx_options = io.TlsContextOptions.create_client_with_mtls_windows_cert_store_path(
148 input_windows
149 )
150 client_options.tls_ctx = io.ClientTlsContext(tls_ctx_options)
151
152 callbacks = Mqtt5TestCallbacks()
153 client = self._create_client(client_options=client_options, callbacks=callbacks)
154 client.start()
155 callbacks.future_connection_success.result(TIMEOUT)
156 client.stop()
157 callbacks.future_stopped.result(TIMEOUT)
158
159 def test_mqtt5_cred_windows_cert(self):
160 test_retry_wrapper(self._test_mqtt5_cred_windows_cert)
161
162 def _test_mqtt5_cred_pkcs11(self):
163 input_host_name = _get_env_variable("AWS_TEST_MQTT5_IOT_CORE_HOST")
164 input_pkcs11_lib = _get_env_variable("AWS_TEST_PKCS11_LIB")
165 input_pkcs11_pin = _get_env_variable("AWS_TEST_PKCS11_PIN")
166 input_pkcs11_token_label = _get_env_variable("AWS_TEST_PKCS11_TOKEN_LABEL")
167 input_pkcs11_private_label = _get_env_variable("AWS_TEST_PKCS11_PKEY_LABEL")
168 input_pkcs11_cert = _get_env_variable("AWS_TEST_PKCS11_CERT_FILE")
169
170 client_options = mqtt5.ClientOptions(
171 host_name=input_host_name,
172 port=8883
173 )
174 test_pkcs11_lib = io.Pkcs11Lib(
175 file=input_pkcs11_lib,
176 behavior=io.Pkcs11Lib.InitializeFinalizeBehavior.STRICT)
177 tls_ctx_options = io.TlsContextOptions.create_client_with_mtls_pkcs11(
178 pkcs11_lib=test_pkcs11_lib,
179 user_pin=input_pkcs11_pin,
180 token_label=input_pkcs11_token_label,
181 private_key_label=input_pkcs11_private_label,
182 cert_file_path=input_pkcs11_cert
183 )
184 client_options.tls_ctx = io.ClientTlsContext(tls_ctx_options)
185
186 callbacks = Mqtt5TestCallbacks()
187 client = self._create_client(client_options=client_options, callbacks=callbacks)
188 client.start()
189 callbacks.future_connection_success.result(TIMEOUT)
190 client.stop()
191 callbacks.future_stopped.result(TIMEOUT)
192
193 def test_mqtt5_cred_pkcs11(self):
194 test_retry_wrapper(self._test_mqtt5_cred_pkcs11)
195
196 def _test_mqtt5_ws_cred_static(self):
197 input_host_name = _get_env_variable("AWS_TEST_MQTT5_IOT_CORE_HOST")
198 input_role_access_key = _get_env_variable("AWS_TEST_MQTT5_ROLE_CREDENTIAL_ACCESS_KEY")
199 input_role_secret_access_key = _get_env_variable("AWS_TEST_MQTT5_ROLE_CREDENTIAL_SECRET_ACCESS_KEY")
200 input_role_session_token = _get_env_variable("AWS_TEST_MQTT5_ROLE_CREDENTIAL_SESSION_TOKEN")
201 input_region = _get_env_variable("AWS_TEST_MQTT5_IOT_CORE_REGION")
202
203 client_options = mqtt5.ClientOptions(
204 host_name=input_host_name,
205 port=443
206 )
207 credentials = auth.AwsCredentialsProvider.new_static(
208 input_role_access_key,
209 input_role_secret_access_key,
210 input_role_session_token
211 )
212
213 def sign_function(transform_args, **kwargs):
214 signing_config = auth.AwsSigningConfig(
215 algorithm=auth.AwsSigningAlgorithm.V4,
216 signature_type=auth.AwsSignatureType.HTTP_REQUEST_QUERY_PARAMS,
217 credentials_provider=credentials,
218 region=input_region,
219 service="iotdevicegateway",
220 omit_session_token=True
221 )
222 signing_future = auth.aws_sign_request(
223 http_request=transform_args.http_request,
224 signing_config=signing_config)
225 signing_future.add_done_callback(lambda x: transform_args.set_done(x.exception()))
226 client_options.websocket_handshake_transform = sign_function
227 client_options.tls_ctx = io.ClientTlsContext(io.TlsContextOptions())
228
229 callbacks = Mqtt5TestCallbacks()
230 client = self._create_client(client_options=client_options, callbacks=callbacks)
231 client.start()
232 callbacks.future_connection_success.result(TIMEOUT)
233 client.stop()
234 callbacks.future_stopped.result(TIMEOUT)
235
236 def test_mqtt5_ws_cred_static(self):
237 test_retry_wrapper(self._test_mqtt5_ws_cred_static)
238
239 def _test_mqtt5_ws_cred_cognito(self):
240 input_host_name = _get_env_variable("AWS_TEST_MQTT5_IOT_CORE_HOST")
241 input_cognito_endpoint = _get_env_variable("AWS_TEST_MQTT5_COGNITO_ENDPOINT")
242 input_cognito_identity = _get_env_variable("AWS_TEST_MQTT5_COGNITO_IDENTITY")
243 input_region = _get_env_variable("AWS_TEST_MQTT5_IOT_CORE_REGION")
244
245 client_options = mqtt5.ClientOptions(
246 host_name=input_host_name,
247 port=443
248 )
249 credentials = auth.AwsCredentialsProvider.new_cognito(
250 endpoint=input_cognito_endpoint,
251 identity=input_cognito_identity,
252 tls_ctx=io.ClientTlsContext(io.TlsContextOptions())
253 )
254
255 def sign_function(transform_args, **kwargs):
256 signing_config = auth.AwsSigningConfig(
257 algorithm=auth.AwsSigningAlgorithm.V4,
258 signature_type=auth.AwsSignatureType.HTTP_REQUEST_QUERY_PARAMS,
259 credentials_provider=credentials,
260 region=input_region,
261 service="iotdevicegateway",
262 omit_session_token=True
263 )
264 signing_future = auth.aws_sign_request(
265 http_request=transform_args.http_request,
266 signing_config=signing_config)
267 signing_future.add_done_callback(lambda x: transform_args.set_done(x.exception()))
268 client_options.websocket_handshake_transform = sign_function
269 client_options.tls_ctx = io.ClientTlsContext(io.TlsContextOptions())
270
271 callbacks = Mqtt5TestCallbacks()
272 client = self._create_client(client_options=client_options, callbacks=callbacks)
273 client.start()
274 callbacks.future_connection_success.result(TIMEOUT)
275 client.stop()
276 callbacks.future_stopped.result(TIMEOUT)
277
278 def test_mqtt5_ws_cred_cognito(self):
279 test_retry_wrapper(self._test_mqtt5_ws_cred_cognito)
280
281 def _test_mqtt5_ws_cred_x509(self):
282 input_host_name = _get_env_variable("AWS_TEST_MQTT5_IOT_CORE_HOST")
283 input_cert = _get_env_variable("AWS_TEST_MQTT5_IOT_CORE_X509_CERT")
284 input_key = _get_env_variable("AWS_TEST_MQTT5_IOT_CORE_X509_KEY")
285 input_x509_endpoint = _get_env_variable("AWS_TEST_MQTT5_IOT_CORE_X509_ENDPOINT")
286 input_x509_role = _get_env_variable("AWS_TEST_MQTT5_IOT_CORE_X509_ROLE_ALIAS")
287 input_x509_thing = _get_env_variable("AWS_TEST_MQTT5_IOT_CORE_X509_THING_NAME")
288 input_region = _get_env_variable("AWS_TEST_MQTT5_IOT_CORE_REGION")
289
290 client_options = mqtt5.ClientOptions(
291 host_name=input_host_name,
292 port=443
293 )
294 x509_tls = io.TlsContextOptions.create_client_with_mtls_from_path(
295 input_cert,
296 input_key
297 )
298 credentials = auth.AwsCredentialsProvider.new_x509(
299 endpoint=input_x509_endpoint,
300 role_alias=input_x509_role,
301 thing_name=input_x509_thing,
302 tls_ctx=io.ClientTlsContext(x509_tls)
303 )
304
305 def sign_function(transform_args, **kwargs):
306 signing_config = auth.AwsSigningConfig(
307 algorithm=auth.AwsSigningAlgorithm.V4,
308 signature_type=auth.AwsSignatureType.HTTP_REQUEST_QUERY_PARAMS,
309 credentials_provider=credentials,
310 region=input_region,
311 service="iotdevicegateway",
312 omit_session_token=True
313 )
314 signing_future = auth.aws_sign_request(
315 http_request=transform_args.http_request,
316 signing_config=signing_config)
317 signing_future.add_done_callback(lambda x: transform_args.set_done(x.exception()))
318 client_options.websocket_handshake_transform = sign_function
319 client_options.tls_ctx = io.ClientTlsContext(io.TlsContextOptions())
320
321 callbacks = Mqtt5TestCallbacks()
322 client = self._create_client(client_options=client_options, callbacks=callbacks)
323 client.start()
324 callbacks.future_connection_success.result(TIMEOUT)
325 client.stop()
326 callbacks.future_stopped.result(TIMEOUT)
327
328 def test_mqtt5_ws_cred_x509(self):
329 test_retry_wrapper(self._test_mqtt5_ws_cred_x509)
330
331 def _test_mqtt5_ws_cred_profile(self):
332 input_host_name = _get_env_variable("AWS_TEST_MQTT5_IOT_CORE_HOST")
333 input_profile_config = _get_env_variable("AWS_TEST_MQTT5_IOT_PROFILE_CONFIG")
334 input_profile_cred = _get_env_variable("AWS_TEST_MQTT5_IOT_PROFILE_CREDENTIALS")
335 input_region = _get_env_variable("AWS_TEST_MQTT5_IOT_CORE_REGION")
336
337 client_options = mqtt5.ClientOptions(
338 host_name=input_host_name,
339 port=443
340 )
341 credentials = auth.AwsCredentialsProvider.new_profile(
342 config_filepath=input_profile_config,
343 credentials_filepath=input_profile_cred
344 )
345
346 def sign_function(transform_args, **kwargs):
347 signing_config = auth.AwsSigningConfig(
348 algorithm=auth.AwsSigningAlgorithm.V4,
349 signature_type=auth.AwsSignatureType.HTTP_REQUEST_QUERY_PARAMS,
350 credentials_provider=credentials,
351 region=input_region,
352 service="iotdevicegateway",
353 omit_session_token=True
354 )
355 signing_future = auth.aws_sign_request(
356 http_request=transform_args.http_request,
357 signing_config=signing_config)
358 signing_future.add_done_callback(lambda x: transform_args.set_done(x.exception()))
359 client_options.websocket_handshake_transform = sign_function
360 client_options.tls_ctx = io.ClientTlsContext(io.TlsContextOptions())
361
362 callbacks = Mqtt5TestCallbacks()
363 client = self._create_client(client_options=client_options, callbacks=callbacks)
364 client.start()
365 callbacks.future_connection_success.result(TIMEOUT)
366 client.stop()
367 callbacks.future_stopped.result(TIMEOUT)
368
369 def test_mqtt5_ws_cred_profile(self):
370 test_retry_wrapper(self._test_mqtt5_ws_cred_profile)
371
372 def _test_mqtt5_ws_cred_environment(self):
373 self._test_mqtt5_ws_cred_environment_aux(use_default_chain=False)
374
375 def test_mqtt5_ws_cred_environment(self):
376 test_retry_wrapper(self._test_mqtt5_ws_cred_environment)
377
378 def _test_mqtt5_ws_cred_default_chain(self):
379 self._test_mqtt5_ws_cred_environment_aux(use_default_chain=True)
380
381 def test_mqtt5_ws_cred_default_chain(self):
382 test_retry_wrapper(self._test_mqtt5_ws_cred_default_chain)
383
384 def _test_mqtt5_ws_cred_environment_aux(self, use_default_chain):
385 input_host_name = _get_env_variable("AWS_TEST_MQTT5_IOT_CORE_HOST")
386 input_access_key = _get_env_variable("AWS_TEST_MQTT5_ROLE_CREDENTIAL_ACCESS_KEY")
387 input_secret_access_key = _get_env_variable("AWS_TEST_MQTT5_ROLE_CREDENTIAL_SECRET_ACCESS_KEY")
388 input_session_token = _get_env_variable("AWS_TEST_MQTT5_ROLE_CREDENTIAL_SESSION_TOKEN")
389 input_region = _get_env_variable("AWS_TEST_MQTT5_IOT_CORE_REGION")
390
391 client_options = mqtt5.ClientOptions(
392 host_name=input_host_name,
393 port=443
394 )
395 # Cache the current credentials
396 cache_access_key = os.environ.get("AWS_ACCESS_KEY_ID")
397 cache_secret_access_key = os.environ.get("AWS_SECRET_ACCESS_KEY")
398 cache_token = os.environ.get("AWS_SESSION_TOKEN")
399 # Set the environment variables from the static credentials
400 os.environ["AWS_ACCESS_KEY_ID"] = input_access_key
401 os.environ["AWS_SECRET_ACCESS_KEY"] = input_secret_access_key
402 os.environ["AWS_SESSION_TOKEN"] = input_session_token
403 # This should load the environment variables we just set
404 if use_default_chain:
405 credentials = auth.AwsCredentialsProvider.new_default_chain()
406 else:
407 credentials = auth.AwsCredentialsProvider.new_environment()
408
409 def sign_function(transform_args, **kwargs):
410 signing_config = auth.AwsSigningConfig(
411 algorithm=auth.AwsSigningAlgorithm.V4,
412 signature_type=auth.AwsSignatureType.HTTP_REQUEST_QUERY_PARAMS,
413 credentials_provider=credentials,
414 region=input_region,
415 service="iotdevicegateway",
416 omit_session_token=True
417 )
418 signing_future = auth.aws_sign_request(
419 http_request=transform_args.http_request,
420 signing_config=signing_config)
421 signing_future.add_done_callback(lambda x: transform_args.set_done(x.exception()))
422 client_options.websocket_handshake_transform = sign_function
423 client_options.tls_ctx = io.ClientTlsContext(io.TlsContextOptions())
424
425 callbacks = Mqtt5TestCallbacks()
426 client = self._create_client(client_options=client_options, callbacks=callbacks)
427 client.start()
428 callbacks.future_connection_success.result(TIMEOUT)
429 client.stop()
430 callbacks.future_stopped.result(TIMEOUT)
431
432 # Set it back to the cached result
433 if (cache_access_key is not None):
434 os.environ["AWS_ACCESS_KEY_ID"] = cache_access_key
435 else:
436 del os.environ["AWS_ACCESS_KEY_ID"]
437 if (cache_secret_access_key is not None):
438 os.environ["AWS_SECRET_ACCESS_KEY"] = cache_secret_access_key
439 else:
440 del os.environ["AWS_SECRET_ACCESS_KEY"]
441 if (cache_token is not None):
442 os.environ["AWS_SESSION_TOKEN"] = cache_token
443 else:
444 del os.environ["AWS_SESSION_TOKEN"]
445
446
447 if __name__ == 'main':
448 unittest.main()