Debian Codegraph @

ansible_collections/community/general/plugins/modules/keycloak_clientscope.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_clientscope
11
12 short_description: Allows administration of Keycloak client_scopes using Keycloak API
13
14 version_added: 3.4.0
15
16 description:
17 - This module allows you to add, remove or modify Keycloak client_scopes 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/8.0/rest-api/index.html).
23 - Attributes are multi-valued in the Keycloak API. All attributes are lists of individual values and are returned that way
24 by this module. You may pass single values for attributes when calling the module, and this is translated into a list
25 suitable for the API.
26 - When updating a client_scope, where possible provide the client_scope ID to the module. This removes a lookup to the API
27 to translate the name into the client_scope ID.
28 attributes:
29 check_mode:
30 support: full
31 diff_mode:
32 support: full
33 action_group:
34 version_added: 10.2.0
35
36 options:
37 state:
38 description:
39 - State of the client_scope.
40 - On V(present), the client_scope is created if it does not yet exist, or updated with the parameters you provide.
41 - On V(absent), the client_scope is removed if it exists.
42 default: 'present'
43 type: str
44 choices:
45 - present
46 - absent
47
48 name:
49 type: str
50 description:
51 - Name of the client_scope.
52 - This parameter is required only when creating or updating the client_scope.
53 realm:
54 type: str
55 description:
56 - They Keycloak realm under which this client_scope resides.
57 default: 'master'
58
59 id:
60 type: str
61 description:
62 - The unique identifier for this client_scope.
63 - This parameter is not required for updating or deleting a client_scope but providing it reduces the number of API
64 calls required.
65 description:
66 type: str
67 description:
68 - Description for this client_scope.
69 - This parameter is not required for updating or deleting a client_scope.
70 protocol:
71 description:
72 - Type of client.
73 - The V(docker-v2) value was added in community.general 8.6.0.
74 choices: ['openid-connect', 'saml', 'wsfed', 'docker-v2']
75 type: str
76
77 protocol_mappers:
78 description:
79 - A list of dicts defining protocol mappers for this client.
80 - This is C(protocolMappers) in the Keycloak REST API.
81 aliases:
82 - protocolMappers
83 type: list
84 elements: dict
85 suboptions:
86 protocol:
87 description:
88 - This specifies for which protocol this protocol mapper.
89 - Is active.
90 choices: ['openid-connect', 'saml', 'wsfed', 'docker-v2']
91 type: str
92
93 protocolMapper:
94 description:
95 - 'The Keycloak-internal name of the type of this protocol-mapper. While an exhaustive list is impossible to provide
96 since this may be extended through SPIs by the user of Keycloak, by default Keycloak as of 3.4 ships with at least:'
97 - V(docker-v2-allow-all-mapper).
98 - V(oidc-address-mapper).
99 - V(oidc-full-name-mapper).
100 - V(oidc-group-membership-mapper).
101 - V(oidc-hardcoded-claim-mapper).
102 - V(oidc-hardcoded-role-mapper).
103 - V(oidc-role-name-mapper).
104 - V(oidc-script-based-protocol-mapper).
105 - V(oidc-sha256-pairwise-sub-mapper).
106 - V(oidc-usermodel-attribute-mapper).
107 - V(oidc-usermodel-client-role-mapper).
108 - V(oidc-usermodel-property-mapper).
109 - V(oidc-usermodel-realm-role-mapper).
110 - V(oidc-usersessionmodel-note-mapper).
111 - V(saml-group-membership-mapper).
112 - V(saml-hardcode-attribute-mapper).
113 - V(saml-hardcode-role-mapper).
114 - V(saml-role-list-mapper).
115 - V(saml-role-name-mapper).
116 - V(saml-user-attribute-mapper).
117 - V(saml-user-property-mapper).
118 - V(saml-user-session-note-mapper).
119 - An exhaustive list of available mappers on your installation can be obtained on the admin console by going to
120 Server Info -> Providers and looking under 'protocol-mapper'.
121 type: str
122
123 name:
124 description:
125 - The name of this protocol mapper.
126 type: str
127
128 id:
129 description:
130 - Usually a UUID specifying the internal ID of this protocol mapper instance.
131 type: str
132
133 config:
134 description:
135 - Dict specifying the configuration options for the protocol mapper; the contents differ depending on the value
136 of O(protocol_mappers[].protocolMapper) and are not documented other than by the source of the mappers and its
137 parent class(es). An example is given below. It is easiest to obtain valid config values by dumping an already-existing
138 protocol mapper configuration through check-mode in the RV(existing) return value.
139 type: dict
140
141 attributes:
142 type: dict
143 description:
144 - A dict of key/value pairs to set as custom attributes for the client_scope.
145 - Values may be single values (for example a string) or a list of strings.
146 extends_documentation_fragment:
147 - community.general._keycloak
148 - community.general._keycloak.actiongroup_keycloak
149 - community.general._attributes
150
151 author:
152 - Gaƫtan Daubresse (@Gaetan2907)
153 """
154
155 EXAMPLES = r"""
156 - name: Create a Keycloak client_scopes, authentication with credentials
157 community.general.keycloak_clientscope:
158 name: my-new-kc-clientscope
159 realm: MyCustomRealm
160 state: present
161 auth_client_id: admin-cli
162 auth_keycloak_url: https://auth.example.com/auth
163 auth_realm: master
164 auth_username: USERNAME
165 auth_password: PASSWORD
166 delegate_to: localhost
167
168 - name: Create a Keycloak client_scopes, authentication with token
169 community.general.keycloak_clientscope:
170 name: my-new-kc-clientscope
171 realm: MyCustomRealm
172 state: present
173 auth_client_id: admin-cli
174 auth_keycloak_url: https://auth.example.com/auth
175 token: TOKEN
176 delegate_to: localhost
177
178 - name: Delete a keycloak client_scopes
179 community.general.keycloak_clientscope:
180 id: '9d59aa76-2755-48c6-b1af-beb70a82c3cd'
181 state: absent
182 realm: MyCustomRealm
183 auth_client_id: admin-cli
184 auth_keycloak_url: https://auth.example.com/auth
185 auth_realm: master
186 auth_username: USERNAME
187 auth_password: PASSWORD
188 delegate_to: localhost
189
190 - name: Delete a Keycloak client_scope based on name
191 community.general.keycloak_clientscope:
192 name: my-clientscope-for-deletion
193 state: absent
194 auth_client_id: admin-cli
195 auth_keycloak_url: https://auth.example.com/auth
196 auth_realm: master
197 auth_username: USERNAME
198 auth_password: PASSWORD
199 delegate_to: localhost
200
201 - name: Update the name of a Keycloak client_scope
202 community.general.keycloak_clientscope:
203 id: '9d59aa76-2755-48c6-b1af-beb70a82c3cd'
204 name: an-updated-kc-clientscope-name
205 state: present
206 auth_client_id: admin-cli
207 auth_keycloak_url: https://auth.example.com/auth
208 auth_realm: master
209 auth_username: USERNAME
210 auth_password: PASSWORD
211 delegate_to: localhost
212
213 - name: Create a Keycloak client_scope with some custom attributes
214 community.general.keycloak_clientscope:
215 auth_client_id: admin-cli
216 auth_keycloak_url: https://auth.example.com/auth
217 auth_realm: master
218 auth_username: USERNAME
219 auth_password: PASSWORD
220 name: my-new_clientscope
221 description: description-of-clientscope
222 protocol: openid-connect
223 protocol_mappers:
224 - config:
225 access.token.claim: true
226 claim.name: "family_name"
227 id.token.claim: true
228 jsonType.label: String
229 user.attribute: lastName
230 userinfo.token.claim: true
231 name: family name
232 protocol: openid-connect
233 protocolMapper: oidc-usermodel-property-mapper
234 - config:
235 attribute.name: Role
236 attribute.nameformat: Basic
237 single: false
238 name: role list
239 protocol: saml
240 protocolMapper: saml-role-list-mapper
241 attributes:
242 attrib1: value1
243 attrib2: value2
244 attrib3:
245 - with
246 - numerous
247 - individual
248 - list
249 - items
250 delegate_to: localhost
251 """
252
253 RETURN = r"""
254 msg:
255 description: Message as to what action was taken.
256 returned: always
257 type: str
258 sample: "Client_scope testclientscope has been updated"
259
260 proposed:
261 description: Representation of proposed client scope.
262 returned: always
263 type: dict
264 sample: {"clientId": "test"}
265
266 existing:
267 description: Representation of existing client scope (sample is truncated).
268 returned: always
269 type: dict
270 sample:
271 {
272 "adminUrl": "http://www.example.com/admin_url",
273 "attributes": {
274 "request.object.signature.alg": "RS256"
275 }
276 }
277
278 end_state:
279 description: Representation of client scope after module execution (sample is truncated).
280 returned: on success
281 type: dict
282 sample:
283 {
284 "adminUrl": "http://www.example.com/admin_url",
285 "attributes": {
286 "request.object.signature.alg": "RS256"
287 }
288 }
289 """
290
291 from ansible.module_utils.basic import AnsibleModule
292
293 from ansible_collections.community.general.plugins.module_utils._keycloak import (
294 KeycloakAPI,
295 KeycloakError,
296 camel,
297 get_token,
298 is_struct_included,
299 keycloak_argument_spec,
300 )
301
302
303 def normalise_cr(clientscoperep, remove_ids=False):
304 """Re-sorts any properties where the order so that diff's is minimised, and adds default values where appropriate so that the
305 the change detection is more effective.
306
307 :param clientscoperep: the clientscoperep dict to be sanitized
308 :param remove_ids: If set to true, then the unique ID's of objects is removed to make the diff and checks for changed
309 not alert when the ID's of objects are not usually known, (e.g. for protocol_mappers)
310 :return: normalised clientscoperep dict
311 """
312 # Avoid the dict passed in to be modified
313 clientscoperep = clientscoperep.copy()
314
315 if "protocolMappers" in clientscoperep:
316 clientscoperep["protocolMappers"] = sorted(
317 clientscoperep["protocolMappers"], key=lambda x: (x.get("name"), x.get("protocol"), x.get("protocolMapper"))
318 )
319 for mapper in clientscoperep["protocolMappers"]:
320 if remove_ids:
321 mapper.pop("id", None)
322
323 # Set to a default value.
324 mapper["consentRequired"] = mapper.get("consentRequired", False)
325
326 return clientscoperep
327
328
329 def sanitize_cr(clientscoperep):
330 """Removes probably sensitive details from a clientscoperep representation.
331
332 :param clientscoperep: the clientscoperep dict to be sanitized
333 :return: sanitized clientrep dict
334 """
335 result = clientscoperep.copy()
336 if "secret" in result:
337 result["secret"] = "no_log"
338 if "attributes" in result:
339 if "saml.signing.private.key" in result["attributes"]:
340 result["attributes"]["saml.signing.private.key"] = "no_log"
341 return normalise_cr(result)
342
343
344 def main():
345 """
346 Module execution
347
348 :return:
349 """
350 argument_spec = keycloak_argument_spec()
351
352 protmapper_spec = dict(
353 id=dict(type="str"),
354 name=dict(type="str"),
355 protocol=dict(type="str", choices=["openid-connect", "saml", "wsfed", "docker-v2"]),
356 protocolMapper=dict(type="str"),
357 config=dict(type="dict"),
358 )
359
360 meta_args = dict(
361 state=dict(default="present", choices=["present", "absent"]),
362 realm=dict(default="master"),
363 id=dict(type="str"),
364 name=dict(type="str"),
365 description=dict(type="str"),
366 protocol=dict(type="str", choices=["openid-connect", "saml", "wsfed", "docker-v2"]),
367 attributes=dict(type="dict"),
368 protocol_mappers=dict(type="list", elements="dict", options=protmapper_spec, aliases=["protocolMappers"]),
369 )
370
371 argument_spec.update(meta_args)
372
373 module = AnsibleModule(
374 argument_spec=argument_spec,
375 supports_check_mode=True,
376 required_one_of=(
377 [
378 ["id", "name"],
379 ["token", "auth_realm", "auth_username", "auth_password", "auth_client_id", "auth_client_secret"],
380 ]
381 ),
382 required_together=([["auth_username", "auth_password"]]),
383 required_by={"refresh_token": "auth_realm"},
384 )
385
386 result = dict(changed=False, msg="", diff={}, proposed={}, existing={}, end_state={})
387
388 # Obtain access token, initialize API
389 try:
390 connection_header = get_token(module.params)
391 except KeycloakError as e:
392 module.fail_json(msg=str(e))
393
394 kc = KeycloakAPI(module, connection_header)
395
396 realm = module.params.get("realm")
397 state = module.params.get("state")
398 cid = module.params.get("id")
399 name = module.params.get("name")
400 protocol_mappers = module.params.get("protocol_mappers")
401
402 # Filter and map the parameters names that apply to the client scope
403 clientscope_params = [
404 x
405 for x in module.params
406 if x not in list(keycloak_argument_spec().keys()) + ["state", "realm"] and module.params.get(x) is not None
407 ]
408
409 # See if it already exists in Keycloak
410 if cid is None:
411 before_clientscope = kc.get_clientscope_by_name(name, realm=realm)
412 else:
413 before_clientscope = kc.get_clientscope_by_clientscopeid(cid, realm=realm)
414
415 if before_clientscope is None:
416 before_clientscope = {}
417
418 # Build a proposed changeset from parameters given to this module
419 changeset = {}
420
421 for clientscope_param in clientscope_params:
422 new_param_value = module.params.get(clientscope_param)
423
424 # Unfortunately, the ansible argument spec checker introduces variables with null values when
425 # they are not specified
426 if clientscope_param == "protocol_mappers":
427 new_param_value = [{k: v for k, v in x.items() if v is not None} for x in new_param_value]
428 changeset[camel(clientscope_param)] = new_param_value
429
430 # Prepare the desired values using the existing values (non-existence results in a dict that is save to use as a basis)
431 desired_clientscope = before_clientscope.copy()
432 desired_clientscope.update(changeset)
433
434 # Cater for when it doesn't exist (an empty dict)
435 if not before_clientscope:
436 if state == "absent":
437 # Do nothing and exit
438 if module._diff:
439 result["diff"] = dict(before="", after="")
440 result["changed"] = False
441 result["end_state"] = {}
442 result["msg"] = "Clientscope does not exist; doing nothing."
443 module.exit_json(**result)
444
445 # Process a creation
446 result["changed"] = True
447
448 if name is None:
449 module.fail_json(msg="name must be specified when creating a new clientscope")
450
451 if module._diff:
452 result["diff"] = dict(before="", after=sanitize_cr(desired_clientscope))
453
454 if module.check_mode:
455 module.exit_json(**result)
456
457 # create it
458 kc.create_clientscope(desired_clientscope, realm=realm)
459 after_clientscope = kc.get_clientscope_by_name(name, realm)
460
461 result["end_state"] = sanitize_cr(after_clientscope)
462
463 result["msg"] = f"Clientscope {after_clientscope['name']} has been created with ID {after_clientscope['id']}"
464
465 else:
466 if state == "present":
467 # Process an update
468
469 # no changes
470 # remove ids for compare, problematic if desired has no ids set (not required),
471 # normalize for consentRequired in protocolMappers
472 if normalise_cr(desired_clientscope, remove_ids=True) == normalise_cr(before_clientscope, remove_ids=True):
473 result["changed"] = False
474 result["end_state"] = sanitize_cr(desired_clientscope)
475 result["msg"] = f"No changes required to clientscope {before_clientscope['name']}."
476 module.exit_json(**result)
477
478 # doing an update
479 result["changed"] = True
480
481 if module._diff:
482 result["diff"] = dict(before=sanitize_cr(before_clientscope), after=sanitize_cr(desired_clientscope))
483
484 if module.check_mode:
485 # We can only compare the current clientscope with the proposed updates we have
486 before_norm = normalise_cr(before_clientscope, remove_ids=True)
487 desired_norm = normalise_cr(desired_clientscope, remove_ids=True)
488 if module._diff:
489 result["diff"] = dict(before=sanitize_cr(before_norm), after=sanitize_cr(desired_norm))
490 result["changed"] = not is_struct_included(desired_norm, before_norm)
491 module.exit_json(**result)
492
493 # do the update
494 kc.update_clientscope(desired_clientscope, realm=realm)
495
496 # do the protocolmappers update
497 if protocol_mappers is not None:
498 for protocol_mapper in protocol_mappers:
499 # update if protocolmapper exist
500 current_protocolmapper = kc.get_clientscope_protocolmapper_by_name(
501 desired_clientscope["id"], protocol_mapper["name"], realm=realm
502 )
503 if current_protocolmapper is not None:
504 protocol_mapper["id"] = current_protocolmapper["id"]
505 kc.update_clientscope_protocolmappers(desired_clientscope["id"], protocol_mapper, realm=realm)
506 # create otherwise
507 else:
508 kc.create_clientscope_protocolmapper(desired_clientscope["id"], protocol_mapper, realm=realm)
509
510 after_clientscope = kc.get_clientscope_by_clientscopeid(desired_clientscope["id"], realm=realm)
511
512 result["end_state"] = after_clientscope
513
514 result["msg"] = f"Clientscope {after_clientscope['id']} has been updated"
515 module.exit_json(**result)
516
517 else:
518 # Process a deletion (because state was not 'present')
519 result["changed"] = True
520
521 if module._diff:
522 result["diff"] = dict(before=sanitize_cr(before_clientscope), after="")
523
524 if module.check_mode:
525 module.exit_json(**result)
526
527 # delete it
528 cid = before_clientscope["id"]
529 kc.delete_clientscope(cid=cid, realm=realm)
530
531 result["end_state"] = {}
532
533 result["msg"] = f"Clientscope {before_clientscope['name']} has been deleted"
534
535 module.exit_json(**result)
536
537
538 if __name__ == "__main__":
539 main()