Debian Codegraph @

ansible_collections/community/general/plugins/modules/keycloak_authentication.py

raw
1 #!/usr/bin/python
2 # Copyright (c) 2019, INSPQ <[email protected]>
3 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
4 # SPDX-License-Identifier: GPL-3.0-or-later
5
6 from __future__ import annotations
7
8 DOCUMENTATION = r"""
9 module: keycloak_authentication
10
11 short_description: Configure authentication in Keycloak
12
13 description:
14 - This module actually can only make a copy of an existing authentication flow, add an execution to it and configure it.
15 - It can also delete the flow.
16 version_added: "3.3.0"
17
18 attributes:
19 check_mode:
20 support: full
21 diff_mode:
22 support: full
23 action_group:
24 version_added: 10.2.0
25
26 options:
27 realm:
28 description:
29 - The name of the realm in which is the authentication.
30 required: true
31 type: str
32 alias:
33 description:
34 - Alias for the authentication flow.
35 required: true
36 type: str
37 description:
38 description:
39 - Description of the flow.
40 type: str
41 providerId:
42 description:
43 - C(providerId) for the new flow when not copied from an existing flow.
44 choices: ["basic-flow", "client-flow"]
45 type: str
46 copyFrom:
47 description:
48 - C(flowAlias) of the authentication flow to use for the copy.
49 type: str
50 authenticationExecutions:
51 description:
52 - Configuration structure for the executions.
53 type: list
54 elements: dict
55 suboptions:
56 providerId:
57 description:
58 - C(providerID) for the new flow when not copied from an existing flow.
59 type: str
60 displayName:
61 description:
62 - Name of the execution or subflow to create or update.
63 type: str
64 requirement:
65 description:
66 - Control status of the subflow or execution.
67 choices: ["REQUIRED", "ALTERNATIVE", "DISABLED", "CONDITIONAL"]
68 type: str
69 flowAlias:
70 description:
71 - Alias of parent flow.
72 type: str
73 authenticationConfig:
74 description:
75 - Describe the config of the authentication.
76 type: dict
77 index:
78 description:
79 - Priority order of the execution.
80 type: int
81 subFlowType:
82 description:
83 - For new subflows, optionally specify the type.
84 - Is only used at creation.
85 choices: ["basic-flow", "form-flow"]
86 default: "basic-flow"
87 type: str
88 version_added: 6.6.0
89 state:
90 description:
91 - Control if the authentication flow must exists or not.
92 choices: ["present", "absent"]
93 default: present
94 type: str
95 force:
96 type: bool
97 default: false
98 description:
99 - If V(true), allows to remove the authentication flow and recreate it.
100 extends_documentation_fragment:
101 - community.general._keycloak
102 - community.general._keycloak.actiongroup_keycloak
103 - community.general._attributes
104
105 author:
106 - Philippe Gauthier (@elfelip)
107 - Gaƫtan Daubresse (@Gaetan2907)
108 """
109
110 EXAMPLES = r"""
111 - name: Create an authentication flow from first broker login and add an execution to it.
112 community.general.keycloak_authentication:
113 auth_keycloak_url: http://localhost:8080/auth
114 auth_realm: master
115 auth_username: admin
116 auth_password: password
117 realm: master
118 alias: "Copy of first broker login"
119 copyFrom: "first broker login"
120 authenticationExecutions:
121 - providerId: "test-execution1"
122 requirement: "REQUIRED"
123 authenticationConfig:
124 alias: "test.execution1.property"
125 config:
126 test1.property: "value"
127 - providerId: "test-execution2"
128 requirement: "REQUIRED"
129 authenticationConfig:
130 alias: "test.execution2.property"
131 config:
132 test2.property: "value"
133 state: present
134
135 - name: Re-create the authentication flow
136 community.general.keycloak_authentication:
137 auth_keycloak_url: http://localhost:8080/auth
138 auth_realm: master
139 auth_username: admin
140 auth_password: password
141 realm: master
142 alias: "Copy of first broker login"
143 copyFrom: "first broker login"
144 authenticationExecutions:
145 - providerId: "test-provisioning"
146 requirement: "REQUIRED"
147 authenticationConfig:
148 alias: "test.provisioning.property"
149 config:
150 test.provisioning.property: "value"
151 state: present
152 force: true
153
154 - name: Create an authentication flow with subflow containing an execution.
155 community.general.keycloak_authentication:
156 auth_keycloak_url: http://localhost:8080/auth
157 auth_realm: master
158 auth_username: admin
159 auth_password: password
160 realm: master
161 alias: "Copy of first broker login"
162 copyFrom: "first broker login"
163 authenticationExecutions:
164 - providerId: "test-execution1"
165 requirement: "REQUIRED"
166 - displayName: "New Subflow"
167 requirement: "REQUIRED"
168 - providerId: "auth-cookie"
169 requirement: "REQUIRED"
170 flowAlias: "New Sublow"
171 state: present
172
173 - name: Remove authentication.
174 community.general.keycloak_authentication:
175 auth_keycloak_url: http://localhost:8080/auth
176 auth_realm: master
177 auth_username: admin
178 auth_password: password
179 realm: master
180 alias: "Copy of first broker login"
181 state: absent
182 """
183
184 RETURN = r"""
185 msg:
186 description: Message as to what action was taken.
187 returned: always
188 type: str
189
190 end_state:
191 description: Representation of the authentication after module execution.
192 returned: on success
193 type: dict
194 sample:
195 {
196 "alias": "Copy of first broker login",
197 "authenticationExecutions": [
198 {
199 "alias": "review profile config",
200 "authenticationConfig": {
201 "alias": "review profile config",
202 "config": {
203 "update.profile.on.first.login": "missing"
204 },
205 "id": "6f09e4fb-aad4-496a-b873-7fa9779df6d7"
206 },
207 "configurable": true,
208 "displayName": "Review Profile",
209 "id": "8f77dab8-2008-416f-989e-88b09ccf0b4c",
210 "index": 0,
211 "level": 0,
212 "providerId": "idp-review-profile",
213 "requirement": "REQUIRED",
214 "requirementChoices": [
215 "REQUIRED",
216 "ALTERNATIVE",
217 "DISABLED"
218 ]
219 }
220 ],
221 "builtIn": false,
222 "description": "Actions taken after first broker login with identity provider account, which is not yet linked to any Keycloak account",
223 "id": "bc228863-5887-4297-b898-4d988f8eaa5c",
224 "providerId": "basic-flow",
225 "topLevel": true
226 }
227 """
228
229 from ansible.module_utils.basic import AnsibleModule
230
231 from ansible_collections.community.general.plugins.module_utils._keycloak import (
232 KeycloakAPI,
233 KeycloakError,
234 get_token,
235 is_struct_included,
236 keycloak_argument_spec,
237 )
238
239
240 def find_exec_in_executions(searched_exec, executions):
241 """
242 Search if exec is contained in the executions.
243 :param searched_exec: Execution to search for.
244 :param executions: List of executions.
245 :return: Index of the execution, -1 if not found..
246 """
247 for i, existing_exec in enumerate(executions, start=0):
248 if (
249 "providerId" in existing_exec
250 and "providerId" in searched_exec
251 and existing_exec["providerId"] == searched_exec["providerId"]
252 or "displayName" in existing_exec
253 and "displayName" in searched_exec
254 and existing_exec["displayName"] == searched_exec["displayName"]
255 ):
256 return i
257 return -1
258
259
260 def create_or_update_executions(kc, config, realm="master"):
261 """
262 Create or update executions for an authentication flow.
263 :param kc: Keycloak API access.
264 :param config: Representation of the authentication flow including its executions.
265 :param realm: Realm
266 :return: tuple (changed, dict(before, after)
267 WHERE
268 bool changed indicates if changes have been made
269 dict(str, str) shows state before and after creation/update
270 """
271 try:
272 changed = False
273 after = ""
274 before = ""
275 execution = None
276 if config.get("authenticationExecutions") is not None:
277 # Get existing executions on the Keycloak server for this alias
278 existing_executions = kc.get_executions_representation(config, realm=realm)
279 for new_exec_index, new_exec in enumerate(config["authenticationExecutions"], start=0):
280 if new_exec["index"] is not None:
281 new_exec_index = new_exec["index"]
282 exec_found = False
283 # Get flowalias parent if given
284 if new_exec["flowAlias"] is not None:
285 flow_alias_parent = new_exec["flowAlias"]
286 else:
287 flow_alias_parent = config["alias"]
288 # Check if same providerId or displayName name between existing and new execution
289 exec_index = find_exec_in_executions(new_exec, existing_executions)
290 if exec_index != -1:
291 # Remove key that doesn't need to be compared with existing_exec
292 exclude_key = ["flowAlias", "subFlowType"]
293 for key in new_exec:
294 if new_exec[key] is None:
295 exclude_key.append(key)
296 # Compare the executions to see if it need changes
297 if (
298 not is_struct_included(new_exec, existing_executions[exec_index], exclude_key)
299 or exec_index != new_exec_index
300 ):
301 exec_found = True
302 if new_exec["index"] is None:
303 new_exec_index = exec_index
304 before += f"{existing_executions[exec_index]}\n"
305 execution = existing_executions[exec_index].copy()
306 # Remove exec from list in case 2 exec with same name
307 existing_executions[exec_index].clear()
308 elif new_exec["providerId"] is not None:
309 kc.create_execution(new_exec, flowAlias=flow_alias_parent, realm=realm)
310 execution = kc.get_executions_representation(config, realm=realm)[exec_index]
311 exec_found = True
312 exec_index = new_exec_index
313 after += f"{new_exec}\n"
314 elif new_exec["displayName"] is not None:
315 kc.create_subflow(
316 new_exec["displayName"], flow_alias_parent, realm=realm, flowType=new_exec["subFlowType"]
317 )
318 execution = kc.get_executions_representation(config, realm=realm)[exec_index]
319 exec_found = True
320 exec_index = new_exec_index
321 after += f"{new_exec}\n"
322 if exec_found:
323 changed = True
324 if exec_index != -1:
325 # Update the existing execution
326 updated_exec = {"id": execution["id"]}
327 # add the execution configuration
328 if new_exec["authenticationConfig"] is not None:
329 if "authenticationConfig" in execution and "id" in execution["authenticationConfig"]:
330 kc.delete_authentication_config(execution["authenticationConfig"]["id"], realm=realm)
331 kc.add_authenticationConfig_to_execution(
332 updated_exec["id"], new_exec["authenticationConfig"], realm=realm
333 )
334 for key in new_exec:
335 # remove unwanted key for the next API call
336 if key not in ("flowAlias", "authenticationConfig", "subFlowType"):
337 updated_exec[key] = new_exec[key]
338 if new_exec["requirement"] is not None:
339 if "priority" in execution:
340 updated_exec["priority"] = execution["priority"]
341 kc.update_authentication_executions(flow_alias_parent, updated_exec, realm=realm)
342 diff = exec_index - new_exec_index
343 kc.change_execution_priority(updated_exec["id"], diff, realm=realm)
344 after += f"{kc.get_executions_representation(config, realm=realm)[new_exec_index]}\n"
345 return changed, dict(before=before, after=after)
346 except Exception as e:
347 kc.module.fail_json(
348 msg=f"Could not create or update executions for authentication flow {config['alias']} in realm {realm}: {e}"
349 )
350
351
352 def main():
353 """
354 Module execution
355
356 :return:
357 """
358 argument_spec = keycloak_argument_spec()
359
360 meta_args = dict(
361 realm=dict(type="str", required=True),
362 alias=dict(type="str", required=True),
363 providerId=dict(type="str", choices=["basic-flow", "client-flow"]),
364 description=dict(type="str"),
365 copyFrom=dict(type="str"),
366 authenticationExecutions=dict(
367 type="list",
368 elements="dict",
369 options=dict(
370 providerId=dict(type="str"),
371 displayName=dict(type="str"),
372 requirement=dict(choices=["REQUIRED", "ALTERNATIVE", "DISABLED", "CONDITIONAL"], type="str"),
373 flowAlias=dict(type="str"),
374 authenticationConfig=dict(type="dict"),
375 index=dict(type="int"),
376 subFlowType=dict(choices=["basic-flow", "form-flow"], default="basic-flow", type="str"),
377 ),
378 ),
379 state=dict(choices=["absent", "present"], default="present"),
380 force=dict(type="bool", default=False),
381 )
382
383 argument_spec.update(meta_args)
384
385 module = AnsibleModule(
386 argument_spec=argument_spec,
387 supports_check_mode=True,
388 required_one_of=(
389 [["token", "auth_realm", "auth_username", "auth_password", "auth_client_id", "auth_client_secret"]]
390 ),
391 required_together=([["auth_username", "auth_password"]]),
392 required_by={"refresh_token": "auth_realm"},
393 )
394
395 result = dict(changed=False, msg="", flow={})
396
397 # Obtain access token, initialize API
398 try:
399 connection_header = get_token(module.params)
400 except KeycloakError as e:
401 module.fail_json(msg=str(e))
402
403 kc = KeycloakAPI(module, connection_header)
404
405 realm = module.params.get("realm")
406 state = module.params.get("state")
407 force = module.params.get("force")
408
409 new_auth_repr = {
410 "alias": module.params.get("alias"),
411 "copyFrom": module.params.get("copyFrom"),
412 "providerId": module.params.get("providerId"),
413 "authenticationExecutions": module.params.get("authenticationExecutions"),
414 "description": module.params.get("description"),
415 "builtIn": module.params.get("builtIn"),
416 "subflow": module.params.get("subflow"),
417 }
418
419 auth_repr = kc.get_authentication_flow_by_alias(alias=new_auth_repr["alias"], realm=realm)
420
421 # Cater for when it doesn't exist (an empty dict)
422 if not auth_repr:
423 if state == "absent":
424 # Do nothing and exit
425 if module._diff:
426 result["diff"] = dict(before="", after="")
427 result["changed"] = False
428 result["end_state"] = {}
429 result["msg"] = f"{new_auth_repr['alias']} absent"
430 module.exit_json(**result)
431
432 elif state == "present":
433 # Process a creation
434 result["changed"] = True
435
436 if module._diff:
437 result["diff"] = dict(before="", after=new_auth_repr)
438
439 if module.check_mode:
440 module.exit_json(**result)
441
442 # If copyFrom is defined, create authentication flow from a copy
443 if "copyFrom" in new_auth_repr and new_auth_repr["copyFrom"] is not None:
444 auth_repr = kc.copy_auth_flow(config=new_auth_repr, realm=realm)
445 else: # Create an empty authentication flow
446 auth_repr = kc.create_empty_auth_flow(config=new_auth_repr, realm=realm)
447
448 # If the authentication still not exist on the server, raise an exception.
449 if auth_repr is None:
450 result["msg"] = f"Authentication just created not found: {new_auth_repr}"
451 module.fail_json(**result)
452
453 # Configure the executions for the flow
454 create_or_update_executions(kc=kc, config=new_auth_repr, realm=realm)
455
456 # Get executions created
457 exec_repr = kc.get_executions_representation(config=new_auth_repr, realm=realm)
458 if exec_repr is not None:
459 auth_repr["authenticationExecutions"] = exec_repr
460 result["end_state"] = auth_repr
461
462 else:
463 if state == "present":
464 # Process an update
465
466 if force: # If force option is true
467 # Delete the actual authentication flow
468 result["changed"] = True
469 if module._diff:
470 result["diff"] = dict(before=auth_repr, after=new_auth_repr)
471 if module.check_mode:
472 module.exit_json(**result)
473 kc.delete_authentication_flow_by_id(id=auth_repr["id"], realm=realm)
474 # If copyFrom is defined, create authentication flow from a copy
475 if "copyFrom" in new_auth_repr and new_auth_repr["copyFrom"] is not None:
476 auth_repr = kc.copy_auth_flow(config=new_auth_repr, realm=realm)
477 else: # Create an empty authentication flow
478 auth_repr = kc.create_empty_auth_flow(config=new_auth_repr, realm=realm)
479 # If the authentication still not exist on the server, raise an exception.
480 if auth_repr is None:
481 result["msg"] = f"Authentication just created not found: {new_auth_repr}"
482 module.fail_json(**result)
483 # Configure the executions for the flow
484
485 if module.check_mode:
486 module.exit_json(**result)
487 changed, diff = create_or_update_executions(kc=kc, config=new_auth_repr, realm=realm)
488 result["changed"] |= changed
489
490 if module._diff:
491 result["diff"] = diff
492
493 # Get executions created
494 exec_repr = kc.get_executions_representation(config=new_auth_repr, realm=realm)
495 if exec_repr is not None:
496 auth_repr["authenticationExecutions"] = exec_repr
497 result["end_state"] = auth_repr
498
499 else:
500 # Process a deletion (because state was not 'present')
501 result["changed"] = True
502
503 if module._diff:
504 result["diff"] = dict(before=auth_repr, after="")
505
506 if module.check_mode:
507 module.exit_json(**result)
508
509 # delete it
510 kc.delete_authentication_flow_by_id(id=auth_repr["id"], realm=realm)
511
512 result["msg"] = f"Authentication flow: {new_auth_repr['alias']} id: {auth_repr['id']} is deleted"
513
514 module.exit_json(**result)
515
516
517 if __name__ == "__main__":
518 main()