| 1 |
#!/usr/bin/python |
| 2 |
|
| 3 |
# Copyright (c) 2017, Eike Frost <[email protected]> |
| 4 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 5 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 6 |
|
| 7 |
from __future__ import annotations |
| 8 |
|
| 9 |
DOCUMENTATION = r""" |
| 10 |
module: keycloak_client |
| 11 |
|
| 12 |
short_description: Allows administration of Keycloak clients using Keycloak API |
| 13 |
|
| 14 |
|
| 15 |
description: |
| 16 |
- This module allows the administration of Keycloak clients using the Keycloak REST API. It requires access to the REST |
| 17 |
API using OpenID Connect; the user connecting and the client being used must have the requisite access rights. In a default |
| 18 |
Keycloak installation, admin-cli and an admin user would work, as would a separate client definition with the scope tailored |
| 19 |
to your needs and a user having the expected roles. |
| 20 |
- The names of module options are snake_cased versions of the camelCase ones found in the Keycloak API and its documentation |
| 21 |
at U(https://www.keycloak.org/docs-api/8.0/rest-api/index.html). Aliases are provided so camelCased versions can be used |
| 22 |
as well. |
| 23 |
- The Keycloak API does not always sanity check inputs, for example you can set SAML-specific settings on an OpenID Connect |
| 24 |
client for instance and the other way around. Be careful. If you do not specify a setting, usually a sensible default |
| 25 |
is chosen. |
| 26 |
attributes: |
| 27 |
check_mode: |
| 28 |
support: full |
| 29 |
diff_mode: |
| 30 |
support: full |
| 31 |
action_group: |
| 32 |
version_added: 10.2.0 |
| 33 |
|
| 34 |
options: |
| 35 |
state: |
| 36 |
description: |
| 37 |
- State of the client. |
| 38 |
- On V(present), the client are created (or updated if it exists already). |
| 39 |
- On V(absent), the client are removed if it exists. |
| 40 |
choices: ['present', 'absent'] |
| 41 |
default: 'present' |
| 42 |
type: str |
| 43 |
|
| 44 |
realm: |
| 45 |
description: |
| 46 |
- The realm to create the client in. |
| 47 |
type: str |
| 48 |
default: master |
| 49 |
|
| 50 |
client_id: |
| 51 |
description: |
| 52 |
- Client ID of client to be worked on. This is usually an alphanumeric name chosen by you. Either this or O(id) is required. |
| 53 |
If you specify both, O(id) takes precedence. This is C(clientId) in the Keycloak REST API. |
| 54 |
aliases: |
| 55 |
- clientId |
| 56 |
type: str |
| 57 |
|
| 58 |
id: |
| 59 |
description: |
| 60 |
- ID of client to be worked on. This is usually an UUID. Either this or O(client_id) is required. If you specify both, |
| 61 |
this takes precedence. |
| 62 |
type: str |
| 63 |
|
| 64 |
name: |
| 65 |
description: |
| 66 |
- Name of the client (this is not the same as O(client_id)). |
| 67 |
type: str |
| 68 |
|
| 69 |
description: |
| 70 |
description: |
| 71 |
- Description of the client in Keycloak. |
| 72 |
type: str |
| 73 |
|
| 74 |
root_url: |
| 75 |
description: |
| 76 |
- Root URL appended to relative URLs for this client. This is C(rootUrl) in the Keycloak REST API. |
| 77 |
aliases: |
| 78 |
- rootUrl |
| 79 |
type: str |
| 80 |
|
| 81 |
admin_url: |
| 82 |
description: |
| 83 |
- URL to the admin interface of the client. This is C(adminUrl) in the Keycloak REST API. |
| 84 |
aliases: |
| 85 |
- adminUrl |
| 86 |
type: str |
| 87 |
|
| 88 |
base_url: |
| 89 |
description: |
| 90 |
- Default URL to use when the auth server needs to redirect or link back to the client This is C(baseUrl) in the Keycloak |
| 91 |
REST API. |
| 92 |
aliases: |
| 93 |
- baseUrl |
| 94 |
type: str |
| 95 |
|
| 96 |
enabled: |
| 97 |
description: |
| 98 |
- Is this client enabled or not? |
| 99 |
type: bool |
| 100 |
|
| 101 |
client_authenticator_type: |
| 102 |
description: |
| 103 |
- How do clients authenticate with the auth server? Either V(client-secret), V(client-jwt), or V(client-x509) can be |
| 104 |
chosen. When using V(client-secret), the module parameter O(secret) can set it, for V(client-jwt), you can use the |
| 105 |
keys C(use.jwks.url), C(jwks.url), and C(jwt.credential.certificate) in the O(attributes) module parameter to configure |
| 106 |
its behavior. For V(client-x509) you can use the keys C(x509.allow.regex.pattern.comparison) and C(x509.subjectdn) |
| 107 |
in the O(attributes) module parameter to configure which certificate(s) to accept. |
| 108 |
- This is C(clientAuthenticatorType) in the Keycloak REST API. |
| 109 |
choices: ['client-secret', 'client-jwt', 'client-x509'] |
| 110 |
aliases: |
| 111 |
- clientAuthenticatorType |
| 112 |
type: str |
| 113 |
|
| 114 |
secret: |
| 115 |
description: |
| 116 |
- When using O(client_authenticator_type=client-secret) (the default), you can specify a secret here (otherwise one |
| 117 |
is generated if it does not exit). If changing this secret, the module does not register a change currently (but the |
| 118 |
changed secret is saved). |
| 119 |
type: str |
| 120 |
|
| 121 |
registration_access_token: |
| 122 |
description: |
| 123 |
- The registration access token provides access for clients to the client registration service. This is C(registrationAccessToken) |
| 124 |
in the Keycloak REST API. |
| 125 |
aliases: |
| 126 |
- registrationAccessToken |
| 127 |
type: str |
| 128 |
|
| 129 |
default_roles: |
| 130 |
description: |
| 131 |
- List of default roles for this client. If the client roles referenced do not exist yet, they are created. This is |
| 132 |
C(defaultRoles) in the Keycloak REST API. |
| 133 |
aliases: |
| 134 |
- defaultRoles |
| 135 |
type: list |
| 136 |
elements: str |
| 137 |
|
| 138 |
redirect_uris: |
| 139 |
description: |
| 140 |
- Acceptable redirect URIs for this client. This is C(redirectUris) in the Keycloak REST API. |
| 141 |
aliases: |
| 142 |
- redirectUris |
| 143 |
type: list |
| 144 |
elements: str |
| 145 |
|
| 146 |
web_origins: |
| 147 |
description: |
| 148 |
- List of allowed CORS origins. This is C(webOrigins) in the Keycloak REST API. |
| 149 |
aliases: |
| 150 |
- webOrigins |
| 151 |
type: list |
| 152 |
elements: str |
| 153 |
|
| 154 |
valid_post_logout_redirect_uris: |
| 155 |
description: |
| 156 |
- Valid post logout redirect URIs for this client. |
| 157 |
- This is stored as C(post.logout.redirect.uris) in the client attributes. |
| 158 |
- Use V(+) as a single list element to allow all redirect URIs. |
| 159 |
aliases: |
| 160 |
- postLogoutRedirectUris |
| 161 |
type: list |
| 162 |
elements: str |
| 163 |
version_added: "12.4.0" |
| 164 |
|
| 165 |
not_before: |
| 166 |
description: |
| 167 |
- Revoke any tokens issued before this date for this client (this is a UNIX timestamp). This is C(notBefore) in the |
| 168 |
Keycloak REST API. |
| 169 |
type: int |
| 170 |
aliases: |
| 171 |
- notBefore |
| 172 |
|
| 173 |
bearer_only: |
| 174 |
description: |
| 175 |
- The access type of this client is bearer-only. This is C(bearerOnly) in the Keycloak REST API. |
| 176 |
aliases: |
| 177 |
- bearerOnly |
| 178 |
type: bool |
| 179 |
|
| 180 |
consent_required: |
| 181 |
description: |
| 182 |
- If enabled, users have to consent to client access. This is C(consentRequired) in the Keycloak REST API. |
| 183 |
aliases: |
| 184 |
- consentRequired |
| 185 |
type: bool |
| 186 |
|
| 187 |
standard_flow_enabled: |
| 188 |
description: |
| 189 |
- Enable standard flow for this client or not (OpenID connect). This is C(standardFlowEnabled) in the Keycloak REST |
| 190 |
API. |
| 191 |
aliases: |
| 192 |
- standardFlowEnabled |
| 193 |
type: bool |
| 194 |
|
| 195 |
implicit_flow_enabled: |
| 196 |
description: |
| 197 |
- Enable implicit flow for this client or not (OpenID connect). This is C(implicitFlowEnabled) in the Keycloak REST |
| 198 |
API. |
| 199 |
aliases: |
| 200 |
- implicitFlowEnabled |
| 201 |
type: bool |
| 202 |
|
| 203 |
direct_access_grants_enabled: |
| 204 |
description: |
| 205 |
- Are direct access grants enabled for this client or not (OpenID connect). This is C(directAccessGrantsEnabled) in |
| 206 |
the Keycloak REST API. |
| 207 |
aliases: |
| 208 |
- directAccessGrantsEnabled |
| 209 |
type: bool |
| 210 |
|
| 211 |
service_accounts_enabled: |
| 212 |
description: |
| 213 |
- Are service accounts enabled for this client or not (OpenID connect). This is C(serviceAccountsEnabled) in the Keycloak |
| 214 |
REST API. |
| 215 |
aliases: |
| 216 |
- serviceAccountsEnabled |
| 217 |
type: bool |
| 218 |
|
| 219 |
authorization_services_enabled: |
| 220 |
description: |
| 221 |
- Are authorization services enabled for this client or not (OpenID connect). This is C(authorizationServicesEnabled) |
| 222 |
in the Keycloak REST API. |
| 223 |
aliases: |
| 224 |
- authorizationServicesEnabled |
| 225 |
type: bool |
| 226 |
|
| 227 |
public_client: |
| 228 |
description: |
| 229 |
- Is the access type for this client public or not. This is C(publicClient) in the Keycloak REST API. |
| 230 |
aliases: |
| 231 |
- publicClient |
| 232 |
type: bool |
| 233 |
|
| 234 |
frontchannel_logout: |
| 235 |
description: |
| 236 |
- Is frontchannel logout enabled for this client or not. This is C(frontchannelLogout) in the Keycloak REST API. |
| 237 |
aliases: |
| 238 |
- frontchannelLogout |
| 239 |
type: bool |
| 240 |
|
| 241 |
backchannel_logout_url: |
| 242 |
description: |
| 243 |
- URL that will cause the client to log itself out when a logout request is sent to this realm. |
| 244 |
- This is stored as C(backchannel.logout.url) in the client attributes. |
| 245 |
aliases: |
| 246 |
- backchannelLogoutUrl |
| 247 |
type: str |
| 248 |
version_added: "12.4.0" |
| 249 |
|
| 250 |
protocol: |
| 251 |
description: |
| 252 |
- Type of client. |
| 253 |
- At creation only, default value is V(openid-connect) if O(protocol) is omitted. |
| 254 |
- The V(docker-v2) value was added in community.general 8.6.0. |
| 255 |
type: str |
| 256 |
choices: ['openid-connect', 'saml', 'docker-v2'] |
| 257 |
|
| 258 |
full_scope_allowed: |
| 259 |
description: |
| 260 |
- Is the "Full Scope Allowed" feature set for this client or not. This is C(fullScopeAllowed) in the Keycloak REST API. |
| 261 |
aliases: |
| 262 |
- fullScopeAllowed |
| 263 |
type: bool |
| 264 |
|
| 265 |
node_re_registration_timeout: |
| 266 |
description: |
| 267 |
- Cluster node re-registration timeout for this client. This is C(nodeReRegistrationTimeout) in the Keycloak REST API. |
| 268 |
type: int |
| 269 |
aliases: |
| 270 |
- nodeReRegistrationTimeout |
| 271 |
|
| 272 |
registered_nodes: |
| 273 |
description: |
| 274 |
- Dict of registered cluster nodes (with C(nodename) as the key and last registration time as the value). This is C(registeredNodes) |
| 275 |
in the Keycloak REST API. |
| 276 |
type: dict |
| 277 |
aliases: |
| 278 |
- registeredNodes |
| 279 |
|
| 280 |
client_template: |
| 281 |
description: |
| 282 |
- Client template to use for this client. If it does not exist this field is silently dropped. This is C(clientTemplate) |
| 283 |
in the Keycloak REST API. |
| 284 |
type: str |
| 285 |
aliases: |
| 286 |
- clientTemplate |
| 287 |
|
| 288 |
use_template_config: |
| 289 |
description: |
| 290 |
- Whether or not to use configuration from the O(client_template). This is C(useTemplateConfig) in the Keycloak REST |
| 291 |
API. |
| 292 |
aliases: |
| 293 |
- useTemplateConfig |
| 294 |
type: bool |
| 295 |
|
| 296 |
use_template_scope: |
| 297 |
description: |
| 298 |
- Whether or not to use scope configuration from the O(client_template). This is C(useTemplateScope) in the Keycloak |
| 299 |
REST API. |
| 300 |
aliases: |
| 301 |
- useTemplateScope |
| 302 |
type: bool |
| 303 |
|
| 304 |
use_template_mappers: |
| 305 |
description: |
| 306 |
- Whether or not to use mapper configuration from the O(client_template). This is C(useTemplateMappers) in the Keycloak |
| 307 |
REST API. |
| 308 |
aliases: |
| 309 |
- useTemplateMappers |
| 310 |
type: bool |
| 311 |
|
| 312 |
always_display_in_console: |
| 313 |
description: |
| 314 |
- Whether or not to display this client in account console, even if the user does not have an active session. |
| 315 |
aliases: |
| 316 |
- alwaysDisplayInConsole |
| 317 |
type: bool |
| 318 |
version_added: 4.7.0 |
| 319 |
|
| 320 |
surrogate_auth_required: |
| 321 |
description: |
| 322 |
- Whether or not surrogate auth is required. This is C(surrogateAuthRequired) in the Keycloak REST API. |
| 323 |
aliases: |
| 324 |
- surrogateAuthRequired |
| 325 |
type: bool |
| 326 |
|
| 327 |
authorization_settings: |
| 328 |
description: |
| 329 |
- A data structure defining the authorization settings for this client. For reference, please see the Keycloak API docs |
| 330 |
at U(https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_resourceserverrepresentation). This is C(authorizationSettings) |
| 331 |
in the Keycloak REST API. |
| 332 |
type: dict |
| 333 |
aliases: |
| 334 |
- authorizationSettings |
| 335 |
|
| 336 |
authentication_flow_binding_overrides: |
| 337 |
description: |
| 338 |
- Override realm authentication flow bindings. |
| 339 |
type: dict |
| 340 |
suboptions: |
| 341 |
browser: |
| 342 |
description: |
| 343 |
- Flow ID of the browser authentication flow. |
| 344 |
- O(authentication_flow_binding_overrides.browser) and O(authentication_flow_binding_overrides.browser_name) are |
| 345 |
mutually exclusive. |
| 346 |
type: str |
| 347 |
|
| 348 |
browser_name: |
| 349 |
description: |
| 350 |
- Flow name of the browser authentication flow. |
| 351 |
- O(authentication_flow_binding_overrides.browser) and O(authentication_flow_binding_overrides.browser_name) are |
| 352 |
mutually exclusive. |
| 353 |
aliases: |
| 354 |
- browserName |
| 355 |
type: str |
| 356 |
version_added: 9.1.0 |
| 357 |
|
| 358 |
direct_grant: |
| 359 |
description: |
| 360 |
- Flow ID of the direct grant authentication flow. |
| 361 |
- O(authentication_flow_binding_overrides.direct_grant) and O(authentication_flow_binding_overrides.direct_grant_name) |
| 362 |
are mutually exclusive. |
| 363 |
aliases: |
| 364 |
- directGrant |
| 365 |
type: str |
| 366 |
|
| 367 |
direct_grant_name: |
| 368 |
description: |
| 369 |
- Flow name of the direct grant authentication flow. |
| 370 |
- O(authentication_flow_binding_overrides.direct_grant) and O(authentication_flow_binding_overrides.direct_grant_name) |
| 371 |
are mutually exclusive. |
| 372 |
aliases: |
| 373 |
- directGrantName |
| 374 |
type: str |
| 375 |
version_added: 9.1.0 |
| 376 |
aliases: |
| 377 |
- authenticationFlowBindingOverrides |
| 378 |
version_added: 3.4.0 |
| 379 |
|
| 380 |
client_scopes_behavior: |
| 381 |
description: |
| 382 |
- Determine how O(default_client_scopes) and O(optional_client_scopes) behave when updating an existing client. |
| 383 |
- 'V(ignore): Do not change the client scopes of an existing client. This is the default for backward compatibility.' |
| 384 |
- 'V(patch): Add missing scopes, do not remove any missing scopes.' |
| 385 |
- 'V(idempotent): Make the client scopes exactly as specified, adding and removing scopes as needed.' |
| 386 |
aliases: |
| 387 |
- clientScopesBehavior |
| 388 |
type: str |
| 389 |
choices: ['ignore', 'patch', 'idempotent'] |
| 390 |
default: 'ignore' |
| 391 |
version_added: 11.4.0 |
| 392 |
|
| 393 |
default_client_scopes: |
| 394 |
description: |
| 395 |
- List of default client scopes. |
| 396 |
- See O(client_scopes_behavior) for how this behaves when updating an existing client. |
| 397 |
aliases: |
| 398 |
- defaultClientScopes |
| 399 |
type: list |
| 400 |
elements: str |
| 401 |
version_added: 4.7.0 |
| 402 |
|
| 403 |
optional_client_scopes: |
| 404 |
description: |
| 405 |
- List of optional client scopes. |
| 406 |
- See O(client_scopes_behavior) for how this behaves when updating an existing client. |
| 407 |
aliases: |
| 408 |
- optionalClientScopes |
| 409 |
type: list |
| 410 |
elements: str |
| 411 |
version_added: 4.7.0 |
| 412 |
|
| 413 |
protocol_mappers: |
| 414 |
description: |
| 415 |
- A list of dicts defining protocol mappers for this client. This is C(protocolMappers) in the Keycloak REST API. |
| 416 |
aliases: |
| 417 |
- protocolMappers |
| 418 |
type: list |
| 419 |
elements: dict |
| 420 |
suboptions: |
| 421 |
consentRequired: |
| 422 |
description: |
| 423 |
- Specifies whether a user needs to provide consent to a client for this mapper to be active. |
| 424 |
type: bool |
| 425 |
|
| 426 |
consentText: |
| 427 |
description: |
| 428 |
- The human-readable name of the consent the user is presented to accept. |
| 429 |
type: str |
| 430 |
|
| 431 |
id: |
| 432 |
description: |
| 433 |
- Usually a UUID specifying the internal ID of this protocol mapper instance. |
| 434 |
type: str |
| 435 |
|
| 436 |
name: |
| 437 |
description: |
| 438 |
- The name of this protocol mapper. |
| 439 |
type: str |
| 440 |
|
| 441 |
protocol: |
| 442 |
description: |
| 443 |
- This specifies for which protocol this protocol mapper is active. |
| 444 |
choices: ['openid-connect', 'saml', 'docker-v2'] |
| 445 |
type: str |
| 446 |
|
| 447 |
protocolMapper: |
| 448 |
description: |
| 449 |
- 'The Keycloak-internal name of the type of this protocol-mapper. While an exhaustive list is impossible to provide |
| 450 |
since this may be extended through SPIs by the user of Keycloak, by default Keycloak as of 3.4 ships with at least:' |
| 451 |
- V(docker-v2-allow-all-mapper). |
| 452 |
- V(oidc-address-mapper). |
| 453 |
- V(oidc-full-name-mapper). |
| 454 |
- V(oidc-group-membership-mapper). |
| 455 |
- V(oidc-hardcoded-claim-mapper). |
| 456 |
- V(oidc-hardcoded-role-mapper). |
| 457 |
- V(oidc-role-name-mapper). |
| 458 |
- V(oidc-script-based-protocol-mapper). |
| 459 |
- V(oidc-sha256-pairwise-sub-mapper). |
| 460 |
- V(oidc-usermodel-attribute-mapper). |
| 461 |
- V(oidc-usermodel-client-role-mapper). |
| 462 |
- V(oidc-usermodel-property-mapper). |
| 463 |
- V(oidc-usermodel-realm-role-mapper). |
| 464 |
- V(oidc-usersessionmodel-note-mapper). |
| 465 |
- V(saml-group-membership-mapper). |
| 466 |
- V(saml-hardcode-attribute-mapper). |
| 467 |
- V(saml-hardcode-role-mapper). |
| 468 |
- V(saml-role-list-mapper). |
| 469 |
- V(saml-role-name-mapper). |
| 470 |
- V(saml-user-attribute-mapper). |
| 471 |
- V(saml-user-property-mapper). |
| 472 |
- V(saml-user-session-note-mapper). |
| 473 |
- An exhaustive list of available mappers on your installation can be obtained on the admin console by going to |
| 474 |
Server Info -> Providers and looking under 'protocol-mapper'. |
| 475 |
type: str |
| 476 |
|
| 477 |
config: |
| 478 |
description: |
| 479 |
- Dict specifying the configuration options for the protocol mapper; the contents differ depending on the value |
| 480 |
of O(protocol_mappers[].protocolMapper) and are not documented other than by the source of the mappers and its |
| 481 |
parent class(es). An example is given below. It is easiest to obtain valid config values by dumping an already-existing |
| 482 |
protocol mapper configuration through check-mode in the RV(existing) field. |
| 483 |
type: dict |
| 484 |
|
| 485 |
attributes: |
| 486 |
description: |
| 487 |
- A dict of further attributes for this client. This can contain various configuration settings; an example is given |
| 488 |
in the examples section. While an exhaustive list of permissible options is not available; possible options as of |
| 489 |
Keycloak 3.4 are listed below. The Keycloak API does not validate whether a given option is appropriate for the protocol |
| 490 |
used; if specified anyway, Keycloak does not use it. |
| 491 |
type: dict |
| 492 |
suboptions: |
| 493 |
saml.authnstatement: |
| 494 |
description: |
| 495 |
- For SAML clients, boolean specifying whether or not a statement containing method and timestamp should be included |
| 496 |
in the login response. |
| 497 |
saml.client.signature: |
| 498 |
description: |
| 499 |
- For SAML clients, boolean specifying whether a client signature is required and validated. |
| 500 |
saml.encrypt: |
| 501 |
description: |
| 502 |
- Boolean specifying whether SAML assertions should be encrypted with the client's public key. |
| 503 |
saml.force.post.binding: |
| 504 |
description: |
| 505 |
- For SAML clients, boolean specifying whether always to use POST binding for responses. |
| 506 |
saml.onetimeuse.condition: |
| 507 |
description: |
| 508 |
- For SAML clients, boolean specifying whether a OneTimeUse condition should be included in login responses. |
| 509 |
saml.server.signature: |
| 510 |
description: |
| 511 |
- Boolean specifying whether SAML documents should be signed by the realm. |
| 512 |
saml.server.signature.keyinfo.ext: |
| 513 |
description: |
| 514 |
- For SAML clients, boolean specifying whether REDIRECT signing key lookup should be optimized through inclusion |
| 515 |
of the signing key ID in the SAML Extensions element. |
| 516 |
saml.signature.algorithm: |
| 517 |
description: |
| 518 |
- Signature algorithm used to sign SAML documents. One of V(RSA_SHA256), V(RSA_SHA1), V(RSA_SHA512), or V(DSA_SHA1). |
| 519 |
saml.signing.certificate: |
| 520 |
description: |
| 521 |
- SAML signing key certificate, base64-encoded. |
| 522 |
saml.signing.private.key: |
| 523 |
description: |
| 524 |
- SAML signing key private key, base64-encoded. |
| 525 |
saml_assertion_consumer_url_post: |
| 526 |
description: |
| 527 |
- SAML POST Binding URL for the client's assertion consumer service (login responses). |
| 528 |
saml_assertion_consumer_url_redirect: |
| 529 |
description: |
| 530 |
- SAML Redirect Binding URL for the client's assertion consumer service (login responses). |
| 531 |
saml_force_name_id_format: |
| 532 |
description: |
| 533 |
- For SAML clients, Boolean specifying whether to ignore requested NameID subject format and using the configured |
| 534 |
one instead. |
| 535 |
saml_name_id_format: |
| 536 |
description: |
| 537 |
- For SAML clients, the NameID format to use (one of V(username), V(email), V(transient), or V(persistent)). |
| 538 |
saml_signature_canonicalization_method: |
| 539 |
description: |
| 540 |
- SAML signature canonicalization method. This is one of four values, namely V(http://www.w3.org/2001/10/xml-exc-c14n#) |
| 541 |
for EXCLUSIVE, V(http://www.w3.org/2001/10/xml-exc-c14n#WithComments) for EXCLUSIVE_WITH_COMMENTS, |
| 542 |
V(http://www.w3.org/TR/2001/REC-xml-c14n-20010315) |
| 543 |
for INCLUSIVE, and V(http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments) for INCLUSIVE_WITH_COMMENTS. |
| 544 |
saml_single_logout_service_url_post: |
| 545 |
description: |
| 546 |
- SAML POST binding URL for the client's single logout service. |
| 547 |
saml_single_logout_service_url_redirect: |
| 548 |
description: |
| 549 |
- SAML redirect binding URL for the client's single logout service. |
| 550 |
user.info.response.signature.alg: |
| 551 |
description: |
| 552 |
- For OpenID-Connect clients, JWA algorithm for signed UserInfo-endpoint responses. One of V(RS256) or V(unsigned). |
| 553 |
request.object.signature.alg: |
| 554 |
description: |
| 555 |
- For OpenID-Connect clients, JWA algorithm which the client needs to use when sending OIDC request object. One |
| 556 |
of V(any), V(none), V(RS256). |
| 557 |
use.jwks.url: |
| 558 |
description: |
| 559 |
- For OpenID-Connect clients, boolean specifying whether to use a JWKS URL to obtain client public keys. |
| 560 |
jwks.url: |
| 561 |
description: |
| 562 |
- For OpenID-Connect clients, URL where client keys in JWK are stored. |
| 563 |
jwt.credential.certificate: |
| 564 |
description: |
| 565 |
- For OpenID-Connect clients, client certificate for validating JWT issued by client and signed by its key, base64-encoded. |
| 566 |
x509.subjectdn: |
| 567 |
description: |
| 568 |
- For OpenID-Connect clients, subject which is used to authenticate the client. |
| 569 |
type: str |
| 570 |
version_added: 9.5.0 |
| 571 |
|
| 572 |
x509.allow.regex.pattern.comparison: |
| 573 |
description: |
| 574 |
- For OpenID-Connect clients, boolean specifying whether to allow C(x509.subjectdn) as regular expression. |
| 575 |
type: bool |
| 576 |
version_added: 9.5.0 |
| 577 |
|
| 578 |
extends_documentation_fragment: |
| 579 |
- community.general._keycloak |
| 580 |
- community.general._keycloak.actiongroup_keycloak |
| 581 |
- community.general._attributes |
| 582 |
|
| 583 |
author: |
| 584 |
- Eike Frost (@eikef) |
| 585 |
- Ivan Kokalović (@koke1997) |
| 586 |
""" |
| 587 |
|
| 588 |
EXAMPLES = r""" |
| 589 |
- name: Create or update Keycloak client (minimal example), authentication with credentials |
| 590 |
community.general.keycloak_client: |
| 591 |
auth_keycloak_url: https://auth.example.com/auth |
| 592 |
auth_realm: master |
| 593 |
auth_username: USERNAME |
| 594 |
auth_password: PASSWORD |
| 595 |
client_id: test |
| 596 |
state: present |
| 597 |
delegate_to: localhost |
| 598 |
|
| 599 |
|
| 600 |
- name: Create or update Keycloak client (minimal example), authentication with token |
| 601 |
community.general.keycloak_client: |
| 602 |
auth_client_id: admin-cli |
| 603 |
auth_keycloak_url: https://auth.example.com/auth |
| 604 |
auth_realm: master |
| 605 |
token: TOKEN |
| 606 |
client_id: test |
| 607 |
state: present |
| 608 |
delegate_to: localhost |
| 609 |
|
| 610 |
|
| 611 |
- name: Delete a Keycloak client |
| 612 |
community.general.keycloak_client: |
| 613 |
auth_client_id: admin-cli |
| 614 |
auth_keycloak_url: https://auth.example.com/auth |
| 615 |
auth_realm: master |
| 616 |
auth_username: USERNAME |
| 617 |
auth_password: PASSWORD |
| 618 |
client_id: test |
| 619 |
state: absent |
| 620 |
delegate_to: localhost |
| 621 |
|
| 622 |
|
| 623 |
- name: Create or update a Keycloak client (minimal example), with x509 authentication |
| 624 |
community.general.keycloak_client: |
| 625 |
auth_client_id: admin-cli |
| 626 |
auth_keycloak_url: https://auth.example.com/auth |
| 627 |
auth_realm: master |
| 628 |
auth_username: USERNAME |
| 629 |
auth_password: PASSWORD |
| 630 |
realm: master |
| 631 |
state: present |
| 632 |
client_id: test |
| 633 |
client_authenticator_type: client-x509 |
| 634 |
attributes: |
| 635 |
x509.subjectdn: "CN=client" |
| 636 |
x509.allow.regex.pattern.comparison: false |
| 637 |
|
| 638 |
|
| 639 |
- name: Create or update a Keycloak client (with all the bells and whistles) |
| 640 |
community.general.keycloak_client: |
| 641 |
auth_client_id: admin-cli |
| 642 |
auth_keycloak_url: https://auth.example.com/auth |
| 643 |
auth_realm: master |
| 644 |
auth_username: USERNAME |
| 645 |
auth_password: PASSWORD |
| 646 |
state: present |
| 647 |
realm: master |
| 648 |
client_id: test |
| 649 |
id: d8b127a3-31f6-44c8-a7e4-4ab9a3e78d95 |
| 650 |
name: this_is_a_test |
| 651 |
description: Description of this wonderful client |
| 652 |
root_url: https://www.example.com/ |
| 653 |
admin_url: https://www.example.com/admin_url |
| 654 |
base_url: basepath |
| 655 |
enabled: true |
| 656 |
client_authenticator_type: client-secret |
| 657 |
secret: REALLYWELLKEPTSECRET |
| 658 |
redirect_uris: |
| 659 |
- https://www.example.com/* |
| 660 |
- http://localhost:8888/ |
| 661 |
web_origins: |
| 662 |
- https://www.example.com/* |
| 663 |
not_before: 1507825725 |
| 664 |
bearer_only: false |
| 665 |
consent_required: false |
| 666 |
standard_flow_enabled: true |
| 667 |
implicit_flow_enabled: false |
| 668 |
direct_access_grants_enabled: false |
| 669 |
service_accounts_enabled: false |
| 670 |
authorization_services_enabled: false |
| 671 |
public_client: false |
| 672 |
frontchannel_logout: false |
| 673 |
protocol: openid-connect |
| 674 |
full_scope_allowed: false |
| 675 |
node_re_registration_timeout: -1 |
| 676 |
client_template: test |
| 677 |
use_template_config: false |
| 678 |
use_template_scope: false |
| 679 |
use_template_mappers: false |
| 680 |
always_display_in_console: true |
| 681 |
registered_nodes: |
| 682 |
node01.example.com: 1507828202 |
| 683 |
registration_access_token: eyJWT_TOKEN |
| 684 |
surrogate_auth_required: false |
| 685 |
default_roles: |
| 686 |
- test01 |
| 687 |
- test02 |
| 688 |
authentication_flow_binding_overrides: |
| 689 |
browser: 4c90336b-bf1d-4b87-916d-3677ba4e5fbb |
| 690 |
protocol_mappers: |
| 691 |
- config: |
| 692 |
access.token.claim: true |
| 693 |
claim.name: "family_name" |
| 694 |
id.token.claim: true |
| 695 |
jsonType.label: String |
| 696 |
user.attribute: lastName |
| 697 |
userinfo.token.claim: true |
| 698 |
consentRequired: true |
| 699 |
consentText: "${familyName}" |
| 700 |
name: family name |
| 701 |
protocol: openid-connect |
| 702 |
protocolMapper: oidc-usermodel-property-mapper |
| 703 |
- config: |
| 704 |
attribute.name: Role |
| 705 |
attribute.nameformat: Basic |
| 706 |
single: false |
| 707 |
consentRequired: false |
| 708 |
name: role list |
| 709 |
protocol: saml |
| 710 |
protocolMapper: saml-role-list-mapper |
| 711 |
attributes: |
| 712 |
saml.authnstatement: true |
| 713 |
saml.client.signature: true |
| 714 |
saml.force.post.binding: true |
| 715 |
saml.server.signature: true |
| 716 |
saml.signature.algorithm: RSA_SHA256 |
| 717 |
saml.signing.certificate: CERTIFICATEHERE |
| 718 |
saml.signing.private.key: PRIVATEKEYHERE |
| 719 |
saml_force_name_id_format: false |
| 720 |
saml_name_id_format: username |
| 721 |
saml_signature_canonicalization_method: "http://www.w3.org/2001/10/xml-exc-c14n#" |
| 722 |
user.info.response.signature.alg: RS256 |
| 723 |
request.object.signature.alg: RS256 |
| 724 |
use.jwks.url: true |
| 725 |
jwks.url: JWKS_URL_FOR_CLIENT_AUTH_JWT |
| 726 |
jwt.credential.certificate: JWT_CREDENTIAL_CERTIFICATE_FOR_CLIENT_AUTH |
| 727 |
delegate_to: localhost |
| 728 |
""" |
| 729 |
|
| 730 |
RETURN = r""" |
| 731 |
msg: |
| 732 |
description: Message as to what action was taken. |
| 733 |
returned: always |
| 734 |
type: str |
| 735 |
sample: "Client testclient has been updated" |
| 736 |
|
| 737 |
proposed: |
| 738 |
description: Representation of proposed client. |
| 739 |
returned: always |
| 740 |
type: dict |
| 741 |
sample: {"clientId": "test"} |
| 742 |
|
| 743 |
existing: |
| 744 |
description: Representation of existing client (sample is truncated). |
| 745 |
returned: always |
| 746 |
type: dict |
| 747 |
sample: |
| 748 |
{ |
| 749 |
"adminUrl": "http://www.example.com/admin_url", |
| 750 |
"attributes": { |
| 751 |
"request.object.signature.alg": "RS256" |
| 752 |
} |
| 753 |
} |
| 754 |
|
| 755 |
end_state: |
| 756 |
description: Representation of client after module execution (sample is truncated). |
| 757 |
returned: on success |
| 758 |
type: dict |
| 759 |
sample: |
| 760 |
{ |
| 761 |
"adminUrl": "http://www.example.com/admin_url", |
| 762 |
"attributes": { |
| 763 |
"request.object.signature.alg": "RS256" |
| 764 |
} |
| 765 |
} |
| 766 |
""" |
| 767 |
|
| 768 |
import copy |
| 769 |
|
| 770 |
from ansible.module_utils.basic import AnsibleModule |
| 771 |
|
| 772 |
from ansible_collections.community.general.plugins.module_utils._keycloak import ( |
| 773 |
KeycloakAPI, |
| 774 |
KeycloakError, |
| 775 |
camel, |
| 776 |
get_token, |
| 777 |
keycloak_argument_spec, |
| 778 |
) |
| 779 |
from ansible_collections.community.general.plugins.module_utils._keycloak_utils import ( |
| 780 |
merge_settings_without_absent_nulls, |
| 781 |
) |
| 782 |
|
| 783 |
PROTOCOL_OPENID_CONNECT = "openid-connect" |
| 784 |
PROTOCOL_SAML = "saml" |
| 785 |
PROTOCOL_DOCKER_V2 = "docker-v2" |
| 786 |
CLIENT_META_DATA = ["authorizationServicesEnabled"] |
| 787 |
|
| 788 |
# Parameters that map to client attributes rather than top-level API fields. |
| 789 |
# Each entry maps the module parameter name to (attribute_key, transform_fn). |
| 790 |
# transform_fn converts the module param value to the attribute string value. |
| 791 |
# Use None for transform_fn when no transformation is needed (identity). |
| 792 |
ATTRIBUTE_PARAMS = { |
| 793 |
"valid_post_logout_redirect_uris": ( |
| 794 |
"post.logout.redirect.uris", |
| 795 |
"##".join, |
| 796 |
), |
| 797 |
"backchannel_logout_url": ( |
| 798 |
"backchannel.logout.url", |
| 799 |
None, |
| 800 |
), |
| 801 |
} |
| 802 |
|
| 803 |
|
| 804 |
def normalise_scopes_for_behavior(desired_client, before_client, clientScopesBehavior): |
| 805 |
""" |
| 806 |
Normalize the desired and existing client scopes according to the specified behavior. |
| 807 |
|
| 808 |
This function adjusts the lists of default and optional client scopes in the desired client |
| 809 |
configuration based on the selected behavior: |
| 810 |
- 'ignore': The desired scopes are set to match the existing scopes. |
| 811 |
- 'patch': Any scopes present in the existing configuration but missing from the desired configuration |
| 812 |
are appended to the desired scopes. |
| 813 |
- 'idempotent': No modification is made; the desired scopes are used as-is. |
| 814 |
|
| 815 |
:param desired_client: |
| 816 |
type: dict |
| 817 |
description: The desired client configuration, including default and optional client scopes. |
| 818 |
|
| 819 |
:param before_client: |
| 820 |
type: dict |
| 821 |
description: The current client configuration, including default and optional client scopes. |
| 822 |
|
| 823 |
:param clientScopesBehavior: |
| 824 |
type: str |
| 825 |
description: The behavior mode for handling client scopes. Must be one of 'ignore', 'patch', or 'idempotent'. |
| 826 |
|
| 827 |
:return: |
| 828 |
type: tuple |
| 829 |
description: Returns a tuple of (desired_client, before_client) after normalization. |
| 830 |
""" |
| 831 |
desired_client = copy.deepcopy(desired_client) |
| 832 |
before_client = copy.deepcopy(before_client) |
| 833 |
if clientScopesBehavior == "ignore": |
| 834 |
desired_client["defaultClientScopes"] = copy.deepcopy(before_client["defaultClientScopes"]) |
| 835 |
desired_client["optionalClientScopes"] = copy.deepcopy(before_client["optionalClientScopes"]) |
| 836 |
elif clientScopesBehavior == "patch": |
| 837 |
for scope in before_client["defaultClientScopes"]: |
| 838 |
if scope not in desired_client["defaultClientScopes"]: |
| 839 |
desired_client["defaultClientScopes"].append(scope) |
| 840 |
for scope in before_client["optionalClientScopes"]: |
| 841 |
if scope not in desired_client["optionalClientScopes"]: |
| 842 |
desired_client["optionalClientScopes"].append(scope) |
| 843 |
|
| 844 |
return desired_client, before_client |
| 845 |
|
| 846 |
|
| 847 |
def check_optional_scopes_not_default(desired_client, clientScopesBehavior, module): |
| 848 |
""" |
| 849 |
Ensure that no client scope is assigned as both default and optional. |
| 850 |
|
| 851 |
This function checks the desired client configuration to verify that no scope is present |
| 852 |
in both the default and optional client scopes. If such a conflict is found, the module |
| 853 |
execution fails with an appropriate error message. |
| 854 |
|
| 855 |
:param desired_client: |
| 856 |
type: dict |
| 857 |
description: The desired client configuration, including default and optional client scopes. |
| 858 |
|
| 859 |
:param clientScopesBehavior: |
| 860 |
type: str |
| 861 |
description: The behavior mode for handling client scopes. Must be one of 'ignore', 'patch', or 'idempotent'. |
| 862 |
|
| 863 |
:param module: |
| 864 |
type: AnsibleModule |
| 865 |
description: The Ansible module instance, used to fail execution if a conflict is detected. |
| 866 |
|
| 867 |
:return: |
| 868 |
type: None |
| 869 |
description: Returns None. Fails the module if a scope is both default and optional. |
| 870 |
""" |
| 871 |
if clientScopesBehavior == "ignore": |
| 872 |
return |
| 873 |
for scope in desired_client["optionalClientScopes"]: |
| 874 |
if scope in desired_client["defaultClientScopes"]: |
| 875 |
module.fail_json(msg=f"Client scope {scope} cannot be both default and optional") |
| 876 |
|
| 877 |
|
| 878 |
def normalise_cr(clientrep, remove_ids=False): |
| 879 |
"""Re-sorts any properties where the order so that diff's is minimised, and adds default values where appropriate so that the |
| 880 |
the change detection is more effective. |
| 881 |
|
| 882 |
:param clientrep: the clientrep dict to be sanitized |
| 883 |
:param remove_ids: If set to true, then the unique ID's of objects is removed to make the diff and checks for changed |
| 884 |
not alert when the ID's of objects are not usually known, (e.g. for protocol_mappers) |
| 885 |
:return: normalised clientrep dict |
| 886 |
""" |
| 887 |
# Avoid the dict passed in to be modified |
| 888 |
clientrep = copy.deepcopy(clientrep) |
| 889 |
|
| 890 |
if remove_ids: |
| 891 |
clientrep.pop("id", None) |
| 892 |
|
| 893 |
if "defaultClientScopes" in clientrep: |
| 894 |
clientrep["defaultClientScopes"] = list(sorted(clientrep["defaultClientScopes"])) |
| 895 |
else: |
| 896 |
clientrep["defaultClientScopes"] = [] |
| 897 |
|
| 898 |
if "optionalClientScopes" in clientrep: |
| 899 |
clientrep["optionalClientScopes"] = list(sorted(clientrep["optionalClientScopes"])) |
| 900 |
else: |
| 901 |
clientrep["optionalClientScopes"] = [] |
| 902 |
|
| 903 |
if "redirectUris" in clientrep: |
| 904 |
clientrep["redirectUris"] = list(sorted(clientrep["redirectUris"])) |
| 905 |
else: |
| 906 |
clientrep["redirectUris"] = [] |
| 907 |
|
| 908 |
if "protocolMappers" in clientrep: |
| 909 |
clientrep["protocolMappers"] = sorted( |
| 910 |
clientrep["protocolMappers"], key=lambda x: (x.get("name"), x.get("protocol"), x.get("protocolMapper")) |
| 911 |
) |
| 912 |
for mapper in clientrep["protocolMappers"]: |
| 913 |
if remove_ids: |
| 914 |
mapper.pop("id", None) |
| 915 |
|
| 916 |
# Convert bool to string |
| 917 |
if "config" in mapper: |
| 918 |
for key, value in mapper["config"].items(): |
| 919 |
if isinstance(value, bool): |
| 920 |
mapper["config"][key] = str(value).lower() |
| 921 |
|
| 922 |
# Set to a default value. |
| 923 |
mapper["consentRequired"] = mapper.get("consentRequired", False) |
| 924 |
else: |
| 925 |
clientrep["protocolMappers"] = [] |
| 926 |
|
| 927 |
if "attributes" in clientrep: |
| 928 |
for key, value in clientrep["attributes"].items(): |
| 929 |
if isinstance(value, bool): |
| 930 |
clientrep["attributes"][key] = str(value).lower() |
| 931 |
clientrep["attributes"].pop("client.secret.creation.time", None) |
| 932 |
else: |
| 933 |
clientrep["attributes"] = [] |
| 934 |
|
| 935 |
if "webOrigins" in clientrep: |
| 936 |
clientrep["webOrigins"] = sorted(clientrep["webOrigins"]) |
| 937 |
else: |
| 938 |
clientrep["webOrigins"] = [] |
| 939 |
|
| 940 |
if "redirectUris" in clientrep: |
| 941 |
clientrep["redirectUris"] = sorted(clientrep["redirectUris"]) |
| 942 |
else: |
| 943 |
clientrep["redirectUris"] = [] |
| 944 |
|
| 945 |
return clientrep |
| 946 |
|
| 947 |
|
| 948 |
def normalize_kc_resp(clientrep): |
| 949 |
# kc drops the variable 'authorizationServicesEnabled' if set to false |
| 950 |
# to minimize diff/changes we set it to false if not set by kc |
| 951 |
if clientrep and "authorizationServicesEnabled" not in clientrep: |
| 952 |
clientrep["authorizationServicesEnabled"] = False |
| 953 |
|
| 954 |
|
| 955 |
def sanitize_cr(clientrep): |
| 956 |
"""Removes probably sensitive details from a client representation. |
| 957 |
|
| 958 |
:param clientrep: the clientrep dict to be sanitized |
| 959 |
:return: sanitized clientrep dict |
| 960 |
""" |
| 961 |
result = copy.deepcopy(clientrep) |
| 962 |
if "secret" in result: |
| 963 |
result["secret"] = "no_log" |
| 964 |
if "attributes" in result: |
| 965 |
attributes = result["attributes"] |
| 966 |
if isinstance(attributes, dict): |
| 967 |
if "saml.signing.private.key" in attributes: |
| 968 |
attributes["saml.signing.private.key"] = "no_log" |
| 969 |
if "saml.encryption.private.key" in attributes: |
| 970 |
attributes["saml.encryption.private.key"] = "no_log" |
| 971 |
return normalise_cr(result) |
| 972 |
|
| 973 |
|
| 974 |
def get_authentication_flow_id(flow_name, realm, kc): |
| 975 |
"""Get the authentication flow ID based on the flow name, realm, and Keycloak client. |
| 976 |
|
| 977 |
Args: |
| 978 |
flow_name (str): The name of the authentication flow. |
| 979 |
realm (str): The name of the realm. |
| 980 |
kc (KeycloakClient): The Keycloak client instance. |
| 981 |
|
| 982 |
Returns: |
| 983 |
str: The ID of the authentication flow. |
| 984 |
|
| 985 |
Raises: |
| 986 |
KeycloakAPIException: If the authentication flow with the given name is not found in the realm. |
| 987 |
""" |
| 988 |
flow = kc.get_authentication_flow_by_alias(flow_name, realm) |
| 989 |
if flow: |
| 990 |
return flow["id"] |
| 991 |
kc.module.fail_json(msg=f"Authentification flow {flow_name} not found in realm {realm}") |
| 992 |
|
| 993 |
|
| 994 |
def flow_binding_from_dict_to_model(newClientFlowBinding, realm, kc): |
| 995 |
"""Convert a dictionary representing client flow bindings to a model representation. |
| 996 |
|
| 997 |
Args: |
| 998 |
newClientFlowBinding (dict): A dictionary containing client flow bindings. |
| 999 |
realm (str): The name of the realm. |
| 1000 |
kc (KeycloakClient): An instance of the KeycloakClient class. |
| 1001 |
|
| 1002 |
Returns: |
| 1003 |
dict: A dictionary representing the model flow bindings. The dictionary has two keys: |
| 1004 |
- "browser" (str or None): The ID of the browser authentication flow binding, or None if not provided. |
| 1005 |
- "direct_grant" (str or None): The ID of the direct grant authentication flow binding, or None if not provided. |
| 1006 |
|
| 1007 |
Raises: |
| 1008 |
KeycloakAPIException: If the authentication flow with the given name is not found in the realm. |
| 1009 |
|
| 1010 |
""" |
| 1011 |
|
| 1012 |
modelFlow = {"browser": None, "direct_grant": None} |
| 1013 |
|
| 1014 |
for k, v in newClientFlowBinding.items(): |
| 1015 |
if not v: |
| 1016 |
continue |
| 1017 |
if k == "browser": |
| 1018 |
modelFlow["browser"] = v |
| 1019 |
elif k == "browser_name": |
| 1020 |
modelFlow["browser"] = get_authentication_flow_id(v, realm, kc) |
| 1021 |
elif k == "direct_grant": |
| 1022 |
modelFlow["direct_grant"] = v |
| 1023 |
elif k == "direct_grant_name": |
| 1024 |
modelFlow["direct_grant"] = get_authentication_flow_id(v, realm, kc) |
| 1025 |
|
| 1026 |
return modelFlow |
| 1027 |
|
| 1028 |
|
| 1029 |
def find_match(iterable, attribute, name): |
| 1030 |
""" |
| 1031 |
Search for an element in a list of dictionaries based on a given attribute and value. |
| 1032 |
|
| 1033 |
This function iterates over the elements of an iterable (typically a list of dictionaries) |
| 1034 |
and returns the first element whose value for the specified attribute matches `name`. |
| 1035 |
|
| 1036 |
:param iterable: |
| 1037 |
type: iterable (commonly list[dict]) |
| 1038 |
description: The collection of elements to search within (usually a list of dictionaries). |
| 1039 |
|
| 1040 |
:param attribute: |
| 1041 |
type: str |
| 1042 |
description: The dictionary key/attribute used for comparison. |
| 1043 |
|
| 1044 |
:param name: |
| 1045 |
type: Any |
| 1046 |
description: The value to search for within the given attribute. |
| 1047 |
|
| 1048 |
:return: |
| 1049 |
type: dict | None |
| 1050 |
description: Returns the first dictionary where the attribute matches the given value case insensitive. |
| 1051 |
Returns `None` if no match is found. |
| 1052 |
""" |
| 1053 |
name_lower = str(name).lower() |
| 1054 |
return next( |
| 1055 |
(value for value in iterable if attribute in value and str(value[attribute]).lower() == name_lower), |
| 1056 |
None, |
| 1057 |
) |
| 1058 |
|
| 1059 |
|
| 1060 |
def add_default_client_scopes(desired_client, before_client, realm, kc): |
| 1061 |
""" |
| 1062 |
Adds missing default client scopes to a Keycloak client. |
| 1063 |
|
| 1064 |
This function compares the desired default client scopes specified in `desired_client` |
| 1065 |
with the current default client scopes in `before_client`. For each scope that is present |
| 1066 |
in `desired_client["defaultClientScopes"]` but missing from `before_client['defaultClientScopes']`, |
| 1067 |
it retrieves the scope information from Keycloak and adds it to the client. |
| 1068 |
|
| 1069 |
:param desired_client: |
| 1070 |
type: dict |
| 1071 |
description: The desired client configuration, including the list of default client scopes. |
| 1072 |
|
| 1073 |
:param before_client: |
| 1074 |
type: dict |
| 1075 |
description: The current client configuration, including the list of default client scopes. |
| 1076 |
|
| 1077 |
:param realm |
| 1078 |
type: str |
| 1079 |
description: The name of the Keycloak realm. |
| 1080 |
|
| 1081 |
:param kc |
| 1082 |
type: KeycloakAPI |
| 1083 |
description: An instance of the Keycloak API client. |
| 1084 |
|
| 1085 |
Returns: |
| 1086 |
None |
| 1087 |
""" |
| 1088 |
desired_default_scope = desired_client["defaultClientScopes"] |
| 1089 |
missing_scopes = [item for item in desired_default_scope if item not in before_client["defaultClientScopes"]] |
| 1090 |
if not missing_scopes: |
| 1091 |
return |
| 1092 |
client_scopes = kc.get_clientscopes(realm) |
| 1093 |
for name in missing_scopes: |
| 1094 |
scope = find_match(client_scopes, "name", name) |
| 1095 |
if scope: |
| 1096 |
kc.add_default_clientscope(scope["id"], realm, desired_client["clientId"]) |
| 1097 |
|
| 1098 |
|
| 1099 |
def add_optional_client_scopes(desired_client, before_client, realm, kc): |
| 1100 |
""" |
| 1101 |
Adds missing optional client scopes to a Keycloak client. |
| 1102 |
|
| 1103 |
This function compares the desired optional client scopes specified in `desired_client` |
| 1104 |
with the current optional client scopes in `before_client`. For each scope that is present |
| 1105 |
in `desired_client["optionalClientScopes"]` but missing from `before_client['optionalClientScopes']`, |
| 1106 |
it retrieves the scope information from Keycloak and adds it to the client. |
| 1107 |
|
| 1108 |
:param desired_client: |
| 1109 |
type: dict |
| 1110 |
description: The desired client configuration, including the list of optional client scopes. |
| 1111 |
|
| 1112 |
:param before_client: |
| 1113 |
type: dict |
| 1114 |
description: The current client configuration, including the list of optional client scopes. |
| 1115 |
|
| 1116 |
:param realm: |
| 1117 |
type: str |
| 1118 |
description: The name of the Keycloak realm. |
| 1119 |
|
| 1120 |
:param kc: |
| 1121 |
type: KeycloakAPI |
| 1122 |
description: An instance of the Keycloak API client. |
| 1123 |
|
| 1124 |
Returns: |
| 1125 |
None |
| 1126 |
""" |
| 1127 |
desired_optional_scope = desired_client["optionalClientScopes"] |
| 1128 |
missing_scopes = [item for item in desired_optional_scope if item not in before_client["optionalClientScopes"]] |
| 1129 |
if not missing_scopes: |
| 1130 |
return |
| 1131 |
client_scopes = kc.get_clientscopes(realm) |
| 1132 |
for name in missing_scopes: |
| 1133 |
scope = find_match(client_scopes, "name", name) |
| 1134 |
if scope: |
| 1135 |
kc.add_optional_clientscope(scope["id"], realm, desired_client["clientId"]) |
| 1136 |
|
| 1137 |
|
| 1138 |
def remove_default_client_scopes(desired_client, before_client, realm, kc): |
| 1139 |
""" |
| 1140 |
Removes default client scopes from a Keycloak client that are no longer desired. |
| 1141 |
|
| 1142 |
This function compares the current default client scopes in `before_client` |
| 1143 |
with the desired default client scopes in `desired_client`. For each scope that is present |
| 1144 |
in `before_client["defaultClientScopes"]` but missing from `desired_client['defaultClientScopes']`, |
| 1145 |
it retrieves the scope information from Keycloak and removes it from the client. |
| 1146 |
|
| 1147 |
:param desired_client: |
| 1148 |
type: dict |
| 1149 |
description: The desired client configuration, including the list of default client scopes. |
| 1150 |
|
| 1151 |
:param before_client: |
| 1152 |
type: dict |
| 1153 |
description: The current client configuration, including the list of default client scopes. |
| 1154 |
|
| 1155 |
:param realm: |
| 1156 |
type: str |
| 1157 |
description: The name of the Keycloak realm. |
| 1158 |
|
| 1159 |
:param kc: |
| 1160 |
type: KeycloakAPI |
| 1161 |
description: An instance of the Keycloak API client. |
| 1162 |
|
| 1163 |
Returns: |
| 1164 |
None |
| 1165 |
""" |
| 1166 |
before_default_scope = before_client["defaultClientScopes"] |
| 1167 |
missing_scopes = [item for item in before_default_scope if item not in desired_client["defaultClientScopes"]] |
| 1168 |
if not missing_scopes: |
| 1169 |
return |
| 1170 |
client_scopes = kc.get_default_clientscopes(realm, desired_client["clientId"]) |
| 1171 |
for name in missing_scopes: |
| 1172 |
scope = find_match(client_scopes, "name", name) |
| 1173 |
if scope: |
| 1174 |
kc.delete_default_clientscope(scope["id"], realm, desired_client["clientId"]) |
| 1175 |
|
| 1176 |
|
| 1177 |
def remove_optional_client_scopes(desired_client, before_client, realm, kc): |
| 1178 |
""" |
| 1179 |
Removes optional client scopes from a Keycloak client that are no longer desired. |
| 1180 |
|
| 1181 |
This function compares the current optional client scopes in `before_client` |
| 1182 |
with the desired optional client scopes in `desired_client`. For each scope that is present |
| 1183 |
in `before_client["optionalClientScopes"]` but missing from `desired_client['optionalClientScopes']`, |
| 1184 |
it retrieves the scope information from Keycloak and removes it from the client. |
| 1185 |
|
| 1186 |
:param desired_client: |
| 1187 |
type: dict |
| 1188 |
description: The desired client configuration, including the list of optional client scopes. |
| 1189 |
|
| 1190 |
:param before_client: |
| 1191 |
type: dict |
| 1192 |
description: The current client configuration, including the list of optional client scopes. |
| 1193 |
|
| 1194 |
:param realm: |
| 1195 |
type: str |
| 1196 |
description: The name of the Keycloak realm. |
| 1197 |
|
| 1198 |
:param kc: |
| 1199 |
type: KeycloakAPI |
| 1200 |
description: An instance of the Keycloak API client. |
| 1201 |
|
| 1202 |
Returns: |
| 1203 |
None |
| 1204 |
""" |
| 1205 |
before_optional_scope = before_client["optionalClientScopes"] |
| 1206 |
missing_scopes = [item for item in before_optional_scope if item not in desired_client["optionalClientScopes"]] |
| 1207 |
if not missing_scopes: |
| 1208 |
return |
| 1209 |
client_scopes = kc.get_optional_clientscopes(realm, desired_client["clientId"]) |
| 1210 |
for name in missing_scopes: |
| 1211 |
scope = find_match(client_scopes, "name", name) |
| 1212 |
if scope: |
| 1213 |
kc.delete_optional_clientscope(scope["id"], realm, desired_client["clientId"]) |
| 1214 |
|
| 1215 |
|
| 1216 |
def main(): |
| 1217 |
""" |
| 1218 |
Module execution |
| 1219 |
|
| 1220 |
:return: |
| 1221 |
""" |
| 1222 |
argument_spec = keycloak_argument_spec() |
| 1223 |
|
| 1224 |
protmapper_spec = dict( |
| 1225 |
consentRequired=dict(type="bool"), |
| 1226 |
consentText=dict(type="str"), |
| 1227 |
id=dict(type="str"), |
| 1228 |
name=dict(type="str"), |
| 1229 |
protocol=dict(type="str", choices=[PROTOCOL_OPENID_CONNECT, PROTOCOL_SAML, PROTOCOL_DOCKER_V2]), |
| 1230 |
protocolMapper=dict(type="str"), |
| 1231 |
config=dict(type="dict"), |
| 1232 |
) |
| 1233 |
|
| 1234 |
authentication_flow_spec = dict( |
| 1235 |
browser=dict(type="str"), |
| 1236 |
browser_name=dict(type="str", aliases=["browserName"]), |
| 1237 |
direct_grant=dict(type="str", aliases=["directGrant"]), |
| 1238 |
direct_grant_name=dict(type="str", aliases=["directGrantName"]), |
| 1239 |
) |
| 1240 |
|
| 1241 |
meta_args = dict( |
| 1242 |
state=dict(default="present", choices=["present", "absent"]), |
| 1243 |
realm=dict(type="str", default="master"), |
| 1244 |
id=dict(type="str"), |
| 1245 |
client_id=dict(type="str", aliases=["clientId"]), |
| 1246 |
name=dict(type="str"), |
| 1247 |
description=dict(type="str"), |
| 1248 |
root_url=dict(type="str", aliases=["rootUrl"]), |
| 1249 |
admin_url=dict(type="str", aliases=["adminUrl"]), |
| 1250 |
base_url=dict(type="str", aliases=["baseUrl"]), |
| 1251 |
surrogate_auth_required=dict(type="bool", aliases=["surrogateAuthRequired"]), |
| 1252 |
enabled=dict(type="bool"), |
| 1253 |
client_authenticator_type=dict( |
| 1254 |
type="str", choices=["client-secret", "client-jwt", "client-x509"], aliases=["clientAuthenticatorType"] |
| 1255 |
), |
| 1256 |
secret=dict(type="str", no_log=True), |
| 1257 |
registration_access_token=dict(type="str", aliases=["registrationAccessToken"], no_log=True), |
| 1258 |
default_roles=dict(type="list", elements="str", aliases=["defaultRoles"]), |
| 1259 |
redirect_uris=dict(type="list", elements="str", aliases=["redirectUris"]), |
| 1260 |
web_origins=dict(type="list", elements="str", aliases=["webOrigins"]), |
| 1261 |
valid_post_logout_redirect_uris=dict(type="list", elements="str", aliases=["postLogoutRedirectUris"]), |
| 1262 |
not_before=dict(type="int", aliases=["notBefore"]), |
| 1263 |
bearer_only=dict(type="bool", aliases=["bearerOnly"]), |
| 1264 |
consent_required=dict(type="bool", aliases=["consentRequired"]), |
| 1265 |
standard_flow_enabled=dict(type="bool", aliases=["standardFlowEnabled"]), |
| 1266 |
implicit_flow_enabled=dict(type="bool", aliases=["implicitFlowEnabled"]), |
| 1267 |
direct_access_grants_enabled=dict(type="bool", aliases=["directAccessGrantsEnabled"]), |
| 1268 |
service_accounts_enabled=dict(type="bool", aliases=["serviceAccountsEnabled"]), |
| 1269 |
authorization_services_enabled=dict(type="bool", aliases=["authorizationServicesEnabled"]), |
| 1270 |
public_client=dict(type="bool", aliases=["publicClient"]), |
| 1271 |
frontchannel_logout=dict(type="bool", aliases=["frontchannelLogout"]), |
| 1272 |
backchannel_logout_url=dict(type="str", aliases=["backchannelLogoutUrl"]), |
| 1273 |
protocol=dict(type="str", choices=[PROTOCOL_OPENID_CONNECT, PROTOCOL_SAML, PROTOCOL_DOCKER_V2]), |
| 1274 |
attributes=dict(type="dict"), |
| 1275 |
full_scope_allowed=dict(type="bool", aliases=["fullScopeAllowed"]), |
| 1276 |
node_re_registration_timeout=dict(type="int", aliases=["nodeReRegistrationTimeout"]), |
| 1277 |
registered_nodes=dict(type="dict", aliases=["registeredNodes"]), |
| 1278 |
client_template=dict(type="str", aliases=["clientTemplate"]), |
| 1279 |
use_template_config=dict(type="bool", aliases=["useTemplateConfig"]), |
| 1280 |
use_template_scope=dict(type="bool", aliases=["useTemplateScope"]), |
| 1281 |
use_template_mappers=dict(type="bool", aliases=["useTemplateMappers"]), |
| 1282 |
always_display_in_console=dict(type="bool", aliases=["alwaysDisplayInConsole"]), |
| 1283 |
authentication_flow_binding_overrides=dict( |
| 1284 |
type="dict", |
| 1285 |
aliases=["authenticationFlowBindingOverrides"], |
| 1286 |
options=authentication_flow_spec, |
| 1287 |
required_one_of=[["browser", "direct_grant", "browser_name", "direct_grant_name"]], |
| 1288 |
mutually_exclusive=[["browser", "browser_name"], ["direct_grant", "direct_grant_name"]], |
| 1289 |
), |
| 1290 |
protocol_mappers=dict(type="list", elements="dict", options=protmapper_spec, aliases=["protocolMappers"]), |
| 1291 |
authorization_settings=dict(type="dict", aliases=["authorizationSettings"]), |
| 1292 |
client_scopes_behavior=dict( |
| 1293 |
type="str", aliases=["clientScopesBehavior"], choices=["ignore", "patch", "idempotent"], default="ignore" |
| 1294 |
), |
| 1295 |
default_client_scopes=dict(type="list", elements="str", aliases=["defaultClientScopes"]), |
| 1296 |
optional_client_scopes=dict(type="list", elements="str", aliases=["optionalClientScopes"]), |
| 1297 |
) |
| 1298 |
|
| 1299 |
argument_spec.update(meta_args) |
| 1300 |
|
| 1301 |
module = AnsibleModule( |
| 1302 |
argument_spec=argument_spec, |
| 1303 |
supports_check_mode=True, |
| 1304 |
required_one_of=( |
| 1305 |
[ |
| 1306 |
["client_id", "id"], |
| 1307 |
["token", "auth_realm", "auth_username", "auth_password", "auth_client_id", "auth_client_secret"], |
| 1308 |
] |
| 1309 |
), |
| 1310 |
required_together=([["auth_username", "auth_password"]]), |
| 1311 |
required_by={"refresh_token": "auth_realm"}, |
| 1312 |
) |
| 1313 |
|
| 1314 |
result = dict(changed=False, msg="", diff={}, proposed={}, existing={}, end_state={}) |
| 1315 |
|
| 1316 |
# Obtain access token, initialize API |
| 1317 |
try: |
| 1318 |
connection_header = get_token(module.params) |
| 1319 |
except KeycloakError as e: |
| 1320 |
module.fail_json(msg=str(e)) |
| 1321 |
|
| 1322 |
kc = KeycloakAPI(module, connection_header) |
| 1323 |
|
| 1324 |
realm = module.params.get("realm") |
| 1325 |
cid = module.params.get("id") |
| 1326 |
clientScopesBehavior = module.params.get("client_scopes_behavior") |
| 1327 |
state = module.params.get("state") |
| 1328 |
|
| 1329 |
# Filter and map the parameters names that apply to the client |
| 1330 |
client_params = [ |
| 1331 |
x |
| 1332 |
for x in module.params |
| 1333 |
if x not in list(keycloak_argument_spec().keys()) + ["state", "realm"] and module.params.get(x) is not None |
| 1334 |
] |
| 1335 |
|
| 1336 |
# See if it already exists in Keycloak |
| 1337 |
if cid is None: |
| 1338 |
before_client = kc.get_client_by_clientid(module.params.get("client_id"), realm=realm) |
| 1339 |
if before_client is not None: |
| 1340 |
cid = before_client["id"] |
| 1341 |
else: |
| 1342 |
before_client = kc.get_client_by_id(cid, realm=realm) |
| 1343 |
|
| 1344 |
normalize_kc_resp(before_client) |
| 1345 |
|
| 1346 |
if before_client is None: |
| 1347 |
before_client = {} |
| 1348 |
|
| 1349 |
# Build a proposed changeset from parameters given to this module |
| 1350 |
changeset = {} |
| 1351 |
|
| 1352 |
# Collect attribute-mapped parameters to inject into attributes later |
| 1353 |
attribute_overrides = {} |
| 1354 |
for param_name, (attr_key, transform_fn) in ATTRIBUTE_PARAMS.items(): |
| 1355 |
param_value = module.params.get(param_name) |
| 1356 |
if param_value is not None: |
| 1357 |
attribute_overrides[attr_key] = transform_fn(param_value) if transform_fn else param_value |
| 1358 |
|
| 1359 |
for client_param in client_params: |
| 1360 |
new_param_value = module.params.get(client_param) |
| 1361 |
|
| 1362 |
# Skip attribute-mapped params; they are handled via attributes |
| 1363 |
if client_param in ATTRIBUTE_PARAMS: |
| 1364 |
continue |
| 1365 |
|
| 1366 |
# Unfortunately, the ansible argument spec checker introduces variables with null values when |
| 1367 |
# they are not specified |
| 1368 |
if client_param == "protocol_mappers": |
| 1369 |
new_param_value = [{k: v for k, v in x.items() if v is not None} for x in new_param_value] |
| 1370 |
elif client_param == "authentication_flow_binding_overrides": |
| 1371 |
desired_flow_binding_overrides = flow_binding_from_dict_to_model(new_param_value, realm, kc) |
| 1372 |
existing_flow_binding_overrides = before_client.get("authenticationFlowBindingOverrides") |
| 1373 |
# ensures idempotency |
| 1374 |
new_param_value = merge_settings_without_absent_nulls( |
| 1375 |
existing_flow_binding_overrides, desired_flow_binding_overrides |
| 1376 |
) |
| 1377 |
elif client_param == "attributes" and "attributes" in before_client: |
| 1378 |
desired_attributes = new_param_value |
| 1379 |
existing_attributes = copy.deepcopy(before_client["attributes"]) |
| 1380 |
# ensures idempotency |
| 1381 |
new_param_value = merge_settings_without_absent_nulls(existing_attributes, desired_attributes) |
| 1382 |
elif client_param in ["clientScopesBehavior", "client_scopes_behavior"]: |
| 1383 |
continue |
| 1384 |
|
| 1385 |
changeset[camel(client_param)] = new_param_value |
| 1386 |
|
| 1387 |
# Inject attribute-mapped parameters into the attributes dict |
| 1388 |
if attribute_overrides: |
| 1389 |
if "attributes" not in changeset: |
| 1390 |
changeset["attributes"] = copy.deepcopy(before_client.get("attributes", {})) |
| 1391 |
if isinstance(changeset["attributes"], dict): |
| 1392 |
changeset["attributes"].update(attribute_overrides) |
| 1393 |
|
| 1394 |
# Prepare the desired values using the existing values (non-existence results in a dict that is save to use as a basis) |
| 1395 |
desired_client = copy.deepcopy(before_client) |
| 1396 |
desired_client.update(changeset) |
| 1397 |
|
| 1398 |
result["proposed"] = sanitize_cr(changeset) |
| 1399 |
result["existing"] = sanitize_cr(before_client) |
| 1400 |
|
| 1401 |
# Cater for when it doesn't exist (an empty dict) |
| 1402 |
if not before_client: |
| 1403 |
if state == "absent": |
| 1404 |
# Do nothing and exit |
| 1405 |
if module._diff: |
| 1406 |
result["diff"] = dict(before="", after="") |
| 1407 |
result["changed"] = False |
| 1408 |
result["end_state"] = {} |
| 1409 |
result["msg"] = "Client does not exist; doing nothing." |
| 1410 |
module.exit_json(**result) |
| 1411 |
|
| 1412 |
# Process a creation |
| 1413 |
result["changed"] = True |
| 1414 |
|
| 1415 |
if "clientId" not in desired_client: |
| 1416 |
module.fail_json(msg="client_id needs to be specified when creating a new client") |
| 1417 |
if "protocol" not in desired_client: |
| 1418 |
desired_client["protocol"] = PROTOCOL_OPENID_CONNECT |
| 1419 |
|
| 1420 |
if module._diff: |
| 1421 |
result["diff"] = dict(before="", after=sanitize_cr(desired_client)) |
| 1422 |
|
| 1423 |
if module.check_mode: |
| 1424 |
module.exit_json(**result) |
| 1425 |
|
| 1426 |
# create it |
| 1427 |
kc.create_client(desired_client, realm=realm) |
| 1428 |
after_client = kc.get_client_by_clientid(desired_client["clientId"], realm=realm) |
| 1429 |
|
| 1430 |
result["end_state"] = sanitize_cr(after_client) |
| 1431 |
|
| 1432 |
result["msg"] = f"Client {desired_client['clientId']} has been created." |
| 1433 |
module.exit_json(**result) |
| 1434 |
|
| 1435 |
else: |
| 1436 |
if state == "present": |
| 1437 |
# We can only compare the current client with the proposed updates we have |
| 1438 |
desired_client_with_scopes, before_client_with_scopes = normalise_scopes_for_behavior( |
| 1439 |
desired_client, before_client, clientScopesBehavior |
| 1440 |
) |
| 1441 |
check_optional_scopes_not_default(desired_client, clientScopesBehavior, module) |
| 1442 |
before_norm = normalise_cr(before_client_with_scopes, remove_ids=True) |
| 1443 |
desired_norm = normalise_cr(desired_client_with_scopes, remove_ids=True) |
| 1444 |
# no changes |
| 1445 |
if before_norm == desired_norm: |
| 1446 |
result["changed"] = False |
| 1447 |
result["end_state"] = sanitize_cr(before_client) |
| 1448 |
result["msg"] = f"No changes required for Client {desired_client['clientId']}." |
| 1449 |
module.exit_json(**result) |
| 1450 |
|
| 1451 |
# Process an update |
| 1452 |
result["changed"] = True |
| 1453 |
|
| 1454 |
if module.check_mode: |
| 1455 |
result["end_state"] = sanitize_cr(desired_client_with_scopes) |
| 1456 |
if module._diff: |
| 1457 |
result["diff"] = dict(before=sanitize_cr(before_norm), after=sanitize_cr(desired_norm)) |
| 1458 |
module.exit_json(**result) |
| 1459 |
|
| 1460 |
# do the update |
| 1461 |
kc.update_client(cid, desired_client, realm=realm) |
| 1462 |
|
| 1463 |
remove_default_client_scopes(desired_client_with_scopes, before_client_with_scopes, realm, kc) |
| 1464 |
remove_optional_client_scopes(desired_client_with_scopes, before_client_with_scopes, realm, kc) |
| 1465 |
add_default_client_scopes(desired_client_with_scopes, before_client_with_scopes, realm, kc) |
| 1466 |
add_optional_client_scopes(desired_client_with_scopes, before_client_with_scopes, realm, kc) |
| 1467 |
|
| 1468 |
after_client = kc.get_client_by_id(cid, realm=realm) |
| 1469 |
normalize_kc_resp(after_client) |
| 1470 |
|
| 1471 |
if module._diff: |
| 1472 |
result["diff"] = dict(before=sanitize_cr(before_client), after=sanitize_cr(after_client)) |
| 1473 |
|
| 1474 |
result["end_state"] = sanitize_cr(after_client) |
| 1475 |
|
| 1476 |
result["msg"] = f"Client {desired_client['clientId']} has been updated." |
| 1477 |
module.exit_json(**result) |
| 1478 |
|
| 1479 |
else: |
| 1480 |
# Process a deletion (because state was not 'present') |
| 1481 |
result["changed"] = True |
| 1482 |
|
| 1483 |
if module._diff: |
| 1484 |
result["diff"] = dict(before=sanitize_cr(before_client), after="") |
| 1485 |
|
| 1486 |
if module.check_mode: |
| 1487 |
module.exit_json(**result) |
| 1488 |
|
| 1489 |
# delete it |
| 1490 |
kc.delete_client(cid, realm=realm) |
| 1491 |
result["proposed"] = {} |
| 1492 |
|
| 1493 |
result["end_state"] = {} |
| 1494 |
|
| 1495 |
result["msg"] = f"Client {before_client['clientId']} has been deleted." |
| 1496 |
|
| 1497 |
module.exit_json(**result) |
| 1498 |
|
| 1499 |
|
| 1500 |
if __name__ == "__main__": |
| 1501 |
main() |