Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2022, Dušan Marković (@bratwurzt)
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5 # SPDX-License-Identifier: GPL-3.0-or-later
6 from __future__ import annotations
7
8 DOCUMENTATION = r"""
9 module: keycloak_user_rolemapping
10
11 short_description: Allows administration of Keycloak user_rolemapping with the Keycloak API
12
13 version_added: 5.7.0
14
15 description:
16 - This module allows you to add, remove or modify Keycloak user_rolemapping with the Keycloak REST API. It requires access
17 to the REST API using OpenID Connect; the user connecting and the client being used must have the requisite access rights.
18 In a default Keycloak installation, admin-cli and an admin user would work, as would a separate client definition with
19 the scope tailored to your needs and a user having the expected roles.
20 - The names of module options are snake_cased versions of the camelCase ones found in the Keycloak API and its documentation
21 at U(https://www.keycloak.org/docs-api/8.0/rest-api/index.html).
22 - Attributes are multi-valued in the Keycloak API. All attributes are lists of individual values and are returned that way
23 by this module. You may pass single values for attributes when calling the module, and this is translated into a list
24 suitable for the API.
25 - When updating a user_rolemapping, where possible provide the role ID to the module. This removes a lookup to the API to
26 translate the name into the role ID.
27 attributes:
28 check_mode:
29 support: full
30 diff_mode:
31 support: full
32 action_group:
33 version_added: 10.2.0
34
35 options:
36 state:
37 description:
38 - State of the user_rolemapping.
39 - On V(present), the user_rolemapping is created if it does not yet exist, or updated with the parameters you provide.
40 - On V(absent), the user_rolemapping is removed if it exists.
41 default: 'present'
42 type: str
43 choices:
44 - present
45 - absent
46
47 realm:
48 type: str
49 description:
50 - They Keycloak realm under which this role_representation resides.
51 default: 'master'
52
53 target_username:
54 type: str
55 description:
56 - Username of the user roles are mapped to.
57 - This parameter is not required (can be replaced by uid for less API call).
58 uid:
59 type: str
60 description:
61 - ID of the user to be mapped.
62 - This parameter is not required for updating or deleting the rolemapping but providing it reduces the number of API
63 calls required.
64 service_account_user_client_id:
65 type: str
66 description:
67 - Client ID of the service-account-user to be mapped.
68 - This parameter is not required for updating or deleting the rolemapping but providing it reduces the number of API
69 calls required.
70 client_id:
71 type: str
72 description:
73 - Name of the client (different than O(cid)) whose role is to be mapped.
74 - This parameter is required if O(cid) is not provided (can be replaced by O(cid) to reduce the number of API calls
75 that must be made).
76 - If neither O(cid) nor O(client_id) is specified, a B(realm) role is mapped instead.
77 cid:
78 type: str
79 description:
80 - ID of the client whose role is to be mapped.
81 - This parameter is not required for updating or deleting the rolemapping but providing it reduces the number of API
82 calls required.
83 - If neither O(cid) nor O(client_id) is specified, a B(realm) role is mapped instead.
84 roles:
85 description:
86 - Roles to be mapped to the user.
87 type: list
88 elements: dict
89 suboptions:
90 name:
91 type: str
92 description:
93 - Name of the role representation.
94 - This parameter is required only when creating or updating the role_representation.
95 id:
96 type: str
97 description:
98 - The unique identifier for this role_representation.
99 - This parameter is not required for updating or deleting a role_representation but providing it reduces the number
100 of API calls required.
101 extends_documentation_fragment:
102 - community.general._keycloak
103 - community.general._keycloak.actiongroup_keycloak
104 - community.general._attributes
105
106 author:
107 - Dušan Marković (@bratwurzt)
108 - Ivan Kokalović (@koke1997)
109 """
110
111 EXAMPLES = r"""
112 - name: Map a realm role to a user, authentication with credentials
113 community.general.keycloak_user_rolemapping:
114 realm: MyCustomRealm
115 auth_client_id: admin-cli
116 auth_keycloak_url: https://auth.example.com/auth
117 auth_realm: master
118 auth_username: USERNAME
119 auth_password: PASSWORD
120 state: present
121 uid: user_uid
122 roles:
123 - name: role_name1
124 id: role_id1
125 - name: role_name2
126 id: role_id2
127 delegate_to: localhost
128
129 - name: Map a client role to a user, authentication with credentials
130 community.general.keycloak_user_rolemapping:
131 realm: MyCustomRealm
132 auth_client_id: admin-cli
133 auth_keycloak_url: https://auth.example.com/auth
134 auth_realm: master
135 auth_username: USERNAME
136 auth_password: PASSWORD
137 state: present
138 client_id: client1
139 uid: user_uid
140 roles:
141 - name: role_name1
142 id: role_id1
143 - name: role_name2
144 id: role_id2
145 delegate_to: localhost
146
147 - name: Map a client role to a service account user for a client, authentication with credentials
148 community.general.keycloak_user_rolemapping:
149 realm: MyCustomRealm
150 auth_client_id: admin-cli
151 auth_keycloak_url: https://auth.example.com/auth
152 auth_realm: master
153 auth_username: USERNAME
154 auth_password: PASSWORD
155 state: present
156 client_id: client1
157 service_account_user_client_id: clientIdOfServiceAccount
158 roles:
159 - name: role_name1
160 id: role_id1
161 - name: role_name2
162 id: role_id2
163 delegate_to: localhost
164
165 - name: Map a client role to a user, authentication with token
166 community.general.keycloak_user_rolemapping:
167 realm: MyCustomRealm
168 auth_client_id: admin-cli
169 auth_keycloak_url: https://auth.example.com/auth
170 token: TOKEN
171 state: present
172 client_id: client1
173 target_username: user1
174 roles:
175 - name: role_name1
176 id: role_id1
177 - name: role_name2
178 id: role_id2
179 delegate_to: localhost
180
181 - name: Unmap client role from a user
182 community.general.keycloak_user_rolemapping:
183 realm: MyCustomRealm
184 auth_client_id: admin-cli
185 auth_keycloak_url: https://auth.example.com/auth
186 auth_realm: master
187 auth_username: USERNAME
188 auth_password: PASSWORD
189 state: absent
190 client_id: client1
191 uid: 70e3ae72-96b6-11e6-9056-9737fd4d0764
192 roles:
193 - name: role_name1
194 id: role_id1
195 - name: role_name2
196 id: role_id2
197 delegate_to: localhost
198 """
199
200 RETURN = r"""
201 msg:
202 description: Message as to what action was taken.
203 returned: always
204 type: str
205 sample: "Role role1 assigned to user user1."
206
207 proposed:
208 description: Representation of proposed client role mapping.
209 returned: always
210 type: dict
211 sample: {"clientId": "test"}
212
213 existing:
214 description:
215 - Representation of existing client role mapping.
216 - The sample is truncated.
217 returned: always
218 type: dict
219 sample:
220 {
221 "adminUrl": "http://www.example.com/admin_url",
222 "attributes": {
223 "request.object.signature.alg": "RS256"
224 }
225 }
226
227 end_state:
228 description:
229 - Representation of client role mapping after module execution.
230 - The sample is truncated.
231 returned: on success
232 type: dict
233 sample:
234 {
235 "adminUrl": "http://www.example.com/admin_url",
236 "attributes": {
237 "request.object.signature.alg": "RS256"
238 }
239 }
240 """
241
242 from ansible.module_utils.basic import AnsibleModule
243
244 from ansible_collections.community.general.plugins.module_utils._keycloak import (
245 KeycloakAPI,
246 KeycloakError,
247 get_token,
248 keycloak_argument_spec,
249 )
250
251
252 def main():
253 """
254 Module execution
255
256 :return:
257 """
258 argument_spec = keycloak_argument_spec()
259
260 roles_spec = dict(
261 name=dict(type="str"),
262 id=dict(type="str"),
263 )
264
265 meta_args = dict(
266 state=dict(default="present", choices=["present", "absent"]),
267 realm=dict(default="master"),
268 uid=dict(type="str"),
269 target_username=dict(type="str"),
270 service_account_user_client_id=dict(type="str"),
271 cid=dict(type="str"),
272 client_id=dict(type="str"),
273 roles=dict(type="list", elements="dict", options=roles_spec),
274 )
275
276 argument_spec.update(meta_args)
277
278 module = AnsibleModule(
279 argument_spec=argument_spec,
280 supports_check_mode=True,
281 required_one_of=(
282 [
283 ["token", "auth_realm", "auth_username", "auth_password", "auth_client_id", "auth_client_secret"],
284 ["uid", "target_username", "service_account_user_client_id"],
285 ]
286 ),
287 required_together=([["auth_username", "auth_password"]]),
288 required_by={"refresh_token": "auth_realm"},
289 )
290
291 result = dict(changed=False, msg="", diff={}, proposed={}, existing={}, end_state={})
292
293 # Obtain access token, initialize API
294 try:
295 connection_header = get_token(module.params)
296 except KeycloakError as e:
297 module.fail_json(msg=str(e))
298
299 kc = KeycloakAPI(module, connection_header)
300
301 realm = module.params.get("realm")
302 state = module.params.get("state")
303 cid = module.params.get("cid")
304 client_id = module.params.get("client_id")
305 uid = module.params.get("uid")
306 target_username = module.params.get("target_username")
307 service_account_user_client_id = module.params.get("service_account_user_client_id")
308 roles = module.params.get("roles")
309
310 # Check the parameters
311 if uid is None and target_username is None and service_account_user_client_id is None:
312 module.fail_json(
313 msg="Either the `target_username`, `uid` or `service_account_user_client_id` has to be specified."
314 )
315
316 # Get the potential missing parameters
317 if uid is None and service_account_user_client_id is None:
318 user_rep = kc.get_user_by_username(username=target_username, realm=realm)
319 if user_rep is not None:
320 uid = user_rep.get("id")
321 else:
322 module.fail_json(msg=f"Could not fetch user for username {target_username}:")
323 else:
324 if uid is None and target_username is None:
325 user_rep = kc.get_service_account_user_by_client_id(client_id=service_account_user_client_id, realm=realm)
326 if user_rep is not None:
327 uid = user_rep["id"]
328 else:
329 module.fail_json(msg=f"Could not fetch service-account-user for client_id {target_username}:")
330
331 if cid is None and client_id is not None:
332 cid = kc.get_client_id(client_id=client_id, realm=realm)
333 if cid is None:
334 module.fail_json(msg=f"Could not fetch client {client_id}:")
335 if roles is None:
336 module.exit_json(msg="Nothing to do (no roles specified).")
337 else:
338 for role in roles:
339 if role.get("name") is None and role.get("id") is None:
340 module.fail_json(msg="Either the `name` or `id` has to be specified on each role.")
341 # Fetch missing role_id
342 if role.get("id") is None:
343 if cid is None:
344 role_id = kc.get_realm_role(name=role.get("name"), realm=realm)["id"]
345 else:
346 role_id = kc.get_client_role_id_by_name(cid=cid, name=role.get("name"), realm=realm)
347 if role_id is not None:
348 role["id"] = role_id
349 else:
350 module.fail_json(
351 msg=f"Could not fetch role {role.get('name')} for client_id {client_id} or realm {realm}"
352 )
353 # Fetch missing role_name
354 else:
355 if cid is None:
356 role_rep = kc.get_realm_user_rolemapping_by_id(uid=uid, rid=role.get("id"), realm=realm)
357 if role_rep is not None:
358 role["name"] = role_rep["name"]
359 else:
360 role_rep = kc.get_client_user_rolemapping_by_id(uid=uid, cid=cid, rid=role.get("id"), realm=realm)
361 if role_rep is not None:
362 role["name"] = role_rep["name"]
363 if role.get("name") is None:
364 module.fail_json(
365 msg=f"Could not fetch role {role.get('id')} for client_id {client_id} or realm {realm}"
366 )
367
368 # Get effective role mappings
369 if cid is None:
370 available_roles_before = kc.get_realm_user_available_rolemappings(uid=uid, realm=realm)
371 assigned_roles_before = kc.get_realm_user_composite_rolemappings(uid=uid, realm=realm)
372 else:
373 available_roles_before = kc.get_client_user_available_rolemappings(uid=uid, cid=cid, realm=realm)
374 assigned_roles_before = kc.get_client_user_composite_rolemappings(uid=uid, cid=cid, realm=realm)
375
376 result["existing"] = assigned_roles_before
377 result["proposed"] = roles
378
379 update_roles = []
380 for role in roles:
381 # Fetch roles to assign if state present
382 if state == "present":
383 for available_role in available_roles_before:
384 if role.get("name") == available_role.get("name"):
385 update_roles.append(
386 {
387 "id": role.get("id"),
388 "name": role.get("name"),
389 }
390 )
391 # Fetch roles to remove if state absent
392 else:
393 for assigned_role in assigned_roles_before:
394 if role.get("name") == assigned_role.get("name"):
395 update_roles.append(
396 {
397 "id": role.get("id"),
398 "name": role.get("name"),
399 }
400 )
401
402 if len(update_roles):
403 if state == "present":
404 # Assign roles
405 result["changed"] = True
406 if module._diff:
407 result["diff"] = dict(before={"roles": assigned_roles_before}, after={"roles": update_roles})
408 if module.check_mode:
409 module.exit_json(**result)
410 kc.add_user_rolemapping(uid=uid, cid=cid, role_rep=update_roles, realm=realm)
411 result["msg"] = f"Roles {update_roles} assigned to userId {uid}."
412 if cid is None:
413 assigned_roles_after = kc.get_realm_user_composite_rolemappings(uid=uid, realm=realm)
414 else:
415 assigned_roles_after = kc.get_client_user_composite_rolemappings(uid=uid, cid=cid, realm=realm)
416 result["end_state"] = assigned_roles_after
417 module.exit_json(**result)
418 else:
419 # Remove mapping of role
420 result["changed"] = True
421 if module._diff:
422 result["diff"] = dict(before={"roles": assigned_roles_before}, after={"roles": update_roles})
423 if module.check_mode:
424 module.exit_json(**result)
425 kc.delete_user_rolemapping(uid=uid, cid=cid, role_rep=update_roles, realm=realm)
426 result["msg"] = f"Roles {update_roles} removed from userId {uid}."
427 if cid is None:
428 assigned_roles_after = kc.get_realm_user_composite_rolemappings(uid=uid, realm=realm)
429 else:
430 assigned_roles_after = kc.get_client_user_composite_rolemappings(uid=uid, cid=cid, realm=realm)
431 result["end_state"] = assigned_roles_after
432 module.exit_json(**result)
433 # Do nothing
434 else:
435 result["changed"] = False
436 result["msg"] = f"Nothing to do, roles {roles} are correctly mapped to user for username {target_username}."
437 module.exit_json(**result)
438
439
440 if __name__ == "__main__":
441 main()