Debian Codegraph @

ansible_collections/community/general/tests/unit/plugins/modules/test_keycloak_authentication.py

raw
1 # Copyright (c) 2021, Ansible Project
2 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
3 # SPDX-License-Identifier: GPL-3.0-or-later
4
5 from __future__ import annotations
6
7 from contextlib import contextmanager
8 from io import StringIO
9 from itertools import count
10 from unittest.mock import patch
11
12 from ansible_collections.community.internal_test_tools.tests.unit.plugins.modules.utils import (
13 AnsibleExitJson,
14 ModuleTestCase,
15 set_module_args,
16 )
17
18 from ansible_collections.community.general.plugins.modules import keycloak_authentication
19
20
21 @contextmanager
22 def patch_keycloak_api(
23 get_authentication_flow_by_alias=None,
24 copy_auth_flow=None,
25 create_empty_auth_flow=None,
26 get_executions_representation=None,
27 delete_authentication_flow_by_id=None,
28 ):
29 """Mock context manager for patching the methods in PwPolicyIPAClient that contact the IPA server
30
31 Patches the `login` and `_post_json` methods
32
33 Keyword arguments are passed to the mock object that patches `_post_json`
34
35 No arguments are passed to the mock object that patches `login` because no tests require it
36
37 Example::
38
39 with patch_ipa(return_value={}) as (mock_login, mock_post):
40 ...
41 """
42
43 obj = keycloak_authentication.KeycloakAPI
44 with patch.object(
45 obj, "get_authentication_flow_by_alias", side_effect=get_authentication_flow_by_alias
46 ) as mock_get_authentication_flow_by_alias:
47 with patch.object(obj, "copy_auth_flow", side_effect=copy_auth_flow) as mock_copy_auth_flow:
48 with patch.object(
49 obj, "create_empty_auth_flow", side_effect=create_empty_auth_flow
50 ) as mock_create_empty_auth_flow:
51 with patch.object(
52 obj, "get_executions_representation", return_value=get_executions_representation
53 ) as mock_get_executions_representation:
54 with patch.object(
55 obj, "delete_authentication_flow_by_id", side_effect=delete_authentication_flow_by_id
56 ) as mock_delete_authentication_flow_by_id:
57 yield (
58 mock_get_authentication_flow_by_alias,
59 mock_copy_auth_flow,
60 mock_create_empty_auth_flow,
61 mock_get_executions_representation,
62 mock_delete_authentication_flow_by_id,
63 )
64
65
66 def get_response(object_with_future_response, method, get_id_call_count):
67 if callable(object_with_future_response):
68 return object_with_future_response()
69 if isinstance(object_with_future_response, dict):
70 return get_response(object_with_future_response[method], method, get_id_call_count)
71 if isinstance(object_with_future_response, list):
72 call_number = next(get_id_call_count)
73 return get_response(object_with_future_response[call_number], method, get_id_call_count)
74 return object_with_future_response
75
76
77 def build_mocked_request(get_id_user_count, response_dict):
78 def _mocked_requests(*args, **kwargs):
79 url = args[0]
80 method = kwargs["method"]
81 future_response = response_dict.get(url, None)
82 return get_response(future_response, method, get_id_user_count)
83
84 return _mocked_requests
85
86
87 def create_wrapper(text_as_string):
88 """Allow to mock many times a call to one address.
89 Without this function, the StringIO is empty for the second call.
90 """
91
92 def _create_wrapper():
93 return StringIO(text_as_string)
94
95 return _create_wrapper
96
97
98 def mock_good_connection():
99 token_response = {
100 "http://keycloak.url/auth/realms/master/protocol/openid-connect/token": create_wrapper(
101 '{"access_token": "alongtoken"}'
102 ),
103 }
104 return patch(
105 "ansible_collections.community.general.plugins.module_utils._keycloak.open_url",
106 side_effect=build_mocked_request(count(), token_response),
107 autospec=True,
108 )
109
110
111 class TestKeycloakAuthentication(ModuleTestCase):
112 def setUp(self):
113 super().setUp()
114 self.module = keycloak_authentication
115
116 def test_create_auth_flow_from_copy(self):
117 """Add a new authentication flow from copy of an other flow"""
118
119 module_args = {
120 "auth_keycloak_url": "http://keycloak.url/auth",
121 "auth_username": "admin",
122 "auth_password": "admin",
123 "auth_realm": "master",
124 "realm": "realm-name",
125 "alias": "Test create authentication flow copy",
126 "copyFrom": "first broker login",
127 "authenticationExecutions": [
128 {
129 "providerId": "identity-provider-redirector",
130 "requirement": "ALTERNATIVE",
131 },
132 ],
133 "state": "present",
134 }
135 return_value_auth_flow_before = [{}]
136 return_value_copied = [
137 {
138 "id": "2ac059fc-c548-414f-9c9e-84d42bd4944e",
139 "alias": "first broker login",
140 "description": "browser based authentication",
141 "providerId": "basic-flow",
142 "topLevel": True,
143 "builtIn": False,
144 "authenticationExecutions": [
145 {
146 "authenticator": "auth-cookie",
147 "requirement": "ALTERNATIVE",
148 "priority": 10,
149 "userSetupAllowed": False,
150 "autheticatorFlow": False,
151 },
152 ],
153 }
154 ]
155 return_value_executions_after = [
156 {
157 "id": "b678e30c-8469-40a7-8c21-8d0cda76a591",
158 "requirement": "ALTERNATIVE",
159 "displayName": "Identity Provider Redirector",
160 "requirementChoices": ["REQUIRED", "DISABLED"],
161 "configurable": True,
162 "providerId": "identity-provider-redirector",
163 "level": 0,
164 "index": 0,
165 },
166 {
167 "id": "fdc208e9-c292-48b7-b7d1-1d98315ee893",
168 "requirement": "ALTERNATIVE",
169 "displayName": "Cookie",
170 "requirementChoices": ["REQUIRED", "ALTERNATIVE", "DISABLED"],
171 "configurable": False,
172 "providerId": "auth-cookie",
173 "level": 0,
174 "index": 1,
175 },
176 ]
177 changed = True
178
179 # Run the module
180
181 with set_module_args(module_args):
182 with mock_good_connection():
183 with patch_keycloak_api(
184 get_authentication_flow_by_alias=return_value_auth_flow_before,
185 copy_auth_flow=return_value_copied,
186 get_executions_representation=return_value_executions_after,
187 ) as (
188 mock_get_authentication_flow_by_alias,
189 mock_copy_auth_flow,
190 mock_create_empty_auth_flow,
191 mock_get_executions_representation,
192 mock_delete_authentication_flow_by_id,
193 ):
194 with self.assertRaises(AnsibleExitJson) as exec_info:
195 self.module.main()
196
197 # Verify number of call on each mock
198 self.assertEqual(len(mock_get_authentication_flow_by_alias.mock_calls), 1)
199 self.assertEqual(len(mock_copy_auth_flow.mock_calls), 1)
200 self.assertEqual(len(mock_create_empty_auth_flow.mock_calls), 0)
201 self.assertEqual(len(mock_get_executions_representation.mock_calls), 2)
202 self.assertEqual(len(mock_delete_authentication_flow_by_id.mock_calls), 0)
203
204 # Verify that the module's changed status matches what is expected
205 self.assertIs(exec_info.exception.args[0]["changed"], changed)
206
207 def test_create_auth_flow_from_copy_idempotency(self):
208 """Add an already existing authentication flow from copy of an other flow to test idempotency"""
209
210 module_args = {
211 "auth_keycloak_url": "http://keycloak.url/auth",
212 "auth_username": "admin",
213 "auth_password": "admin",
214 "auth_realm": "master",
215 "realm": "realm-name",
216 "alias": "Test create authentication flow copy",
217 "copyFrom": "first broker login",
218 "authenticationExecutions": [
219 {
220 "providerId": "identity-provider-redirector",
221 "requirement": "ALTERNATIVE",
222 },
223 ],
224 "state": "present",
225 }
226 return_value_auth_flow_before = [
227 {
228 "id": "71275d5e-e11f-4be4-b119-0abfa87987a4",
229 "alias": "Test create authentication flow copy",
230 "description": "",
231 "providerId": "basic-flow",
232 "topLevel": True,
233 "builtIn": False,
234 "authenticationExecutions": [
235 {
236 "authenticator": "identity-provider-redirector",
237 "requirement": "ALTERNATIVE",
238 "priority": 0,
239 "userSetupAllowed": False,
240 "autheticatorFlow": False,
241 },
242 {
243 "authenticator": "auth-cookie",
244 "requirement": "ALTERNATIVE",
245 "priority": 0,
246 "userSetupAllowed": False,
247 "autheticatorFlow": False,
248 },
249 ],
250 }
251 ]
252 return_value_executions_after = [
253 {
254 "id": "b678e30c-8469-40a7-8c21-8d0cda76a591",
255 "requirement": "ALTERNATIVE",
256 "displayName": "Identity Provider Redirector",
257 "requirementChoices": ["REQUIRED", "DISABLED"],
258 "configurable": True,
259 "providerId": "identity-provider-redirector",
260 "level": 0,
261 "index": 0,
262 },
263 {
264 "id": "fdc208e9-c292-48b7-b7d1-1d98315ee893",
265 "requirement": "ALTERNATIVE",
266 "displayName": "Cookie",
267 "requirementChoices": ["REQUIRED", "ALTERNATIVE", "DISABLED"],
268 "configurable": False,
269 "providerId": "auth-cookie",
270 "level": 0,
271 "index": 1,
272 },
273 ]
274 changed = False
275
276 # Run the module
277
278 with set_module_args(module_args):
279 with mock_good_connection():
280 with patch_keycloak_api(
281 get_authentication_flow_by_alias=return_value_auth_flow_before,
282 get_executions_representation=return_value_executions_after,
283 ) as (
284 mock_get_authentication_flow_by_alias,
285 mock_copy_auth_flow,
286 mock_create_empty_auth_flow,
287 mock_get_executions_representation,
288 mock_delete_authentication_flow_by_id,
289 ):
290 with self.assertRaises(AnsibleExitJson) as exec_info:
291 self.module.main()
292
293 # Verify number of call on each mock
294 self.assertEqual(len(mock_get_authentication_flow_by_alias.mock_calls), 1)
295 self.assertEqual(len(mock_copy_auth_flow.mock_calls), 0)
296 self.assertEqual(len(mock_create_empty_auth_flow.mock_calls), 0)
297 self.assertEqual(len(mock_get_executions_representation.mock_calls), 2)
298 self.assertEqual(len(mock_delete_authentication_flow_by_id.mock_calls), 0)
299
300 # Verify that the module's changed status matches what is expected
301 self.assertIs(exec_info.exception.args[0]["changed"], changed)
302
303 def test_create_auth_flow_without_copy(self):
304 """Add authentication without copy"""
305
306 module_args = {
307 "auth_keycloak_url": "http://keycloak.url/auth",
308 "auth_username": "admin",
309 "auth_password": "admin",
310 "auth_realm": "master",
311 "realm": "realm-name",
312 "alias": "Test create authentication flow copy",
313 "authenticationExecutions": [
314 {
315 "providerId": "identity-provider-redirector",
316 "requirement": "ALTERNATIVE",
317 "authenticationConfig": {
318 "alias": "name",
319 "config": {"defaultProvider": "value"},
320 },
321 },
322 ],
323 "state": "present",
324 }
325 return_value_auth_flow_before = [{}]
326 return_value_created_empty_flow = [
327 {
328 "alias": "Test of the keycloak_auth module",
329 "authenticationExecutions": [],
330 "builtIn": False,
331 "description": "",
332 "id": "513f5baa-cc42-47bf-b4b6-1d23ccc0a67f",
333 "providerId": "basic-flow",
334 "topLevel": True,
335 },
336 ]
337 return_value_executions_after = [
338 {
339 "id": "b678e30c-8469-40a7-8c21-8d0cda76a591",
340 "requirement": "ALTERNATIVE",
341 "displayName": "Identity Provider Redirector",
342 "requirementChoices": ["REQUIRED", "DISABLED"],
343 "configurable": True,
344 "providerId": "identity-provider-redirector",
345 "level": 0,
346 "index": 0,
347 },
348 ]
349 changed = True
350
351 # Run the module
352
353 with set_module_args(module_args):
354 with mock_good_connection():
355 with patch_keycloak_api(
356 get_authentication_flow_by_alias=return_value_auth_flow_before,
357 get_executions_representation=return_value_executions_after,
358 create_empty_auth_flow=return_value_created_empty_flow,
359 ) as (
360 mock_get_authentication_flow_by_alias,
361 mock_copy_auth_flow,
362 mock_create_empty_auth_flow,
363 mock_get_executions_representation,
364 mock_delete_authentication_flow_by_id,
365 ):
366 with self.assertRaises(AnsibleExitJson) as exec_info:
367 self.module.main()
368
369 # Verify number of call on each mock
370 self.assertEqual(len(mock_get_authentication_flow_by_alias.mock_calls), 1)
371 self.assertEqual(len(mock_copy_auth_flow.mock_calls), 0)
372 self.assertEqual(len(mock_create_empty_auth_flow.mock_calls), 1)
373 self.assertEqual(len(mock_get_executions_representation.mock_calls), 3)
374 self.assertEqual(len(mock_delete_authentication_flow_by_id.mock_calls), 0)
375
376 # Verify that the module's changed status matches what is expected
377 self.assertIs(exec_info.exception.args[0]["changed"], changed)
378
379 def test_update_auth_flow_adding_exec(self):
380 """Update authentication flow by adding execution"""
381
382 module_args = {
383 "auth_keycloak_url": "http://keycloak.url/auth",
384 "auth_username": "admin",
385 "auth_password": "admin",
386 "auth_realm": "master",
387 "realm": "realm-name",
388 "alias": "Test create authentication flow copy",
389 "authenticationExecutions": [
390 {
391 "providerId": "identity-provider-redirector",
392 "requirement": "ALTERNATIVE",
393 "authenticationConfig": {
394 "alias": "name",
395 "config": {"defaultProvider": "value"},
396 },
397 },
398 ],
399 "state": "present",
400 }
401 return_value_auth_flow_before = [
402 {
403 "id": "71275d5e-e11f-4be4-b119-0abfa87987a4",
404 "alias": "Test create authentication flow copy",
405 "description": "",
406 "providerId": "basic-flow",
407 "topLevel": True,
408 "builtIn": False,
409 "authenticationExecutions": [
410 {
411 "authenticator": "auth-cookie",
412 "requirement": "ALTERNATIVE",
413 "priority": 0,
414 "userSetupAllowed": False,
415 "autheticatorFlow": False,
416 },
417 ],
418 }
419 ]
420 return_value_executions_after = [
421 {
422 "id": "b678e30c-8469-40a7-8c21-8d0cda76a591",
423 "requirement": "DISABLED",
424 "displayName": "Identity Provider Redirector",
425 "requirementChoices": ["REQUIRED", "DISABLED"],
426 "configurable": True,
427 "providerId": "identity-provider-redirector",
428 "level": 0,
429 "index": 0,
430 },
431 {
432 "id": "fdc208e9-c292-48b7-b7d1-1d98315ee893",
433 "requirement": "ALTERNATIVE",
434 "displayName": "Cookie",
435 "requirementChoices": ["REQUIRED", "ALTERNATIVE", "DISABLED"],
436 "configurable": False,
437 "providerId": "auth-cookie",
438 "level": 0,
439 "index": 1,
440 },
441 ]
442 changed = True
443
444 # Run the module
445
446 with set_module_args(module_args):
447 with mock_good_connection():
448 with patch_keycloak_api(
449 get_authentication_flow_by_alias=return_value_auth_flow_before,
450 get_executions_representation=return_value_executions_after,
451 ) as (
452 mock_get_authentication_flow_by_alias,
453 mock_copy_auth_flow,
454 mock_create_empty_auth_flow,
455 mock_get_executions_representation,
456 mock_delete_authentication_flow_by_id,
457 ):
458 with self.assertRaises(AnsibleExitJson) as exec_info:
459 self.module.main()
460
461 # Verify number of call on each mock
462 self.assertEqual(len(mock_get_authentication_flow_by_alias.mock_calls), 1)
463 self.assertEqual(len(mock_copy_auth_flow.mock_calls), 0)
464 self.assertEqual(len(mock_create_empty_auth_flow.mock_calls), 0)
465 self.assertEqual(len(mock_get_executions_representation.mock_calls), 3)
466 self.assertEqual(len(mock_delete_authentication_flow_by_id.mock_calls), 0)
467
468 # Verify that the module's changed status matches what is expected
469 self.assertIs(exec_info.exception.args[0]["changed"], changed)
470
471 def test_delete_auth_flow(self):
472 """Delete authentication flow"""
473
474 module_args = {
475 "auth_keycloak_url": "http://keycloak.url/auth",
476 "auth_username": "admin",
477 "auth_password": "admin",
478 "auth_realm": "master",
479 "realm": "realm-name",
480 "alias": "Test create authentication flow copy",
481 "state": "absent",
482 }
483 return_value_auth_flow_before = [
484 {
485 "id": "71275d5e-e11f-4be4-b119-0abfa87987a4",
486 "alias": "Test create authentication flow copy",
487 "description": "",
488 "providerId": "basic-flow",
489 "topLevel": True,
490 "builtIn": False,
491 "authenticationExecutions": [
492 {
493 "authenticator": "auth-cookie",
494 "requirement": "ALTERNATIVE",
495 "priority": 0,
496 "userSetupAllowed": False,
497 "autheticatorFlow": False,
498 },
499 ],
500 }
501 ]
502 changed = True
503
504 # Run the module
505
506 with set_module_args(module_args):
507 with mock_good_connection():
508 with patch_keycloak_api(get_authentication_flow_by_alias=return_value_auth_flow_before) as (
509 mock_get_authentication_flow_by_alias,
510 mock_copy_auth_flow,
511 mock_create_empty_auth_flow,
512 mock_get_executions_representation,
513 mock_delete_authentication_flow_by_id,
514 ):
515 with self.assertRaises(AnsibleExitJson) as exec_info:
516 self.module.main()
517
518 # Verify number of call on each mock
519 self.assertEqual(len(mock_get_authentication_flow_by_alias.mock_calls), 1)
520 self.assertEqual(len(mock_copy_auth_flow.mock_calls), 0)
521 self.assertEqual(len(mock_create_empty_auth_flow.mock_calls), 0)
522 self.assertEqual(len(mock_get_executions_representation.mock_calls), 0)
523 self.assertEqual(len(mock_delete_authentication_flow_by_id.mock_calls), 1)
524
525 # Verify that the module's changed status matches what is expected
526 self.assertIs(exec_info.exception.args[0]["changed"], changed)
527
528 def test_delete_auth_flow_idempotency(self):
529 """Delete second time authentication flow to test idempotency"""
530
531 module_args = {
532 "auth_keycloak_url": "http://keycloak.url/auth",
533 "auth_username": "admin",
534 "auth_password": "admin",
535 "auth_realm": "master",
536 "realm": "realm-name",
537 "alias": "Test create authentication flow copy",
538 "state": "absent",
539 }
540 return_value_auth_flow_before = [{}]
541 changed = False
542
543 # Run the module
544
545 with set_module_args(module_args):
546 with mock_good_connection():
547 with patch_keycloak_api(get_authentication_flow_by_alias=return_value_auth_flow_before) as (
548 mock_get_authentication_flow_by_alias,
549 mock_copy_auth_flow,
550 mock_create_empty_auth_flow,
551 mock_get_executions_representation,
552 mock_delete_authentication_flow_by_id,
553 ):
554 with self.assertRaises(AnsibleExitJson) as exec_info:
555 self.module.main()
556
557 # Verify number of call on each mock
558 self.assertEqual(len(mock_get_authentication_flow_by_alias.mock_calls), 1)
559 self.assertEqual(len(mock_copy_auth_flow.mock_calls), 0)
560 self.assertEqual(len(mock_create_empty_auth_flow.mock_calls), 0)
561 self.assertEqual(len(mock_get_executions_representation.mock_calls), 0)
562 self.assertEqual(len(mock_delete_authentication_flow_by_id.mock_calls), 0)
563
564 # Verify that the module's changed status matches what is expected
565 self.assertIs(exec_info.exception.args[0]["changed"], changed)
566
567 def test_force_update_auth_flow(self):
568 """Delete authentication flow and create new one"""
569
570 module_args = {
571 "auth_keycloak_url": "http://keycloak.url/auth",
572 "auth_username": "admin",
573 "auth_password": "admin",
574 "auth_realm": "master",
575 "realm": "realm-name",
576 "alias": "Test create authentication flow copy",
577 "authenticationExecutions": [
578 {
579 "providerId": "identity-provider-redirector",
580 "requirement": "ALTERNATIVE",
581 "authenticationConfig": {
582 "alias": "name",
583 "config": {"defaultProvider": "value"},
584 },
585 },
586 ],
587 "state": "present",
588 "force": "yes",
589 }
590 return_value_auth_flow_before = [
591 {
592 "id": "71275d5e-e11f-4be4-b119-0abfa87987a4",
593 "alias": "Test create authentication flow copy",
594 "description": "",
595 "providerId": "basic-flow",
596 "topLevel": True,
597 "builtIn": False,
598 "authenticationExecutions": [
599 {
600 "authenticator": "auth-cookie",
601 "requirement": "ALTERNATIVE",
602 "priority": 0,
603 "userSetupAllowed": False,
604 "autheticatorFlow": False,
605 },
606 ],
607 }
608 ]
609 return_value_created_empty_flow = [
610 {
611 "alias": "Test of the keycloak_auth module",
612 "authenticationExecutions": [],
613 "builtIn": False,
614 "description": "",
615 "id": "513f5baa-cc42-47bf-b4b6-1d23ccc0a67f",
616 "providerId": "basic-flow",
617 "topLevel": True,
618 },
619 ]
620 return_value_executions_after = [
621 {
622 "id": "b678e30c-8469-40a7-8c21-8d0cda76a591",
623 "requirement": "DISABLED",
624 "displayName": "Identity Provider Redirector",
625 "requirementChoices": ["REQUIRED", "DISABLED"],
626 "configurable": True,
627 "providerId": "identity-provider-redirector",
628 "level": 0,
629 "index": 0,
630 },
631 ]
632 changed = True
633
634 # Run the module
635
636 with set_module_args(module_args):
637 with mock_good_connection():
638 with patch_keycloak_api(
639 get_authentication_flow_by_alias=return_value_auth_flow_before,
640 get_executions_representation=return_value_executions_after,
641 create_empty_auth_flow=return_value_created_empty_flow,
642 ) as (
643 mock_get_authentication_flow_by_alias,
644 mock_copy_auth_flow,
645 mock_create_empty_auth_flow,
646 mock_get_executions_representation,
647 mock_delete_authentication_flow_by_id,
648 ):
649 with self.assertRaises(AnsibleExitJson) as exec_info:
650 self.module.main()
651
652 # Verify number of call on each mock
653 self.assertEqual(len(mock_get_authentication_flow_by_alias.mock_calls), 1)
654 self.assertEqual(len(mock_copy_auth_flow.mock_calls), 0)
655 self.assertEqual(len(mock_create_empty_auth_flow.mock_calls), 1)
656 self.assertEqual(len(mock_get_executions_representation.mock_calls), 3)
657 self.assertEqual(len(mock_delete_authentication_flow_by_id.mock_calls), 1)
658
659 # Verify that the module's changed status matches what is expected
660 self.assertIs(exec_info.exception.args[0]["changed"], changed)