Debian Codegraph @

ansible_collections/community/general/plugins/modules/keycloak_user_federation.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_user_federation
11
12 short_description: Allows administration of Keycloak user federations using Keycloak API
13
14 version_added: 3.7.0
15
16 description:
17 - This module allows you to add, remove or modify Keycloak user federations using the Keycloak REST API. It requires access
18 to the REST API using OpenID Connect; the user connecting and the client being used must have the requisite access rights.
19 In a default Keycloak installation, admin-cli and an admin user would work, as would a separate client definition with
20 the scope tailored to your needs and a user having the expected roles.
21 - The names of module options are snake_cased versions of the camelCase ones found in the Keycloak API and its documentation
22 at U(https://www.keycloak.org/docs-api/20.0.2/rest-api/index.html).
23 attributes:
24 check_mode:
25 support: full
26 diff_mode:
27 support: full
28 action_group:
29 version_added: 10.2.0
30
31 options:
32 state:
33 description:
34 - State of the user federation.
35 - On V(present), the user federation is created if it does not yet exist, or updated with the parameters you provide.
36 - On V(absent), the user federation is removed if it exists.
37 default: 'present'
38 type: str
39 choices:
40 - present
41 - absent
42
43 realm:
44 description:
45 - The Keycloak realm under which this user federation resides.
46 default: 'master'
47 type: str
48
49 id:
50 description:
51 - The unique ID for this user federation. If left empty, the user federation is searched by its O(name).
52 type: str
53
54 name:
55 description:
56 - Display name of provider when linked in admin console.
57 type: str
58
59 provider_id:
60 description:
61 - Provider for this user federation. Built-in providers are V(ldap), V(kerberos), and V(sssd). Custom user storage providers
62 can also be used.
63 aliases:
64 - providerId
65 type: str
66
67 provider_type:
68 description:
69 - Component type for user federation (only supported value is V(org.keycloak.storage.UserStorageProvider)).
70 aliases:
71 - providerType
72 default: org.keycloak.storage.UserStorageProvider
73 type: str
74
75 parent_id:
76 description:
77 - Unique ID for the parent of this user federation. Realm ID is automatically used if left blank.
78 aliases:
79 - parentId
80 type: str
81
82 remove_unspecified_mappers:
83 description:
84 - Remove mappers that are not specified in the configuration for this federation.
85 - Set to V(false) to keep mappers that are not listed in O(mappers).
86 type: bool
87 default: true
88 version_added: 9.4.0
89
90 bind_credential_update_mode:
91 description:
92 - The value of the config parameter O(config.bindCredential) is redacted in the Keycloak responses. Comparing the redacted
93 value with the desired value always evaluates to not equal. This means the before and desired states are never equal
94 if the parameter is set.
95 - Set to V(always) to include O(config.bindCredential) in the comparison of before and desired state. Because of the
96 redacted value returned by Keycloak the module always detects a change and make an update if a O(config.bindCredential)
97 value is set.
98 - Set to V(only_indirect) to exclude O(config.bindCredential) when comparing the before state with the desired state.
99 The value of O(config.bindCredential) is only updated if there are other changes to the user federation that require
100 an update.
101 type: str
102 default: always
103 choices:
104 - always
105 - only_indirect
106 version_added: 9.5.0
107
108 config:
109 description:
110 - Dict specifying the configuration options for the provider; the contents differ depending on the value of O(provider_id).
111 Examples are given below for V(ldap), V(kerberos) and V(sssd). It is easiest to obtain valid config values by dumping
112 an already-existing user federation configuration through check-mode in the RV(existing) field.
113 - The value V(sssd) has been supported since community.general 4.2.0.
114 type: dict
115 suboptions:
116 enabled:
117 description:
118 - Enable/disable this user federation.
119 default: true
120 type: bool
121
122 priority:
123 description:
124 - Priority of provider when doing a user lookup. Lowest first.
125 default: 0
126 type: int
127
128 importEnabled:
129 description:
130 - If V(true), LDAP users are imported into Keycloak DB and synced by the configured sync policies.
131 default: true
132 type: bool
133
134 editMode:
135 description:
136 - V(READ_ONLY) is a read-only LDAP store. V(WRITABLE) means data is synced back to LDAP on demand. V(UNSYNCED) means
137 user data is imported, but not synced back to LDAP.
138 type: str
139 choices:
140 - READ_ONLY
141 - WRITABLE
142 - UNSYNCED
143
144 syncRegistrations:
145 description:
146 - Should newly created users be created within LDAP store? Priority effects which provider is chosen to sync the
147 new user.
148 default: false
149 type: bool
150
151 vendor:
152 description:
153 - LDAP vendor (provider).
154 - Use short name. For instance, write V(rhds) for "Red Hat Directory Server".
155 type: str
156
157 usernameLDAPAttribute:
158 description:
159 - Name of LDAP attribute, which is mapped as Keycloak username. For many LDAP server vendors it can be V(uid). For
160 Active directory it can be V(sAMAccountName) or V(cn). The attribute should be filled for all LDAP user records
161 you want to import from LDAP to Keycloak.
162 type: str
163
164 rdnLDAPAttribute:
165 description:
166 - Name of LDAP attribute, which is used as RDN (top attribute) of typical user DN. Usually it is the same as Username
167 LDAP attribute, however it is not required. For example for Active directory, it is common to use V(cn) as RDN
168 attribute when username attribute might be V(sAMAccountName).
169 type: str
170
171 uuidLDAPAttribute:
172 description:
173 - Name of LDAP attribute, which is used as unique object identifier (UUID) for objects in LDAP. For many LDAP server
174 vendors, it is V(entryUUID); however some are different. For example for Active directory it should be V(objectGUID).
175 If your LDAP server does not support the notion of UUID, you can use any other attribute that is supposed to be
176 unique among LDAP users in tree.
177 type: str
178
179 userObjectClasses:
180 description:
181 - All values of LDAP objectClass attribute for users in LDAP divided by comma. For example V(inetOrgPerson, organizationalPerson).
182 Newly created Keycloak users are written to LDAP with all those object classes and existing LDAP user records
183 are found just if they contain all those object classes.
184 type: str
185
186 connectionUrl:
187 description:
188 - Connection URL to your LDAP server.
189 type: str
190
191 usersDn:
192 description:
193 - Full DN of LDAP tree where your users are. This DN is the parent of LDAP users.
194 type: str
195
196 customUserSearchFilter:
197 description:
198 - Additional LDAP Filter for filtering searched users. Leave this empty if you do not need additional filter.
199 type: str
200
201 searchScope:
202 description:
203 - For one level, the search applies only for users in the DNs specified by User DNs. For subtree, the search applies
204 to the whole subtree. See LDAP documentation for more details.
205 default: '1'
206 type: str
207 choices:
208 - '1'
209 - '2'
210
211 authType:
212 description:
213 - Type of the Authentication method used during LDAP Bind operation. It is used in most of the requests sent to
214 the LDAP server.
215 default: 'none'
216 type: str
217 choices:
218 - none
219 - simple
220
221 bindDn:
222 description:
223 - DN of LDAP user which is used by Keycloak to access LDAP server.
224 type: str
225
226 bindCredential:
227 description:
228 - Password of LDAP admin.
229 type: str
230
231 startTls:
232 description:
233 - Encrypts the connection to LDAP using STARTTLS, which disables connection pooling.
234 default: false
235 type: bool
236
237 usePasswordModifyExtendedOp:
238 description:
239 - Use the LDAPv3 Password Modify Extended Operation (RFC-3062). The password modify extended operation usually requires
240 that LDAP user already has password in the LDAP server. So when this is used with 'Sync Registrations', it can
241 be good to add also 'Hardcoded LDAP attribute mapper' with randomly generated initial password.
242 default: false
243 type: bool
244
245 validatePasswordPolicy:
246 description:
247 - Determines if Keycloak should validate the password with the realm password policy before updating it.
248 default: false
249 type: bool
250
251 trustEmail:
252 description:
253 - If enabled, email provided by this provider is not verified even if verification is enabled for the realm.
254 default: false
255 type: bool
256
257 useTruststoreSpi:
258 description:
259 - Specifies whether LDAP connection uses the truststore SPI with the truststore configured in standalone.xml/domain.xml.
260 V(always) means that it always uses it. V(never) means that it does not use it. V(ldapsOnly) means that it uses
261 if your connection URL use ldaps.
262 - Note even if standalone.xml/domain.xml is not configured, the default Java cacerts or certificate specified by
263 C(javax.net.ssl.trustStore) property is used.
264 default: ldapsOnly
265 type: str
266 choices:
267 - always
268 - ldapsOnly
269 - never
270
271 connectionTimeout:
272 description:
273 - LDAP Connection Timeout in milliseconds.
274 type: int
275
276 readTimeout:
277 description:
278 - LDAP Read Timeout in milliseconds. This timeout applies for LDAP read operations.
279 type: int
280
281 pagination:
282 description:
283 - Does the LDAP server support pagination.
284 default: true
285 type: bool
286
287 connectionPooling:
288 description:
289 - Determines if Keycloak should use connection pooling for accessing LDAP server.
290 default: true
291 type: bool
292
293 connectionPoolingAuthentication:
294 description:
295 - A list of space-separated authentication types of connections that may be pooled.
296 type: str
297 choices:
298 - none
299 - simple
300 - DIGEST-MD5
301
302 connectionPoolingDebug:
303 description:
304 - A string that indicates the level of debug output to produce. Example valid values are V(fine) (trace connection
305 creation and removal) and V(all) (all debugging information).
306 type: str
307
308 connectionPoolingInitSize:
309 description:
310 - The number of connections per connection identity to create when initially creating a connection for the identity.
311 type: int
312
313 connectionPoolingMaxSize:
314 description:
315 - The maximum number of connections per connection identity that can be maintained concurrently.
316 type: int
317
318 connectionPoolingPrefSize:
319 description:
320 - The preferred number of connections per connection identity that should be maintained concurrently.
321 type: int
322
323 connectionPoolingProtocol:
324 description:
325 - A list of space-separated protocol types of connections that may be pooled. Valid types are V(plain) and V(ssl).
326 type: str
327
328 connectionPoolingTimeout:
329 description:
330 - The number of milliseconds that an idle connection may remain in the pool without being closed and removed from
331 the pool.
332 type: int
333
334 allowKerberosAuthentication:
335 description:
336 - Enable/disable HTTP authentication of users with SPNEGO/Kerberos tokens. The data about authenticated users is
337 provisioned from this LDAP server.
338 default: false
339 type: bool
340
341 kerberosRealm:
342 description:
343 - Name of kerberos realm.
344 type: str
345
346 krbPrincipalAttribute:
347 description:
348 - Name of the LDAP attribute, which refers to Kerberos principal. This is used to lookup appropriate LDAP user after
349 successful Kerberos/SPNEGO authentication in Keycloak. When this is empty, the LDAP user is looked up based on
350 LDAP username corresponding to the first part of his Kerberos principal. For instance, for principal C([email protected]),
351 it assumes that LDAP username is V(john).
352 type: str
353 version_added: 8.1.0
354
355 serverPrincipal:
356 description:
357 - Full name of server principal for HTTP service including server and domain name. For example V(HTTP/[email protected]).
358 Use V(*) to accept any service principal in the KeyTab file.
359 type: str
360
361 keyTab:
362 description:
363 - Location of Kerberos KeyTab file containing the credentials of server principal. For example V(/etc/krb5.keytab).
364 type: str
365
366 debug:
367 description:
368 - Enable/disable debug logging to standard output for Krb5LoginModule.
369 type: bool
370
371 useKerberosForPasswordAuthentication:
372 description:
373 - Use Kerberos login module for authenticate username/password against Kerberos server instead of authenticating
374 against LDAP server with Directory Service API.
375 default: false
376 type: bool
377
378 allowPasswordAuthentication:
379 description:
380 - Enable/disable possibility of username/password authentication against Kerberos database.
381 type: bool
382
383 batchSizeForSync:
384 description:
385 - Count of LDAP users to be imported from LDAP to Keycloak within a single transaction.
386 default: 1000
387 type: int
388
389 fullSyncPeriod:
390 description:
391 - Period for full synchronization in seconds.
392 default: -1
393 type: int
394
395 changedSyncPeriod:
396 description:
397 - Period for synchronization of changed or newly created LDAP users in seconds.
398 default: -1
399 type: int
400
401 updateProfileFirstLogin:
402 description:
403 - Update profile on first login.
404 type: bool
405
406 cachePolicy:
407 description:
408 - Cache Policy for this storage provider.
409 type: str
410 default: 'DEFAULT'
411 choices:
412 - DEFAULT
413 - EVICT_DAILY
414 - EVICT_WEEKLY
415 - MAX_LIFESPAN
416 - NO_CACHE
417
418 evictionDay:
419 description:
420 - Day of the week the entry is set to become invalid on.
421 type: str
422
423 evictionHour:
424 description:
425 - Hour of day the entry is set to become invalid on.
426 type: str
427
428 evictionMinute:
429 description:
430 - Minute of day the entry is set to become invalid on.
431 type: str
432
433 maxLifespan:
434 description:
435 - Max lifespan of cache entry in milliseconds.
436 type: int
437
438 referral:
439 description:
440 - Specifies if LDAP referrals should be followed or ignored. Please note that enabling referrals can slow down authentication
441 as it allows the LDAP server to decide which other LDAP servers to use. This could potentially include untrusted
442 servers.
443 type: str
444 choices:
445 - ignore
446 - follow
447 version_added: 9.5.0
448
449 mappers:
450 description:
451 - A list of dicts defining mappers associated with this Identity Provider.
452 type: list
453 elements: dict
454 suboptions:
455 id:
456 description:
457 - Unique ID of this mapper.
458 type: str
459
460 name:
461 description:
462 - Name of the mapper. If no ID is given, the mapper is searched by name.
463 type: str
464
465 parentId:
466 description:
467 - Unique ID for the parent of this mapper. ID of the user federation is automatically used if left blank.
468 type: str
469
470 providerId:
471 description:
472 - The mapper type for this mapper (for instance V(user-attribute-ldap-mapper)).
473 type: str
474
475 providerType:
476 description:
477 - Component type for this mapper.
478 type: str
479 default: org.keycloak.storage.ldap.mappers.LDAPStorageMapper
480
481 config:
482 description:
483 - Dict specifying the configuration options for the mapper; the contents differ depending on the value of I(identityProviderMapper).
484 type: dict
485
486 extends_documentation_fragment:
487 - community.general._keycloak
488 - community.general._keycloak.actiongroup_keycloak
489 - community.general._attributes
490
491 author:
492 - Laurent Paumier (@laurpaum)
493 """
494
495 EXAMPLES = r"""
496 - name: Create LDAP user federation
497 community.general.keycloak_user_federation:
498 auth_keycloak_url: https://keycloak.example.com/auth
499 auth_realm: master
500 auth_username: admin
501 auth_password: password
502 realm: my-realm
503 name: my-ldap
504 state: present
505 provider_id: ldap
506 provider_type: org.keycloak.storage.UserStorageProvider
507 config:
508 priority: 0
509 enabled: true
510 cachePolicy: DEFAULT
511 batchSizeForSync: 1000
512 editMode: READ_ONLY
513 importEnabled: true
514 syncRegistrations: false
515 vendor: other
516 usernameLDAPAttribute: uid
517 rdnLDAPAttribute: uid
518 uuidLDAPAttribute: entryUUID
519 userObjectClasses: inetOrgPerson, organizationalPerson
520 connectionUrl: ldaps://ldap.example.com:636
521 usersDn: ou=Users,dc=example,dc=com
522 authType: simple
523 bindDn: cn=directory reader
524 bindCredential: password
525 searchScope: 1
526 validatePasswordPolicy: false
527 trustEmail: false
528 useTruststoreSpi: ldapsOnly
529 connectionPooling: true
530 pagination: true
531 allowKerberosAuthentication: false
532 debug: false
533 useKerberosForPasswordAuthentication: false
534 mappers:
535 - name: "full name"
536 providerId: "full-name-ldap-mapper"
537 providerType: "org.keycloak.storage.ldap.mappers.LDAPStorageMapper"
538 config:
539 ldap.full.name.attribute: cn
540 read.only: true
541 write.only: false
542
543 - name: Create Kerberos user federation
544 community.general.keycloak_user_federation:
545 auth_keycloak_url: https://keycloak.example.com/auth
546 auth_realm: master
547 auth_username: admin
548 auth_password: password
549 realm: my-realm
550 name: my-kerberos
551 state: present
552 provider_id: kerberos
553 provider_type: org.keycloak.storage.UserStorageProvider
554 config:
555 priority: 0
556 enabled: true
557 cachePolicy: DEFAULT
558 kerberosRealm: EXAMPLE.COM
559 serverPrincipal: HTTP/[email protected]
560 keyTab: keytab
561 allowPasswordAuthentication: false
562 updateProfileFirstLogin: false
563
564 - name: Create sssd user federation
565 community.general.keycloak_user_federation:
566 auth_keycloak_url: https://keycloak.example.com/auth
567 auth_realm: master
568 auth_username: admin
569 auth_password: password
570 realm: my-realm
571 name: my-sssd
572 state: present
573 provider_id: sssd
574 provider_type: org.keycloak.storage.UserStorageProvider
575 config:
576 priority: 0
577 enabled: true
578 cachePolicy: DEFAULT
579
580 - name: Delete user federation
581 community.general.keycloak_user_federation:
582 auth_keycloak_url: https://keycloak.example.com/auth
583 auth_realm: master
584 auth_username: admin
585 auth_password: password
586 realm: my-realm
587 name: my-federation
588 state: absent
589 """
590
591 RETURN = r"""
592 msg:
593 description: Message as to what action was taken.
594 returned: always
595 type: str
596 sample: "No changes required to user federation 164bb483-c613-482e-80fe-7f1431308799."
597
598 proposed:
599 description: Representation of proposed user federation.
600 returned: always
601 type: dict
602 sample:
603 {
604 "config": {
605 "allowKerberosAuthentication": "false",
606 "authType": "simple",
607 "batchSizeForSync": "1000",
608 "bindCredential": "**********",
609 "bindDn": "cn=directory reader",
610 "cachePolicy": "DEFAULT",
611 "connectionPooling": "true",
612 "connectionUrl": "ldaps://ldap.example.com:636",
613 "debug": "false",
614 "editMode": "READ_ONLY",
615 "enabled": "true",
616 "importEnabled": "true",
617 "pagination": "true",
618 "priority": "0",
619 "rdnLDAPAttribute": "uid",
620 "searchScope": "1",
621 "syncRegistrations": "false",
622 "trustEmail": "false",
623 "useKerberosForPasswordAuthentication": "false",
624 "useTruststoreSpi": "ldapsOnly",
625 "userObjectClasses": "inetOrgPerson, organizationalPerson",
626 "usernameLDAPAttribute": "uid",
627 "usersDn": "ou=Users,dc=example,dc=com",
628 "uuidLDAPAttribute": "entryUUID",
629 "validatePasswordPolicy": "false",
630 "vendor": "other"
631 },
632 "name": "ldap",
633 "providerId": "ldap",
634 "providerType": "org.keycloak.storage.UserStorageProvider"
635 }
636
637 existing:
638 description: Representation of existing user federation.
639 returned: always
640 type: dict
641 sample:
642 {
643 "config": {
644 "allowKerberosAuthentication": "false",
645 "authType": "simple",
646 "batchSizeForSync": "1000",
647 "bindCredential": "**********",
648 "bindDn": "cn=directory reader",
649 "cachePolicy": "DEFAULT",
650 "changedSyncPeriod": "-1",
651 "connectionPooling": "true",
652 "connectionUrl": "ldaps://ldap.example.com:636",
653 "debug": "false",
654 "editMode": "READ_ONLY",
655 "enabled": "true",
656 "fullSyncPeriod": "-1",
657 "importEnabled": "true",
658 "pagination": "true",
659 "priority": "0",
660 "rdnLDAPAttribute": "uid",
661 "searchScope": "1",
662 "syncRegistrations": "false",
663 "trustEmail": "false",
664 "useKerberosForPasswordAuthentication": "false",
665 "useTruststoreSpi": "ldapsOnly",
666 "userObjectClasses": "inetOrgPerson, organizationalPerson",
667 "usernameLDAPAttribute": "uid",
668 "usersDn": "ou=Users,dc=example,dc=com",
669 "uuidLDAPAttribute": "entryUUID",
670 "validatePasswordPolicy": "false",
671 "vendor": "other"
672 },
673 "id": "01122837-9047-4ae4-8ca0-6e2e891a765f",
674 "mappers": [
675 {
676 "config": {
677 "always.read.value.from.ldap": "false",
678 "is.mandatory.in.ldap": "false",
679 "ldap.attribute": "mail",
680 "read.only": "true",
681 "user.model.attribute": "email"
682 },
683 "id": "17d60ce2-2d44-4c2c-8b1f-1fba601b9a9f",
684 "name": "email",
685 "parentId": "01122837-9047-4ae4-8ca0-6e2e891a765f",
686 "providerId": "user-attribute-ldap-mapper",
687 "providerType": "org.keycloak.storage.ldap.mappers.LDAPStorageMapper"
688 }
689 ],
690 "name": "myfed",
691 "parentId": "myrealm",
692 "providerId": "ldap",
693 "providerType": "org.keycloak.storage.UserStorageProvider"
694 }
695
696 end_state:
697 description: Representation of user federation after module execution.
698 returned: on success
699 type: dict
700 sample:
701 {
702 "config": {
703 "allowPasswordAuthentication": "false",
704 "cachePolicy": "DEFAULT",
705 "enabled": "true",
706 "kerberosRealm": "EXAMPLE.COM",
707 "keyTab": "/etc/krb5.keytab",
708 "priority": "0",
709 "serverPrincipal": "HTTP/[email protected]",
710 "updateProfileFirstLogin": "false"
711 },
712 "id": "cf52ae4f-4471-4435-a0cf-bb620cadc122",
713 "mappers": [],
714 "name": "kerberos",
715 "parentId": "myrealm",
716 "providerId": "kerberos",
717 "providerType": "org.keycloak.storage.UserStorageProvider"
718 }
719 """
720
721 from copy import deepcopy
722 from urllib.parse import urlencode
723
724 from ansible.module_utils.basic import AnsibleModule
725
726 from ansible_collections.community.general.plugins.module_utils._keycloak import (
727 KeycloakAPI,
728 KeycloakError,
729 camel,
730 get_token,
731 keycloak_argument_spec,
732 )
733
734
735 def normalize_kc_comp(comp):
736 if "config" in comp:
737 # kc completely removes the parameter `krbPrincipalAttribute` if it is set to `''`; the unset kc parameter is equivalent to `''`;
738 # to make change detection and diff more accurate we set it again in the kc responses
739 if "krbPrincipalAttribute" not in comp["config"]:
740 comp["config"]["krbPrincipalAttribute"] = [""]
741
742 # kc stores a timestamp of the last sync in `lastSync` to time the periodic sync, it is removed to minimize diff/changes
743 comp["config"].pop("lastSync", None)
744
745
746 def sanitize(comp):
747 def sanitize_value(v):
748 """Convert list values: single-element lists to strings, multi-element lists sorted alphabetically, others as-is."""
749 if isinstance(v, list):
750 if len(v) == 0:
751 return None
752 elif len(v) == 1:
753 return v[0]
754 else:
755 return sorted(v)
756 else:
757 return v
758
759 compcopy = deepcopy(comp)
760 if "config" in compcopy:
761 compcopy["config"] = {k: sanitize_value(v) for k, v in compcopy["config"].items()}
762 # Remove None values (empty lists converted)
763 compcopy["config"] = {k: v for k, v in compcopy["config"].items() if v is not None}
764 if "bindCredential" in compcopy["config"]:
765 compcopy["config"]["bindCredential"] = "**********"
766 if "mappers" in compcopy:
767 for mapper in compcopy["mappers"]:
768 if "config" in mapper:
769 mapper["config"] = {k: sanitize_value(v) for k, v in mapper["config"].items()}
770 mapper["config"] = {k: v for k, v in mapper["config"].items() if v is not None}
771 return compcopy
772
773
774 def main():
775 """
776 Module execution
777
778 :return:
779 """
780 argument_spec = keycloak_argument_spec()
781
782 config_spec = dict(
783 allowKerberosAuthentication=dict(type="bool", default=False),
784 allowPasswordAuthentication=dict(type="bool"),
785 authType=dict(type="str", choices=["none", "simple"], default="none"),
786 batchSizeForSync=dict(type="int", default=1000),
787 bindCredential=dict(type="str", no_log=True),
788 bindDn=dict(type="str"),
789 cachePolicy=dict(
790 type="str",
791 choices=["DEFAULT", "EVICT_DAILY", "EVICT_WEEKLY", "MAX_LIFESPAN", "NO_CACHE"],
792 default="DEFAULT",
793 ),
794 changedSyncPeriod=dict(type="int", default=-1),
795 connectionPooling=dict(type="bool", default=True),
796 connectionPoolingAuthentication=dict(type="str", choices=["none", "simple", "DIGEST-MD5"]),
797 connectionPoolingDebug=dict(type="str"),
798 connectionPoolingInitSize=dict(type="int"),
799 connectionPoolingMaxSize=dict(type="int"),
800 connectionPoolingPrefSize=dict(type="int"),
801 connectionPoolingProtocol=dict(type="str"),
802 connectionPoolingTimeout=dict(type="int"),
803 connectionTimeout=dict(type="int"),
804 connectionUrl=dict(type="str"),
805 customUserSearchFilter=dict(type="str"),
806 debug=dict(type="bool"),
807 editMode=dict(type="str", choices=["READ_ONLY", "WRITABLE", "UNSYNCED"]),
808 enabled=dict(type="bool", default=True),
809 evictionDay=dict(type="str"),
810 evictionHour=dict(type="str"),
811 evictionMinute=dict(type="str"),
812 fullSyncPeriod=dict(type="int", default=-1),
813 importEnabled=dict(type="bool", default=True),
814 kerberosRealm=dict(type="str"),
815 keyTab=dict(type="str", no_log=False),
816 maxLifespan=dict(type="int"),
817 pagination=dict(type="bool", default=True),
818 priority=dict(type="int", default=0),
819 rdnLDAPAttribute=dict(type="str"),
820 readTimeout=dict(type="int"),
821 referral=dict(type="str", choices=["ignore", "follow"]),
822 searchScope=dict(type="str", choices=["1", "2"], default="1"),
823 serverPrincipal=dict(type="str"),
824 krbPrincipalAttribute=dict(type="str"),
825 startTls=dict(type="bool", default=False),
826 syncRegistrations=dict(type="bool", default=False),
827 trustEmail=dict(type="bool", default=False),
828 updateProfileFirstLogin=dict(type="bool"),
829 useKerberosForPasswordAuthentication=dict(type="bool", default=False),
830 usePasswordModifyExtendedOp=dict(type="bool", default=False, no_log=False),
831 useTruststoreSpi=dict(type="str", choices=["always", "ldapsOnly", "never"], default="ldapsOnly"),
832 userObjectClasses=dict(type="str"),
833 usernameLDAPAttribute=dict(type="str"),
834 usersDn=dict(type="str"),
835 uuidLDAPAttribute=dict(type="str"),
836 validatePasswordPolicy=dict(type="bool", default=False),
837 vendor=dict(type="str"),
838 )
839
840 mapper_spec = dict(
841 id=dict(type="str"),
842 name=dict(type="str"),
843 parentId=dict(type="str"),
844 providerId=dict(type="str"),
845 providerType=dict(type="str", default="org.keycloak.storage.ldap.mappers.LDAPStorageMapper"),
846 config=dict(type="dict"),
847 )
848
849 meta_args = dict(
850 config=dict(type="dict", options=config_spec),
851 state=dict(type="str", default="present", choices=["present", "absent"]),
852 realm=dict(type="str", default="master"),
853 id=dict(type="str"),
854 name=dict(type="str"),
855 provider_id=dict(type="str", aliases=["providerId"]),
856 provider_type=dict(type="str", aliases=["providerType"], default="org.keycloak.storage.UserStorageProvider"),
857 parent_id=dict(type="str", aliases=["parentId"]),
858 remove_unspecified_mappers=dict(type="bool", default=True),
859 bind_credential_update_mode=dict(type="str", default="always", choices=["always", "only_indirect"]),
860 mappers=dict(type="list", elements="dict", options=mapper_spec),
861 )
862
863 argument_spec.update(meta_args)
864
865 module = AnsibleModule(
866 argument_spec=argument_spec,
867 supports_check_mode=True,
868 required_one_of=(
869 [
870 ["id", "name"],
871 ["token", "auth_realm", "auth_username", "auth_password", "auth_client_id", "auth_client_secret"],
872 ]
873 ),
874 required_together=([["auth_username", "auth_password"]]),
875 required_by={"refresh_token": "auth_realm"},
876 )
877
878 result = dict(changed=False, msg="", diff={}, proposed={}, existing={}, end_state={})
879
880 # Obtain access token, initialize API
881 try:
882 connection_header = get_token(module.params)
883 except KeycloakError as e:
884 module.fail_json(msg=str(e))
885
886 kc = KeycloakAPI(module, connection_header)
887
888 realm = module.params.get("realm")
889 state = module.params.get("state")
890 config = module.params.get("config")
891 mappers = module.params.get("mappers")
892 cid = module.params.get("id")
893 name = module.params.get("name")
894
895 # Keycloak API expects config parameters to be arrays containing a single string element
896 if config is not None:
897 module.params["config"] = {
898 k: [str(v).lower() if not isinstance(v, str) else v] for k, v in config.items() if config[k] is not None
899 }
900
901 if mappers is not None:
902 for mapper in mappers:
903 if mapper.get("config") is not None:
904 new_config = {}
905 for k, v in mapper["config"].items():
906 if v is None:
907 continue
908 if isinstance(v, list):
909 new_config[k] = [str(item).lower() if not isinstance(item, str) else item for item in v]
910 else:
911 new_config[k] = [str(v).lower() if not isinstance(v, str) else v]
912 mapper["config"] = new_config
913
914 # Filter and map the parameters names that apply
915 comp_params = [
916 x
917 for x in module.params
918 if x
919 not in list(keycloak_argument_spec().keys())
920 + ["state", "realm", "mappers", "remove_unspecified_mappers", "bind_credential_update_mode"]
921 and module.params.get(x) is not None
922 ]
923
924 # See if it already exists in Keycloak
925 if cid is None:
926 found = kc.get_components(urlencode(dict(type="org.keycloak.storage.UserStorageProvider", name=name)), realm)
927 if len(found) > 1:
928 module.fail_json(
929 msg=f"No ID given and found multiple user federations with name `{name}`. Cannot continue."
930 )
931 before_comp = next(iter(found), None)
932 if before_comp is not None:
933 cid = before_comp["id"]
934 else:
935 before_comp = kc.get_component(cid, realm)
936
937 if before_comp is None:
938 before_comp = {}
939
940 # if user federation exists, get associated mappers
941 if cid is not None and before_comp:
942 before_comp["mappers"] = sorted(
943 kc.get_components(urlencode(dict(parent=cid)), realm), key=lambda x: x.get("name") or ""
944 )
945
946 normalize_kc_comp(before_comp)
947
948 # Build a proposed changeset from parameters given to this module
949 changeset = {}
950
951 for param in comp_params:
952 new_param_value = module.params.get(param)
953 old_value = before_comp[camel(param)] if camel(param) in before_comp else None
954 if param == "mappers":
955 new_param_value = [{k: v for k, v in x.items() if v is not None} for x in new_param_value]
956 if new_param_value != old_value:
957 changeset[camel(param)] = new_param_value
958
959 # special handling of mappers list to allow change detection
960 if module.params.get("mappers") is not None:
961 if module.params["provider_id"] in ["kerberos", "sssd"]:
962 module.fail_json(msg=f"Cannot configure mappers for {module.params['provider_id']} provider.")
963 for change in module.params["mappers"]:
964 change = {k: v for k, v in change.items() if v is not None}
965 if change.get("id") is None and change.get("name") is None:
966 module.fail_json(msg="Either `name` or `id` has to be specified on each mapper.")
967 if cid is None:
968 old_mapper = {}
969 elif change.get("id") is not None:
970 old_mapper = next(
971 (
972 before_mapper
973 for before_mapper in before_comp.get("mappers", [])
974 if before_mapper["id"] == change["id"]
975 ),
976 None,
977 )
978 if old_mapper is None:
979 old_mapper = {}
980 else:
981 found = [
982 before_mapper
983 for before_mapper in before_comp.get("mappers", [])
984 if before_mapper["name"] == change["name"]
985 ]
986 if len(found) > 1:
987 module.fail_json(msg=f"Found multiple mappers with name `{change['name']}`. Cannot continue.")
988 if len(found) == 1:
989 old_mapper = found[0]
990 else:
991 old_mapper = {}
992 new_mapper = old_mapper.copy()
993 new_mapper.update(change)
994 # changeset contains all desired mappers: those existing, to update or to create
995 if changeset.get("mappers") is None:
996 changeset["mappers"] = list()
997 changeset["mappers"].append(new_mapper)
998 changeset["mappers"] = sorted(changeset["mappers"], key=lambda x: x.get("name") or "")
999
1000 # to keep unspecified existing mappers we add them to the desired mappers list, unless they're already present
1001 if not module.params["remove_unspecified_mappers"] and "mappers" in before_comp:
1002 changeset_mapper_ids = [mapper["id"] for mapper in changeset["mappers"] if "id" in mapper]
1003 changeset["mappers"].extend(
1004 [mapper for mapper in before_comp["mappers"] if mapper["id"] not in changeset_mapper_ids]
1005 )
1006
1007 # Prepare the desired values using the existing values (non-existence results in a dict that is save to use as a basis)
1008 desired_comp = before_comp.copy()
1009 desired_comp.update(changeset)
1010
1011 result["proposed"] = sanitize(changeset)
1012 result["existing"] = sanitize(before_comp)
1013
1014 # Cater for when it doesn't exist (an empty dict)
1015 if not before_comp:
1016 if state == "absent":
1017 # Do nothing and exit
1018 if module._diff:
1019 result["diff"] = dict(before="", after="")
1020 result["changed"] = False
1021 result["end_state"] = {}
1022 result["msg"] = "User federation does not exist; doing nothing."
1023 module.exit_json(**result)
1024
1025 # Process a creation
1026 result["changed"] = True
1027
1028 if module.check_mode:
1029 if module._diff:
1030 result["diff"] = dict(before="", after=sanitize(desired_comp))
1031 module.exit_json(**result)
1032
1033 # create it
1034 desired_mappers = desired_comp.pop("mappers", [])
1035 after_comp = kc.create_component(desired_comp, realm)
1036 cid = after_comp["id"]
1037 updated_mappers = []
1038 # when creating a user federation, keycloak automatically creates default mappers
1039 default_mappers = kc.get_components(urlencode(dict(parent=cid)), realm)
1040
1041 # create new mappers or update existing default mappers
1042 for desired_mapper in desired_mappers:
1043 found = [
1044 default_mapper for default_mapper in default_mappers if default_mapper["name"] == desired_mapper["name"]
1045 ]
1046 if len(found) > 1:
1047 module.fail_json(msg=f"Found multiple mappers with name `{desired_mapper['name']}`. Cannot continue.")
1048 if len(found) == 1:
1049 old_mapper = found[0]
1050 else:
1051 old_mapper = {}
1052
1053 new_mapper = old_mapper.copy()
1054 new_mapper.update(desired_mapper)
1055
1056 if new_mapper.get("id") is not None:
1057 kc.update_component(new_mapper, realm)
1058 updated_mappers.append(new_mapper)
1059 else:
1060 if new_mapper.get("parentId") is None:
1061 new_mapper["parentId"] = cid
1062 updated_mappers.append(kc.create_component(new_mapper, realm))
1063
1064 if module.params["remove_unspecified_mappers"]:
1065 # we remove all unwanted default mappers
1066 # we use ids so we dont accidently remove one of the previously updated default mapper
1067 for default_mapper in default_mappers:
1068 if default_mapper["id"] not in [x["id"] for x in updated_mappers]:
1069 kc.delete_component(default_mapper["id"], realm)
1070
1071 after_comp["mappers"] = kc.get_components(urlencode(dict(parent=cid)), realm)
1072 normalize_kc_comp(after_comp)
1073 if module._diff:
1074 result["diff"] = dict(before="", after=sanitize(after_comp))
1075 result["end_state"] = sanitize(after_comp)
1076 result["msg"] = f"User federation {cid} has been created"
1077 module.exit_json(**result)
1078
1079 else:
1080 if state == "present":
1081 # Process an update
1082
1083 desired_copy = deepcopy(desired_comp)
1084 before_copy = deepcopy(before_comp)
1085 # exclude bindCredential when checking wether an update is required, therefore
1086 # updating it only if there are other changes
1087 if module.params["bind_credential_update_mode"] == "only_indirect":
1088 desired_copy.get("config", []).pop("bindCredential", None)
1089 before_copy.get("config", []).pop("bindCredential", None)
1090 # no changes
1091 if desired_copy == before_copy:
1092 result["changed"] = False
1093 result["end_state"] = sanitize(desired_comp)
1094 result["msg"] = f"No changes required to user federation {cid}."
1095 module.exit_json(**result)
1096
1097 # doing an update
1098 result["changed"] = True
1099
1100 if module._diff:
1101 result["diff"] = dict(before=sanitize(before_comp), after=sanitize(desired_comp))
1102
1103 if module.check_mode:
1104 module.exit_json(**result)
1105
1106 # do the update
1107 desired_mappers = desired_comp.pop("mappers", [])
1108 kc.update_component(desired_comp, realm)
1109
1110 for before_mapper in before_comp.get("mappers", []):
1111 # remove unwanted existing mappers that will not be updated
1112 if before_mapper["id"] not in [x["id"] for x in desired_mappers if "id" in x]:
1113 kc.delete_component(before_mapper["id"], realm)
1114
1115 for mapper in desired_mappers:
1116 if mapper in before_comp.get("mappers", []):
1117 continue
1118 if mapper.get("id") is not None:
1119 kc.update_component(mapper, realm)
1120 else:
1121 if mapper.get("parentId") is None:
1122 mapper["parentId"] = desired_comp["id"]
1123 kc.create_component(mapper, realm)
1124
1125 after_comp = kc.get_component(cid, realm)
1126 after_comp["mappers"] = sorted(
1127 kc.get_components(urlencode(dict(parent=cid)), realm), key=lambda x: x.get("name") or ""
1128 )
1129 normalize_kc_comp(after_comp)
1130 after_comp_sanitized = sanitize(after_comp)
1131 before_comp_sanitized = sanitize(before_comp)
1132 result["end_state"] = after_comp_sanitized
1133 if module._diff:
1134 result["diff"] = dict(before=before_comp_sanitized, after=after_comp_sanitized)
1135 result["changed"] = before_comp_sanitized != after_comp_sanitized
1136 result["msg"] = f"User federation {cid} has been updated"
1137 module.exit_json(**result)
1138
1139 elif state == "absent":
1140 # Process a deletion
1141 result["changed"] = True
1142
1143 if module._diff:
1144 result["diff"] = dict(before=sanitize(before_comp), after="")
1145
1146 if module.check_mode:
1147 module.exit_json(**result)
1148
1149 # delete it
1150 kc.delete_component(cid, realm)
1151
1152 result["end_state"] = {}
1153
1154 result["msg"] = f"User federation {cid} has been deleted"
1155
1156 module.exit_json(**result)
1157
1158
1159 if __name__ == "__main__":
1160 main()