Debian Codegraph @

ansible_collections/community/general/tests/unit/plugins/modules/test_keycloak_role.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_role
19
20
21 @contextmanager
22 def patch_keycloak_api(
23 get_realm_role=None,
24 create_realm_role=None,
25 update_realm_role=None,
26 delete_realm_role=None,
27 get_client_role=None,
28 create_client_role=None,
29 update_client_role=None,
30 delete_client_role=None,
31 get_client_by_id=None,
32 get_role_composites=None,
33 ):
34 """Mock context manager for patching the methods in PwPolicyIPAClient that contact the IPA server
35
36 Patches the `login` and `_post_json` methods
37
38 Keyword arguments are passed to the mock object that patches `_post_json`
39
40 No arguments are passed to the mock object that patches `login` because no tests require it
41
42 Example::
43
44 with patch_ipa(return_value={}) as (mock_login, mock_post):
45 ...
46 """
47
48 obj = keycloak_role.KeycloakAPI
49 with patch.object(obj, "get_realm_role", side_effect=get_realm_role) as mock_get_realm_role:
50 with patch.object(obj, "create_realm_role", side_effect=create_realm_role) as mock_create_realm_role:
51 with patch.object(obj, "update_realm_role", side_effect=update_realm_role) as mock_update_realm_role:
52 with patch.object(obj, "delete_realm_role", side_effect=delete_realm_role) as mock_delete_realm_role:
53 with patch.object(obj, "get_client_role", side_effect=get_client_role) as mock_get_client_role:
54 with patch.object(
55 obj, "create_client_role", side_effect=create_client_role
56 ) as mock_create_client_role:
57 with patch.object(
58 obj, "update_client_role", side_effect=update_client_role
59 ) as mock_update_client_role:
60 with patch.object(
61 obj, "delete_client_role", side_effect=delete_client_role
62 ) as mock_delete_client_role:
63 with patch.object(
64 obj, "get_client_by_id", side_effect=get_client_by_id
65 ) as mock_get_client_by_id:
66 with patch.object(
67 obj, "get_role_composites", side_effect=get_role_composites
68 ) as mock_get_role_composites:
69 yield (
70 mock_get_realm_role,
71 mock_create_realm_role,
72 mock_update_realm_role,
73 mock_delete_realm_role,
74 mock_get_client_role,
75 mock_create_client_role,
76 mock_update_client_role,
77 mock_delete_client_role,
78 mock_get_client_by_id,
79 mock_get_role_composites,
80 )
81
82
83 def get_response(object_with_future_response, method, get_id_call_count):
84 if callable(object_with_future_response):
85 return object_with_future_response()
86 if isinstance(object_with_future_response, dict):
87 return get_response(object_with_future_response[method], method, get_id_call_count)
88 if isinstance(object_with_future_response, list):
89 call_number = next(get_id_call_count)
90 return get_response(object_with_future_response[call_number], method, get_id_call_count)
91 return object_with_future_response
92
93
94 def build_mocked_request(get_id_user_count, response_dict):
95 def _mocked_requests(*args, **kwargs):
96 url = args[0]
97 method = kwargs["method"]
98 future_response = response_dict.get(url, None)
99 return get_response(future_response, method, get_id_user_count)
100
101 return _mocked_requests
102
103
104 def create_wrapper(text_as_string):
105 """Allow to mock many times a call to one address.
106 Without this function, the StringIO is empty for the second call.
107 """
108
109 def _create_wrapper():
110 return StringIO(text_as_string)
111
112 return _create_wrapper
113
114
115 def mock_good_connection():
116 token_response = {
117 "http://keycloak.url/auth/realms/master/protocol/openid-connect/token": create_wrapper(
118 '{"access_token": "alongtoken"}'
119 ),
120 }
121 return patch(
122 "ansible_collections.community.general.plugins.module_utils._keycloak.open_url",
123 side_effect=build_mocked_request(count(), token_response),
124 autospec=True,
125 )
126
127
128 class TestKeycloakRealmRole(ModuleTestCase):
129 def setUp(self):
130 super().setUp()
131 self.module = keycloak_role
132
133 def test_create_when_absent(self):
134 """Add a new realm role"""
135
136 module_args = {
137 "auth_keycloak_url": "http://keycloak.url/auth",
138 "auth_password": "admin",
139 "auth_realm": "master",
140 "auth_username": "admin",
141 "auth_client_id": "admin-cli",
142 "validate_certs": True,
143 "realm": "realm-name",
144 "name": "role-name",
145 "description": "role-description",
146 }
147 return_value_absent = [
148 None,
149 {
150 "attributes": {},
151 "clientRole": False,
152 "composite": False,
153 "containerId": "realm-name",
154 "description": "role-description",
155 "id": "90f1cdb6-be88-496e-89c6-da1fb6bc6966",
156 "name": "role-name",
157 },
158 ]
159 return_value_created = [None]
160 changed = True
161
162 # Run the module
163
164 with set_module_args(module_args):
165 with mock_good_connection():
166 with patch_keycloak_api(get_realm_role=return_value_absent, create_realm_role=return_value_created) as (
167 mock_get_realm_role,
168 mock_create_realm_role,
169 mock_update_realm_role,
170 mock_delete_realm_role,
171 mock_get_client_role,
172 mock_create_client_role,
173 mock_update_client_role,
174 mock_delete_client_role,
175 mock_get_client_by_client_id,
176 mock_get_role_composites,
177 ):
178 with self.assertRaises(AnsibleExitJson) as exec_info:
179 self.module.main()
180
181 self.assertEqual(len(mock_get_realm_role.mock_calls), 2)
182 self.assertEqual(len(mock_create_realm_role.mock_calls), 1)
183 self.assertEqual(len(mock_update_realm_role.mock_calls), 0)
184
185 # Verify that the module's changed status matches what is expected
186 self.assertIs(exec_info.exception.args[0]["changed"], changed)
187
188 def test_create_when_present_with_change(self):
189 """Update with change a realm role"""
190
191 module_args = {
192 "auth_keycloak_url": "http://keycloak.url/auth",
193 "auth_password": "admin",
194 "auth_realm": "master",
195 "auth_username": "admin",
196 "auth_client_id": "admin-cli",
197 "validate_certs": True,
198 "realm": "realm-name",
199 "name": "role-name",
200 "description": "new-role-description",
201 }
202 return_value_present = [
203 {
204 "attributes": {},
205 "clientRole": False,
206 "composite": False,
207 "containerId": "realm-name",
208 "description": "role-description",
209 "id": "90f1cdb6-be88-496e-89c6-da1fb6bc6966",
210 "name": "role-name",
211 },
212 {
213 "attributes": {},
214 "clientRole": False,
215 "composite": False,
216 "containerId": "realm-name",
217 "description": "new-role-description",
218 "id": "90f1cdb6-be88-496e-89c6-da1fb6bc6966",
219 "name": "role-name",
220 },
221 ]
222 return_value_updated = [None]
223 changed = True
224
225 # Run the module
226
227 with set_module_args(module_args):
228 with mock_good_connection():
229 with patch_keycloak_api(
230 get_realm_role=return_value_present, update_realm_role=return_value_updated
231 ) as (
232 mock_get_realm_role,
233 mock_create_realm_role,
234 mock_update_realm_role,
235 mock_delete_realm_role,
236 mock_get_client_role,
237 mock_create_client_role,
238 mock_update_client_role,
239 mock_delete_client_role,
240 mock_get_client_by_client_id,
241 mock_get_role_composites,
242 ):
243 with self.assertRaises(AnsibleExitJson) as exec_info:
244 self.module.main()
245
246 self.assertEqual(len(mock_get_realm_role.mock_calls), 2)
247 self.assertEqual(len(mock_create_realm_role.mock_calls), 0)
248 self.assertEqual(len(mock_update_realm_role.mock_calls), 1)
249
250 # Verify that the module's changed status matches what is expected
251 self.assertIs(exec_info.exception.args[0]["changed"], changed)
252
253 def test_create_when_present_no_change(self):
254 """Update without change a realm role"""
255
256 module_args = {
257 "auth_keycloak_url": "http://keycloak.url/auth",
258 "auth_password": "admin",
259 "auth_realm": "master",
260 "auth_username": "admin",
261 "auth_client_id": "admin-cli",
262 "validate_certs": True,
263 "realm": "realm-name",
264 "name": "role-name",
265 "description": "role-description",
266 }
267 return_value_present = [
268 {
269 "attributes": {},
270 "clientRole": False,
271 "composite": False,
272 "containerId": "realm-name",
273 "description": "role-description",
274 "id": "90f1cdb6-be88-496e-89c6-da1fb6bc6966",
275 "name": "role-name",
276 },
277 {
278 "attributes": {},
279 "clientRole": False,
280 "composite": False,
281 "containerId": "realm-name",
282 "description": "role-description",
283 "id": "90f1cdb6-be88-496e-89c6-da1fb6bc6966",
284 "name": "role-name",
285 },
286 ]
287 return_value_updated = [None]
288 changed = False
289
290 # Run the module
291
292 with set_module_args(module_args):
293 with mock_good_connection():
294 with patch_keycloak_api(
295 get_realm_role=return_value_present, update_realm_role=return_value_updated
296 ) as (
297 mock_get_realm_role,
298 mock_create_realm_role,
299 mock_update_realm_role,
300 mock_delete_realm_role,
301 mock_get_client_role,
302 mock_create_client_role,
303 mock_update_client_role,
304 mock_delete_client_role,
305 mock_get_client_by_client_id,
306 mock_get_role_composites,
307 ):
308 with self.assertRaises(AnsibleExitJson) as exec_info:
309 self.module.main()
310
311 self.assertEqual(len(mock_get_realm_role.mock_calls), 1)
312 self.assertEqual(len(mock_create_realm_role.mock_calls), 0)
313 self.assertEqual(len(mock_update_realm_role.mock_calls), 0)
314
315 # Verify that the module's changed status matches what is expected
316 self.assertIs(exec_info.exception.args[0]["changed"], changed)
317
318 def test_create_with_composites_when_present_no_change(self):
319 """Update without change a realm role"""
320
321 module_args = {
322 "auth_keycloak_url": "http://keycloak.url/auth",
323 "auth_password": "admin",
324 "auth_realm": "master",
325 "auth_username": "admin",
326 "auth_client_id": "admin-cli",
327 "validate_certs": True,
328 "realm": "realm-name",
329 "name": "role-name",
330 "description": "role-description",
331 "composite": True,
332 "composites": [{"client_id": "client_1", "name": "client-role1"}, {"name": "realm-role-1"}],
333 }
334 return_value_present = [
335 {
336 "attributes": {},
337 "clientRole": False,
338 "composite": True,
339 "containerId": "realm-name",
340 "description": "role-description",
341 "id": "90f1cdb6-be88-496e-89c6-da1fb6bc6966",
342 "name": "role-name",
343 },
344 {
345 "attributes": {},
346 "clientRole": False,
347 "composite": True,
348 "containerId": "realm-name",
349 "description": "role-description",
350 "id": "90f1cdb6-be88-496e-89c6-da1fb6bc6966",
351 "name": "role-name",
352 },
353 ]
354 return_value_updated = [None]
355 return_get_role_composites = [
356 [
357 {"clientRole": True, "containerId": "c4367fac-f427-11ed-8e2f-aff070d20f0e", "name": "client-role1"},
358 {"clientRole": False, "containerId": "realm-name", "name": "realm-role-1"},
359 ]
360 ]
361 return_get_client_by_client_id = [
362 {
363 "id": "de152444-f126-4a7a-8273-4ee1544133ad",
364 "clientId": "client_1",
365 "name": "client_1",
366 "description": "client_1",
367 "surrogateAuthRequired": False,
368 "enabled": True,
369 "alwaysDisplayInConsole": False,
370 "clientAuthenticatorType": "client-secret",
371 "redirectUris": [
372 "http://localhost:8080/*",
373 ],
374 "webOrigins": ["*"],
375 "notBefore": 0,
376 "bearerOnly": False,
377 "consentRequired": False,
378 "standardFlowEnabled": True,
379 "implicitFlowEnabled": False,
380 "directAccessGrantsEnabled": False,
381 "serviceAccountsEnabled": False,
382 "publicClient": False,
383 "frontchannelLogout": False,
384 "protocol": "openid-connect",
385 "attributes": {
386 "backchannel.logout.session.required": "true",
387 "backchannel.logout.revoke.offline.tokens": "false",
388 },
389 "authenticationFlowBindingOverrides": {},
390 "fullScopeAllowed": True,
391 "nodeReRegistrationTimeout": -1,
392 "defaultClientScopes": ["web-origins", "acr", "profile", "roles", "email"],
393 "optionalClientScopes": ["address", "phone", "offline_access", "microprofile-jwt"],
394 }
395 ]
396
397 changed = False
398
399 # Run the module
400
401 with set_module_args(module_args):
402 with mock_good_connection():
403 with patch_keycloak_api(
404 get_realm_role=return_value_present,
405 update_realm_role=return_value_updated,
406 get_client_by_id=return_get_client_by_client_id,
407 get_role_composites=return_get_role_composites,
408 ) as (
409 mock_get_realm_role,
410 mock_create_realm_role,
411 mock_update_realm_role,
412 mock_delete_realm_role,
413 mock_get_client_role,
414 mock_create_client_role,
415 mock_update_client_role,
416 mock_delete_client_role,
417 mock_get_client_by_client_id,
418 mock_get_role_composites,
419 ):
420 with self.assertRaises(AnsibleExitJson) as exec_info:
421 self.module.main()
422
423 self.assertEqual(len(mock_get_realm_role.mock_calls), 1)
424 self.assertEqual(len(mock_create_realm_role.mock_calls), 0)
425 self.assertEqual(len(mock_update_realm_role.mock_calls), 0)
426 self.assertEqual(len(mock_get_client_by_client_id.mock_calls), 1)
427 self.assertEqual(len(mock_get_role_composites.mock_calls), 1)
428
429 # Verify that the module's changed status matches what is expected
430 self.assertIs(exec_info.exception.args[0]["changed"], changed)
431
432 def test_delete_when_absent(self):
433 """Remove an absent realm role"""
434
435 module_args = {
436 "auth_keycloak_url": "http://keycloak.url/auth",
437 "auth_password": "admin",
438 "auth_realm": "master",
439 "auth_username": "admin",
440 "auth_client_id": "admin-cli",
441 "validate_certs": True,
442 "realm": "realm-name",
443 "name": "role-name",
444 "state": "absent",
445 }
446 return_value_absent = [None]
447 return_value_deleted = [None]
448 changed = False
449
450 # Run the module
451
452 with set_module_args(module_args):
453 with mock_good_connection():
454 with patch_keycloak_api(get_realm_role=return_value_absent, delete_realm_role=return_value_deleted) as (
455 mock_get_realm_role,
456 mock_create_realm_role,
457 mock_update_realm_role,
458 mock_delete_realm_role,
459 mock_get_client_role,
460 mock_create_client_role,
461 mock_update_client_role,
462 mock_delete_client_role,
463 mock_get_client_by_client_id,
464 mock_get_role_composites,
465 ):
466 with self.assertRaises(AnsibleExitJson) as exec_info:
467 self.module.main()
468
469 self.assertEqual(len(mock_get_realm_role.mock_calls), 1)
470 self.assertEqual(len(mock_delete_realm_role.mock_calls), 0)
471
472 # Verify that the module's changed status matches what is expected
473 self.assertIs(exec_info.exception.args[0]["changed"], changed)
474
475 def test_delete_when_present(self):
476 """Remove a present realm role"""
477
478 module_args = {
479 "auth_keycloak_url": "http://keycloak.url/auth",
480 "auth_password": "admin",
481 "auth_realm": "master",
482 "auth_username": "admin",
483 "auth_client_id": "admin-cli",
484 "validate_certs": True,
485 "realm": "realm-name",
486 "name": "role-name",
487 "state": "absent",
488 }
489 return_value_absent = [
490 {
491 "attributes": {},
492 "clientRole": False,
493 "composite": False,
494 "containerId": "realm-name",
495 "description": "role-description",
496 "id": "90f1cdb6-be88-496e-89c6-da1fb6bc6966",
497 "name": "role-name",
498 }
499 ]
500 return_value_deleted = [None]
501 changed = True
502
503 # Run the module
504
505 with set_module_args(module_args):
506 with mock_good_connection():
507 with patch_keycloak_api(get_realm_role=return_value_absent, delete_realm_role=return_value_deleted) as (
508 mock_get_realm_role,
509 mock_create_realm_role,
510 mock_update_realm_role,
511 mock_delete_realm_role,
512 mock_get_client_role,
513 mock_create_client_role,
514 mock_update_client_role,
515 mock_delete_client_role,
516 mock_get_client_by_client_id,
517 mock_get_role_composites,
518 ):
519 with self.assertRaises(AnsibleExitJson) as exec_info:
520 self.module.main()
521
522 self.assertEqual(len(mock_get_realm_role.mock_calls), 1)
523 self.assertEqual(len(mock_delete_realm_role.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
529 class TestKeycloakClientRole(ModuleTestCase):
530 def setUp(self):
531 super().setUp()
532 self.module = keycloak_role
533
534 def test_create_client_role_with_composites_when_absent(self):
535 """Update with change a realm role"""
536
537 module_args = {
538 "auth_keycloak_url": "http://keycloak.url/auth",
539 "auth_password": "admin",
540 "auth_realm": "master",
541 "auth_username": "admin",
542 "auth_client_id": "admin-cli",
543 "validate_certs": True,
544 "realm": "realm-name",
545 "client_id": "client-name",
546 "name": "role-name",
547 "description": "role-description",
548 "composite": True,
549 "composites": [{"client_id": "client_1", "name": "client-role1"}, {"name": "realm-role-1"}],
550 }
551 return_get_client_role = [
552 None,
553 {
554 "attributes": {},
555 "clientRole": True,
556 "composite": True,
557 "composites": [{"client": {"client1": ["client-role1"]}}, {"realm": ["realm-role-1"]}],
558 "containerId": "9ae25ec2-f40a-11ed-9261-b3bacf720f69",
559 "description": "role-description",
560 "id": "90f1cdb6-be88-496e-89c6-da1fb6bc6966",
561 "name": "role-name",
562 },
563 ]
564 changed = True
565
566 # Run the module
567
568 with set_module_args(module_args):
569 with mock_good_connection():
570 with patch_keycloak_api(get_client_role=return_get_client_role) as (
571 mock_get_realm_role,
572 mock_create_realm_role,
573 mock_update_realm_role,
574 mock_delete_realm_role,
575 mock_get_client_role,
576 mock_create_client_role,
577 mock_update_client_role,
578 mock_delete_client_role,
579 mock_get_client_by_client_id,
580 mock_get_role_composites,
581 ):
582 with self.assertRaises(AnsibleExitJson) as exec_info:
583 self.module.main()
584
585 self.assertEqual(len(mock_get_realm_role.mock_calls), 0)
586 self.assertEqual(len(mock_create_realm_role.mock_calls), 0)
587 self.assertEqual(len(mock_update_realm_role.mock_calls), 0)
588 self.assertEqual(len(mock_get_client_role.mock_calls), 2)
589 self.assertEqual(len(mock_create_client_role.mock_calls), 1)
590 self.assertEqual(len(mock_update_client_role.mock_calls), 0)
591
592 # Verify that the module's changed status matches what is expected
593 self.assertIs(exec_info.exception.args[0]["changed"], changed)
594
595 def test_create_client_role_with_composites_when_present_no_change(self):
596 """Update with change a realm role"""
597
598 module_args = {
599 "auth_keycloak_url": "http://keycloak.url/auth",
600 "auth_password": "admin",
601 "auth_realm": "master",
602 "auth_username": "admin",
603 "auth_client_id": "admin-cli",
604 "validate_certs": True,
605 "realm": "realm-name",
606 "client_id": "client-name",
607 "name": "role-name",
608 "description": "role-description",
609 "composite": True,
610 "composites": [{"client_id": "client_1", "name": "client-role1"}, {"name": "realm-role-1"}],
611 }
612 return_get_client_role = [
613 {
614 "attributes": {},
615 "clientRole": True,
616 "composite": True,
617 "containerId": "9ae25ec2-f40a-11ed-9261-b3bacf720f69",
618 "description": "role-description",
619 "id": "90f1cdb6-be88-496e-89c6-da1fb6bc6966",
620 "name": "role-name",
621 }
622 ]
623 return_get_role_composites = [
624 [
625 {"clientRole": True, "containerId": "c4367fac-f427-11ed-8e2f-aff070d20f0e", "name": "client-role1"},
626 {"clientRole": False, "containerId": "realm-name", "name": "realm-role-1"},
627 ]
628 ]
629 return_get_client_by_client_id = [
630 {
631 "id": "de152444-f126-4a7a-8273-4ee1544133ad",
632 "clientId": "client_1",
633 "name": "client_1",
634 "description": "client_1",
635 "surrogateAuthRequired": False,
636 "enabled": True,
637 "alwaysDisplayInConsole": False,
638 "clientAuthenticatorType": "client-secret",
639 "redirectUris": [
640 "http://localhost:8080/*",
641 ],
642 "webOrigins": ["*"],
643 "notBefore": 0,
644 "bearerOnly": False,
645 "consentRequired": False,
646 "standardFlowEnabled": True,
647 "implicitFlowEnabled": False,
648 "directAccessGrantsEnabled": False,
649 "serviceAccountsEnabled": False,
650 "publicClient": False,
651 "frontchannelLogout": False,
652 "protocol": "openid-connect",
653 "attributes": {
654 "backchannel.logout.session.required": "true",
655 "backchannel.logout.revoke.offline.tokens": "false",
656 },
657 "authenticationFlowBindingOverrides": {},
658 "fullScopeAllowed": True,
659 "nodeReRegistrationTimeout": -1,
660 "defaultClientScopes": ["web-origins", "acr", "profile", "roles", "email"],
661 "optionalClientScopes": ["address", "phone", "offline_access", "microprofile-jwt"],
662 }
663 ]
664 changed = False
665
666 # Run the module
667
668 with set_module_args(module_args):
669 with mock_good_connection():
670 with patch_keycloak_api(
671 get_client_role=return_get_client_role,
672 get_client_by_id=return_get_client_by_client_id,
673 get_role_composites=return_get_role_composites,
674 ) as (
675 mock_get_realm_role,
676 mock_create_realm_role,
677 mock_update_realm_role,
678 mock_delete_realm_role,
679 mock_get_client_role,
680 mock_create_client_role,
681 mock_update_client_role,
682 mock_delete_client_role,
683 mock_get_client_by_client_id,
684 mock_get_role_composites,
685 ):
686 with self.assertRaises(AnsibleExitJson) as exec_info:
687 self.module.main()
688
689 self.assertEqual(len(mock_get_realm_role.mock_calls), 0)
690 self.assertEqual(len(mock_create_realm_role.mock_calls), 0)
691 self.assertEqual(len(mock_update_realm_role.mock_calls), 0)
692 self.assertEqual(len(mock_get_client_role.mock_calls), 1)
693 self.assertEqual(len(mock_create_client_role.mock_calls), 0)
694 self.assertEqual(len(mock_update_client_role.mock_calls), 0)
695 self.assertEqual(len(mock_get_client_by_client_id.mock_calls), 1)
696 self.assertEqual(len(mock_get_role_composites.mock_calls), 1)
697
698 # Verify that the module's changed status matches what is expected
699 self.assertIs(exec_info.exception.args[0]["changed"], changed)