Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright (c) Ansible project
4 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
5 # SPDX-License-Identifier: GPL-3.0-or-later
6
7 from __future__ import annotations
8
9 DOCUMENTATION = r"""
10 module: keycloak_authentication_v2
11
12 short_description: Configure authentication flows in Keycloak in an idempotent and safe manner.
13 version_added: 12.5.0
14 description:
15 - This module allows the creation, deletion, and modification of Keycloak authentication flows using the Keycloak REST API.
16 - Rather than modifying an existing flow in place, the module re-creates the flow using the B(Safe Swap) mechanism described below.
17 - B(Safe Swap mechanism) - When an authentication flow needs to be updated, the module never modifies the existing flow in place.
18 Instead it follows a multi-step swap procedure to ensure the flow is never left in an intermediate or unsafe state during the update.
19 This is especially important when the flow is actively bound to a realm binding, a client override, or as an identity-provider
20 login-flow or post-flow, because a partially-updated flow could inadvertently allow unauthorised access.
21 - The B(Safe Swap mechanism) is as follows. 1. A new flow is created under a temporary name (the original alias plus a configurable suffix,
22 for example C(myflow_tmp_for_swap)).
23 2. All executions and their configurations are added to the new temporary flow. 3. If the existing flow is currently bound to a realm or a client,
24 all bindings are redirected to the new temporary flow. This ensures continuity and avoids any gap in active authentication coverage.
25 4. The old flow is deleted. 5. The temporary flow is renamed to the original alias, restoring the expected name.
26 - B(Handling pre-existing temporary swap flows) - If a temporary swap flow already exists (for example, from a previously interrupted run),
27 the module can optionally delete it before proceeding. This behaviour is controlled by the O(force_temporary_swap_flow_deletion) option.
28 If the option is V(false) and a temporary flow already exists, the module will fail to prevent accidental data loss.
29 - B(Idempotency) - If the existing flow already matches the desired configuration, no changes are made.
30 The module compares a normalised representation of the existing flow against the desired state before deciding whether to trigger the Safe Swap procedure.
31 - A depth of 4 sub-flows is supported.
32
33 attributes:
34 check_mode:
35 support: full
36 diff_mode:
37 support: full
38
39 options:
40 realm:
41 description:
42 - The name of the realm in which the authentication flow resides.
43 required: true
44 type: str
45 alias:
46 description:
47 - The name of the authentication flow.
48 required: true
49 type: str
50 description:
51 description:
52 - A human-readable description of the flow.
53 type: str
54 providerId:
55 description:
56 - The C(providerId) for the new flow.
57 choices: [basic-flow, client-flow]
58 type: str
59 default: basic-flow
60 authenticationExecutions:
61 description:
62 - The desired execution configuration for the flow.
63 - Executions at root level.
64 type: list
65 elements: dict
66 suboptions:
67 requirement:
68 description:
69 - The requirement status of the execution or sub-flow.
70 choices: [REQUIRED, ALTERNATIVE, DISABLED, CONDITIONAL]
71 type: str
72 required: true
73 providerId:
74 description:
75 - The C(providerId) of the execution.
76 type: str
77 authenticationConfig:
78 description:
79 - The configuration for the execution.
80 type: dict
81 suboptions:
82 alias:
83 description: Name of the execution config.
84 type: str
85 required: true
86 config:
87 description: Options for the execution config.
88 required: true
89 type: dict
90 subFlow:
91 description:
92 - The name of the sub-flow.
93 type: str
94 subFlowType:
95 description:
96 - The type of the sub-flow.
97 choices: [basic-flow, form-flow]
98 default: basic-flow
99 type: str
100 authenticationExecutions:
101 description:
102 - The execution configuration for executions within the sub-flow.
103 - Executions at sub level 1.
104 type: list
105 elements: dict
106 suboptions:
107 requirement:
108 description:
109 - The requirement status of the execution or sub-flow.
110 choices: [REQUIRED, ALTERNATIVE, DISABLED, CONDITIONAL]
111 type: str
112 required: true
113 providerId:
114 description:
115 - The C(providerId) of the execution.
116 type: str
117 authenticationConfig:
118 description:
119 - The configuration for the execution.
120 type: dict
121 suboptions:
122 alias:
123 description: Name of the execution config.
124 type: str
125 required: true
126 config:
127 description: Options for the execution config.
128 required: true
129 type: dict
130 subFlow:
131 description:
132 - The name of the sub-flow.
133 type: str
134 subFlowType:
135 description:
136 - The type of the sub-flow.
137 choices: [basic-flow, form-flow]
138 default: basic-flow
139 type: str
140 authenticationExecutions:
141 description:
142 - The execution configuration for executions within the sub-flow.
143 - Executions at sub level 2.
144 type: list
145 elements: dict
146 suboptions:
147 requirement:
148 description:
149 - The requirement status of the execution or sub-flow.
150 choices: [REQUIRED, ALTERNATIVE, DISABLED, CONDITIONAL]
151 type: str
152 required: true
153 providerId:
154 description:
155 - The C(providerId) of the execution.
156 type: str
157 authenticationConfig:
158 description:
159 - The configuration for the execution.
160 type: dict
161 suboptions:
162 alias:
163 description: Name of the execution config.
164 type: str
165 required: true
166 config:
167 description: Options for the execution config.
168 required: true
169 type: dict
170 subFlow:
171 description:
172 - The name of the sub-flow.
173 type: str
174 subFlowType:
175 description:
176 - The type of the sub-flow.
177 choices: [basic-flow, form-flow]
178 default: basic-flow
179 type: str
180 authenticationExecutions:
181 description:
182 - The execution configuration for executions within the sub-flow.
183 - Executions at sub level 3.
184 type: list
185 elements: dict
186 suboptions:
187 requirement:
188 description:
189 - The requirement status of the execution or sub-flow.
190 choices: [REQUIRED, ALTERNATIVE, DISABLED, CONDITIONAL]
191 type: str
192 required: true
193 providerId:
194 description:
195 - The C(providerId) of the execution.
196 type: str
197 authenticationConfig:
198 description:
199 - The configuration for the execution.
200 type: dict
201 suboptions:
202 alias:
203 description: Name of the execution config.
204 type: str
205 required: true
206 config:
207 description: Options for the execution config.
208 required: true
209 type: dict
210 subFlow:
211 description:
212 - The name of the sub-flow.
213 type: str
214 subFlowType:
215 description:
216 - The type of the sub-flow.
217 choices: [basic-flow, form-flow]
218 default: basic-flow
219 type: str
220 authenticationExecutions:
221 description:
222 - The execution configuration for executions within the sub-flow.
223 - Executions at sub level 4 (last sub level).
224 type: list
225 elements: dict
226 suboptions:
227 requirement:
228 description:
229 - The requirement status of the execution or sub-flow.
230 choices: [REQUIRED, ALTERNATIVE, DISABLED, CONDITIONAL]
231 type: str
232 required: true
233 providerId:
234 description:
235 - The C(providerId) of the execution.
236 type: str
237 required: true
238 authenticationConfig:
239 description:
240 - The configuration for the execution.
241 type: dict
242 suboptions:
243 alias:
244 description: Name of the execution config.
245 type: str
246 required: true
247 config:
248 description: Options for the execution config.
249 required: true
250 type: dict
251 state:
252 description:
253 - Whether the authentication flow should exist or not.
254 choices: [present, absent]
255 default: present
256 type: str
257 temporary_swap_flow_suffix:
258 description:
259 - The suffix appended to the alias of the temporary flow created during a Safe Swap update.
260 - The temporary flow exists only for the duration of the swap procedure and is renamed to
261 the original alias once all bindings have been successfully transferred.
262 type: str
263 default: _tmp_for_swap
264 force_temporary_swap_flow_deletion:
265 description:
266 - If C(true), any pre-existing temporary swap flow (identified by the original alias plus
267 O(temporary_swap_flow_suffix)) is deleted before the Safe Swap procedure begins.
268 - Set this to C(false) to cause the module to fail instead of silently removing a
269 pre-existing temporary flow, for example to avoid accidental data loss after an
270 interrupted run.
271 default: true
272 type: bool
273 extends_documentation_fragment:
274 - community.general._keycloak
275 - community.general._keycloak.actiongroup_keycloak
276 - community.general._attributes
277
278 author:
279 - Thomas Bargetz (@thomasbargetz)
280 """
281
282 EXAMPLES = r"""
283 - name: Create or modify the 'My Login Flow'.
284 community.general.keycloak_authentication_v2:
285 auth_keycloak_url: http://localhost:8080/auth
286 auth_realm: master
287 auth_username: admin
288 auth_password: password
289 realm: master
290 alias: My Login Flow
291 authenticationExecutions:
292 - providerId: idp-review-profile
293 requirement: REQUIRED
294 authenticationConfig:
295 alias: My Login Flow - review profile config
296 config:
297 update.profile.on.first.login: "missing"
298 - subFlow: My Login Flow - User creation or linking
299 requirement: REQUIRED
300 authenticationExecutions:
301 - providerId: idp-create-user-if-unique
302 requirement: ALTERNATIVE
303 authenticationConfig:
304 alias: My Login Flow - create unique user config
305 config:
306 require.password.update.after.registration: "true"
307 - providerId: auth-cookie
308 requirement: REQUIRED
309 - subFlow: My Login Flow - Handle Existing Account
310 requirement: ALTERNATIVE
311 authenticationExecutions:
312 - providerId: idp-confirm-link
313 requirement: REQUIRED
314 - providerId: auth-cookie
315 requirement: DISABLED
316 state: present
317
318 - name: Remove an authentication flow.
319 community.general.keycloak_authentication_v2:
320 auth_keycloak_url: http://localhost:8080/auth
321 auth_realm: master
322 auth_username: admin
323 auth_password: password
324 realm: master
325 alias: My Login Flow
326 state: absent
327 """
328
329 RETURN = r"""
330 end_state:
331 description: Representation of the authentication flow after module execution.
332 returned: on success
333 type: dict
334 sample:
335 {
336 "alias": "My Login Flow",
337 "builtIn": false,
338 "description": "Actions taken after first broker login with identity provider account, which is not yet linked to any Keycloak account",
339 "id": "bc228863-5887-4297-b898-4d988f8eaa5c",
340 "providerId": "basic-flow",
341 "topLevel": true,
342 "authenticationExecutions": [
343 {
344 "alias": "review profile config",
345 "authenticationConfig": {
346 "alias": "review profile config",
347 "config": {
348 "update.profile.on.first.login": "missing"
349 },
350 "id": "6f09e4fb-aad4-496a-b873-7fa9779df6d7"
351 },
352 "configurable": true,
353 "displayName": "Review Profile",
354 "id": "8f77dab8-2008-416f-989e-88b09ccf0b4c",
355 "index": 0,
356 "level": 0,
357 "providerId": "idp-review-profile",
358 "requirement": "REQUIRED",
359 "requirementChoices": [
360 "REQUIRED",
361 "ALTERNATIVE",
362 "DISABLED"
363 ]
364 }
365 ]
366 }
367 """
368
369 import copy
370 import traceback
371 import typing as t
372
373 from ansible.module_utils.basic import AnsibleModule
374
375 from ansible_collections.community.general.plugins.module_utils._keycloak import (
376 KeycloakAPI,
377 KeycloakError,
378 get_token,
379 keycloak_argument_spec,
380 )
381
382
383 def rename_auth_flow(kc: KeycloakAPI, realm: str, flow_id: str, new_alias: str) -> None:
384 """Rename an existing authentication flow to a new alias.
385
386 :param kc: a KeycloakAPI instance.
387 :param realm: the realm in which the flow resides.
388 :param flow_id: the ID of the flow to rename.
389 :param new_alias: the new alias to assign to the flow.
390 """
391 auth = kc.get_authentication_flow_by_id(flow_id, realm)
392 if auth is not None:
393 updated = copy.deepcopy(auth)
394 updated["alias"] = new_alias
395 # The authenticationExecutions key is not accepted by the update endpoint.
396 updated.pop("authenticationExecutions", None)
397 kc.update_authentication_flow(flow_id, config=updated, realm=realm)
398
399
400 def append_suffix_to_executions(executions: list, suffix: str) -> None:
401 """Recursively append a suffix to all sub-flow and authentication config aliases.
402
403 :param executions: a list of execution dicts to process.
404 :param suffix: the suffix string to append.
405 """
406 for execution in executions:
407 if execution.get("authenticationConfig") is not None:
408 execution["authenticationConfig"]["alias"] += suffix
409 if execution.get("subFlow") is not None:
410 execution["subFlow"] += suffix
411 if execution.get("authenticationExecutions") is not None:
412 append_suffix_to_executions(execution["authenticationExecutions"], suffix)
413
414
415 def append_suffix_to_flow_names(desired_auth: dict, suffix: str) -> None:
416 """Append a suffix to the top-level alias and all nested aliases in a flow definition.
417
418 This is used during the Safe Swap procedure to give the temporary flow a distinct name.
419
420 :param desired_auth: the desired authentication flow dict (mutated in place).
421 :param suffix: the suffix string to append.
422 """
423 desired_auth["alias"] += suffix
424 append_suffix_to_executions(desired_auth["authenticationExecutions"], suffix)
425
426
427 def remove_suffix_from_flow_names(kc: KeycloakAPI, realm: str, auth: dict, suffix: str) -> None:
428 """Remove a previously-added suffix from the top-level flow alias, all sub-flow aliases,
429 and all authentication config aliases.
430
431 This is the final step of the Safe Swap procedure, which restores the original alias after
432 the temporary flow has been bound and the old flow deleted.
433
434 :param kc: a KeycloakAPI instance.
435 :param realm: the realm in which the flow resides.
436 :param auth: the authentication flow dict (mutated in place to reflect the renamed alias).
437 :param suffix: the suffix to remove.
438 """
439 new_alias = auth["alias"].removesuffix(suffix)
440 rename_auth_flow(kc, realm, auth["id"], new_alias)
441 auth["alias"] = new_alias
442
443 executions = kc.get_executions_representation(config=auth, realm=realm)
444 for execution in executions:
445 if execution.get("authenticationFlow"):
446 new_sub_flow_alias = execution["displayName"].removesuffix(suffix)
447 rename_auth_flow(kc, realm, execution["flowId"], new_sub_flow_alias)
448 if execution.get("configurable"):
449 auth_config = execution.get("authenticationConfig")
450 if auth_config is not None:
451 auth_config["alias"] = auth_config["alias"].removesuffix(suffix)
452 kc.update_authentication_config(
453 configId=auth_config["id"],
454 authenticationConfig=auth_config,
455 realm=realm,
456 )
457
458
459 def update_execution_requirement_and_config(
460 kc: KeycloakAPI,
461 realm: str,
462 top_level_auth: dict,
463 execution: dict,
464 parent_flow_alias: str,
465 ) -> None:
466 """Update a newly-created execution to set its requirement and, if present, its configuration.
467
468 Keycloak ignores the requirement value on execution creation and defaults all new executions
469 to DISABLED. A subsequent update is therefore required to apply the correct requirement.
470
471 :param kc: a KeycloakAPI instance.
472 :param realm: the realm in which the flow resides.
473 :param top_level_auth: the top-level authentication flow dict used to look up executions.
474 :param execution: the desired execution dict containing 'requirement' and optionally
475 'authenticationConfig'.
476 :param parent_flow_alias: the alias of the flow or sub-flow that owns this execution.
477 """
478 # The most recently added execution is always last in the list.
479 created_exec = kc.get_executions_representation(top_level_auth, realm=realm)[-1]
480 exec_update = {
481 "id": created_exec["id"],
482 "providerId": execution["providerId"],
483 "requirement": execution["requirement"],
484 "priority": created_exec["priority"],
485 }
486 kc.update_authentication_executions(
487 flowAlias=parent_flow_alias,
488 updatedExec=exec_update,
489 realm=realm,
490 )
491
492 if execution.get("authenticationConfig") is not None:
493 kc.add_authenticationConfig_to_execution(
494 created_exec["id"],
495 execution["authenticationConfig"],
496 realm=realm,
497 )
498
499
500 def create_executions(
501 kc: KeycloakAPI,
502 realm: str,
503 top_level_auth: dict,
504 executions: list,
505 parent_flow_alias: str,
506 ) -> None:
507 """Recursively create all executions and sub-flows under the given parent flow.
508
509 :param kc: a KeycloakAPI instance.
510 :param realm: the realm in which the flow resides.
511 :param top_level_auth: the top-level authentication flow dict, used when querying the
512 current execution list after each creation.
513 :param executions: a list of desired execution dicts to create.
514 :param parent_flow_alias: the alias of the flow or sub-flow that will own the executions.
515 """
516 for desired_exec in executions:
517 sub_flow = desired_exec["subFlow"]
518 sub_flow_type = desired_exec["subFlowType"]
519 sub_flow_execs = desired_exec.get("authenticationExecutions")
520
521 # Build the minimal payload accepted by the execution creation endpoint.
522 exec_payload = {
523 "providerId": desired_exec.get("providerId"),
524 "requirement": desired_exec["requirement"],
525 }
526 if desired_exec.get("authenticationConfig") is not None:
527 exec_payload["authenticationConfig"] = desired_exec["authenticationConfig"]
528
529 if sub_flow is not None:
530 kc.create_subflow(sub_flow, parent_flow_alias, realm=realm, flowType=sub_flow_type)
531 update_execution_requirement_and_config(kc, realm, top_level_auth, exec_payload, parent_flow_alias)
532 if sub_flow_execs is not None:
533 create_executions(kc, realm, top_level_auth, sub_flow_execs, sub_flow)
534 else:
535 kc.create_execution(exec_payload, flowAlias=parent_flow_alias, realm=realm)
536 update_execution_requirement_and_config(kc, realm, top_level_auth, exec_payload, parent_flow_alias)
537
538
539 def create_empty_flow(kc: KeycloakAPI, realm: str, auth_flow_config: dict) -> dict:
540 """Create an empty authentication flow from the given configuration dict.
541
542 :param kc: a KeycloakAPI instance.
543 :param realm: the realm in which to create the flow.
544 :param auth_flow_config: the flow configuration dict (must include at least 'alias').
545 :returns: the newly-created flow dict as returned by the Keycloak API.
546 :raises RuntimeError: if the created flow cannot be retrieved immediately after creation.
547 """
548 created_auth = kc.create_empty_auth_flow(config=auth_flow_config, realm=realm)
549 if created_auth is None:
550 raise RuntimeError(f"Could not retrieve the authentication flow that was just created: {auth_flow_config}")
551
552 return created_auth
553
554
555 def desired_auth_to_diff_repr(desired_auth: dict) -> dict:
556 """Convert a desired authentication flow dict into the normalized representation used for
557 diff comparison.
558
559 :param desired_auth: the desired flow dict as provided by the module parameters.
560 :returns: a normalized dict suitable for comparison with 'existing_auth_to_diff_repr'.
561 """
562 desired_copy = copy.deepcopy(desired_auth)
563 desired_copy["topLevel"] = True
564 desired_copy["authenticationExecutions"] = desired_executions_to_diff_repr(desired_copy["authenticationExecutions"])
565 return desired_copy
566
567
568 def desired_executions_to_diff_repr(desired_executions: list) -> list:
569 return desired_executions_to_diff_repr_rec(executions=desired_executions, level=0)
570
571
572 def desired_executions_to_diff_repr_rec(executions: list, level: int) -> list:
573 """Recursively flatten and normalize a nested execution list into the same flat structure
574 that the Keycloak API returns, so that the two representations can be compared directly.
575
576 :param executions: a list of desired execution dicts (possibly nested).
577 :param level: the current nesting depth (0 for top-level executions).
578 :returns: a flat list of normalized execution dicts.
579 """
580 converted: list = []
581 for index, execution in enumerate(executions):
582 converted.append(execution)
583 execution["index"] = index
584 execution["priority"] = index
585 execution["level"] = level
586
587 if execution.get("authenticationConfig") is None:
588 execution.pop("authenticationConfig", None)
589
590 if execution.get("subFlow") is not None:
591 execution.pop("providerId", None)
592 execution["authenticationFlow"] = True
593 if execution.get("authenticationExecutions") is not None:
594 converted += desired_executions_to_diff_repr_rec(execution["authenticationExecutions"], level + 1)
595
596 execution.pop("subFlow", None)
597 execution.pop("subFlowType", None)
598 execution.pop("authenticationExecutions", None)
599
600 return converted
601
602
603 def existing_auth_to_diff_repr(kc: KeycloakAPI, realm: str, existing_auth: dict) -> dict:
604 """Build a normalized representation of an existing flow that can be compared with the
605 output of 'desired_auth_to_diff_repr'.
606
607 Server-side fields that have no equivalent in the desired state (such as 'id',
608 'builtIn', 'requirementChoices', and 'configurable') are stripped so that the
609 comparison is not skewed by fields the user cannot control.
610
611 :param kc: a KeycloakAPI instance.
612 :param realm: the realm in which the flow resides.
613 :param existing_auth: the existing flow dict as returned by the Keycloak API.
614 :returns: a normalized dict.
615 """
616 existing_copy = copy.deepcopy(existing_auth)
617 existing_copy.pop("id", None)
618 existing_copy.pop("builtIn", None)
619
620 executions = kc.get_executions_representation(config=existing_copy, realm=realm)
621 for execution in executions:
622 execution.pop("id", None)
623 execution.pop("requirementChoices", None)
624 execution.pop("configurable", None)
625 execution.pop("displayName", None)
626 execution.pop("description", None)
627 execution.pop("flowId", None)
628
629 if execution.get("authenticationConfig") is not None:
630 execution["authenticationConfig"].pop("id", None)
631 # The alias is already stored inside the authenticationConfig object; the
632 # top-level alias field on the execution is redundant and is removed.
633 execution.pop("alias", None)
634
635 existing_copy["authenticationExecutions"] = executions
636 # Normalize a missing description to None so that it compares equal to an unset desired value.
637 existing_copy["description"] = existing_copy.get("description") or None
638 return existing_copy
639
640
641 def is_auth_flow_in_use(kc: KeycloakAPI, realm: str, existing_auth: dict) -> bool:
642 """Determine whether the given flow is currently bound to a realm binding, a client
643 authentication flow override or as an identity-provider login-flow or post-flow.
644
645 :param kc: a KeycloakAPI instance.
646 :param realm: the realm to inspect.
647 :param existing_auth: the existing flow dict (must include 'id' and 'alias').
648 :returns: True if the flow is bound anywhere, False otherwise.
649 """
650 flow_id = existing_auth["id"]
651 flow_alias = existing_auth["alias"]
652 realm_data = kc.get_realm_by_id(realm)
653 if realm_data is None:
654 raise RuntimeError(f"realm '{realm}' does not exist")
655
656 realm_binding_keys = [
657 "browserFlow",
658 "registrationFlow",
659 "directGrantFlow",
660 "resetCredentialsFlow",
661 "clientAuthenticationFlow",
662 "dockerAuthenticationFlow",
663 "firstBrokerLoginFlow",
664 ]
665 for binding_key in realm_binding_keys:
666 if realm_data.get(binding_key) == flow_alias:
667 return True
668
669 for client in kc.get_clients(realm=realm):
670 overrides = client.get("authenticationFlowBindingOverrides", {})
671 if overrides.get("browser") == flow_id:
672 return True
673 if overrides.get("direct_grant") == flow_id:
674 return True
675
676 for identity_provider in kc.get_identity_providers(realm):
677 first_broker_login_flow_alias = identity_provider.get("firstBrokerLoginFlowAlias")
678 post_broker_login_flow_alias = identity_provider.get("postBrokerLoginFlowAlias")
679 if first_broker_login_flow_alias == flow_alias or post_broker_login_flow_alias == flow_alias:
680 return True
681
682 return False
683
684
685 def rebind_auth_flow_bindings(
686 kc: KeycloakAPI,
687 realm: str,
688 from_id: str,
689 from_alias: str,
690 to_id: str,
691 to_alias: str,
692 ) -> None:
693 """Re-point all realm bindings, client flow overrides and identity-provider login-flows or post-flows
694 that reference the source flow to the target flow.
695
696 This is the critical step in the Safe Swap procedure that transfers live bindings from the
697 old flow to the newly-created temporary flow without any gap in coverage.
698
699 :param kc: a KeycloakAPI instance.
700 :param realm: the realm to update.
701 :param from_id: the ID of the flow to rebind away from.
702 :param from_alias: the alias of the flow to rebind away from.
703 :param to_id: the ID of the flow to rebind to.
704 :param to_alias: the alias of the flow to rebind to.
705 """
706 realm_data = kc.get_realm_by_id(realm)
707 if realm_data is None:
708 raise RuntimeError(f"realm '{realm}' does not exist")
709 realm_changed = False
710
711 realm_binding_keys = [
712 "browserFlow",
713 "registrationFlow",
714 "directGrantFlow",
715 "resetCredentialsFlow",
716 "clientAuthenticationFlow",
717 "dockerAuthenticationFlow",
718 "firstBrokerLoginFlow",
719 ]
720 for binding_key in realm_binding_keys:
721 if realm_data.get(binding_key) == from_alias:
722 realm_data[binding_key] = to_alias
723 realm_changed = True
724
725 if realm_changed:
726 kc.update_realm(realm_data, realm)
727
728 for client in kc.get_clients(realm=realm):
729 overrides = client.get("authenticationFlowBindingOverrides", {})
730 client_changed = False
731
732 if overrides.get("browser") == from_id:
733 client["authenticationFlowBindingOverrides"]["browser"] = to_id
734 client_changed = True
735 if overrides.get("direct_grant") == from_id:
736 client["authenticationFlowBindingOverrides"]["direct_grant"] = to_id
737 client_changed = True
738
739 if client_changed:
740 kc.update_client(id=client["id"], clientrep=client, realm=realm)
741
742 for identity_provider in kc.get_identity_providers(realm):
743 first_broker_login_flow_alias = identity_provider.get("firstBrokerLoginFlowAlias")
744 post_broker_login_flow_alias = identity_provider.get("postBrokerLoginFlowAlias")
745 identity_provider_changed = False
746
747 if first_broker_login_flow_alias == from_alias:
748 identity_provider["firstBrokerLoginFlowAlias"] = to_alias
749 identity_provider_changed = True
750
751 if post_broker_login_flow_alias == from_alias:
752 identity_provider["postBrokerLoginFlowAlias"] = to_alias
753 identity_provider_changed = True
754
755 if identity_provider_changed:
756 kc.update_identity_provider(idprep=identity_provider, realm=realm)
757
758
759 def delete_tmp_swap_flow_if_exists(
760 kc: KeycloakAPI,
761 realm: str,
762 tmp_swap_alias: str,
763 fallback_id: str,
764 fallback_alias: str,
765 ) -> None:
766 """Delete a pre-existing temporary swap flow, rebinding any of its bindings back to the
767 fallback flow first to avoid orphaned bindings.
768
769 :param kc: a KeycloakAPI instance.
770 :param realm: the realm to inspect.
771 :param tmp_swap_alias: the alias of the temporary swap flow to delete.
772 :param fallback_id: the ID of the flow to rebind to before deleting the temporary flow.
773 :param fallback_alias: the alias of the flow to rebind to before deleting the temporary flow.
774 """
775 existing_tmp = kc.get_authentication_flow_by_alias(tmp_swap_alias, realm)
776 if existing_tmp is not None and len(existing_tmp) > 0:
777 rebind_auth_flow_bindings(
778 kc,
779 realm,
780 from_id=existing_tmp["id"],
781 from_alias=existing_tmp["alias"],
782 to_id=fallback_id,
783 to_alias=fallback_alias,
784 )
785 kc.delete_authentication_flow_by_id(id=existing_tmp["id"], realm=realm)
786
787
788 def create_authentication_execution_spec_options(depth: int) -> dict[str, t.Any]:
789 options: dict[str, t.Any] = dict(
790 providerId=dict(type="str", required=depth == 0),
791 requirement=dict(type="str", required=True, choices=["REQUIRED", "ALTERNATIVE", "DISABLED", "CONDITIONAL"]),
792 authenticationConfig=dict(
793 type="dict",
794 options=dict(
795 alias=dict(type="str", required=True),
796 config=dict(type="dict", required=True),
797 ),
798 ),
799 )
800 if depth > 0:
801 options.update(
802 subFlow=dict(type="str"),
803 subFlowType=dict(type="str", choices=["basic-flow", "form-flow"], default="basic-flow"),
804 authenticationExecutions=dict(
805 type="list",
806 elements="dict",
807 options=create_authentication_execution_spec_options(depth - 1),
808 ),
809 )
810 return options
811
812
813 def validate_executions(kc: KeycloakAPI, realm: str, executions: dict) -> None:
814 valid_providers = kc.get_authenticator_providers(realm)
815 valid_provider_ids = {provider["id"] for provider in valid_providers}
816
817 invalid_provider_ids = validate_executions_rec(valid_provider_ids, executions)
818 if len(invalid_provider_ids) > 0:
819 invalid_provider_ids_str = ", ".join(f"'{item}'" for item in invalid_provider_ids)
820 raise ValueError(
821 f"The following execution providerIds are unknown and therefore invalid: {invalid_provider_ids_str}"
822 )
823
824
825 def validate_executions_rec(valid_provider_ids: set, executions: dict) -> list:
826 invalid_provider_ids = []
827 for execution in executions:
828 provider_id = execution["providerId"]
829 sub_flow = execution["subFlow"]
830 if provider_id is not None:
831 if provider_id not in valid_provider_ids:
832 invalid_provider_ids.append(provider_id)
833
834 if sub_flow is not None:
835 invalid_provider_ids.extend(
836 validate_executions_rec(valid_provider_ids, execution["authenticationExecutions"])
837 )
838
839 return invalid_provider_ids
840
841
842 def main() -> None:
843 """Module entry point."""
844 argument_spec = keycloak_argument_spec()
845
846 meta_args = dict(
847 realm=dict(type="str", required=True),
848 alias=dict(type="str", required=True),
849 providerId=dict(type="str", choices=["basic-flow", "client-flow"], default="basic-flow"),
850 description=dict(type="str"),
851 authenticationExecutions=dict(
852 type="list",
853 elements="dict",
854 options=create_authentication_execution_spec_options(4),
855 ),
856 state=dict(choices=["absent", "present"], default="present"),
857 force_temporary_swap_flow_deletion=dict(type="bool", default=True),
858 temporary_swap_flow_suffix=dict(type="str", default="_tmp_for_swap"),
859 )
860 argument_spec.update(meta_args)
861
862 module = AnsibleModule(
863 argument_spec=argument_spec,
864 supports_check_mode=True,
865 required_one_of=(
866 [["token", "auth_realm", "auth_username", "auth_password", "auth_client_id", "auth_client_secret"]]
867 ),
868 required_together=([["auth_username", "auth_password"]]),
869 required_by={"refresh_token": "auth_realm"},
870 )
871
872 result = dict(changed=False, msg="", end_state={})
873
874 # Obtain an access token and initialize the API client.
875 try:
876 connection_header = get_token(module.params)
877 except KeycloakError as e:
878 module.fail_json(msg=str(e))
879
880 kc = KeycloakAPI(module, connection_header)
881
882 realm = module.params.get("realm")
883 state = module.params.get("state")
884 force_swap_deletion = module.params.get("force_temporary_swap_flow_deletion")
885 tmp_swap_suffix = module.params.get("temporary_swap_flow_suffix")
886
887 desired_auth = {
888 "alias": module.params.get("alias"),
889 "providerId": module.params.get("providerId"),
890 "authenticationExecutions": module.params.get("authenticationExecutions") or [],
891 "description": module.params.get("description") or None,
892 }
893 desired_auth_diff_repr = desired_auth_to_diff_repr(desired_auth)
894
895 existing_auth = kc.get_authentication_flow_by_alias(alias=desired_auth["alias"], realm=realm)
896 existing_auth_diff_repr = None
897 if existing_auth:
898 existing_auth_diff_repr = existing_auth_to_diff_repr(kc, realm, existing_auth)
899
900 try:
901 try:
902 validate_executions(kc, realm, desired_auth["authenticationExecutions"])
903 except ValueError as e:
904 module.fail_json(
905 msg=f"Validation of executions failed: {e}",
906 exception=traceback.format_exc(),
907 )
908
909 if not existing_auth:
910 if state == "absent":
911 # The flow does not exist and is not required; nothing to do.
912 result["diff"] = dict(before="", after="")
913 result["changed"] = False
914 result["end_state"] = {}
915 result["msg"] = f"'{desired_auth['alias']}' is already absent"
916 module.exit_json(**result)
917
918 elif state == "present":
919 # The flow does not yet exist; create it.
920 if module.check_mode:
921 result["changed"] = True
922 result["diff"] = dict(before="", after=desired_auth_diff_repr)
923 module.exit_json(**result)
924
925 created_auth = create_empty_flow(kc, realm, desired_auth)
926 result["changed"] = True
927
928 create_executions(
929 kc=kc,
930 realm=realm,
931 top_level_auth=created_auth,
932 executions=desired_auth["authenticationExecutions"],
933 parent_flow_alias=desired_auth["alias"],
934 )
935
936 exec_repr = kc.get_executions_representation(config=desired_auth, realm=realm)
937 if exec_repr is not None:
938 created_auth["authenticationExecutions"] = exec_repr
939
940 result["diff"] = dict(before="", after=created_auth)
941 result["end_state"] = created_auth
942 result["msg"] = f"Authentication flow '{created_auth['alias']}' with id: '{created_auth['id']}' created"
943
944 else:
945 is_flow_in_use = is_auth_flow_in_use(kc, realm, existing_auth)
946
947 if state == "present":
948 change_required = existing_auth_diff_repr != desired_auth_diff_repr
949 if change_required:
950 result["diff"] = dict(before=existing_auth_diff_repr, after=desired_auth_diff_repr)
951
952 if module.check_mode:
953 result["changed"] = change_required
954 module.exit_json(**result)
955
956 if not change_required:
957 # The existing flow already matches the desired state; nothing to do.
958 result["end_state"] = existing_auth_diff_repr
959 module.exit_json(**result)
960
961 # The flow needs to be updated. Rather than modifying the existing flow in place,
962 # the Safe Swap procedure is used to guarantee that the flow is never left in an
963 # unsafe intermediate state. See the module documentation for a full description.
964 if is_flow_in_use:
965 tmp_swap_alias = desired_auth["alias"] + tmp_swap_suffix
966
967 if force_swap_deletion:
968 # Remove any leftover temporary flow from a previous interrupted run,
969 # rebinding its bindings back to the current flow first.
970 delete_tmp_swap_flow_if_exists(
971 kc=kc,
972 realm=realm,
973 tmp_swap_alias=tmp_swap_alias,
974 fallback_id=existing_auth["id"],
975 fallback_alias=existing_auth["alias"],
976 )
977
978 # Build the new flow under a temporary name so that both flows coexist
979 # during the swap.
980 append_suffix_to_flow_names(desired_auth, tmp_swap_suffix)
981 else:
982 # The flow is not bound anywhere; it is safe to delete it immediately and
983 # recreate it under the original name.
984 kc.delete_authentication_flow_by_id(existing_auth["id"], realm=realm)
985
986 created_auth = create_empty_flow(kc, realm, desired_auth)
987 result["changed"] = True
988 create_executions(
989 kc=kc,
990 realm=realm,
991 top_level_auth=created_auth,
992 executions=desired_auth["authenticationExecutions"],
993 parent_flow_alias=desired_auth["alias"],
994 )
995
996 if is_flow_in_use:
997 # Transfer all bindings from the old flow to the new temporary flow, then
998 # delete the old flow and strip the temporary suffix from all aliases.
999 rebind_auth_flow_bindings(
1000 kc=kc,
1001 realm=realm,
1002 from_id=existing_auth["id"],
1003 from_alias=existing_auth["alias"],
1004 to_id=created_auth["id"],
1005 to_alias=created_auth["alias"],
1006 )
1007 kc.delete_authentication_flow_by_id(existing_auth["id"], realm=realm)
1008 remove_suffix_from_flow_names(kc, realm, created_auth, tmp_swap_suffix)
1009
1010 created_auth_diff_repr = existing_auth_to_diff_repr(kc, realm, created_auth)
1011 result["diff"] = dict(before=existing_auth_diff_repr, after=created_auth_diff_repr)
1012 result["end_state"] = created_auth_diff_repr
1013 result["msg"] = f"Authentication flow: {created_auth['alias']} id: {created_auth['id']} updated"
1014
1015 else:
1016 if is_flow_in_use:
1017 module.fail_json(
1018 msg=f"Flow {existing_auth['alias']} with id {existing_auth['id']} is in use and therefore cannot be deleted in realm {realm}"
1019 )
1020
1021 result["diff"] = dict(before=existing_auth_diff_repr, after="")
1022 if module.check_mode:
1023 result["changed"] = True
1024 module.exit_json(**result)
1025
1026 kc.delete_authentication_flow_by_id(id=existing_auth["id"], realm=realm)
1027 result["changed"] = True
1028 result["msg"] = f"Authentication flow: {desired_auth['alias']} id: {existing_auth['id']} is deleted"
1029 except Exception as e:
1030 module.fail_json(
1031 msg=f"An unexpected error occurred: {e}",
1032 exception=traceback.format_exc(),
1033 )
1034
1035 module.exit_json(**result)
1036
1037
1038 if __name__ == "__main__":
1039 main()