Debian Codegraph @

ansible_collections/community/general/plugins/module_utils/_keycloak.py

raw
1 # Copyright (c) 2017, Eike Frost <[email protected]>
2 # BSD 2-Clause license (see LICENSES/BSD-2-Clause.txt)
3 # SPDX-License-Identifier: BSD-2-Clause
4
5 # Note that this module util is **PRIVATE** to the collection. It can have breaking changes at any time.
6 # Do not use this from other collections or standalone plugins/modules!
7
8 from __future__ import annotations
9
10 import copy
11 import json
12 import traceback
13 import typing as t
14 from http import HTTPStatus
15 from urllib.error import HTTPError
16 from urllib.parse import quote, urlencode
17
18 from ansible.module_utils.common.text.converters import to_native, to_text
19 from ansible.module_utils.urls import open_url
20
21 if t.TYPE_CHECKING:
22 from collections.abc import Sequence
23
24 from ansible.module_utils.basic import AnsibleModule
25
26
27 URL_REALM_INFO = "{url}/realms/{realm}"
28 URL_REALMS = "{url}/admin/realms"
29 URL_REALM = "{url}/admin/realms/{realm}"
30 URL_REALM_KEYS_METADATA = "{url}/admin/realms/{realm}/keys"
31
32 URL_LOCALIZATIONS = "{url}/admin/realms/{realm}/localization/{locale}"
33 URL_LOCALIZATION = "{url}/admin/realms/{realm}/localization/{locale}/{key}"
34
35 URL_TOKEN = "{url}/realms/{realm}/protocol/openid-connect/token"
36 URL_CLIENT = "{url}/admin/realms/{realm}/clients/{id}"
37 URL_CLIENTS = "{url}/admin/realms/{realm}/clients"
38
39 URL_CLIENT_ROLES = "{url}/admin/realms/{realm}/clients/{id}/roles"
40 URL_CLIENT_ROLE = "{url}/admin/realms/{realm}/clients/{id}/roles/{name}"
41 URL_CLIENT_ROLE_COMPOSITES = "{url}/admin/realms/{realm}/clients/{id}/roles/{name}/composites"
42
43 URL_CLIENT_ROLE_SCOPE_CLIENTS = "{url}/admin/realms/{realm}/clients/{id}/scope-mappings/clients/{scopeid}"
44 URL_CLIENT_ROLE_SCOPE_REALM = "{url}/admin/realms/{realm}/clients/{id}/scope-mappings/realm"
45
46 URL_REALM_ROLES = "{url}/admin/realms/{realm}/roles"
47 URL_REALM_ROLE = "{url}/admin/realms/{realm}/roles/{name}"
48 URL_REALM_ROLEMAPPINGS = "{url}/admin/realms/{realm}/users/{id}/role-mappings/realm"
49 URL_REALM_ROLEMAPPINGS_AVAILABLE = "{url}/admin/realms/{realm}/users/{id}/role-mappings/realm/available"
50 URL_REALM_ROLEMAPPINGS_COMPOSITE = "{url}/admin/realms/{realm}/users/{id}/role-mappings/realm/composite"
51 URL_REALM_ROLE_COMPOSITES = "{url}/admin/realms/{realm}/roles/{name}/composites"
52
53 URL_ROLES_BY_ID = "{url}/admin/realms/{realm}/roles-by-id/{id}"
54 URL_ROLES_BY_ID_COMPOSITES_CLIENTS = "{url}/admin/realms/{realm}/roles-by-id/{id}/composites/clients/{cid}"
55 URL_ROLES_BY_ID_COMPOSITES = "{url}/admin/realms/{realm}/roles-by-id/{id}/composites"
56
57 URL_CLIENTTEMPLATE = "{url}/admin/realms/{realm}/client-templates/{id}"
58 URL_CLIENTTEMPLATES = "{url}/admin/realms/{realm}/client-templates"
59 URL_GROUPS = "{url}/admin/realms/{realm}/groups"
60 URL_GROUP = "{url}/admin/realms/{realm}/groups/{groupid}"
61 URL_GROUP_CHILDREN = "{url}/admin/realms/{realm}/groups/{groupid}/children"
62
63 URL_CLIENTSCOPES = "{url}/admin/realms/{realm}/client-scopes"
64 URL_CLIENTSCOPE = "{url}/admin/realms/{realm}/client-scopes/{id}"
65 URL_CLIENTSCOPE_PROTOCOLMAPPERS = "{url}/admin/realms/{realm}/client-scopes/{id}/protocol-mappers/models"
66 URL_CLIENTSCOPE_PROTOCOLMAPPER = "{url}/admin/realms/{realm}/client-scopes/{id}/protocol-mappers/models/{mapper_id}"
67
68 URL_DEFAULT_CLIENTSCOPES = "{url}/admin/realms/{realm}/default-default-client-scopes"
69 URL_DEFAULT_CLIENTSCOPE = "{url}/admin/realms/{realm}/default-default-client-scopes/{id}"
70 URL_OPTIONAL_CLIENTSCOPES = "{url}/admin/realms/{realm}/default-optional-client-scopes"
71 URL_OPTIONAL_CLIENTSCOPE = "{url}/admin/realms/{realm}/default-optional-client-scopes/{id}"
72
73 URL_CLIENT_DEFAULT_CLIENTSCOPES = "{url}/admin/realms/{realm}/clients/{cid}/default-client-scopes"
74 URL_CLIENT_DEFAULT_CLIENTSCOPE = "{url}/admin/realms/{realm}/clients/{cid}/default-client-scopes/{id}"
75 URL_CLIENT_OPTIONAL_CLIENTSCOPES = "{url}/admin/realms/{realm}/clients/{cid}/optional-client-scopes"
76 URL_CLIENT_OPTIONAL_CLIENTSCOPE = "{url}/admin/realms/{realm}/clients/{cid}/optional-client-scopes/{id}"
77
78 URL_CLIENT_GROUP_ROLEMAPPINGS = "{url}/admin/realms/{realm}/groups/{id}/role-mappings/clients/{client}"
79 URL_CLIENT_GROUP_ROLEMAPPINGS_AVAILABLE = (
80 "{url}/admin/realms/{realm}/groups/{id}/role-mappings/clients/{client}/available"
81 )
82 URL_CLIENT_GROUP_ROLEMAPPINGS_COMPOSITE = (
83 "{url}/admin/realms/{realm}/groups/{id}/role-mappings/clients/{client}/composite"
84 )
85
86 URL_USERS = "{url}/admin/realms/{realm}/users"
87 URL_USER = "{url}/admin/realms/{realm}/users/{id}"
88 URL_USER_ROLE_MAPPINGS = "{url}/admin/realms/{realm}/users/{id}/role-mappings"
89 URL_USER_REALM_ROLE_MAPPINGS = "{url}/admin/realms/{realm}/users/{id}/role-mappings/realm"
90 URL_USER_CLIENTS_ROLE_MAPPINGS = "{url}/admin/realms/{realm}/users/{id}/role-mappings/clients"
91 URL_USER_CLIENT_ROLE_MAPPINGS = "{url}/admin/realms/{realm}/users/{id}/role-mappings/clients/{client_id}"
92 URL_USER_GROUPS = "{url}/admin/realms/{realm}/users/{id}/groups"
93 URL_USER_GROUP = "{url}/admin/realms/{realm}/users/{id}/groups/{group_id}"
94 URL_EXECUTE_ACTION = "{url}/admin/realms/{realm}/users/{user_id}/execute-actions-email"
95
96 URL_CLIENT_SERVICE_ACCOUNT_USER = "{url}/admin/realms/{realm}/clients/{id}/service-account-user"
97 URL_CLIENT_USER_ROLEMAPPINGS = "{url}/admin/realms/{realm}/users/{id}/role-mappings/clients/{client}"
98 URL_CLIENT_USER_ROLEMAPPINGS_AVAILABLE = (
99 "{url}/admin/realms/{realm}/users/{id}/role-mappings/clients/{client}/available"
100 )
101 URL_CLIENT_USER_ROLEMAPPINGS_COMPOSITE = (
102 "{url}/admin/realms/{realm}/users/{id}/role-mappings/clients/{client}/composite"
103 )
104
105 URL_REALM_GROUP_ROLEMAPPINGS = "{url}/admin/realms/{realm}/groups/{group}/role-mappings/realm"
106
107 URL_CLIENTSECRET = "{url}/admin/realms/{realm}/clients/{id}/client-secret"
108
109 URL_AUTHENTICATION_AUTHENTICATOR_PROVIDERS = "{url}/admin/realms/{realm}/authentication/authenticator-providers"
110 URL_AUTHENTICATION_FLOWS = "{url}/admin/realms/{realm}/authentication/flows"
111 URL_AUTHENTICATION_FLOW = "{url}/admin/realms/{realm}/authentication/flows/{id}"
112 URL_AUTHENTICATION_FLOW_COPY = "{url}/admin/realms/{realm}/authentication/flows/{copyfrom}/copy"
113 URL_AUTHENTICATION_FLOW_EXECUTIONS = "{url}/admin/realms/{realm}/authentication/flows/{flowalias}/executions"
114 URL_AUTHENTICATION_FLOW_EXECUTIONS_EXECUTION = (
115 "{url}/admin/realms/{realm}/authentication/flows/{flowalias}/executions/execution"
116 )
117 URL_AUTHENTICATION_FLOW_EXECUTIONS_FLOW = "{url}/admin/realms/{realm}/authentication/flows/{flowalias}/executions/flow"
118 URL_AUTHENTICATION_EXECUTION_CONFIG = "{url}/admin/realms/{realm}/authentication/executions/{id}/config"
119 URL_AUTHENTICATION_EXECUTION_RAISE_PRIORITY = "{url}/admin/realms/{realm}/authentication/executions/{id}/raise-priority"
120 URL_AUTHENTICATION_EXECUTION_LOWER_PRIORITY = "{url}/admin/realms/{realm}/authentication/executions/{id}/lower-priority"
121 URL_AUTHENTICATION_CONFIG = "{url}/admin/realms/{realm}/authentication/config/{id}"
122 URL_AUTHENTICATION_REGISTER_REQUIRED_ACTION = "{url}/admin/realms/{realm}/authentication/register-required-action"
123 URL_AUTHENTICATION_REQUIRED_ACTIONS = "{url}/admin/realms/{realm}/authentication/required-actions"
124 URL_AUTHENTICATION_REQUIRED_ACTIONS_ALIAS = "{url}/admin/realms/{realm}/authentication/required-actions/{alias}"
125
126 URL_IDENTITY_PROVIDERS = "{url}/admin/realms/{realm}/identity-provider/instances"
127 URL_IDENTITY_PROVIDER = "{url}/admin/realms/{realm}/identity-provider/instances/{alias}"
128 URL_IDENTITY_PROVIDER_MAPPERS = "{url}/admin/realms/{realm}/identity-provider/instances/{alias}/mappers"
129 URL_IDENTITY_PROVIDER_MAPPER = "{url}/admin/realms/{realm}/identity-provider/instances/{alias}/mappers/{id}"
130 URL_IDENTITY_PROVIDER_IMPORT = "{url}/admin/realms/{realm}/identity-provider/import-config"
131
132 URL_COMPONENTS = "{url}/admin/realms/{realm}/components"
133 URL_COMPONENT = "{url}/admin/realms/{realm}/components/{id}"
134
135 URL_AUTHZ_AUTHORIZATION_SCOPE = "{url}/admin/realms/{realm}/clients/{client_id}/authz/resource-server/scope/{id}"
136 URL_AUTHZ_AUTHORIZATION_SCOPES = "{url}/admin/realms/{realm}/clients/{client_id}/authz/resource-server/scope"
137
138 # This URL is used for:
139 # - Querying client authorization permissions
140 # - Removing client authorization permissions
141 URL_AUTHZ_POLICIES = "{url}/admin/realms/{realm}/clients/{client_id}/authz/resource-server/policy"
142 URL_AUTHZ_POLICY = "{url}/admin/realms/{realm}/clients/{client_id}/authz/resource-server/policy/{id}"
143
144 URL_AUTHZ_PERMISSION = (
145 "{url}/admin/realms/{realm}/clients/{client_id}/authz/resource-server/permission/{permission_type}/{id}"
146 )
147 URL_AUTHZ_PERMISSIONS = (
148 "{url}/admin/realms/{realm}/clients/{client_id}/authz/resource-server/permission/{permission_type}"
149 )
150
151 URL_AUTHZ_RESOURCES = "{url}/admin/realms/{realm}/clients/{client_id}/authz/resource-server/resource"
152
153 URL_AUTHZ_CUSTOM_POLICY = "{url}/admin/realms/{realm}/clients/{client_id}/authz/resource-server/policy/{policy_type}"
154 URL_AUTHZ_CUSTOM_POLICIES = "{url}/admin/realms/{realm}/clients/{client_id}/authz/resource-server/policy"
155
156
157 def keycloak_argument_spec() -> dict[str, t.Any]:
158 """
159 Returns argument_spec of options common to keycloak_*-modules
160
161 :return: argument_spec dict
162 """
163 return dict(
164 auth_keycloak_url=dict(type="str", aliases=["url"], required=True, no_log=False),
165 auth_client_id=dict(type="str", default="admin-cli"),
166 auth_realm=dict(type="str"),
167 auth_client_secret=dict(type="str", default=None, no_log=True),
168 auth_username=dict(type="str", aliases=["username"]),
169 auth_password=dict(type="str", aliases=["password"], no_log=True),
170 validate_certs=dict(type="bool", default=True),
171 connection_timeout=dict(type="int", default=10),
172 token=dict(type="str", no_log=True),
173 refresh_token=dict(type="str", no_log=True),
174 http_agent=dict(type="str", default="Ansible"),
175 )
176
177
178 def camel(words: str) -> str:
179 return words.split("_")[0] + "".join(x.capitalize() or "_" for x in words.split("_")[1:])
180
181
182 class KeycloakError(Exception):
183 def __init__(self, msg: str, authError: Exception | None = None) -> None:
184 self.msg = msg
185 self.authError = authError
186
187 def __str__(self) -> str:
188 return str(self.msg)
189
190
191 def _token_request(module_params: dict[str, t.Any], payload: dict[str, t.Any]) -> str:
192 """Obtains connection header with token for the authentication,
193 using the provided auth_username/auth_password
194 :param module_params: parameters of the module
195 :param payload:
196 type:
197 dict
198 description:
199 Authentication request payload. Must contain at least
200 'grant_type' and 'client_id', optionally 'client_secret',
201 along with parameters based on 'grant_type'; e.g.,
202 'username'/'password' for type 'password',
203 'refresh_token' for type 'refresh_token'.
204 :return: access token
205 """
206 base_url = module_params["auth_keycloak_url"]
207 if not base_url.lower().startswith(("http", "https")):
208 raise KeycloakError(f"auth_url '{base_url}' should either start with 'http' or 'https'.")
209 auth_realm = module_params.get("auth_realm")
210 auth_url = URL_TOKEN.format(url=base_url, realm=auth_realm)
211 http_agent = module_params.get("http_agent")
212 validate_certs = module_params.get("validate_certs")
213 connection_timeout = module_params.get("connection_timeout")
214
215 try:
216 r = json.loads(
217 open_url(
218 auth_url,
219 method="POST",
220 validate_certs=validate_certs,
221 http_agent=http_agent,
222 timeout=connection_timeout,
223 data=urlencode(payload),
224 ).read()
225 )
226
227 return r["access_token"]
228 except ValueError as e:
229 raise KeycloakError(f"API returned invalid JSON when trying to obtain access token from {auth_url}: {e}") from e
230 except KeyError as e:
231 raise KeycloakError(f"API did not include access_token field in response from {auth_url}") from e
232 except Exception as e:
233 raise KeycloakError(f"Could not obtain access token from {auth_url}: {e}", authError=e) from e
234
235
236 def _request_token_using_credentials(module_params: dict[str, t.Any]) -> str:
237 """Obtains connection header with token for the authentication,
238 using the provided auth_username/auth_password
239 :param module_params: parameters of the module. Must include 'auth_username' and 'auth_password'.
240 :return: connection header
241 """
242 client_id = module_params.get("auth_client_id")
243 auth_username = module_params.get("auth_username")
244 auth_password = module_params.get("auth_password")
245 client_secret = module_params.get("auth_client_secret")
246
247 temp_payload = {
248 "grant_type": "password",
249 "client_id": client_id,
250 "client_secret": client_secret,
251 "username": auth_username,
252 "password": auth_password,
253 }
254 # Remove empty items, for instance missing client_secret
255 payload = {k: v for k, v in temp_payload.items() if v is not None}
256
257 return _token_request(module_params, payload)
258
259
260 def _request_token_using_refresh_token(module_params: dict[str, t.Any]) -> str:
261 """Obtains connection header with token for the authentication,
262 using the provided refresh_token
263 :param module_params: parameters of the module. Must include 'refresh_token'.
264 :return: connection header
265 """
266 client_id = module_params.get("auth_client_id")
267 refresh_token = module_params.get("refresh_token")
268 client_secret = module_params.get("auth_client_secret")
269
270 temp_payload = {
271 "grant_type": "refresh_token",
272 "client_id": client_id,
273 "client_secret": client_secret,
274 "refresh_token": refresh_token,
275 }
276 # Remove empty items, for instance missing client_secret
277 payload = {k: v for k, v in temp_payload.items() if v is not None}
278
279 return _token_request(module_params, payload)
280
281
282 def _request_token_using_client_credentials(module_params: dict[str, t.Any]) -> str:
283 """Obtains connection header with token for the authentication,
284 using the provided auth_client_id and auth_client_secret by grant_type
285 client_credentials. Ensure that the used client uses client authorization
286 with service account roles enabled and required service roles assigned.
287 :param module_params: parameters of the module. Must include 'auth_client_id'
288 and 'auth_client_secret'..
289 :return: connection header
290 """
291 client_id = module_params.get("auth_client_id")
292 client_secret = module_params.get("auth_client_secret")
293
294 temp_payload = {
295 "grant_type": "client_credentials",
296 "client_id": client_id,
297 "client_secret": client_secret,
298 }
299 # Remove empty items, for instance missing client_secret
300 payload = {k: v for k, v in temp_payload.items() if v is not None}
301
302 return _token_request(module_params, payload)
303
304
305 def get_token(module_params: dict[str, t.Any]) -> dict[str, str]:
306 """Obtains connection header with token for the authentication,
307 token already given or obtained from credentials
308 :param module_params: parameters of the module
309 :return: connection header
310 """
311 token = module_params.get("token")
312
313 if token is None:
314 auth_client_id = module_params.get("auth_client_id")
315 auth_client_secret = module_params.get("auth_client_secret")
316 auth_username = module_params.get("auth_username")
317 if auth_client_id is not None and auth_client_secret is not None and auth_username is None:
318 token = _request_token_using_client_credentials(module_params)
319 else:
320 token = _request_token_using_credentials(module_params)
321
322 return {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
323
324
325 def is_struct_included(struct1: object, struct2: object, exclude: Sequence[str] | None = None) -> bool:
326 """
327 This function compare if the first parameter structure is included in the second.
328 The function use every elements of struct1 and validates they are present in the struct2 structure.
329 The two structure does not need to be equals for that function to return true.
330 Each elements are compared recursively.
331 :param struct1:
332 type:
333 dict for the initial call, can be dict, list, bool, int or str for recursive calls
334 description:
335 reference structure
336 :param struct2:
337 type:
338 dict for the initial call, can be dict, list, bool, int or str for recursive calls
339 description:
340 structure to compare with first parameter.
341 :param exclude:
342 type:
343 list
344 description:
345 Key to exclude from the comparison.
346 default: None
347 :return:
348 type:
349 bool
350 description:
351 Return True if all element of dict 1 are present in dict 2, return false otherwise.
352 """
353 if isinstance(struct1, list) and isinstance(struct2, list):
354 if not struct1 and not struct2:
355 return True
356 for item1 in struct1:
357 if isinstance(item1, (list, dict)):
358 for item2 in struct2:
359 if is_struct_included(item1, item2, exclude):
360 break
361 else:
362 return False
363 else:
364 if item1 not in struct2:
365 return False
366 return True
367 elif isinstance(struct1, dict) and isinstance(struct2, dict):
368 if not struct1 and not struct2:
369 return True
370 try:
371 for key in struct1:
372 if not (exclude and key in exclude):
373 if not is_struct_included(struct1[key], struct2[key], exclude):
374 return False
375 except KeyError:
376 return False
377 return True
378 elif isinstance(struct1, bool) and isinstance(struct2, bool):
379 return struct1 == struct2
380 else:
381 return to_text(struct1, "utf-8") == to_text(struct2, "utf-8")
382
383
384 class KeycloakAPI:
385 """Keycloak API access; Keycloak uses OAuth 2.0 to protect its API, an access token for which
386 is obtained through OpenID connect
387 """
388
389 def __init__(self, module: AnsibleModule, connection_header: dict[str, str]) -> None:
390 self.module = module
391 self.baseurl = self.module.params.get("auth_keycloak_url")
392 self.validate_certs = self.module.params.get("validate_certs")
393 self.connection_timeout = self.module.params.get("connection_timeout")
394 self.restheaders = connection_header
395 self.http_agent = self.module.params.get("http_agent")
396
397 def _request(
398 self, url: str, method: str, data: str | bytes | None = None, *, extra_headers: dict[str, str] | None = None
399 ):
400 """Makes a request to Keycloak and returns the raw response.
401 If a 401 is returned, attempts to re-authenticate
402 using first the module's refresh_token (if provided)
403 and then the module's username/password (if provided).
404 On successful re-authentication, the new token is stored
405 in the restheaders for future requests.
406
407 :param url: request path
408 :param method: request method (e.g., 'GET', 'POST', etc.)
409 :param data: (optional) data for request
410 :param extra_headers headers to be sent with request, defaults to self.restheaders
411 :return: raw API response
412 """
413
414 def make_request_catching_401(headers: dict[str, str]) -> object | HTTPError:
415 try:
416 return open_url(
417 url,
418 method=method,
419 data=data,
420 http_agent=self.http_agent,
421 headers=headers,
422 timeout=self.connection_timeout,
423 validate_certs=self.validate_certs,
424 )
425 except HTTPError as e:
426 if e.code != HTTPStatus.UNAUTHORIZED:
427 raise e
428 return e
429
430 headers = self.restheaders
431 if extra_headers is not None:
432 headers = headers.copy()
433 headers.update(extra_headers)
434
435 r = make_request_catching_401(headers)
436
437 if isinstance(r, Exception):
438 # Try to refresh token and retry, if available
439 refresh_token = self.module.params.get("refresh_token")
440 if refresh_token is not None:
441 try:
442 token = _request_token_using_refresh_token(self.module.params)
443 self.restheaders["Authorization"] = f"Bearer {token}"
444
445 r = make_request_catching_401(headers)
446 except KeycloakError as e:
447 # Token refresh returns 400 if token is expired/invalid, so continue on if we get a 400
448 if e.authError is not None and e.authError.code != HTTPStatus.BAD_REQUEST: # type: ignore # TODO!
449 raise e
450
451 if isinstance(r, Exception):
452 # Try to re-auth with username/password, if available
453 auth_username = self.module.params.get("auth_username")
454 auth_password = self.module.params.get("auth_password")
455 if auth_username is not None and auth_password is not None:
456 token = _request_token_using_credentials(self.module.params)
457 self.restheaders["Authorization"] = f"Bearer {token}"
458
459 r = make_request_catching_401(headers)
460
461 if isinstance(r, Exception):
462 # Try to re-auth with client_id and client_secret, if available
463 auth_client_id = self.module.params.get("auth_client_id")
464 auth_client_secret = self.module.params.get("auth_client_secret")
465 if auth_client_id is not None and auth_client_secret is not None:
466 try:
467 token = _request_token_using_client_credentials(self.module.params)
468 self.restheaders["Authorization"] = f"Bearer {token}"
469
470 r = make_request_catching_401(headers)
471 except KeycloakError as e:
472 # Token refresh returns 400 if token is expired/invalid, so continue on if we get a 400
473 if e.authError is not None and e.authError.code != HTTPStatus.BAD_REQUEST: # type: ignore # TODO!
474 raise e
475
476 if isinstance(r, Exception):
477 # Either no re-auth options were available, or they all failed
478 raise r
479
480 return r
481
482 def _request_and_deserialize(self, url: str, method: str, data: str | bytes | None = None):
483 """Wraps the _request method with JSON deserialization of the response.
484
485 :param url: request path
486 :param method: request method (e.g., 'GET', 'POST', etc.)
487 :param data: (optional) data for request
488 :return: raw API response
489 """
490 return json.loads(self._request(url, method, data).read())
491
492 def get_realm_info_by_id(self, realm: str = "master") -> dict[str, t.Any] | None:
493 """Obtain realm public info by id
494
495 :param realm: realm id
496 :return: dict of real, representation or None if none matching exist
497 """
498 realm_info_url = URL_REALM_INFO.format(url=self.baseurl, realm=realm)
499
500 try:
501 return self._request_and_deserialize(realm_info_url, method="GET")
502
503 except HTTPError as e:
504 if e.code == HTTPStatus.NOT_FOUND:
505 return None
506 else:
507 self.fail_request(e, msg=f"Could not obtain realm {realm}: {e}", exception=traceback.format_exc())
508 except ValueError as e:
509 self.module.fail_json(
510 msg=f"API returned incorrect JSON when trying to obtain realm {realm}: {e}",
511 exception=traceback.format_exc(),
512 )
513 except Exception as e:
514 self.module.fail_json(msg=f"Could not obtain realm {realm}: {e}", exception=traceback.format_exc())
515
516 def get_realm_keys_metadata_by_id(self, realm: str = "master") -> dict[str, t.Any] | None:
517 """Obtain realm public info by id
518
519 :param realm: realm id
520
521 :return: None, or a 'KeysMetadataRepresentation'
522 (https://www.keycloak.org/docs-api/latest/rest-api/index.html#KeysMetadataRepresentation)
523 -- a dict containing the keys 'active' and 'keys', the former containing a mapping
524 from algorithms to key-ids, the latter containing a list of dicts with key
525 information.
526 """
527 realm_keys_metadata_url = URL_REALM_KEYS_METADATA.format(url=self.baseurl, realm=realm)
528
529 try:
530 return self._request_and_deserialize(realm_keys_metadata_url, method="GET")
531
532 except HTTPError as e:
533 if e.code == HTTPStatus.NOT_FOUND:
534 return None
535 else:
536 self.fail_request(e, msg=f"Could not obtain realm {realm}: {e}", exception=traceback.format_exc())
537 except ValueError as e:
538 self.module.fail_json(
539 msg=f"API returned incorrect JSON when trying to obtain realm {realm}: {e}",
540 exception=traceback.format_exc(),
541 )
542 except Exception as e:
543 self.module.fail_json(msg=f"Could not obtain realm {realm}: {e}", exception=traceback.format_exc())
544
545 # The Keycloak API expects the realm name (like `master`) not the ID when fetching the realm data.
546 # See the Keycloak API docs: https://www.keycloak.org/docs-api/latest/rest-api/#_realms_admin
547 def get_realm_by_id(self, realm: str = "master") -> dict[str, t.Any] | None:
548 """Obtain realm representation by id
549
550 :param realm: realm id
551 :return: dict of real, representation or None if none matching exist
552 """
553 realm_url = URL_REALM.format(url=self.baseurl, realm=realm)
554
555 try:
556 return self._request_and_deserialize(realm_url, method="GET")
557
558 except HTTPError as e:
559 if e.code == HTTPStatus.NOT_FOUND:
560 return None
561 else:
562 self.fail_request(e, msg=f"Could not obtain realm {realm}: {e}", exception=traceback.format_exc())
563 except ValueError as e:
564 self.module.fail_json(
565 msg=f"API returned incorrect JSON when trying to obtain realm {realm}: {e}",
566 exception=traceback.format_exc(),
567 )
568 except Exception as e:
569 self.module.fail_json(msg=f"Could not obtain realm {realm}: {e}", exception=traceback.format_exc())
570
571 def update_realm(self, realmrep, realm: str = "master"):
572 """Update an existing realm
573 :param realmrep: corresponding (partial/full) realm representation with updates
574 :param realm: realm to be updated in Keycloak
575 :return: HTTPResponse object on success
576 """
577 realm_url = URL_REALM.format(url=self.baseurl, realm=realm)
578
579 try:
580 return self._request(realm_url, method="PUT", data=json.dumps(realmrep))
581 except Exception as e:
582 self.fail_request(e, msg=f"Could not update realm {realm}: {e}", exception=traceback.format_exc())
583
584 def create_realm(self, realmrep):
585 """Create a realm in keycloak
586 :param realmrep: Realm representation of realm to be created.
587 :return: HTTPResponse object on success
588 """
589 realm_url = URL_REALMS.format(url=self.baseurl)
590
591 try:
592 return self._request(realm_url, method="POST", data=json.dumps(realmrep))
593 except Exception as e:
594 self.fail_request(e, msg=f"Could not create realm {realmrep['id']}: {e}", exception=traceback.format_exc())
595
596 def delete_realm(self, realm: str = "master"):
597 """Delete a realm from Keycloak
598
599 :param realm: realm to be deleted
600 :return: HTTPResponse object on success
601 """
602 realm_url = URL_REALM.format(url=self.baseurl, realm=realm)
603
604 try:
605 return self._request(realm_url, method="DELETE")
606 except Exception as e:
607 self.fail_request(e, msg=f"Could not delete realm {realm}: {e}", exception=traceback.format_exc())
608
609 def get_localization_values(self, locale: str, realm: str = "master") -> dict[str, str]:
610 """
611 Get all localization overrides for a given realm and locale.
612
613 :param locale: Locale code (for example, 'en', 'fi', 'de').
614 :param realm: Realm name. Defaults to 'master'.
615
616 :return: Mapping of localization keys to override values.
617
618 :raise KeycloakError: Wrapped HTTP/JSON error with context
619 """
620 realm_url = URL_LOCALIZATIONS.format(url=self.baseurl, realm=realm, locale=locale)
621
622 try:
623 return self._request_and_deserialize(realm_url, method="GET")
624 except Exception as e:
625 self.fail_request(
626 e,
627 msg=f"Could not read localization overrides for realm {realm}, locale {locale}: {e}",
628 exception=traceback.format_exc(),
629 )
630
631 def set_localization_value(self, locale: str, key: str, value: str, realm: str = "master"):
632 """
633 Create or update a single localization override for the given key.
634
635 :param locale: Locale code (for example, 'en').
636 :param key: Localization message key to set.
637 :param value: Override value to set.
638 :param realm: Realm name. Defaults to 'master'.
639
640 :return: HTTPResponse: Response object on success.
641
642 :raise KeycloakError: Wrapped HTTP error with context
643 """
644 realm_url = URL_LOCALIZATION.format(url=self.baseurl, realm=realm, locale=locale, key=key)
645
646 headers = {}
647 headers["Content-Type"] = "text/plain; charset=utf-8"
648
649 try:
650 return self._request(realm_url, method="PUT", data=to_native(value), extra_headers=headers)
651 except Exception as e:
652 self.fail_request(
653 e,
654 msg=f"Could not set localization value in realm {realm}, locale {locale}: {key}={value}: {e}",
655 exception=traceback.format_exc(),
656 )
657
658 def delete_localization_value(self, locale: str, key: str, realm: str = "master"):
659 """
660 Delete a single localization override key for the given locale.
661
662 :param locale: Locale code (for example, 'en').
663 :param key: Localization message key to delete.
664 :param realm: Realm name. Defaults to 'master'.
665
666 :return: HTTPResponse: Response object on success.
667
668 :raise KeycloakError: Wrapped HTTP error with context
669 """
670 realm_url = URL_LOCALIZATION.format(url=self.baseurl, realm=realm, locale=locale, key=key)
671
672 try:
673 return self._request(realm_url, method="DELETE")
674 except Exception as e:
675 self.fail_request(
676 e,
677 msg=f"Could not delete localization value in realm {realm}, locale {locale}, key {key}: {e}",
678 exception=traceback.format_exc(),
679 )
680
681 def get_clients(self, realm: str = "master", filter=None):
682 """Obtains client representations for clients in a realm
683
684 :param realm: realm to be queried
685 :param filter: if defined, only the client with clientId specified in the filter is returned
686 :return: list of dicts of client representations
687 """
688 clientlist_url = URL_CLIENTS.format(url=self.baseurl, realm=realm)
689 if filter is not None:
690 clientlist_url += f"?clientId={filter}"
691
692 try:
693 return self._request_and_deserialize(clientlist_url, method="GET")
694 except ValueError as e:
695 self.module.fail_json(
696 msg=f"API returned incorrect JSON when trying to obtain list of clients for realm {realm}: {e}"
697 )
698 except Exception as e:
699 self.fail_request(e, msg=f"Could not obtain list of clients for realm {realm}: {e}")
700
701 def get_client_by_clientid(self, client_id, realm: str = "master"):
702 """Get client representation by clientId
703 :param client_id: The clientId to be queried
704 :param realm: realm from which to obtain the client representation
705 :return: dict with a client representation or None if none matching exist
706 """
707 r = self.get_clients(realm=realm, filter=client_id)
708 if len(r) > 0:
709 return r[0]
710 else:
711 return None
712
713 def get_client_by_id(self, id, realm: str = "master"):
714 """Obtain client representation by id
715
716 :param id: id (not clientId) of client to be queried
717 :param realm: client from this realm
718 :return: dict of client representation or None if none matching exist
719 """
720 client_url = URL_CLIENT.format(url=self.baseurl, realm=realm, id=id)
721
722 try:
723 return self._request_and_deserialize(client_url, method="GET")
724
725 except HTTPError as e:
726 if e.code == HTTPStatus.NOT_FOUND:
727 return None
728 else:
729 self.fail_request(e, msg=f"Could not obtain client {id} for realm {realm}: {e}")
730 except ValueError as e:
731 self.module.fail_json(
732 msg=f"API returned incorrect JSON when trying to obtain client {id} for realm {realm}: {e}"
733 )
734 except Exception as e:
735 self.module.fail_json(msg=f"Could not obtain client {id} for realm {realm}: {e}")
736
737 def get_client_id(self, client_id, realm: str = "master"):
738 """Obtain id of client by client_id
739
740 :param client_id: client_id of client to be queried
741 :param realm: client template from this realm
742 :return: id of client (usually a UUID)
743 """
744 result = self.get_client_by_clientid(client_id, realm)
745 if isinstance(result, dict) and "id" in result:
746 return result["id"]
747 else:
748 return None
749
750 def update_client(self, id, clientrep, realm: str = "master"):
751 """Update an existing client
752 :param id: id (not clientId) of client to be updated in Keycloak
753 :param clientrep: corresponding (partial/full) client representation with updates
754 :param realm: realm the client is in
755 :return: HTTPResponse object on success
756 """
757 client_url = URL_CLIENT.format(url=self.baseurl, realm=realm, id=id)
758
759 try:
760 return self._request(client_url, method="PUT", data=json.dumps(clientrep))
761 except Exception as e:
762 self.fail_request(e, msg=f"Could not update client {id} in realm {realm}: {e}")
763
764 def create_client(self, clientrep, realm: str = "master"):
765 """Create a client in keycloak
766 :param clientrep: Client representation of client to be created. Must at least contain field clientId.
767 :param realm: realm for client to be created.
768 :return: HTTPResponse object on success
769 """
770 client_url = URL_CLIENTS.format(url=self.baseurl, realm=realm)
771
772 try:
773 return self._request(client_url, method="POST", data=json.dumps(clientrep))
774 except Exception as e:
775 self.fail_request(e, msg=f"Could not create client {clientrep['clientId']} in realm {realm}: {e}")
776
777 def delete_client(self, id, realm: str = "master"):
778 """Delete a client from Keycloak
779
780 :param id: id (not clientId) of client to be deleted
781 :param realm: realm of client to be deleted
782 :return: HTTPResponse object on success
783 """
784 client_url = URL_CLIENT.format(url=self.baseurl, realm=realm, id=id)
785
786 try:
787 return self._request(client_url, method="DELETE")
788 except Exception as e:
789 self.fail_request(e, msg=f"Could not delete client {id} in realm {realm}: {e}")
790
791 def get_client_roles_by_id(self, cid, realm: str = "master"):
792 """Fetch the roles of the a client on the Keycloak server.
793
794 :param cid: ID of the client from which to obtain the rolemappings.
795 :param realm: Realm from which to obtain the rolemappings.
796 :return: The rollemappings of specified group and client of the realm (default "master").
797 """
798 client_roles_url = URL_CLIENT_ROLES.format(url=self.baseurl, realm=realm, id=cid)
799 try:
800 return self._request_and_deserialize(client_roles_url, method="GET")
801 except Exception as e:
802 self.fail_request(e, msg=f"Could not fetch rolemappings for client {cid} in realm {realm}: {e}")
803
804 def get_client_role_id_by_name(self, cid, name, realm: str = "master"):
805 """Get the role ID of a client.
806
807 :param cid: ID of the client from which to obtain the rolemappings.
808 :param name: Name of the role.
809 :param realm: Realm from which to obtain the rolemappings.
810 :return: The ID of the role, None if not found.
811 """
812 rolemappings = self.get_client_roles_by_id(cid, realm=realm)
813 for role in rolemappings:
814 if name == role["name"]:
815 return role["id"]
816 return None
817
818 def get_client_group_rolemapping_by_id(self, gid, cid, rid, realm: str = "master"):
819 """Obtain client representation by id
820
821 :param gid: ID of the group from which to obtain the rolemappings.
822 :param cid: ID of the client from which to obtain the rolemappings.
823 :param rid: ID of the role.
824 :param realm: client from this realm
825 :return: dict of rolemapping representation or None if none matching exist
826 """
827 rolemappings_url = URL_CLIENT_GROUP_ROLEMAPPINGS.format(url=self.baseurl, realm=realm, id=gid, client=cid)
828 try:
829 rolemappings = self._request_and_deserialize(rolemappings_url, method="GET")
830 for role in rolemappings:
831 if rid == role["id"]:
832 return role
833 except Exception as e:
834 self.fail_request(
835 e, msg=f"Could not fetch rolemappings for client {cid} in group {gid}, realm {realm}: {e}"
836 )
837 return None
838
839 def get_client_group_available_rolemappings(self, gid, cid, realm: str = "master"):
840 """Fetch the available role of a client in a specified group on the Keycloak server.
841
842 :param gid: ID of the group from which to obtain the rolemappings.
843 :param cid: ID of the client from which to obtain the rolemappings.
844 :param realm: Realm from which to obtain the rolemappings.
845 :return: The rollemappings of specified group and client of the realm (default "master").
846 """
847 available_rolemappings_url = URL_CLIENT_GROUP_ROLEMAPPINGS_AVAILABLE.format(
848 url=self.baseurl, realm=realm, id=gid, client=cid
849 )
850 try:
851 return self._request_and_deserialize(available_rolemappings_url, method="GET")
852 except Exception as e:
853 self.fail_request(
854 e, msg=f"Could not fetch available rolemappings for client {cid} in group {gid}, realm {realm}: {e}"
855 )
856
857 def get_client_group_composite_rolemappings(self, gid, cid, realm: str = "master"):
858 """Fetch the composite role of a client in a specified group on the Keycloak server.
859
860 :param gid: ID of the group from which to obtain the rolemappings.
861 :param cid: ID of the client from which to obtain the rolemappings.
862 :param realm: Realm from which to obtain the rolemappings.
863 :return: The rollemappings of specified group and client of the realm (default "master").
864 """
865 composite_rolemappings_url = URL_CLIENT_GROUP_ROLEMAPPINGS_COMPOSITE.format(
866 url=self.baseurl, realm=realm, id=gid, client=cid
867 )
868 try:
869 return self._request_and_deserialize(composite_rolemappings_url, method="GET")
870 except Exception as e:
871 self.fail_request(
872 e, msg=f"Could not fetch available rolemappings for client {cid} in group {gid}, realm {realm}: {e}"
873 )
874
875 def get_role_by_id(self, rid, realm: str = "master"):
876 """Fetch a role by its id on the Keycloak server.
877
878 :param rid: ID of the role.
879 :param realm: Realm from which to obtain the rolemappings.
880 :return: The role.
881 """
882 client_roles_url = URL_ROLES_BY_ID.format(url=self.baseurl, realm=realm, id=rid)
883 try:
884 return self._request_and_deserialize(client_roles_url, method="GET")
885 except Exception as e:
886 self.fail_request(e, msg=f"Could not fetch role for id {rid} in realm {realm}: {e}")
887
888 def get_client_roles_by_id_composite_rolemappings(self, rid, cid, realm: str = "master"):
889 """Fetch a role by its id on the Keycloak server.
890
891 :param rid: ID of the composite role.
892 :param cid: ID of the client from which to obtain the rolemappings.
893 :param realm: Realm from which to obtain the rolemappings.
894 :return: The role.
895 """
896 client_roles_url = URL_ROLES_BY_ID_COMPOSITES_CLIENTS.format(url=self.baseurl, realm=realm, id=rid, cid=cid)
897 try:
898 return self._request_and_deserialize(client_roles_url, method="GET")
899 except Exception as e:
900 self.fail_request(e, msg=f"Could not fetch role for id {rid} and cid {cid} in realm {realm}: {e}")
901
902 def add_client_roles_by_id_composite_rolemapping(self, rid, roles_rep, realm: str = "master"):
903 """Assign roles to composite role
904
905 :param rid: ID of the composite role.
906 :param roles_rep: Representation of the roles to assign.
907 :param realm: Realm from which to obtain the rolemappings.
908 :return: None.
909 """
910 available_rolemappings_url = URL_ROLES_BY_ID_COMPOSITES.format(url=self.baseurl, realm=realm, id=rid)
911 try:
912 self._request(available_rolemappings_url, method="POST", data=json.dumps(roles_rep))
913 except Exception as e:
914 self.fail_request(e, msg=f"Could not assign roles to composite role {rid} and realm {realm}: {e}")
915
916 def add_group_realm_rolemapping(self, gid, role_rep, realm: str = "master"):
917 """Add the specified realm role to specified group on the Keycloak server.
918
919 :param gid: ID of the group to add the role mapping.
920 :param role_rep: Representation of the role to assign.
921 :param realm: Realm from which to obtain the rolemappings.
922 :return: None.
923 """
924 url = URL_REALM_GROUP_ROLEMAPPINGS.format(url=self.baseurl, realm=realm, group=gid)
925 try:
926 self._request(url, method="POST", data=json.dumps(role_rep))
927 except Exception as e:
928 self.fail_request(e, msg=f"Could add realm role mappings for group {gid}, realm {realm}: {e}")
929
930 def delete_group_realm_rolemapping(self, gid, role_rep, realm: str = "master"):
931 """Delete the specified realm role from the specified group on the Keycloak server.
932
933 :param gid: ID of the group from which to obtain the rolemappings.
934 :param role_rep: Representation of the role to assign.
935 :param realm: Realm from which to obtain the rolemappings.
936 :return: None.
937 """
938 url = URL_REALM_GROUP_ROLEMAPPINGS.format(url=self.baseurl, realm=realm, group=gid)
939 try:
940 self._request(url, method="DELETE", data=json.dumps(role_rep))
941 except Exception as e:
942 self.fail_request(e, msg=f"Could not delete realm role mappings for group {gid}, realm {realm}: {e}")
943
944 def add_group_rolemapping(self, gid, cid, role_rep, realm: str = "master"):
945 """Fetch the composite role of a client in a specified group on the Keycloak server.
946
947 :param gid: ID of the group from which to obtain the rolemappings.
948 :param cid: ID of the client from which to obtain the rolemappings.
949 :param role_rep: Representation of the role to assign.
950 :param realm: Realm from which to obtain the rolemappings.
951 :return: None.
952 """
953 available_rolemappings_url = URL_CLIENT_GROUP_ROLEMAPPINGS.format(
954 url=self.baseurl, realm=realm, id=gid, client=cid
955 )
956 try:
957 self._request(available_rolemappings_url, method="POST", data=json.dumps(role_rep))
958 except Exception as e:
959 self.fail_request(
960 e, msg=f"Could not fetch available rolemappings for client {cid} in group {gid}, realm {realm}: {e}"
961 )
962
963 def delete_group_rolemapping(self, gid, cid, role_rep, realm: str = "master"):
964 """Delete the rolemapping of a client in a specified group on the Keycloak server.
965
966 :param gid: ID of the group from which to obtain the rolemappings.
967 :param cid: ID of the client from which to obtain the rolemappings.
968 :param role_rep: Representation of the role to assign.
969 :param realm: Realm from which to obtain the rolemappings.
970 :return: None.
971 """
972 available_rolemappings_url = URL_CLIENT_GROUP_ROLEMAPPINGS.format(
973 url=self.baseurl, realm=realm, id=gid, client=cid
974 )
975 try:
976 self._request(available_rolemappings_url, method="DELETE", data=json.dumps(role_rep))
977 except Exception as e:
978 self.fail_request(
979 e, msg=f"Could not delete available rolemappings for client {cid} in group {gid}, realm {realm}: {e}"
980 )
981
982 def get_client_user_rolemapping_by_id(self, uid, cid, rid, realm: str = "master"):
983 """Obtain client representation by id
984
985 :param uid: ID of the user from which to obtain the rolemappings.
986 :param cid: ID of the client from which to obtain the rolemappings.
987 :param rid: ID of the role.
988 :param realm: client from this realm
989 :return: dict of rolemapping representation or None if none matching exist
990 """
991 rolemappings_url = URL_CLIENT_USER_ROLEMAPPINGS.format(url=self.baseurl, realm=realm, id=uid, client=cid)
992 try:
993 rolemappings = self._request_and_deserialize(rolemappings_url, method="GET")
994 for role in rolemappings:
995 if rid == role["id"]:
996 return role
997 except Exception as e:
998 self.fail_request(
999 e, msg=f"Could not fetch rolemappings for client {cid} and user {uid}, realm {realm}: {e}"
1000 )
1001 return None
1002
1003 def get_client_user_available_rolemappings(self, uid, cid, realm: str = "master"):
1004 """Fetch the available role of a client for a specified user on the Keycloak server.
1005
1006 :param uid: ID of the user from which to obtain the rolemappings.
1007 :param cid: ID of the client from which to obtain the rolemappings.
1008 :param realm: Realm from which to obtain the rolemappings.
1009 :return: The effective rollemappings of specified client and user of the realm (default "master").
1010 """
1011 available_rolemappings_url = URL_CLIENT_USER_ROLEMAPPINGS_AVAILABLE.format(
1012 url=self.baseurl, realm=realm, id=uid, client=cid
1013 )
1014 try:
1015 return self._request_and_deserialize(available_rolemappings_url, method="GET")
1016 except Exception as e:
1017 self.fail_request(
1018 e, msg=f"Could not fetch effective rolemappings for client {cid} and user {uid}, realm {realm}: {e}"
1019 )
1020
1021 def get_client_user_composite_rolemappings(self, uid, cid, realm: str = "master"):
1022 """Fetch the composite role of a client for a specified user on the Keycloak server.
1023
1024 :param uid: ID of the user from which to obtain the rolemappings.
1025 :param cid: ID of the client from which to obtain the rolemappings.
1026 :param realm: Realm from which to obtain the rolemappings.
1027 :return: The rollemappings of specified group and client of the realm (default "master").
1028 """
1029 composite_rolemappings_url = URL_CLIENT_USER_ROLEMAPPINGS_COMPOSITE.format(
1030 url=self.baseurl, realm=realm, id=uid, client=cid
1031 )
1032 try:
1033 return self._request_and_deserialize(composite_rolemappings_url, method="GET")
1034 except Exception as e:
1035 self.fail_request(e, msg=f"Could not fetch available rolemappings for user {uid} of realm {realm}: {e}")
1036
1037 def get_realm_user_rolemapping_by_id(self, uid, rid, realm: str = "master"):
1038 """Obtain role representation by id
1039
1040 :param uid: ID of the user from which to obtain the rolemappings.
1041 :param rid: ID of the role.
1042 :param realm: client from this realm
1043 :return: dict of rolemapping representation or None if none matching exist
1044 """
1045 rolemappings_url = URL_REALM_ROLEMAPPINGS.format(url=self.baseurl, realm=realm, id=uid)
1046 try:
1047 rolemappings = self._request_and_deserialize(rolemappings_url, method="GET")
1048 for role in rolemappings:
1049 if rid == role["id"]:
1050 return role
1051 except Exception as e:
1052 self.fail_request(e, msg=f"Could not fetch rolemappings for user {uid}, realm {realm}: {e}")
1053 return None
1054
1055 def get_realm_user_available_rolemappings(self, uid, realm: str = "master"):
1056 """Fetch the available role of a realm for a specified user on the Keycloak server.
1057
1058 :param uid: ID of the user from which to obtain the rolemappings.
1059 :param realm: Realm from which to obtain the rolemappings.
1060 :return: The rollemappings of specified group and client of the realm (default "master").
1061 """
1062 available_rolemappings_url = URL_REALM_ROLEMAPPINGS_AVAILABLE.format(url=self.baseurl, realm=realm, id=uid)
1063 try:
1064 return self._request_and_deserialize(available_rolemappings_url, method="GET")
1065 except Exception as e:
1066 self.fail_request(e, msg=f"Could not fetch available rolemappings for user {uid} of realm {realm}: {e}")
1067
1068 def get_realm_user_composite_rolemappings(self, uid, realm: str = "master"):
1069 """Fetch the composite role of a realm for a specified user on the Keycloak server.
1070
1071 :param uid: ID of the user from which to obtain the rolemappings.
1072 :param realm: Realm from which to obtain the rolemappings.
1073 :return: The effective rollemappings of specified client and user of the realm (default "master").
1074 """
1075 composite_rolemappings_url = URL_REALM_ROLEMAPPINGS_COMPOSITE.format(url=self.baseurl, realm=realm, id=uid)
1076 try:
1077 return self._request_and_deserialize(composite_rolemappings_url, method="GET")
1078 except Exception as e:
1079 self.fail_request(e, msg=f"Could not fetch effective rolemappings for user {uid}, realm {realm}: {e}")
1080
1081 def get_user_by_username(self, username, realm: str = "master"):
1082 """Fetch a keycloak user within a realm based on its username.
1083
1084 If the user does not exist, None is returned.
1085 :param username: Username of the user to fetch.
1086 :param realm: Realm in which the user resides; default 'master'
1087 """
1088 users_url = URL_USERS.format(url=self.baseurl, realm=realm)
1089 users_url += f"?username={quote(username, safe='')}&exact=true"
1090 try:
1091 userrep = None
1092 users = self._request_and_deserialize(users_url, method="GET")
1093 for user in users:
1094 if user["username"] == username:
1095 userrep = user
1096 break
1097 return userrep
1098
1099 except ValueError as e:
1100 self.module.fail_json(
1101 msg=f"API returned incorrect JSON when trying to obtain the user for realm {realm} and username {username}: {e}"
1102 )
1103 except Exception as e:
1104 self.fail_request(e, msg=f"Could not obtain the user for realm {realm} and username {username}: {e}")
1105
1106 def get_service_account_user_by_client_id(self, client_id, realm: str = "master"):
1107 """Fetch a keycloak service account user within a realm based on its client_id.
1108
1109 If the user does not exist, None is returned.
1110 :param client_id: clientId of the service account user to fetch.
1111 :param realm: Realm in which the user resides; default 'master'
1112 """
1113 cid = self.get_client_id(client_id, realm=realm)
1114
1115 service_account_user_url = URL_CLIENT_SERVICE_ACCOUNT_USER.format(url=self.baseurl, realm=realm, id=cid)
1116 try:
1117 return self._request_and_deserialize(service_account_user_url, method="GET")
1118 except ValueError as e:
1119 self.module.fail_json(
1120 msg=f"API returned incorrect JSON when trying to obtain the service-account-user for realm {realm} and client_id {client_id}: {e}"
1121 )
1122 except Exception as e:
1123 self.fail_request(
1124 e, msg=f"Could not obtain the service-account-user for realm {realm} and client_id {client_id}: {e}"
1125 )
1126
1127 def add_user_rolemapping(self, uid, cid, role_rep, realm: str = "master"):
1128 """Assign a realm or client role to a specified user on the Keycloak server.
1129
1130 :param uid: ID of the user roles are assigned to.
1131 :param cid: ID of the client from which to obtain the rolemappings. If empty, roles are from the realm
1132 :param role_rep: Representation of the role to assign.
1133 :param realm: Realm from which to obtain the rolemappings.
1134 :return: None.
1135 """
1136 if cid is None:
1137 user_realm_rolemappings_url = URL_REALM_ROLEMAPPINGS.format(url=self.baseurl, realm=realm, id=uid)
1138 try:
1139 self._request(user_realm_rolemappings_url, method="POST", data=json.dumps(role_rep))
1140 except Exception as e:
1141 self.fail_request(
1142 e,
1143 msg=f"Could not map roles to userId {uid} for realm {realm} and roles {json.dumps(role_rep)}: {e}",
1144 )
1145 else:
1146 user_client_rolemappings_url = URL_CLIENT_USER_ROLEMAPPINGS.format(
1147 url=self.baseurl, realm=realm, id=uid, client=cid
1148 )
1149 try:
1150 self._request(user_client_rolemappings_url, method="POST", data=json.dumps(role_rep))
1151 except Exception as e:
1152 self.fail_request(
1153 e,
1154 msg=f"Could not map roles to userId {cid} for client {uid}, realm {realm} and roles {json.dumps(role_rep)}: {e}",
1155 )
1156
1157 def delete_user_rolemapping(self, uid, cid, role_rep, realm: str = "master"):
1158 """Delete the rolemapping of a client in a specified user on the Keycloak server.
1159
1160 :param uid: ID of the user from which to remove the rolemappings.
1161 :param cid: ID of the client from which to remove the rolemappings.
1162 :param role_rep: Representation of the role to remove from rolemappings.
1163 :param realm: Realm from which to remove the rolemappings.
1164 :return: None.
1165 """
1166 if cid is None:
1167 user_realm_rolemappings_url = URL_REALM_ROLEMAPPINGS.format(url=self.baseurl, realm=realm, id=uid)
1168 try:
1169 self._request(user_realm_rolemappings_url, method="DELETE", data=json.dumps(role_rep))
1170 except Exception as e:
1171 self.fail_request(
1172 e, msg=f"Could not remove roles {json.dumps(role_rep)} from userId {uid}, realm {realm}: {e}"
1173 )
1174 else:
1175 user_client_rolemappings_url = URL_CLIENT_USER_ROLEMAPPINGS.format(
1176 url=self.baseurl, realm=realm, id=uid, client=cid
1177 )
1178 try:
1179 self._request(user_client_rolemappings_url, method="DELETE", data=json.dumps(role_rep))
1180 except Exception as e:
1181 self.fail_request(
1182 e,
1183 msg=f"Could not remove roles {json.dumps(role_rep)} for client {cid} from userId {uid}, realm {realm}: {e}",
1184 )
1185
1186 def get_client_templates(self, realm: str = "master"):
1187 """Obtains client template representations for client templates in a realm
1188
1189 :param realm: realm to be queried
1190 :return: list of dicts of client representations
1191 """
1192 url = URL_CLIENTTEMPLATES.format(url=self.baseurl, realm=realm)
1193
1194 try:
1195 return self._request_and_deserialize(url, method="GET")
1196 except ValueError as e:
1197 self.module.fail_json(
1198 msg=f"API returned incorrect JSON when trying to obtain list of client templates for realm {realm}: {e}"
1199 )
1200 except Exception as e:
1201 self.fail_request(e, msg=f"Could not obtain list of client templates for realm {realm}: {e}")
1202
1203 def get_client_template_by_id(self, id, realm: str = "master"):
1204 """Obtain client template representation by id
1205
1206 :param id: id (not name) of client template to be queried
1207 :param realm: client template from this realm
1208 :return: dict of client template representation or None if none matching exist
1209 """
1210 url = URL_CLIENTTEMPLATE.format(url=self.baseurl, id=id, realm=realm)
1211
1212 try:
1213 return self._request_and_deserialize(url, method="GET")
1214 except ValueError as e:
1215 self.module.fail_json(
1216 msg=f"API returned incorrect JSON when trying to obtain client templates {id} for realm {realm}: {e}"
1217 )
1218 except Exception as e:
1219 self.fail_request(e, msg=f"Could not obtain client template {id} for realm {realm}: {e}")
1220
1221 def get_client_template_by_name(self, name, realm: str = "master"):
1222 """Obtain client template representation by name
1223
1224 :param name: name of client template to be queried
1225 :param realm: client template from this realm
1226 :return: dict of client template representation or None if none matching exist
1227 """
1228 result = self.get_client_templates(realm)
1229 if isinstance(result, list):
1230 result = [x for x in result if x["name"] == name]
1231 if len(result) > 0:
1232 return result[0]
1233 return None
1234
1235 def get_client_template_id(self, name, realm: str = "master"):
1236 """Obtain client template id by name
1237
1238 :param name: name of client template to be queried
1239 :param realm: client template from this realm
1240 :return: client template id (usually a UUID)
1241 """
1242 result = self.get_client_template_by_name(name, realm)
1243 if isinstance(result, dict) and "id" in result:
1244 return result["id"]
1245 else:
1246 return None
1247
1248 def update_client_template(self, id, clienttrep, realm: str = "master"):
1249 """Update an existing client template
1250 :param id: id (not name) of client template to be updated in Keycloak
1251 :param clienttrep: corresponding (partial/full) client template representation with updates
1252 :param realm: realm the client template is in
1253 :return: HTTPResponse object on success
1254 """
1255 url = URL_CLIENTTEMPLATE.format(url=self.baseurl, realm=realm, id=id)
1256
1257 try:
1258 return self._request(url, method="PUT", data=json.dumps(clienttrep))
1259 except Exception as e:
1260 self.fail_request(e, msg=f"Could not update client template {id} in realm {realm}: {e}")
1261
1262 def create_client_template(self, clienttrep, realm: str = "master"):
1263 """Create a client in keycloak
1264 :param clienttrep: Client template representation of client template to be created. Must at least contain field name
1265 :param realm: realm for client template to be created in
1266 :return: HTTPResponse object on success
1267 """
1268 url = URL_CLIENTTEMPLATES.format(url=self.baseurl, realm=realm)
1269
1270 try:
1271 return self._request(url, method="POST", data=json.dumps(clienttrep))
1272 except Exception as e:
1273 self.fail_request(e, msg=f"Could not create client template {clienttrep['clientId']} in realm {realm}: {e}")
1274
1275 def delete_client_template(self, id, realm: str = "master"):
1276 """Delete a client template from Keycloak
1277
1278 :param id: id (not name) of client to be deleted
1279 :param realm: realm of client template to be deleted
1280 :return: HTTPResponse object on success
1281 """
1282 url = URL_CLIENTTEMPLATE.format(url=self.baseurl, realm=realm, id=id)
1283
1284 try:
1285 return self._request(url, method="DELETE")
1286 except Exception as e:
1287 self.fail_request(e, msg=f"Could not delete client template {id} in realm {realm}: {e}")
1288
1289 def get_clientscopes(self, realm: str = "master"):
1290 """Fetch the name and ID of all clientscopes on the Keycloak server.
1291
1292 To fetch the full data of the group, make a subsequent call to
1293 get_clientscope_by_clientscopeid, passing in the ID of the group you wish to return.
1294
1295 :param realm: Realm in which the clientscope resides; default 'master'.
1296 :return The clientscopes of this realm (default "master")
1297 """
1298 clientscopes_url = URL_CLIENTSCOPES.format(url=self.baseurl, realm=realm)
1299 try:
1300 return self._request_and_deserialize(clientscopes_url, method="GET")
1301 except Exception as e:
1302 self.fail_request(e, msg=f"Could not fetch list of clientscopes in realm {realm}: {e}")
1303
1304 def get_clientscope_by_clientscopeid(self, cid, realm: str = "master"):
1305 """Fetch a keycloak clientscope from the provided realm using the clientscope's unique ID.
1306
1307 If the clientscope does not exist, None is returned.
1308
1309 gid is a UUID provided by the Keycloak API
1310 :param cid: UUID of the clientscope to be returned
1311 :param realm: Realm in which the clientscope resides; default 'master'.
1312 """
1313 clientscope_url = URL_CLIENTSCOPE.format(url=self.baseurl, realm=realm, id=cid)
1314 try:
1315 return self._request_and_deserialize(clientscope_url, method="GET")
1316
1317 except HTTPError as e:
1318 if e.code == HTTPStatus.NOT_FOUND:
1319 return None
1320 else:
1321 self.fail_request(e, msg=f"Could not fetch clientscope {cid} in realm {realm}: {e}")
1322 except Exception as e:
1323 self.module.fail_json(msg=f"Could not clientscope group {cid} in realm {realm}: {e}")
1324
1325 def get_clientscope_by_name(self, name, realm: str = "master"):
1326 """Fetch a keycloak clientscope within a realm based on its name.
1327
1328 The Keycloak API does not allow filtering of the clientscopes resource by name.
1329 As a result, this method first retrieves the entire list of clientscopes - name and ID -
1330 then performs a second query to fetch the group.
1331
1332 If the clientscope does not exist, None is returned.
1333 :param name: Name of the clientscope to fetch.
1334 :param realm: Realm in which the clientscope resides; default 'master'
1335 """
1336 try:
1337 all_clientscopes = self.get_clientscopes(realm=realm)
1338
1339 for clientscope in all_clientscopes:
1340 if clientscope["name"] == name:
1341 return self.get_clientscope_by_clientscopeid(clientscope["id"], realm=realm)
1342
1343 return None
1344
1345 except Exception as e:
1346 self.module.fail_json(msg=f"Could not fetch clientscope {name} in realm {realm}: {e}")
1347
1348 def create_clientscope(self, clientscoperep, realm: str = "master"):
1349 """Create a Keycloak clientscope.
1350
1351 :param clientscoperep: a ClientScopeRepresentation of the clientscope to be created. Must contain at minimum the field name.
1352 :return: HTTPResponse object on success
1353 """
1354 clientscopes_url = URL_CLIENTSCOPES.format(url=self.baseurl, realm=realm)
1355 try:
1356 return self._request(clientscopes_url, method="POST", data=json.dumps(clientscoperep))
1357 except Exception as e:
1358 self.fail_request(e, msg=f"Could not create clientscope {clientscoperep['name']} in realm {realm}: {e}")
1359
1360 def update_clientscope(self, clientscoperep, realm: str = "master"):
1361 """Update an existing clientscope.
1362
1363 :param grouprep: A GroupRepresentation of the updated group.
1364 :return HTTPResponse object on success
1365 """
1366 clientscope_url = URL_CLIENTSCOPE.format(url=self.baseurl, realm=realm, id=clientscoperep["id"])
1367
1368 try:
1369 return self._request(clientscope_url, method="PUT", data=json.dumps(clientscoperep))
1370
1371 except Exception as e:
1372 self.fail_request(e, msg=f"Could not update clientscope {clientscoperep['name']} in realm {realm}: {e}")
1373
1374 def delete_clientscope(self, name=None, cid=None, realm: str = "master"):
1375 """Delete a clientscope. One of name or cid must be provided.
1376
1377 Providing the clientscope ID is preferred as it avoids a second lookup to
1378 convert a clientscope name to an ID.
1379
1380 :param name: The name of the clientscope. A lookup will be performed to retrieve the clientscope ID.
1381 :param cid: The ID of the clientscope (preferred to name).
1382 :param realm: The realm in which this group resides, default "master".
1383 """
1384
1385 if cid is None and name is None:
1386 # prefer an exception since this is almost certainly a programming error in the module itself.
1387 raise Exception("Unable to delete group - one of group ID or name must be provided.")
1388
1389 # only lookup the name if cid is not provided.
1390 # in the case that both are provided, prefer the ID, since it is one
1391 # less lookup.
1392 if cid is None and name is not None:
1393 for clientscope in self.get_clientscopes(realm=realm):
1394 if clientscope["name"] == name:
1395 cid = clientscope["id"]
1396 break
1397
1398 # if the group doesn't exist - no problem, nothing to delete.
1399 if cid is None:
1400 return None
1401
1402 # should have a good cid by here.
1403 clientscope_url = URL_CLIENTSCOPE.format(realm=realm, id=cid, url=self.baseurl)
1404 try:
1405 return self._request(clientscope_url, method="DELETE")
1406
1407 except Exception as e:
1408 self.fail_request(e, msg=f"Unable to delete clientscope {cid}: {e}")
1409
1410 def get_clientscope_protocolmappers(self, cid, realm: str = "master"):
1411 """Fetch the name and ID of all clientscopes on the Keycloak server.
1412
1413 To fetch the full data of the group, make a subsequent call to
1414 get_clientscope_by_clientscopeid, passing in the ID of the group you wish to return.
1415
1416 :param cid: id of clientscope (not name).
1417 :param realm: Realm in which the clientscope resides; default 'master'.
1418 :return The protocolmappers of this realm (default "master")
1419 """
1420 protocolmappers_url = URL_CLIENTSCOPE_PROTOCOLMAPPERS.format(id=cid, url=self.baseurl, realm=realm)
1421 try:
1422 return self._request_and_deserialize(protocolmappers_url, method="GET")
1423 except Exception as e:
1424 self.fail_request(e, msg=f"Could not fetch list of protocolmappers in realm {realm}: {e}")
1425
1426 def get_clientscope_protocolmapper_by_protocolmapperid(self, pid, cid, realm: str = "master"):
1427 """Fetch a keycloak clientscope from the provided realm using the clientscope's unique ID.
1428
1429 If the clientscope does not exist, None is returned.
1430
1431 gid is a UUID provided by the Keycloak API
1432
1433 :param cid: UUID of the protocolmapper to be returned
1434 :param cid: UUID of the clientscope to be returned
1435 :param realm: Realm in which the clientscope resides; default 'master'.
1436 """
1437 protocolmapper_url = URL_CLIENTSCOPE_PROTOCOLMAPPER.format(url=self.baseurl, realm=realm, id=cid, mapper_id=pid)
1438 try:
1439 return self._request_and_deserialize(protocolmapper_url, method="GET")
1440
1441 except HTTPError as e:
1442 if e.code == HTTPStatus.NOT_FOUND:
1443 return None
1444 else:
1445 self.fail_request(e, msg=f"Could not fetch protocolmapper {pid} in realm {realm}: {e}")
1446 except Exception as e:
1447 self.module.fail_json(msg=f"Could not fetch protocolmapper {cid} in realm {realm}: {e}")
1448
1449 def get_clientscope_protocolmapper_by_name(self, cid, name, realm: str = "master"):
1450 """Fetch a keycloak clientscope within a realm based on its name.
1451
1452 The Keycloak API does not allow filtering of the clientscopes resource by name.
1453 As a result, this method first retrieves the entire list of clientscopes - name and ID -
1454 then performs a second query to fetch the group.
1455
1456 If the clientscope does not exist, None is returned.
1457 :param cid: Id of the clientscope (not name).
1458 :param name: Name of the protocolmapper to fetch.
1459 :param realm: Realm in which the clientscope resides; default 'master'
1460 """
1461 try:
1462 all_protocolmappers = self.get_clientscope_protocolmappers(cid, realm=realm)
1463
1464 for protocolmapper in all_protocolmappers:
1465 if protocolmapper["name"] == name:
1466 return self.get_clientscope_protocolmapper_by_protocolmapperid(
1467 protocolmapper["id"], cid, realm=realm
1468 )
1469
1470 return None
1471
1472 except Exception as e:
1473 self.module.fail_json(msg=f"Could not fetch protocolmapper {name} in realm {realm}: {e}")
1474
1475 def create_clientscope_protocolmapper(self, cid, mapper_rep, realm: str = "master"):
1476 """Create a Keycloak clientscope protocolmapper.
1477
1478 :param cid: Id of the clientscope.
1479 :param mapper_rep: a ProtocolMapperRepresentation of the protocolmapper to be created. Must contain at minimum the field name.
1480 :return: HTTPResponse object on success
1481 """
1482 protocolmappers_url = URL_CLIENTSCOPE_PROTOCOLMAPPERS.format(url=self.baseurl, id=cid, realm=realm)
1483 try:
1484 return self._request(protocolmappers_url, method="POST", data=json.dumps(mapper_rep))
1485 except Exception as e:
1486 self.fail_request(e, msg=f"Could not create protocolmapper {mapper_rep['name']} in realm {realm}: {e}")
1487
1488 def update_clientscope_protocolmappers(self, cid, mapper_rep, realm: str = "master"):
1489 """Update an existing clientscope.
1490
1491 :param cid: Id of the clientscope.
1492 :param mapper_rep: A ProtocolMapperRepresentation of the updated protocolmapper.
1493 :return HTTPResponse object on success
1494 """
1495 protocolmapper_url = URL_CLIENTSCOPE_PROTOCOLMAPPER.format(
1496 url=self.baseurl, realm=realm, id=cid, mapper_id=mapper_rep["id"]
1497 )
1498
1499 try:
1500 return self._request(protocolmapper_url, method="PUT", data=json.dumps(mapper_rep))
1501
1502 except Exception as e:
1503 self.fail_request(
1504 e, msg=f"Could not update protocolmappers for clientscope {mapper_rep} in realm {realm}: {e}"
1505 )
1506
1507 def get_default_clientscopes(self, realm, client_id=None):
1508 """Fetch the name and ID of all clientscopes on the Keycloak server.
1509
1510 To fetch the full data of the client scope, make a subsequent call to
1511 get_clientscope_by_clientscopeid, passing in the ID of the client scope you wish to return.
1512
1513 :param realm: Realm in which the clientscope resides.
1514 :param client_id: The client in which the clientscope resides.
1515 :return The default clientscopes of this realm or client
1516 """
1517 url = URL_DEFAULT_CLIENTSCOPES if client_id is None else URL_CLIENT_DEFAULT_CLIENTSCOPES
1518 return self._get_clientscopes_of_type(realm, url, "default", client_id)
1519
1520 def get_optional_clientscopes(self, realm, client_id=None):
1521 """Fetch the name and ID of all clientscopes on the Keycloak server.
1522
1523 To fetch the full data of the client scope, make a subsequent call to
1524 get_clientscope_by_clientscopeid, passing in the ID of the client scope you wish to return.
1525
1526 :param realm: Realm in which the clientscope resides.
1527 :param client_id: The client in which the clientscope resides.
1528 :return The optional clientscopes of this realm or client
1529 """
1530 url = URL_OPTIONAL_CLIENTSCOPES if client_id is None else URL_CLIENT_OPTIONAL_CLIENTSCOPES
1531 return self._get_clientscopes_of_type(realm, url, "optional", client_id)
1532
1533 def _get_clientscopes_of_type(self, realm, url_template, scope_type, client_id=None):
1534 """Fetch the name and ID of all clientscopes on the Keycloak server.
1535
1536 To fetch the full data of the client scope, make a subsequent call to
1537 get_clientscope_by_clientscopeid, passing in the ID of the client scope you wish to return.
1538
1539 :param realm: Realm in which the clientscope resides.
1540 :param url_template the template for the right type
1541 :param scope_type this can be either optional or default
1542 :param client_id: The client in which the clientscope resides.
1543 :return The clientscopes of the specified type of this realm
1544 """
1545 if client_id is None:
1546 clientscopes_url = url_template.format(url=self.baseurl, realm=realm)
1547 try:
1548 return self._request_and_deserialize(clientscopes_url, method="GET")
1549 except Exception as e:
1550 self.fail_request(e, msg=f"Could not fetch list of {scope_type} clientscopes in realm {realm}: {e}")
1551 else:
1552 cid = self.get_client_id(client_id=client_id, realm=realm)
1553 clientscopes_url = url_template.format(url=self.baseurl, realm=realm, cid=cid)
1554 try:
1555 return self._request_and_deserialize(clientscopes_url, method="GET")
1556 except Exception as e:
1557 self.fail_request(
1558 e,
1559 msg=f"Could not fetch list of {scope_type} clientscopes in client {client_id}: {clientscopes_url}",
1560 )
1561
1562 def _decide_url_type_clientscope(self, client_id=None, scope_type="default"):
1563 """Decides which url to use.
1564 :param scope_type this can be either optional or default
1565 :param client_id: The client in which the clientscope resides.
1566 """
1567 if client_id is None:
1568 if scope_type == "default":
1569 return URL_DEFAULT_CLIENTSCOPE
1570 if scope_type == "optional":
1571 return URL_OPTIONAL_CLIENTSCOPE
1572 else:
1573 if scope_type == "default":
1574 return URL_CLIENT_DEFAULT_CLIENTSCOPE
1575 if scope_type == "optional":
1576 return URL_CLIENT_OPTIONAL_CLIENTSCOPE
1577
1578 def add_default_clientscope(self, id, realm: str = "master", client_id=None):
1579 """Add a client scope as default either on realm or client level.
1580
1581 :param id: Client scope Id.
1582 :param realm: Realm in which the clientscope resides.
1583 :param client_id: The client in which the clientscope resides.
1584 """
1585 self._action_type_clientscope(id, client_id, "default", realm, "add")
1586
1587 def add_optional_clientscope(self, id, realm: str = "master", client_id=None):
1588 """Add a client scope as optional either on realm or client level.
1589
1590 :param id: Client scope Id.
1591 :param realm: Realm in which the clientscope resides.
1592 :param client_id: The client in which the clientscope resides.
1593 """
1594 self._action_type_clientscope(id, client_id, "optional", realm, "add")
1595
1596 def delete_default_clientscope(self, id, realm: str = "master", client_id=None):
1597 """Remove a client scope as default either on realm or client level.
1598
1599 :param id: Client scope Id.
1600 :param realm: Realm in which the clientscope resides.
1601 :param client_id: The client in which the clientscope resides.
1602 """
1603 self._action_type_clientscope(id, client_id, "default", realm, "delete")
1604
1605 def delete_optional_clientscope(self, id, realm: str = "master", client_id=None):
1606 """Remove a client scope as optional either on realm or client level.
1607
1608 :param id: Client scope Id.
1609 :param realm: Realm in which the clientscope resides.
1610 :param client_id: The client in which the clientscope resides.
1611 """
1612 self._action_type_clientscope(id, client_id, "optional", realm, "delete")
1613
1614 def _action_type_clientscope(
1615 self, id=None, client_id=None, scope_type="default", realm: str = "master", action="add"
1616 ):
1617 """Delete or add a clientscope of type.
1618 :param name: The name of the clientscope. A lookup will be performed to retrieve the clientscope ID.
1619 :param client_id: The ID of the clientscope (preferred to name).
1620 :param scope_type 'default' or 'optional'
1621 :param realm: The realm in which this group resides, default "master".
1622 """
1623 cid = None if client_id is None else self.get_client_id(client_id=client_id, realm=realm)
1624 # should have a good cid by here.
1625 clientscope_type_url = self._decide_url_type_clientscope(client_id, scope_type).format(
1626 realm=realm, id=id, cid=cid, url=self.baseurl
1627 )
1628 try:
1629 method = "PUT" if action == "add" else "DELETE"
1630 return self._request(clientscope_type_url, method=method)
1631
1632 except Exception as e:
1633 place = "realm" if client_id is None else f"client {client_id}"
1634 self.fail_request(e, msg=f"Unable to {action} {scope_type} clientscope {id} @ {place} : {e}")
1635
1636 def create_clientsecret(self, id, realm: str = "master"):
1637 """Generate a new client secret by id
1638
1639 :param id: id (not clientId) of client to be queried
1640 :param realm: client from this realm
1641 :return: dict of credential representation
1642 """
1643 clientsecret_url = URL_CLIENTSECRET.format(url=self.baseurl, realm=realm, id=id)
1644
1645 try:
1646 return self._request_and_deserialize(clientsecret_url, method="POST")
1647
1648 except HTTPError as e:
1649 if e.code == HTTPStatus.NOT_FOUND:
1650 return None
1651 else:
1652 self.fail_request(e, msg=f"Could not obtain clientsecret of client {id} for realm {realm}: {e}")
1653 except Exception as e:
1654 self.module.fail_json(msg=f"Could not obtain clientsecret of client {id} for realm {realm}: {e}")
1655
1656 def get_clientsecret(self, id, realm: str = "master"):
1657 """Obtain client secret by id
1658
1659 :param id: id (not clientId) of client to be queried
1660 :param realm: client from this realm
1661 :return: dict of credential representation
1662 """
1663 clientsecret_url = URL_CLIENTSECRET.format(url=self.baseurl, realm=realm, id=id)
1664
1665 try:
1666 return self._request_and_deserialize(clientsecret_url, method="GET")
1667
1668 except HTTPError as e:
1669 if e.code == HTTPStatus.NOT_FOUND:
1670 return None
1671 else:
1672 self.fail_request(e, msg=f"Could not obtain clientsecret of client {id} for realm {realm}: {e}")
1673 except Exception as e:
1674 self.module.fail_json(msg=f"Could not obtain clientsecret of client {id} for realm {realm}: {e}")
1675
1676 def get_groups(self, realm: str = "master"):
1677 """Fetch the name and ID of all groups on the Keycloak server.
1678
1679 To fetch the full data of the group, make a subsequent call to
1680 get_group_by_groupid, passing in the ID of the group you wish to return.
1681
1682 :param realm: Return the groups of this realm (default "master").
1683 """
1684 groups_url = URL_GROUPS.format(url=self.baseurl, realm=realm)
1685 try:
1686 return self._request_and_deserialize(groups_url, method="GET")
1687 except Exception as e:
1688 self.fail_request(e, msg=f"Could not fetch list of groups in realm {realm}: {e}")
1689
1690 def get_group_by_groupid(self, gid, realm: str = "master"):
1691 """Fetch a keycloak group from the provided realm using the group's unique ID.
1692
1693 If the group does not exist, None is returned.
1694
1695 gid is a UUID provided by the Keycloak API
1696 :param gid: UUID of the group to be returned
1697 :param realm: Realm in which the group resides; default 'master'.
1698 """
1699 groups_url = URL_GROUP.format(url=self.baseurl, realm=realm, groupid=gid)
1700 try:
1701 return self._request_and_deserialize(groups_url, method="GET")
1702 except HTTPError as e:
1703 if e.code == HTTPStatus.NOT_FOUND:
1704 return None
1705 else:
1706 self.fail_request(e, msg=f"Could not fetch group {gid} in realm {realm}: {e}")
1707 except Exception as e:
1708 self.module.fail_json(msg=f"Could not fetch group {gid} in realm {realm}: {e}")
1709
1710 def get_subgroups(self, parent, realm: str = "master"):
1711 if "subGroupCount" in parent:
1712 # Since version 23, when GETting a group Keycloak does not
1713 # return subGroups but only a subGroupCount.
1714 # Children must be fetched in a second request.
1715 if parent["subGroupCount"] == 0:
1716 group_children = []
1717 else:
1718 group_children_url = f"{URL_GROUP_CHILDREN.format(url=self.baseurl, realm=realm, groupid=parent['id'])}?max={parent['subGroupCount']}"
1719 group_children = self._request_and_deserialize(group_children_url, method="GET")
1720 subgroups = group_children
1721 else:
1722 subgroups = parent["subGroups"]
1723 return subgroups
1724
1725 def get_group_by_name(self, name, realm: str = "master", parents=None):
1726 """Fetch a keycloak group within a realm based on its name.
1727
1728 Uses the Keycloak search API with exact matching for efficient lookup
1729 instead of fetching all groups.
1730
1731 If the group does not exist, None is returned.
1732 :param name: Name of the group to fetch.
1733 :param realm: Realm in which the group resides; default 'master'
1734 :param parents: Optional list of parents when group to look for is a subgroup
1735 """
1736 try:
1737 if parents:
1738 parent = self.get_subgroup_direct_parent(parents, realm)
1739
1740 if not parent:
1741 return None
1742
1743 # For subgroups: use children endpoint with search parameter
1744 search_url = "{url}?search={name}&exact=true".format(
1745 url=URL_GROUP_CHILDREN.format(url=self.baseurl, realm=realm, groupid=parent["id"]),
1746 name=quote(name, safe=""),
1747 )
1748 else:
1749 # For top-level groups: use groups endpoint with search parameter
1750 search_url = "{url}?search={name}&exact=true".format(
1751 url=URL_GROUPS.format(url=self.baseurl, realm=realm), name=quote(name, safe="")
1752 )
1753
1754 groups = self._request_and_deserialize(search_url, method="GET")
1755
1756 # exact=true should return only exact matches, but verify the name
1757 for group in groups:
1758 if group["name"] == name:
1759 return self.get_group_by_groupid(group["id"], realm=realm)
1760
1761 return None
1762
1763 except Exception as e:
1764 self.module.fail_json(msg=f"Could not fetch group {name} in realm {realm}: {e}")
1765
1766 def _get_normed_group_parent(self, parent):
1767 """Converts parent dict information into a more easy to use form.
1768
1769 :param parent: parent describing dict
1770 """
1771 if parent["id"]:
1772 return (parent["id"], True)
1773
1774 return (parent["name"], False)
1775
1776 def get_subgroup_by_chain(self, name_chain, realm: str = "master"):
1777 """Access a subgroup API object by walking down a given name/id chain.
1778
1779 Groups can be given either as by name or by ID, the first element
1780 must either be a toplvl group or given as ID, all parents must exist.
1781
1782 If the group cannot be found, None is returned.
1783 :param name_chain: Topdown ordered list of subgroup parent (ids or names) + its own name at the end
1784 :param realm: Realm in which the group resides; default 'master'
1785 """
1786 cp = name_chain[0]
1787
1788 # for 1st parent in chain we must query the server
1789 cp, is_id = self._get_normed_group_parent(cp)
1790
1791 if is_id:
1792 tmp = self.get_group_by_groupid(cp, realm=realm)
1793 else:
1794 # given as name, assume toplvl group
1795 tmp = self.get_group_by_name(cp, realm=realm)
1796
1797 if not tmp:
1798 return None
1799
1800 for p in name_chain[1:]:
1801 for sg in self.get_subgroups(tmp, realm):
1802 pv, is_id = self._get_normed_group_parent(p)
1803
1804 if is_id:
1805 cmpkey = "id"
1806 else:
1807 cmpkey = "name"
1808
1809 if pv == sg[cmpkey]:
1810 tmp = sg
1811 break
1812
1813 if not tmp:
1814 return None
1815
1816 return tmp
1817
1818 def get_subgroup_direct_parent(self, parents, realm: str = "master", children_to_resolve=None):
1819 """Get keycloak direct parent group API object for a given chain of parents.
1820
1821 To successfully work the API for subgroups we actually don't need
1822 to "walk the whole tree" for nested groups but only need to know
1823 the ID for the direct predecessor of current subgroup. This
1824 method will guarantee us this information getting there with
1825 as minimal work as possible.
1826
1827 Note that given parent list can and might be incomplete at the
1828 upper levels as long as it starts with an ID instead of a name
1829
1830 If the group does not exist, None is returned.
1831 :param parents: Topdown ordered list of subgroup parents
1832 :param realm: Realm in which the group resides; default 'master'
1833 """
1834 if children_to_resolve is None:
1835 # start recursion by reversing parents (in optimal cases
1836 # we dont need to walk the whole tree upwarts)
1837 parents = list(reversed(parents))
1838 children_to_resolve = []
1839
1840 if not parents:
1841 # walk complete parents list to the top, all names, no id's,
1842 # try to resolve it assuming list is complete and 1st
1843 # element is a toplvl group
1844 return self.get_subgroup_by_chain(list(reversed(children_to_resolve)), realm=realm)
1845
1846 cp = parents[0]
1847 unused, is_id = self._get_normed_group_parent(cp)
1848
1849 if is_id:
1850 # current parent is given as ID, we can stop walking
1851 # upwards searching for an entry point
1852 return self.get_subgroup_by_chain([cp] + list(reversed(children_to_resolve)), realm=realm)
1853 else:
1854 # current parent is given as name, it must be resolved
1855 # later, try next parent (recurse)
1856 children_to_resolve.append(cp)
1857 return self.get_subgroup_direct_parent(parents[1:], realm=realm, children_to_resolve=children_to_resolve)
1858
1859 def create_group(self, grouprep, realm: str = "master"):
1860 """Create a Keycloak group.
1861
1862 :param grouprep: a GroupRepresentation of the group to be created. Must contain at minimum the field name.
1863 :return: HTTPResponse object on success
1864 """
1865 groups_url = URL_GROUPS.format(url=self.baseurl, realm=realm)
1866 try:
1867 return self._request(groups_url, method="POST", data=json.dumps(grouprep))
1868 except Exception as e:
1869 self.fail_request(e, msg=f"Could not create group {grouprep['name']} in realm {realm}: {e}")
1870
1871 def create_subgroup(self, parents, grouprep, realm: str = "master"):
1872 """Create a Keycloak subgroup.
1873
1874 :param parents: list of one or more parent groups
1875 :param grouprep: a GroupRepresentation of the group to be created. Must contain at minimum the field name.
1876 :return: HTTPResponse object on success
1877 """
1878 parent_id = "---UNDETERMINED---"
1879 try:
1880 parent_id = self.get_subgroup_direct_parent(parents, realm)
1881
1882 if not parent_id:
1883 raise Exception(
1884 "Could not determine subgroup parent ID for given"
1885 f" parent chain {parents}. Assure that all parents exist"
1886 " already and the list is complete and properly"
1887 " ordered, starts with an ID or starts at the"
1888 " top level"
1889 )
1890
1891 parent_id = parent_id["id"]
1892 url = URL_GROUP_CHILDREN.format(url=self.baseurl, realm=realm, groupid=parent_id)
1893 return self._request(url, method="POST", data=json.dumps(grouprep))
1894 except Exception as e:
1895 self.fail_request(
1896 e,
1897 msg=f"Could not create subgroup {grouprep['name']} for parent group {parent_id} in realm {realm}: {e}",
1898 )
1899
1900 def update_group(self, grouprep, realm: str = "master"):
1901 """Update an existing group.
1902
1903 :param grouprep: A GroupRepresentation of the updated group.
1904 :return HTTPResponse object on success
1905 """
1906 group_url = URL_GROUP.format(url=self.baseurl, realm=realm, groupid=grouprep["id"])
1907
1908 try:
1909 return self._request(group_url, method="PUT", data=json.dumps(grouprep))
1910 except Exception as e:
1911 self.fail_request(e, msg=f"Could not update group {grouprep['name']} in realm {realm}: {e}")
1912
1913 def delete_group(self, name=None, groupid=None, realm: str = "master"):
1914 """Delete a group. One of name or groupid must be provided.
1915
1916 Providing the group ID is preferred as it avoids a second lookup to
1917 convert a group name to an ID.
1918
1919 :param name: The name of the group. A lookup will be performed to retrieve the group ID.
1920 :param groupid: The ID of the group (preferred to name).
1921 :param realm: The realm in which this group resides, default "master".
1922 """
1923
1924 if groupid is None and name is None:
1925 # prefer an exception since this is almost certainly a programming error in the module itself.
1926 raise Exception("Unable to delete group - one of group ID or name must be provided.")
1927
1928 # only lookup the name if groupid isn't provided.
1929 # in the case that both are provided, prefer the ID, since it is one
1930 # less lookup.
1931 if groupid is None and name is not None:
1932 for group in self.get_groups(realm=realm):
1933 if group["name"] == name:
1934 groupid = group["id"]
1935 break
1936
1937 # if the group doesn't exist - no problem, nothing to delete.
1938 if groupid is None:
1939 return None
1940
1941 # should have a good groupid by here.
1942 group_url = URL_GROUP.format(realm=realm, groupid=groupid, url=self.baseurl)
1943 try:
1944 return self._request(group_url, method="DELETE")
1945 except Exception as e:
1946 self.fail_request(e, msg=f"Unable to delete group {groupid}: {e}")
1947
1948 def get_realm_roles(self, realm: str = "master"):
1949 """Obtains role representations for roles in a realm
1950
1951 :param realm: realm to be queried
1952 :return: list of dicts of role representations
1953 """
1954 rolelist_url = URL_REALM_ROLES.format(url=self.baseurl, realm=realm)
1955 try:
1956 return self._request_and_deserialize(rolelist_url, method="GET")
1957 except ValueError as e:
1958 self.module.fail_json(
1959 msg=f"API returned incorrect JSON when trying to obtain list of roles for realm {realm}: {e}"
1960 )
1961 except Exception as e:
1962 self.fail_request(e, msg=f"Could not obtain list of roles for realm {realm}: {e}")
1963
1964 def get_realm_role(self, name, realm: str = "master"):
1965 """Fetch a keycloak role from the provided realm using the role's name.
1966
1967 If the role does not exist, None is returned.
1968 :param name: Name of the role to fetch.
1969 :param realm: Realm in which the role resides; default 'master'.
1970 """
1971 role_url = URL_REALM_ROLE.format(url=self.baseurl, realm=realm, name=quote(name, safe=""))
1972 try:
1973 return self._request_and_deserialize(role_url, method="GET")
1974 except HTTPError as e:
1975 if e.code == HTTPStatus.NOT_FOUND:
1976 return None
1977 else:
1978 self.fail_request(e, msg=f"Could not fetch role {name} in realm {realm}: {e}")
1979 except Exception as e:
1980 self.module.fail_json(msg=f"Could not fetch role {name} in realm {realm}: {e}")
1981
1982 def create_realm_role(self, rolerep, realm: str = "master"):
1983 """Create a Keycloak realm role.
1984
1985 :param rolerep: a RoleRepresentation of the role to be created. Must contain at minimum the field name.
1986 :return: HTTPResponse object on success
1987 """
1988 roles_url = URL_REALM_ROLES.format(url=self.baseurl, realm=realm)
1989 try:
1990 if "composites" in rolerep:
1991 keycloak_compatible_composites = self.convert_role_composites(rolerep["composites"])
1992 rolerep["composites"] = keycloak_compatible_composites
1993 return self._request(roles_url, method="POST", data=json.dumps(rolerep))
1994 except Exception as e:
1995 self.fail_request(e, msg=f"Could not create role {rolerep['name']} in realm {realm}: {e}")
1996
1997 def update_realm_role(self, rolerep, realm: str = "master"):
1998 """Update an existing realm role.
1999
2000 :param rolerep: A RoleRepresentation of the updated role.
2001 :return HTTPResponse object on success
2002 """
2003 role_url = URL_REALM_ROLE.format(url=self.baseurl, realm=realm, name=quote(rolerep["name"]), safe="")
2004 try:
2005 composites = None
2006 if "composites" in rolerep:
2007 composites = copy.deepcopy(rolerep["composites"])
2008 del rolerep["composites"]
2009 role_response = self._request(role_url, method="PUT", data=json.dumps(rolerep))
2010 if composites is not None:
2011 self.update_role_composites(rolerep=rolerep, composites=composites, realm=realm)
2012 return role_response
2013 except Exception as e:
2014 self.fail_request(e, msg=f"Could not update role {rolerep['name']} in realm {realm}: {e}")
2015
2016 def get_role_composites(self, rolerep, clientid=None, realm: str = "master"):
2017 composite_url = ""
2018 try:
2019 if clientid is not None:
2020 client = self.get_client_by_clientid(client_id=clientid, realm=realm)
2021 cid = client["id"]
2022 composite_url = URL_CLIENT_ROLE_COMPOSITES.format(
2023 url=self.baseurl, realm=realm, id=cid, name=quote(rolerep["name"], safe="")
2024 )
2025 else:
2026 composite_url = URL_REALM_ROLE_COMPOSITES.format(
2027 url=self.baseurl, realm=realm, name=quote(rolerep["name"], safe="")
2028 )
2029 # Get existing composites
2030 return self._request_and_deserialize(composite_url, method="GET")
2031 except Exception as e:
2032 self.fail_request(e, msg=f"Could not get role {rolerep['name']} composites in realm {realm}: {e}")
2033
2034 def create_role_composites(self, rolerep, composites, clientid=None, realm: str = "master"):
2035 composite_url = ""
2036 try:
2037 if clientid is not None:
2038 client = self.get_client_by_clientid(client_id=clientid, realm=realm)
2039 cid = client["id"]
2040 composite_url = URL_CLIENT_ROLE_COMPOSITES.format(
2041 url=self.baseurl, realm=realm, id=cid, name=quote(rolerep["name"], safe="")
2042 )
2043 else:
2044 composite_url = URL_REALM_ROLE_COMPOSITES.format(
2045 url=self.baseurl, realm=realm, name=quote(rolerep["name"], safe="")
2046 )
2047 # Get existing composites
2048 # create new composites
2049 return self._request(composite_url, method="POST", data=json.dumps(composites))
2050 except Exception as e:
2051 self.fail_request(e, msg=f"Could not create role {rolerep['name']} composites in realm {realm}: {e}")
2052
2053 def delete_role_composites(self, rolerep, composites, clientid=None, realm: str = "master"):
2054 composite_url = ""
2055 try:
2056 if clientid is not None:
2057 client = self.get_client_by_clientid(client_id=clientid, realm=realm)
2058 cid = client["id"]
2059 composite_url = URL_CLIENT_ROLE_COMPOSITES.format(
2060 url=self.baseurl, realm=realm, id=cid, name=quote(rolerep["name"], safe="")
2061 )
2062 else:
2063 composite_url = URL_REALM_ROLE_COMPOSITES.format(
2064 url=self.baseurl, realm=realm, name=quote(rolerep["name"], safe="")
2065 )
2066 # Get existing composites
2067 # create new composites
2068 return self._request(composite_url, method="DELETE", data=json.dumps(composites))
2069 except Exception as e:
2070 self.fail_request(e, msg=f"Could not create role {rolerep['name']} composites in realm {realm}: {e}")
2071
2072 def update_role_composites(self, rolerep, composites, clientid=None, realm: str = "master"):
2073 # Get existing composites
2074 existing_composites = self.get_role_composites(rolerep=rolerep, clientid=clientid, realm=realm)
2075 composites_to_be_created = []
2076 composites_to_be_deleted = []
2077 for composite in composites:
2078 composite_found = False
2079 existing_composite_client = None
2080 for existing_composite in existing_composites:
2081 if existing_composite["clientRole"]:
2082 existing_composite_client = self.get_client_by_id(existing_composite["containerId"], realm=realm)
2083 if (
2084 "client_id" in composite
2085 and composite["client_id"] is not None
2086 and existing_composite_client["clientId"] == composite["client_id"]
2087 and composite["name"] == existing_composite["name"]
2088 ):
2089 composite_found = True
2090 break
2091 else:
2092 if ("client_id" not in composite or composite["client_id"] is None) and composite[
2093 "name"
2094 ] == existing_composite["name"]:
2095 composite_found = True
2096 break
2097 if not composite_found and ("state" not in composite or composite["state"] == "present"):
2098 if "client_id" in composite and composite["client_id"] is not None:
2099 client_roles = self.get_client_roles(clientid=composite["client_id"], realm=realm)
2100 for client_role in client_roles:
2101 if client_role["name"] == composite["name"]:
2102 composites_to_be_created.append(client_role)
2103 break
2104 else:
2105 realm_role = self.get_realm_role(name=composite["name"], realm=realm)
2106 composites_to_be_created.append(realm_role)
2107 elif composite_found and "state" in composite and composite["state"] == "absent":
2108 if "client_id" in composite and composite["client_id"] is not None:
2109 client_roles = self.get_client_roles(clientid=composite["client_id"], realm=realm)
2110 for client_role in client_roles:
2111 if client_role["name"] == composite["name"]:
2112 composites_to_be_deleted.append(client_role)
2113 break
2114 else:
2115 realm_role = self.get_realm_role(name=composite["name"], realm=realm)
2116 composites_to_be_deleted.append(realm_role)
2117
2118 if len(composites_to_be_created) > 0:
2119 # create new composites
2120 self.create_role_composites(
2121 rolerep=rolerep, composites=composites_to_be_created, clientid=clientid, realm=realm
2122 )
2123 if len(composites_to_be_deleted) > 0:
2124 # delete new composites
2125 self.delete_role_composites(
2126 rolerep=rolerep, composites=composites_to_be_deleted, clientid=clientid, realm=realm
2127 )
2128
2129 def delete_realm_role(self, name, realm: str = "master"):
2130 """Delete a realm role.
2131
2132 :param name: The name of the role.
2133 :param realm: The realm in which this role resides, default "master".
2134 """
2135 role_url = URL_REALM_ROLE.format(url=self.baseurl, realm=realm, name=quote(name, safe=""))
2136 try:
2137 return self._request(role_url, method="DELETE")
2138 except Exception as e:
2139 self.fail_request(e, msg=f"Unable to delete role {name} in realm {realm}: {e}")
2140
2141 def get_client_roles(self, clientid, realm: str = "master"):
2142 """Obtains role representations for client roles in a specific client
2143
2144 :param clientid: Client id to be queried
2145 :param realm: Realm to be queried
2146 :return: List of dicts of role representations
2147 """
2148 cid = self.get_client_id(clientid, realm=realm)
2149 if cid is None:
2150 self.module.fail_json(msg=f"Could not find client {clientid} in realm {realm}")
2151 rolelist_url = URL_CLIENT_ROLES.format(url=self.baseurl, realm=realm, id=cid)
2152 try:
2153 return self._request_and_deserialize(rolelist_url, method="GET")
2154 except ValueError as e:
2155 self.module.fail_json(
2156 msg=f"API returned incorrect JSON when trying to obtain list of roles for client {clientid} in realm {realm}: {e}"
2157 )
2158 except Exception as e:
2159 self.fail_request(e, msg=f"Could not obtain list of roles for client {clientid} in realm {realm}: {e}")
2160
2161 def get_client_role(self, name, clientid, realm: str = "master"):
2162 """Fetch a keycloak client role from the provided realm using the role's name.
2163
2164 :param name: Name of the role to fetch.
2165 :param clientid: Client id for the client role
2166 :param realm: Realm in which the role resides
2167 :return: Dict of role representation
2168 If the role does not exist, None is returned.
2169 """
2170 cid = self.get_client_id(clientid, realm=realm)
2171 if cid is None:
2172 self.module.fail_json(msg=f"Could not find client {clientid} in realm {realm}")
2173 role_url = URL_CLIENT_ROLE.format(url=self.baseurl, realm=realm, id=cid, name=quote(name, safe=""))
2174 try:
2175 return self._request_and_deserialize(role_url, method="GET")
2176 except HTTPError as e:
2177 if e.code == HTTPStatus.NOT_FOUND:
2178 return None
2179 else:
2180 self.fail_request(e, msg=f"Could not fetch role {name} in client {clientid} of realm {realm}: {e}")
2181 except Exception as e:
2182 self.module.fail_json(msg=f"Could not fetch role {name} for client {clientid} in realm {realm}: {e}")
2183
2184 def create_client_role(self, rolerep, clientid, realm: str = "master"):
2185 """Create a Keycloak client role.
2186
2187 :param rolerep: a RoleRepresentation of the role to be created. Must contain at minimum the field name.
2188 :param clientid: Client id for the client role
2189 :param realm: Realm in which the role resides
2190 :return: HTTPResponse object on success
2191 """
2192 cid = self.get_client_id(clientid, realm=realm)
2193 if cid is None:
2194 self.module.fail_json(msg=f"Could not find client {clientid} in realm {realm}")
2195 roles_url = URL_CLIENT_ROLES.format(url=self.baseurl, realm=realm, id=cid)
2196 try:
2197 if "composites" in rolerep:
2198 keycloak_compatible_composites = self.convert_role_composites(rolerep["composites"])
2199 rolerep["composites"] = keycloak_compatible_composites
2200 return self._request(roles_url, method="POST", data=json.dumps(rolerep))
2201 except Exception as e:
2202 self.fail_request(
2203 e, msg=f"Could not create role {rolerep['name']} for client {clientid} in realm {realm}: {e}"
2204 )
2205
2206 def convert_role_composites(self, composites):
2207 keycloak_compatible_composites = {"client": {}, "realm": []}
2208 for composite in composites:
2209 if "state" not in composite or composite["state"] == "present":
2210 if "client_id" in composite and composite["client_id"] is not None:
2211 if composite["client_id"] not in keycloak_compatible_composites["client"]:
2212 keycloak_compatible_composites["client"][composite["client_id"]] = []
2213 keycloak_compatible_composites["client"][composite["client_id"]].append(composite["name"])
2214 else:
2215 keycloak_compatible_composites["realm"].append(composite["name"])
2216 return keycloak_compatible_composites
2217
2218 def update_client_role(self, rolerep, clientid, realm: str = "master"):
2219 """Update an existing client role.
2220
2221 :param rolerep: A RoleRepresentation of the updated role.
2222 :param clientid: Client id for the client role
2223 :param realm: Realm in which the role resides
2224 :return HTTPResponse object on success
2225 """
2226 cid = self.get_client_id(clientid, realm=realm)
2227 if cid is None:
2228 self.module.fail_json(msg=f"Could not find client {clientid} in realm {realm}")
2229 role_url = URL_CLIENT_ROLE.format(url=self.baseurl, realm=realm, id=cid, name=quote(rolerep["name"], safe=""))
2230 try:
2231 composites = None
2232 if "composites" in rolerep:
2233 composites = copy.deepcopy(rolerep["composites"])
2234 del rolerep["composites"]
2235 update_role_response = self._request(role_url, method="PUT", data=json.dumps(rolerep))
2236 if composites is not None:
2237 self.update_role_composites(rolerep=rolerep, clientid=clientid, composites=composites, realm=realm)
2238 return update_role_response
2239 except Exception as e:
2240 self.fail_request(
2241 e, msg=f"Could not update role {rolerep['name']} for client {clientid} in realm {realm}: {e}"
2242 )
2243
2244 def delete_client_role(self, name, clientid, realm: str = "master"):
2245 """Delete a role. One of name or roleid must be provided.
2246
2247 :param name: The name of the role.
2248 :param clientid: Client id for the client role
2249 :param realm: Realm in which the role resides
2250 """
2251 cid = self.get_client_id(clientid, realm=realm)
2252 if cid is None:
2253 self.module.fail_json(msg=f"Could not find client {clientid} in realm {realm}")
2254 role_url = URL_CLIENT_ROLE.format(url=self.baseurl, realm=realm, id=cid, name=quote(name, safe=""))
2255 try:
2256 return self._request(role_url, method="DELETE")
2257 except Exception as e:
2258 self.fail_request(e, msg=f"Unable to delete role {name} for client {clientid} in realm {realm}: {e}")
2259
2260 def get_authenticator_providers(self, realm: str = "master"):
2261 """
2262 Get all available authenticator providers of the realm.
2263 :param realm: Realm.
2264 :return: List of authenticator provider representations.
2265 """
2266 try:
2267 return self._request_and_deserialize(
2268 URL_AUTHENTICATION_AUTHENTICATOR_PROVIDERS.format(url=self.baseurl, realm=realm), method="GET"
2269 )
2270 except Exception as e:
2271 self.fail_request(e, msg=f"Unable get authenticator providers in realm {realm}: {e}")
2272
2273 def get_authentication_flow_by_alias(self, alias, realm: str = "master"):
2274 """
2275 Get an authentication flow by its alias
2276 :param alias: Alias of the authentication flow to get.
2277 :param realm: Realm.
2278 :return: Authentication flow representation.
2279 """
2280 try:
2281 authentication_flow = {}
2282 # Check if the authentication flow exists on the Keycloak serveraders
2283 authentications = json.load(
2284 self._request(URL_AUTHENTICATION_FLOWS.format(url=self.baseurl, realm=realm), method="GET")
2285 )
2286 for authentication in authentications:
2287 if authentication["alias"] == alias:
2288 authentication_flow = authentication
2289 break
2290 return authentication_flow
2291 except Exception as e:
2292 self.fail_request(e, msg=f"Unable get authentication flow {alias}: {e}")
2293
2294 def get_authentication_flow_by_id(self, id, realm: str = "master"):
2295 """
2296 Get an authentication flow by its id
2297 :param id: id of the authentication flow to get.
2298 :param realm: Realm.
2299 :return: Authentication flow representation.
2300 """
2301 flow_url = URL_AUTHENTICATION_FLOW.format(url=self.baseurl, realm=realm, id=id)
2302
2303 try:
2304 return json.load(self._request(flow_url, method="GET"))
2305 except Exception as e:
2306 self.fail_request(e, msg=f"Could not get authentication flow {id} in realm {realm}: {e}")
2307
2308 def update_authentication_flow(self, id, config, realm: str = "master"):
2309 """
2310 Updates an authentication flow
2311 :param id: id of the authentication flow to update.
2312 :param config: Authentication flow configuration.
2313 :param realm: Realm.
2314 :return: Authentication flow representation.
2315 """
2316 flow_url = URL_AUTHENTICATION_FLOW.format(url=self.baseurl, realm=realm, id=id)
2317
2318 try:
2319 return self._request(flow_url, method="PUT", data=json.dumps(config))
2320 except Exception as e:
2321 self.fail_request(e, msg=f"Could not get authentication flow {id} in realm {realm}: {e}")
2322
2323 def delete_authentication_flow_by_id(self, id, realm: str = "master"):
2324 """
2325 Delete an authentication flow from Keycloak
2326 :param id: id of authentication flow to be deleted
2327 :param realm: realm of client to be deleted
2328 :return: HTTPResponse object on success
2329 """
2330 flow_url = URL_AUTHENTICATION_FLOW.format(url=self.baseurl, realm=realm, id=id)
2331
2332 try:
2333 return self._request(flow_url, method="DELETE")
2334 except Exception as e:
2335 self.fail_request(e, msg=f"Could not delete authentication flow {id} in realm {realm}: {e}")
2336
2337 def copy_auth_flow(self, config, realm: str = "master"):
2338 """
2339 Create a new authentication flow from a copy of another.
2340 :param config: Representation of the authentication flow to create.
2341 :param realm: Realm.
2342 :return: Representation of the new authentication flow.
2343 """
2344 try:
2345 new_name = dict(newName=config["alias"])
2346 self._request(
2347 URL_AUTHENTICATION_FLOW_COPY.format(
2348 url=self.baseurl, realm=realm, copyfrom=quote(config["copyFrom"], safe="")
2349 ),
2350 method="POST",
2351 data=json.dumps(new_name),
2352 )
2353 flow_list = json.load(
2354 self._request(URL_AUTHENTICATION_FLOWS.format(url=self.baseurl, realm=realm), method="GET")
2355 )
2356 for flow in flow_list:
2357 if flow["alias"] == config["alias"]:
2358 return flow
2359 return None
2360 except Exception as e:
2361 self.fail_request(e, msg=f"Could not copy authentication flow {config['alias']} in realm {realm}: {e}")
2362
2363 def create_empty_auth_flow(self, config, realm: str = "master"):
2364 """
2365 Create a new empty authentication flow.
2366 :param config: Representation of the authentication flow to create.
2367 :param realm: Realm.
2368 :return: Representation of the new authentication flow.
2369 """
2370 try:
2371 new_flow = dict(
2372 alias=config["alias"], providerId=config["providerId"], description=config["description"], topLevel=True
2373 )
2374 self._request(
2375 URL_AUTHENTICATION_FLOWS.format(url=self.baseurl, realm=realm), method="POST", data=json.dumps(new_flow)
2376 )
2377 flow_list = json.load(
2378 self._request(URL_AUTHENTICATION_FLOWS.format(url=self.baseurl, realm=realm), method="GET")
2379 )
2380 for flow in flow_list:
2381 if flow["alias"] == config["alias"]:
2382 return flow
2383 return None
2384 except Exception as e:
2385 self.fail_request(
2386 e, msg=f"Could not create empty authentication flow {config['alias']} in realm {realm}: {e}"
2387 )
2388
2389 def update_authentication_executions(self, flowAlias, updatedExec, realm: str = "master"):
2390 """Update authentication executions
2391
2392 :param flowAlias: name of the parent flow
2393 :param updatedExec: JSON containing updated execution
2394 :return: HTTPResponse object on success
2395 """
2396 try:
2397 self._request(
2398 URL_AUTHENTICATION_FLOW_EXECUTIONS.format(
2399 url=self.baseurl, realm=realm, flowalias=quote(flowAlias, safe="")
2400 ),
2401 method="PUT",
2402 data=json.dumps(updatedExec),
2403 )
2404 except HTTPError as e:
2405 self.fail_request(
2406 e,
2407 msg=f"Unable to update execution '{flowAlias}': {e!r}: {e.url};{e.msg};{e.code};{e.hdrs} {updatedExec}",
2408 )
2409 except Exception as e:
2410 self.module.fail_json(msg=f"Unable to update executions {updatedExec}: {e}")
2411
2412 def add_authenticationConfig_to_execution(self, executionId, authenticationConfig, realm: str = "master"):
2413 """Add autenticatorConfig to the execution
2414
2415 :param executionId: id of execution
2416 :param authenticationConfig: config to add to the execution
2417 :return: HTTPResponse object on success
2418 """
2419 try:
2420 self._request(
2421 URL_AUTHENTICATION_EXECUTION_CONFIG.format(url=self.baseurl, realm=realm, id=executionId),
2422 method="POST",
2423 data=json.dumps(authenticationConfig),
2424 )
2425 except Exception as e:
2426 self.fail_request(e, msg=f"Unable to add authenticationConfig {executionId}: {e}")
2427
2428 def update_authentication_config(self, configId, authenticationConfig, realm: str = "master"):
2429 """
2430 Updates an authentication config
2431 :param configId: id of the authentication config
2432 :param authenticationConfig: The authentication config
2433 :param realm: realm of authentication config
2434 """
2435 try:
2436 self._request(
2437 URL_AUTHENTICATION_CONFIG.format(url=self.baseurl, realm=realm, id=configId),
2438 method="PUT",
2439 data=json.dumps(authenticationConfig),
2440 )
2441 except Exception as e:
2442 self.fail_request(e, msg=f"Unable to update the authentication config {configId}: {e}")
2443
2444 def delete_authentication_config(self, configId, realm: str = "master"):
2445 """Delete authenticator config
2446
2447 :param configId: id of authentication config
2448 :param realm: realm of authentication config to be deleted
2449 """
2450 try:
2451 # Send a DELETE request to remove the specified authentication config from the Keycloak server.
2452 self._request(URL_AUTHENTICATION_CONFIG.format(url=self.baseurl, realm=realm, id=configId), method="DELETE")
2453 except Exception as e:
2454 self.fail_request(e, msg=f"Unable to delete authentication config {configId}: {e}")
2455
2456 def create_subflow(self, subflowName, flowAlias, realm: str = "master", flowType="basic-flow"):
2457 """Create new sublow on the flow
2458
2459 :param subflowName: name of the subflow to create
2460 :param flowAlias: name of the parent flow
2461 :return: HTTPResponse object on success
2462 """
2463 try:
2464 newSubFlow = {}
2465 newSubFlow["alias"] = subflowName
2466 newSubFlow["provider"] = "registration-page-form"
2467 newSubFlow["type"] = flowType
2468 self._request(
2469 URL_AUTHENTICATION_FLOW_EXECUTIONS_FLOW.format(
2470 url=self.baseurl, realm=realm, flowalias=quote(flowAlias, safe="")
2471 ),
2472 method="POST",
2473 data=json.dumps(newSubFlow),
2474 )
2475 except Exception as e:
2476 self.fail_request(e, msg=f"Unable to create new subflow {subflowName}: {e}")
2477
2478 def create_execution(self, execution, flowAlias, realm: str = "master"):
2479 """Create new execution on the flow
2480
2481 :param execution: name of execution to create
2482 :param flowAlias: name of the parent flow
2483 :return: HTTPResponse object on success
2484 """
2485 try:
2486 newExec = {}
2487 newExec["provider"] = execution["providerId"]
2488 newExec["requirement"] = execution["requirement"]
2489 self._request(
2490 URL_AUTHENTICATION_FLOW_EXECUTIONS_EXECUTION.format(
2491 url=self.baseurl, realm=realm, flowalias=quote(flowAlias, safe="")
2492 ),
2493 method="POST",
2494 data=json.dumps(newExec),
2495 )
2496 except HTTPError as e:
2497 self.fail_request(
2498 e,
2499 msg=f"Unable to create new execution '{flowAlias}' {execution['providerId']}: {e!r}: {e.url};{e.msg};{e.code};{e.hdrs} {newExec}",
2500 )
2501 except Exception as e:
2502 self.module.fail_json(msg=f"Unable to create new execution '{flowAlias}' {execution['providerId']}: {e}")
2503
2504 def change_execution_priority(self, executionId, diff, realm: str = "master"):
2505 """Raise or lower execution priority of diff time
2506
2507 :param executionId: id of execution to lower priority
2508 :param realm: realm the client is in
2509 :param diff: Integer number, raise of diff time if positive lower of diff time if negative
2510 :return: HTTPResponse object on success
2511 """
2512 try:
2513 if diff > 0:
2514 for _i in range(diff):
2515 self._request(
2516 URL_AUTHENTICATION_EXECUTION_RAISE_PRIORITY.format(
2517 url=self.baseurl, realm=realm, id=executionId
2518 ),
2519 method="POST",
2520 )
2521 elif diff < 0:
2522 for _i in range(-diff):
2523 self._request(
2524 URL_AUTHENTICATION_EXECUTION_LOWER_PRIORITY.format(
2525 url=self.baseurl, realm=realm, id=executionId
2526 ),
2527 method="POST",
2528 )
2529 except Exception as e:
2530 self.fail_request(e, msg=f"Unable to change execution priority {executionId}: {e}")
2531
2532 def get_executions_representation(self, config, realm: str = "master"):
2533 """
2534 Get a representation of the executions for an authentication flow.
2535 :param config: Representation of the authentication flow
2536 :param realm: Realm
2537 :return: Representation of the executions
2538 """
2539 try:
2540 # Get executions created
2541 executions = json.load(
2542 self._request(
2543 URL_AUTHENTICATION_FLOW_EXECUTIONS.format(
2544 url=self.baseurl, realm=realm, flowalias=quote(config["alias"], safe="")
2545 ),
2546 method="GET",
2547 )
2548 )
2549 for execution in executions:
2550 if "authenticationConfig" in execution:
2551 execConfigId = execution["authenticationConfig"]
2552 execConfig = json.load(
2553 self._request(
2554 URL_AUTHENTICATION_CONFIG.format(url=self.baseurl, realm=realm, id=execConfigId),
2555 method="GET",
2556 )
2557 )
2558 execution["authenticationConfig"] = execConfig
2559 return executions
2560 except Exception as e:
2561 self.fail_request(
2562 e, msg=f"Could not get executions for authentication flow {config['alias']} in realm {realm}: {e}"
2563 )
2564
2565 def get_required_actions(self, realm: str = "master"):
2566 """
2567 Get required actions.
2568 :param realm: Realm name (not id).
2569 :return: List of representations of the required actions.
2570 """
2571
2572 try:
2573 required_actions = json.load(
2574 self._request(URL_AUTHENTICATION_REQUIRED_ACTIONS.format(url=self.baseurl, realm=realm), method="GET")
2575 )
2576
2577 return required_actions
2578 except Exception:
2579 return None
2580
2581 def register_required_action(self, rep, realm: str = "master"):
2582 """
2583 Register required action.
2584 :param rep: JSON containing 'providerId', and 'name' attributes.
2585 :param realm: Realm name (not id).
2586 :return: Representation of the required action.
2587 """
2588
2589 data = {"name": rep["name"], "providerId": rep["providerId"]}
2590
2591 try:
2592 return self._request(
2593 URL_AUTHENTICATION_REGISTER_REQUIRED_ACTION.format(url=self.baseurl, realm=realm),
2594 method="POST",
2595 data=json.dumps(data),
2596 )
2597 except Exception as e:
2598 self.fail_request(e, msg=f"Unable to register required action {rep['name']} in realm {realm}: {e}")
2599
2600 def update_required_action(self, alias, rep, realm: str = "master"):
2601 """
2602 Update required action.
2603 :param alias: Alias of required action.
2604 :param rep: JSON describing new state of required action.
2605 :param realm: Realm name (not id).
2606 :return: HTTPResponse object on success.
2607 """
2608
2609 try:
2610 return self._request(
2611 URL_AUTHENTICATION_REQUIRED_ACTIONS_ALIAS.format(
2612 url=self.baseurl, alias=quote(alias, safe=""), realm=realm
2613 ),
2614 method="PUT",
2615 data=json.dumps(rep),
2616 )
2617 except Exception as e:
2618 self.fail_request(e, msg=f"Unable to update required action {alias} in realm {realm}: {e}")
2619
2620 def delete_required_action(self, alias, realm: str = "master"):
2621 """
2622 Delete required action.
2623 :param alias: Alias of required action.
2624 :param realm: Realm name (not id).
2625 :return: HTTPResponse object on success.
2626 """
2627
2628 try:
2629 return self._request(
2630 URL_AUTHENTICATION_REQUIRED_ACTIONS_ALIAS.format(
2631 url=self.baseurl, alias=quote(alias, safe=""), realm=realm
2632 ),
2633 method="DELETE",
2634 )
2635 except Exception as e:
2636 self.fail_request(e, msg=f"Unable to delete required action {alias} in realm {realm}: {e}")
2637
2638 def get_identity_providers(self, realm: str = "master"):
2639 """Fetch representations for identity providers in a realm
2640 :param realm: realm to be queried
2641 :return: list of representations for identity providers
2642 """
2643 idps_url = URL_IDENTITY_PROVIDERS.format(url=self.baseurl, realm=realm)
2644 try:
2645 return self._request_and_deserialize(idps_url, method="GET")
2646 except ValueError as e:
2647 self.module.fail_json(
2648 msg=f"API returned incorrect JSON when trying to obtain list of identity providers for realm {realm}: {e}"
2649 )
2650 except Exception as e:
2651 self.fail_request(e, msg=f"Could not obtain list of identity providers for realm {realm}: {e}")
2652
2653 def get_identity_provider(self, alias, realm: str = "master"):
2654 """Fetch identity provider representation from a realm using the idp's alias.
2655 If the identity provider does not exist, None is returned.
2656 :param alias: Alias of the identity provider to fetch.
2657 :param realm: Realm in which the identity provider resides; default 'master'.
2658 """
2659 idp_url = URL_IDENTITY_PROVIDER.format(url=self.baseurl, realm=realm, alias=alias)
2660 try:
2661 return self._request_and_deserialize(idp_url, method="GET")
2662 except HTTPError as e:
2663 if e.code == HTTPStatus.NOT_FOUND:
2664 return None
2665 else:
2666 self.fail_request(e, msg=f"Could not fetch identity provider {alias} in realm {realm}: {e}")
2667 except Exception as e:
2668 self.module.fail_json(msg=f"Could not fetch identity provider {alias} in realm {realm}: {e}")
2669
2670 def create_identity_provider(self, idprep, realm: str = "master"):
2671 """Create an identity provider.
2672 :param idprep: Identity provider representation of the idp to be created.
2673 :param realm: Realm in which this identity provider resides, default "master".
2674 :return: HTTPResponse object on success
2675 """
2676 idps_url = URL_IDENTITY_PROVIDERS.format(url=self.baseurl, realm=realm)
2677 try:
2678 return self._request(idps_url, method="POST", data=json.dumps(idprep))
2679 except Exception as e:
2680 self.fail_request(e, msg=f"Could not create identity provider {idprep['alias']} in realm {realm}: {e}")
2681
2682 def update_identity_provider(self, idprep, realm: str = "master"):
2683 """Update an existing identity provider.
2684 :param idprep: Identity provider representation of the idp to be updated.
2685 :param realm: Realm in which this identity provider resides, default "master".
2686 :return HTTPResponse object on success
2687 """
2688 idp_url = URL_IDENTITY_PROVIDER.format(url=self.baseurl, realm=realm, alias=idprep["alias"])
2689 try:
2690 return self._request(idp_url, method="PUT", data=json.dumps(idprep))
2691 except Exception as e:
2692 self.fail_request(e, msg=f"Could not update identity provider {idprep['alias']} in realm {realm}: {e}")
2693
2694 def delete_identity_provider(self, alias, realm: str = "master"):
2695 """Delete an identity provider.
2696 :param alias: Alias of the identity provider.
2697 :param realm: Realm in which this identity provider resides, default "master".
2698 """
2699 idp_url = URL_IDENTITY_PROVIDER.format(url=self.baseurl, realm=realm, alias=alias)
2700 try:
2701 return self._request(idp_url, method="DELETE")
2702 except Exception as e:
2703 self.fail_request(e, msg=f"Unable to delete identity provider {alias} in realm {realm}: {e}")
2704
2705 def get_identity_provider_mappers(self, alias, realm: str = "master"):
2706 """Fetch representations for identity provider mappers
2707 :param alias: Alias of the identity provider.
2708 :param realm: realm to be queried
2709 :return: list of representations for identity provider mappers
2710 """
2711 mappers_url = URL_IDENTITY_PROVIDER_MAPPERS.format(url=self.baseurl, realm=realm, alias=alias)
2712 try:
2713 return self._request_and_deserialize(mappers_url, method="GET")
2714 except ValueError as e:
2715 self.module.fail_json(
2716 msg=f"API returned incorrect JSON when trying to obtain list of identity provider mappers for idp {alias} in realm {realm}: {e}"
2717 )
2718 except Exception as e:
2719 self.fail_request(
2720 e, msg=f"Could not obtain list of identity provider mappers for idp {alias} in realm {realm}: {e}"
2721 )
2722
2723 def fetch_idp_endpoints_import_config_url(self, fromUrl, providerId="oidc", realm: str = "master"):
2724 """Import an identity provider configuration through Keycloak server from a well-known URL.
2725 :param fromUrl: URL to import the identity provider configuration from.
2726 "param providerId: Provider ID of the identity provider to import, default 'oidc'.
2727 :param realm: Realm
2728 :return: IDP endpoins.
2729 """
2730 try:
2731 payload = {"providerId": providerId, "fromUrl": fromUrl}
2732 idps_url = URL_IDENTITY_PROVIDER_IMPORT.format(url=self.baseurl, realm=realm)
2733 return self._request_and_deserialize(idps_url, method="POST", data=json.dumps(payload))
2734 except Exception as e:
2735 self.fail_request(e, msg=f"Could not import the IdP config in realm {realm}: {e}")
2736
2737 def get_identity_provider_mapper(self, mid, alias, realm: str = "master"):
2738 """Fetch identity provider representation from a realm using the idp's alias.
2739 If the identity provider does not exist, None is returned.
2740 :param mid: Unique ID of the mapper to fetch.
2741 :param alias: Alias of the identity provider.
2742 :param realm: Realm in which the identity provider resides; default 'master'.
2743 """
2744 mapper_url = URL_IDENTITY_PROVIDER_MAPPER.format(url=self.baseurl, realm=realm, alias=alias, id=mid)
2745 try:
2746 return self._request_and_deserialize(mapper_url, method="GET")
2747 except HTTPError as e:
2748 if e.code == HTTPStatus.NOT_FOUND:
2749 return None
2750 else:
2751 self.fail_request(
2752 e, msg=f"Could not fetch mapper {mid} for identity provider {alias} in realm {realm}: {e}"
2753 )
2754 except Exception as e:
2755 self.module.fail_json(
2756 msg=f"Could not fetch mapper {mid} for identity provider {alias} in realm {realm}: {e}"
2757 )
2758
2759 def create_identity_provider_mapper(self, mapper, alias, realm: str = "master"):
2760 """Create an identity provider mapper.
2761 :param mapper: IdentityProviderMapperRepresentation of the mapper to be created.
2762 :param alias: Alias of the identity provider.
2763 :param realm: Realm in which this identity provider resides, default "master".
2764 :return: HTTPResponse object on success
2765 """
2766 mappers_url = URL_IDENTITY_PROVIDER_MAPPERS.format(url=self.baseurl, realm=realm, alias=alias)
2767 try:
2768 return self._request(mappers_url, method="POST", data=json.dumps(mapper))
2769 except Exception as e:
2770 self.fail_request(
2771 e,
2772 msg=f"Could not create identity provider mapper {mapper['name']} for idp {alias} in realm {realm}: {e}",
2773 )
2774
2775 def update_identity_provider_mapper(self, mapper, alias, realm: str = "master"):
2776 """Update an existing identity provider.
2777 :param mapper: IdentityProviderMapperRepresentation of the mapper to be updated.
2778 :param alias: Alias of the identity provider.
2779 :param realm: Realm in which this identity provider resides, default "master".
2780 :return HTTPResponse object on success
2781 """
2782 mapper_url = URL_IDENTITY_PROVIDER_MAPPER.format(url=self.baseurl, realm=realm, alias=alias, id=mapper["id"])
2783 try:
2784 return self._request(mapper_url, method="PUT", data=json.dumps(mapper))
2785 except Exception as e:
2786 self.fail_request(
2787 e, msg=f"Could not update mapper {mapper['id']} for identity provider {alias} in realm {realm}: {e}"
2788 )
2789
2790 def delete_identity_provider_mapper(self, mid, alias, realm: str = "master"):
2791 """Delete an identity provider.
2792 :param mid: Unique ID of the mapper to delete.
2793 :param alias: Alias of the identity provider.
2794 :param realm: Realm in which this identity provider resides, default "master".
2795 """
2796 mapper_url = URL_IDENTITY_PROVIDER_MAPPER.format(url=self.baseurl, realm=realm, alias=alias, id=mid)
2797 try:
2798 return self._request(mapper_url, method="DELETE")
2799 except Exception as e:
2800 self.fail_request(
2801 e, msg=f"Unable to delete mapper {mid} for identity provider {alias} in realm {realm}: {e}"
2802 )
2803
2804 def get_components(self, filter=None, realm: str = "master"):
2805 """Fetch representations for components in a realm
2806 :param realm: realm to be queried
2807 :param filter: search filter
2808 :return: list of representations for components
2809 """
2810 comps_url = URL_COMPONENTS.format(url=self.baseurl, realm=realm)
2811 if filter is not None:
2812 comps_url += f"?{filter}"
2813
2814 try:
2815 return self._request_and_deserialize(comps_url, method="GET")
2816 except ValueError as e:
2817 self.module.fail_json(
2818 msg=f"API returned incorrect JSON when trying to obtain list of components for realm {realm}: {e}"
2819 )
2820 except Exception as e:
2821 self.fail_request(e, msg=f"Could not obtain list of components for realm {realm}: {e}")
2822
2823 def get_component(self, cid, realm: str = "master"):
2824 """Fetch component representation from a realm using its cid.
2825 If the component does not exist, None is returned.
2826 :param cid: Unique ID of the component to fetch.
2827 :param realm: Realm in which the component resides; default 'master'.
2828 """
2829 comp_url = URL_COMPONENT.format(url=self.baseurl, realm=realm, id=cid)
2830 try:
2831 return self._request_and_deserialize(comp_url, method="GET")
2832 except HTTPError as e:
2833 if e.code == HTTPStatus.NOT_FOUND:
2834 return None
2835 else:
2836 self.fail_request(e, msg=f"Could not fetch component {cid} in realm {realm}: {e}")
2837 except Exception as e:
2838 self.module.fail_json(msg=f"Could not fetch component {cid} in realm {realm}: {e}")
2839
2840 def create_component(self, comprep, realm: str = "master"):
2841 """Create an component.
2842 :param comprep: Component representation of the component to be created.
2843 :param realm: Realm in which this component resides, default "master".
2844 :return: Component representation of the created component
2845 """
2846 comps_url = URL_COMPONENTS.format(url=self.baseurl, realm=realm)
2847 try:
2848 resp = self._request(comps_url, method="POST", data=json.dumps(comprep))
2849 comp_url = resp.getheader("Location")
2850 if comp_url is None:
2851 self.module.fail_json(msg=f"Could not create component in realm {realm}: unexpected response")
2852 return self._request_and_deserialize(comp_url, method="GET")
2853 except Exception as e:
2854 self.fail_request(e, msg=f"Could not create component in realm {realm}: {e}")
2855
2856 def update_component(self, comprep, realm: str = "master"):
2857 """Update an existing component.
2858 :param comprep: Component representation of the component to be updated.
2859 :param realm: Realm in which this component resides, default "master".
2860 :return HTTPResponse object on success
2861 """
2862 cid = comprep.get("id")
2863 if cid is None:
2864 self.module.fail_json(msg="Cannot update component without id")
2865 comp_url = URL_COMPONENT.format(url=self.baseurl, realm=realm, id=cid)
2866 try:
2867 return self._request(comp_url, method="PUT", data=json.dumps(comprep))
2868 except Exception as e:
2869 self.fail_request(e, msg=f"Could not update component {cid} in realm {realm}: {e}")
2870
2871 def delete_component(self, cid, realm: str = "master"):
2872 """Delete an component.
2873 :param cid: Unique ID of the component.
2874 :param realm: Realm in which this component resides, default "master".
2875 """
2876 comp_url = URL_COMPONENT.format(url=self.baseurl, realm=realm, id=cid)
2877 try:
2878 return self._request(comp_url, method="DELETE")
2879 except Exception as e:
2880 self.fail_request(e, msg=f"Unable to delete component {cid} in realm {realm}: {e}")
2881
2882 def get_authz_authorization_scope_by_name(self, name, client_id, realm):
2883 url = URL_AUTHZ_AUTHORIZATION_SCOPES.format(url=self.baseurl, client_id=client_id, realm=realm)
2884 search_url = f"{url}/search?name={quote(name, safe='')}"
2885
2886 try:
2887 return self._request_and_deserialize(search_url, method="GET")
2888 except Exception:
2889 return False
2890
2891 def create_authz_authorization_scope(self, payload, client_id, realm):
2892 """Create an authorization scope for a Keycloak client"""
2893 url = URL_AUTHZ_AUTHORIZATION_SCOPES.format(url=self.baseurl, client_id=client_id, realm=realm)
2894
2895 try:
2896 return self._request(url, method="POST", data=json.dumps(payload))
2897 except Exception as e:
2898 self.fail_request(
2899 e,
2900 msg=f"Could not create authorization scope {payload['name']} for client {client_id} in realm {realm}: {e}",
2901 )
2902
2903 def update_authz_authorization_scope(self, payload, id, client_id, realm):
2904 """Update an authorization scope for a Keycloak client"""
2905 url = URL_AUTHZ_AUTHORIZATION_SCOPE.format(url=self.baseurl, id=id, client_id=client_id, realm=realm)
2906
2907 try:
2908 return self._request(url, method="PUT", data=json.dumps(payload))
2909 except Exception as e:
2910 self.fail_request(
2911 e, msg=f"Could not create update scope {payload['name']} for client {client_id} in realm {realm}: {e}"
2912 )
2913
2914 def remove_authz_authorization_scope(self, id, client_id, realm):
2915 """Remove an authorization scope from a Keycloak client"""
2916 url = URL_AUTHZ_AUTHORIZATION_SCOPE.format(url=self.baseurl, id=id, client_id=client_id, realm=realm)
2917
2918 try:
2919 return self._request(url, method="DELETE")
2920 except Exception as e:
2921 self.fail_request(e, msg=f"Could not delete scope {id} for client {client_id} in realm {realm}: {e}")
2922
2923 def get_user_by_id(self, user_id, realm: str = "master"):
2924 """
2925 Get a User by its ID.
2926 :param user_id: ID of the user.
2927 :param realm: Realm
2928 :return: Representation of the user.
2929 """
2930 try:
2931 user_url = URL_USER.format(url=self.baseurl, realm=realm, id=user_id)
2932 userrep = json.load(self._request(user_url, method="GET"))
2933 return userrep
2934 except Exception as e:
2935 self.fail_request(e, msg=f"Could not get user {user_id} in realm {realm}: {e}")
2936
2937 def create_user(self, userrep, realm: str = "master"):
2938 """
2939 Create a new User.
2940 :param userrep: Representation of the user to create
2941 :param realm: Realm
2942 :return: Representation of the user created.
2943 """
2944 try:
2945 if "attributes" in userrep and isinstance(userrep["attributes"], list):
2946 attributes = copy.deepcopy(userrep["attributes"])
2947 userrep["attributes"] = self.convert_user_attributes_to_keycloak_dict(attributes=attributes)
2948 users_url = URL_USERS.format(url=self.baseurl, realm=realm)
2949 self._request(users_url, method="POST", data=json.dumps(userrep))
2950 created_user = self.get_user_by_username(username=userrep["username"], realm=realm)
2951 return created_user
2952 except Exception as e:
2953 self.fail_request(e, msg=f"Could not create user {userrep['username']} in realm {realm}: {e}")
2954
2955 def convert_user_attributes_to_keycloak_dict(self, attributes):
2956 keycloak_user_attributes_dict = {}
2957 for attribute in attributes:
2958 if ("state" not in attribute or attribute["state"] == "present") and "name" in attribute:
2959 keycloak_user_attributes_dict[attribute["name"]] = attribute["values"] if "values" in attribute else []
2960 return keycloak_user_attributes_dict
2961
2962 def convert_keycloak_user_attributes_dict_to_module_list(self, attributes):
2963 module_attributes_list = []
2964 for key in attributes:
2965 attr = {}
2966 attr["name"] = key
2967 attr["values"] = attributes[key]
2968 module_attributes_list.append(attr)
2969 return module_attributes_list
2970
2971 def update_user(self, userrep, realm: str = "master"):
2972 """
2973 Update a User.
2974 :param userrep: Representation of the user to update. This representation must include the ID of the user.
2975 :param realm: Realm
2976 :return: Representation of the updated user.
2977 """
2978 try:
2979 if "attributes" in userrep and isinstance(userrep["attributes"], list):
2980 attributes = copy.deepcopy(userrep["attributes"])
2981 userrep["attributes"] = self.convert_user_attributes_to_keycloak_dict(attributes=attributes)
2982 user_url = URL_USER.format(url=self.baseurl, realm=realm, id=userrep["id"])
2983 self._request(user_url, method="PUT", data=json.dumps(userrep))
2984 updated_user = self.get_user_by_id(user_id=userrep["id"], realm=realm)
2985 return updated_user
2986 except Exception as e:
2987 self.fail_request(e, msg=f"Could not update user {userrep['username']} in realm {realm}: {e}")
2988
2989 def delete_user(self, user_id, realm: str = "master"):
2990 """
2991 Delete a User.
2992 :param user_id: ID of the user to be deleted
2993 :param realm: Realm
2994 :return: HTTP response.
2995 """
2996 try:
2997 user_url = URL_USER.format(url=self.baseurl, realm=realm, id=user_id)
2998 return self._request(user_url, method="DELETE")
2999 except Exception as e:
3000 self.fail_request(e, msg=f"Could not delete user {user_id} in realm {realm}: {e}")
3001
3002 def get_user_groups(self, user_id, realm: str = "master"):
3003 """
3004 Get the group names for a user.
3005 :param user_id: User ID
3006 :param realm: Realm
3007 :return: The client group names as a list of strings.
3008 """
3009 user_groups = self.get_user_group_details(user_id, realm)
3010 return [user_group["name"] for user_group in user_groups if "name" in user_group]
3011
3012 def get_user_group_details(self, user_id, realm: str = "master"):
3013 """
3014 Get the group details for a user.
3015 :param user_id: User ID
3016 :param realm: Realm
3017 :return: The client group details as a list of dictionaries.
3018 """
3019 try:
3020 user_groups_url = URL_USER_GROUPS.format(url=self.baseurl, realm=realm, id=user_id)
3021 return self._request_and_deserialize(user_groups_url, method="GET")
3022 except Exception as e:
3023 self.fail_request(e, msg=f"Could not get groups for user {user_id} in realm {realm}: {e}")
3024
3025 def add_user_to_group(self, user_id, group_id, realm: str = "master"):
3026 """
3027 Add a user to a group.
3028 :param user_id: User ID
3029 :param group_id: Group Id to add the user to.
3030 :param realm: Realm
3031 :return: HTTP Response
3032 """
3033 try:
3034 user_group_url = URL_USER_GROUP.format(url=self.baseurl, realm=realm, id=user_id, group_id=group_id)
3035 return self._request(user_group_url, method="PUT")
3036 except Exception as e:
3037 self.fail_request(e, msg=f"Could not add user {user_id} to group {group_id} in realm {realm}: {e}")
3038
3039 def remove_user_from_group(self, user_id, group_id, realm: str = "master"):
3040 """
3041 Remove a user from a group for a user.
3042 :param user_id: User ID
3043 :param group_id: Group Id to add the user to.
3044 :param realm: Realm
3045 :return: HTTP response
3046 """
3047 try:
3048 user_group_url = URL_USER_GROUP.format(url=self.baseurl, realm=realm, id=user_id, group_id=group_id)
3049 return self._request(user_group_url, method="DELETE")
3050 except Exception as e:
3051 self.fail_request(e, msg=f"Could not remove user {user_id} from group {group_id} in realm {realm}: {e}")
3052
3053 def update_user_groups_membership(self, userrep, groups, realm: str = "master"):
3054 """
3055 Update user's group membership
3056 :param userrep: Representation of the user. This representation must include the ID.
3057 :param realm: Realm
3058 :return: True if group membership has been changed. False Otherwise.
3059 """
3060 try:
3061 groups_to_add, groups_to_remove = self.extract_groups_to_add_to_and_remove_from_user(groups)
3062 if not groups_to_add and not groups_to_remove:
3063 return False
3064
3065 user_groups = self.get_user_group_details(user_id=userrep["id"], realm=realm)
3066 user_group_names = [user_group["name"] for user_group in user_groups if "name" in user_group]
3067 user_group_paths = [user_group["path"] for user_group in user_groups if "path" in user_group]
3068
3069 groups_to_add = [
3070 group_to_add
3071 for group_to_add in groups_to_add
3072 if group_to_add not in user_group_names and group_to_add not in user_group_paths
3073 ]
3074 groups_to_remove = [
3075 group_to_remove
3076 for group_to_remove in groups_to_remove
3077 if group_to_remove in user_group_names or group_to_remove in user_group_paths
3078 ]
3079 if not groups_to_add and not groups_to_remove:
3080 return False
3081
3082 for group_to_add in groups_to_add:
3083 realm_group = self.find_group_by_path(group_to_add, realm=realm)
3084 if realm_group:
3085 self.add_user_to_group(user_id=userrep["id"], group_id=realm_group["id"], realm=realm)
3086
3087 for group_to_remove in groups_to_remove:
3088 realm_group = self.find_group_by_path(group_to_remove, realm=realm)
3089 if realm_group:
3090 self.remove_user_from_group(user_id=userrep["id"], group_id=realm_group["id"], realm=realm)
3091
3092 return True
3093 except Exception as e:
3094 self.module.fail_json(
3095 msg=f"Could not update group membership for user {userrep['username']} in realm {realm}: {e}"
3096 )
3097
3098 def extract_groups_to_add_to_and_remove_from_user(self, groups):
3099 groups_to_add = []
3100 groups_to_remove = []
3101 if isinstance(groups, list):
3102 for group in groups:
3103 group_name = group["name"] if isinstance(group, dict) and "name" in group else group
3104 if isinstance(group, dict):
3105 if "state" not in group or group["state"] == "present":
3106 groups_to_add.append(group_name)
3107 else:
3108 groups_to_remove.append(group_name)
3109 return groups_to_add, groups_to_remove
3110
3111 def find_group_by_path(self, target, realm: str = "master"):
3112 """
3113 Finds a realm group by path, e.g. '/my/group'.
3114 The path is formed by prepending a '/' character to `target` unless it's already present.
3115 This adds support for finding top level groups by name and subgroups by path.
3116 """
3117 groups = self.get_groups(realm=realm)
3118 path = target if target.startswith("/") else f"/{target}"
3119 for segment in path.split("/"):
3120 if not segment:
3121 continue
3122 abort = True
3123 for group in groups:
3124 if group["path"] == path:
3125 return self.get_group_by_groupid(group["id"], realm=realm)
3126 if group["name"] == segment:
3127 groups = self.get_subgroups(group, realm=realm)
3128 abort = False
3129 break
3130 if abort:
3131 break
3132 return None
3133
3134 def convert_user_group_list_of_str_to_list_of_dict(self, groups):
3135 list_of_groups = []
3136 if isinstance(groups, list) and len(groups) > 0:
3137 for group in groups:
3138 if isinstance(group, str):
3139 group_dict = {}
3140 group_dict["name"] = group
3141 list_of_groups.append(group_dict)
3142 return list_of_groups
3143
3144 def create_authz_custom_policy(self, policy_type, payload, client_id, realm):
3145 """Create a custom policy for a Keycloak client"""
3146 url = URL_AUTHZ_CUSTOM_POLICY.format(
3147 url=self.baseurl, policy_type=policy_type, client_id=client_id, realm=realm
3148 )
3149
3150 try:
3151 return self._request(url, method="POST", data=json.dumps(payload))
3152 except Exception as e:
3153 self.fail_request(
3154 e, msg=f"Could not create permission {payload['name']} for client {client_id} in realm {realm}: {e}"
3155 )
3156
3157 def remove_authz_custom_policy(self, policy_id, client_id, realm):
3158 """Remove a custom policy from a Keycloak client"""
3159 url = URL_AUTHZ_CUSTOM_POLICIES.format(url=self.baseurl, client_id=client_id, realm=realm)
3160 delete_url = f"{url}/{policy_id}"
3161
3162 try:
3163 return self._request(delete_url, method="DELETE")
3164 except Exception as e:
3165 self.fail_request(
3166 e, msg=f"Could not delete custom policy {id} for client {client_id} in realm {realm}: {e}"
3167 )
3168
3169 def get_authz_permission_by_name(self, name, client_id, realm):
3170 """Get authorization permission by name"""
3171 url = URL_AUTHZ_POLICIES.format(url=self.baseurl, client_id=client_id, realm=realm)
3172 search_url = f"{url}/search?name={quote(name, safe='')}"
3173
3174 try:
3175 return self._request_and_deserialize(search_url, method="GET")
3176 except Exception:
3177 return False
3178
3179 def create_authz_permission(self, payload, permission_type, client_id, realm):
3180 """Create an authorization permission for a Keycloak client"""
3181 url = URL_AUTHZ_PERMISSIONS.format(
3182 url=self.baseurl, permission_type=permission_type, client_id=client_id, realm=realm
3183 )
3184
3185 try:
3186 return self._request(url, method="POST", data=json.dumps(payload))
3187 except Exception as e:
3188 self.fail_request(
3189 e, msg=f"Could not create permission {payload['name']} for client {client_id} in realm {realm}: {e}"
3190 )
3191
3192 def remove_authz_permission(self, id, client_id, realm):
3193 """Create an authorization permission for a Keycloak client"""
3194 url = URL_AUTHZ_POLICY.format(url=self.baseurl, id=id, client_id=client_id, realm=realm)
3195
3196 try:
3197 return self._request(url, method="DELETE")
3198 except Exception as e:
3199 self.fail_request(e, msg=f"Could not delete permission {id} for client {client_id} in realm {realm}: {e}")
3200
3201 def update_authz_permission(self, payload, permission_type, id, client_id, realm):
3202 """Update a permission for a Keycloak client"""
3203 url = URL_AUTHZ_PERMISSION.format(
3204 url=self.baseurl, permission_type=permission_type, id=id, client_id=client_id, realm=realm
3205 )
3206
3207 try:
3208 return self._request(url, method="PUT", data=json.dumps(payload))
3209 except Exception as e:
3210 self.fail_request(
3211 e,
3212 msg=f"Could not create update permission {payload['name']} for client {client_id} in realm {realm}: {e}",
3213 )
3214
3215 def get_authz_resource_by_name(self, name, client_id, realm):
3216 """Get authorization resource by name"""
3217 url = URL_AUTHZ_RESOURCES.format(url=self.baseurl, client_id=client_id, realm=realm)
3218 search_url = f"{url}/search?name={quote(name, safe='')}"
3219
3220 try:
3221 return self._request_and_deserialize(search_url, method="GET")
3222 except Exception:
3223 return False
3224
3225 def get_authz_policy_by_name(self, name, client_id, realm):
3226 """Get authorization policy by name"""
3227 url = URL_AUTHZ_POLICIES.format(url=self.baseurl, client_id=client_id, realm=realm)
3228 search_url = f"{url}/search?name={quote(name, safe='')}"
3229
3230 try:
3231 return self._request_and_deserialize(search_url, method="GET")
3232 except Exception:
3233 return False
3234
3235 def get_client_role_scope_from_client(self, clientid, clientscopeid, realm: str = "master"):
3236 """Fetch the roles associated with the client's scope for a specific client on the Keycloak server.
3237 :param clientid: ID of the client from which to obtain the associated roles.
3238 :param clientscopeid: ID of the client who owns the roles.
3239 :param realm: Realm from which to obtain the scope.
3240 :return: The client scope of roles from specified client.
3241 """
3242 client_role_scope_url = URL_CLIENT_ROLE_SCOPE_CLIENTS.format(
3243 url=self.baseurl, realm=realm, id=clientid, scopeid=clientscopeid
3244 )
3245 try:
3246 return self._request_and_deserialize(client_role_scope_url, method="GET")
3247 except Exception as e:
3248 self.fail_request(e, msg=f"Could not fetch roles scope for client {clientid} in realm {realm}: {e}")
3249
3250 def update_client_role_scope_from_client(self, payload, clientid, clientscopeid, realm: str = "master"):
3251 """Update and fetch the roles associated with the client's scope on the Keycloak server.
3252 :param payload: List of roles to be added to the scope.
3253 :param clientid: ID of the client to update scope.
3254 :param clientscopeid: ID of the client who owns the roles.
3255 :param realm: Realm from which to obtain the clients.
3256 :return: The client scope of roles from specified client.
3257 """
3258 client_role_scope_url = URL_CLIENT_ROLE_SCOPE_CLIENTS.format(
3259 url=self.baseurl, realm=realm, id=clientid, scopeid=clientscopeid
3260 )
3261 try:
3262 self._request(client_role_scope_url, method="POST", data=json.dumps(payload))
3263
3264 except Exception as e:
3265 self.fail_request(e, msg=f"Could not update roles scope for client {clientid} in realm {realm}: {e}")
3266
3267 return self.get_client_role_scope_from_client(clientid, clientscopeid, realm)
3268
3269 def delete_client_role_scope_from_client(self, payload, clientid, clientscopeid, realm: str = "master"):
3270 """Delete the roles contains in the payload from the client's scope on the Keycloak server.
3271 :param payload: List of roles to be deleted.
3272 :param clientid: ID of the client to delete roles from scope.
3273 :param clientscopeid: ID of the client who owns the roles.
3274 :param realm: Realm from which to obtain the clients.
3275 :return: The client scope of roles from specified client.
3276 """
3277 client_role_scope_url = URL_CLIENT_ROLE_SCOPE_CLIENTS.format(
3278 url=self.baseurl, realm=realm, id=clientid, scopeid=clientscopeid
3279 )
3280 try:
3281 self._request(client_role_scope_url, method="DELETE", data=json.dumps(payload))
3282
3283 except Exception as e:
3284 self.fail_request(e, msg=f"Could not delete roles scope for client {clientid} in realm {realm}: {e}")
3285
3286 return self.get_client_role_scope_from_client(clientid, clientscopeid, realm)
3287
3288 def get_client_role_scope_from_realm(self, clientid, realm: str = "master"):
3289 """Fetch the realm roles from the client's scope on the Keycloak server.
3290 :param clientid: ID of the client from which to obtain the associated realm roles.
3291 :param realm: Realm from which to obtain the clients.
3292 :return: The client realm roles scope.
3293 """
3294 client_role_scope_url = URL_CLIENT_ROLE_SCOPE_REALM.format(url=self.baseurl, realm=realm, id=clientid)
3295 try:
3296 return self._request_and_deserialize(client_role_scope_url, method="GET")
3297 except Exception as e:
3298 self.fail_request(e, msg=f"Could not fetch roles scope for client {clientid} in realm {realm}: {e}")
3299
3300 def update_client_role_scope_from_realm(self, payload, clientid, realm: str = "master"):
3301 """Update and fetch the realm roles from the client's scope on the Keycloak server.
3302 :param payload: List of realm roles to add.
3303 :param clientid: ID of the client to update scope.
3304 :param realm: Realm from which to obtain the clients.
3305 :return: The client realm roles scope.
3306 """
3307 client_role_scope_url = URL_CLIENT_ROLE_SCOPE_REALM.format(url=self.baseurl, realm=realm, id=clientid)
3308 try:
3309 self._request(client_role_scope_url, method="POST", data=json.dumps(payload))
3310
3311 except Exception as e:
3312 self.fail_request(e, msg=f"Could not update roles scope for client {clientid} in realm {realm}: {e}")
3313
3314 return self.get_client_role_scope_from_realm(clientid, realm)
3315
3316 def delete_client_role_scope_from_realm(self, payload, clientid, realm: str = "master"):
3317 """Delete the realm roles contains in the payload from the client's scope on the Keycloak server.
3318 :param payload: List of realm roles to delete.
3319 :param clientid: ID of the client to delete roles from scope.
3320 :param realm: Realm from which to obtain the clients.
3321 :return: The client realm roles scope.
3322 """
3323 client_role_scope_url = URL_CLIENT_ROLE_SCOPE_REALM.format(url=self.baseurl, realm=realm, id=clientid)
3324 try:
3325 self._request(client_role_scope_url, method="DELETE", data=json.dumps(payload))
3326
3327 except Exception as e:
3328 self.fail_request(e, msg=f"Could not delete roles scope for client {clientid} in realm {realm}: {e}")
3329
3330 return self.get_client_role_scope_from_realm(clientid, realm)
3331
3332 def fail_request(self, e: Exception, msg: str, **kwargs: t.Any) -> t.NoReturn:
3333 """Triggers a module failure. This should be called
3334 when an exception occurs during/after a request.
3335 Attempts to parse the exception e as an HTTP error
3336 and append it to msg.
3337
3338 :param e: exception which triggered the failure
3339 :param msg: error message to display to the user
3340 :param kwargs: additional arguments to pass to module.fail_json
3341 """
3342 try:
3343 if isinstance(e, HTTPError):
3344 msg = f"{msg}: {to_native(e.read())}"
3345 except Exception:
3346 pass
3347 self.module.fail_json(msg, **kwargs)
3348
3349 def fail_open_url(self, e: Exception, msg: str, **kwargs: t.Any) -> t.NoReturn:
3350 """DEPRECATED: Use fail_request instead.
3351
3352 Triggers a module failure. This should be called
3353 when an exception occurs during/after a request.
3354 Attempts to parse the exception e as an HTTP error
3355 and append it to msg.
3356
3357 :param e: exception which triggered the failure
3358 :param msg: error message to display to the user
3359 :param kwargs: additional arguments to pass to module.fail_json
3360 """
3361 self.fail_request(e, msg, **kwargs)
3362
3363 def send_execute_actions_email(
3364 self, user_id, realm: str = "master", client_id=None, data=None, redirect_uri=None, lifespan=None
3365 ):
3366 """
3367 Send an email to the user with a link they can click to perform required actions (e.g. reset password).
3368 Uses execute-actions-email endpoint with provided required actions (defaults handled by caller).
3369
3370 :param user_id: ID of the user
3371 :param realm: Realm name (not the ID)
3372 :param client_id: Optional client id for the redirect
3373 :param redirect_uri: Optional redirect uri
3374 :param data: List of required action names (list[str])
3375 :param lifespan: Optional lifespan (seconds) for the action token
3376 :return: HTTP response (204 No Content on success)
3377 """
3378 try:
3379 execute_action_url = URL_EXECUTE_ACTION.format(url=self.baseurl, realm=realm, user_id=user_id)
3380
3381 params = {}
3382 if client_id is not None:
3383 params["client_id"] = client_id
3384 if redirect_uri is not None:
3385 params["redirect_uri"] = redirect_uri
3386 if lifespan is not None:
3387 params["lifespan"] = lifespan
3388
3389 if params:
3390 execute_action_url = f"{execute_action_url}?{urlencode(params)}"
3391
3392 body = None
3393 if data is not None:
3394 # API expects JSON array of action names
3395 body = json.dumps(data)
3396
3397 return self._request(execute_action_url, method="PUT", data=body)
3398 except Exception as e:
3399 self.fail_request(e, msg=f"Could not send execute actions email to user {user_id} in realm {realm}: {e}")