2023-04-23 12:07:58 +00:00
|
|
|
#!/usr/bin/python
|
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
|
|
|
|
# Copyright (c) 2017, Eike Frost <ei@kefro.st>
|
|
|
|
# Copyright (c) 2021, Christophe Gilles <christophe.gilles54@gmail.com>
|
|
|
|
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or
|
|
|
|
# https://www.gnu.org/licenses/gpl-3.0.txt)
|
|
|
|
# SPDX-License-Identifier: GPL-3.0-or-later
|
|
|
|
from __future__ import absolute_import, division, print_function
|
|
|
|
__metaclass__ = type
|
|
|
|
|
2024-12-26 12:42:44 +00:00
|
|
|
DOCUMENTATION = r"""
|
2023-04-23 12:07:58 +00:00
|
|
|
module: keycloak_authz_authorization_scope
|
|
|
|
|
2024-12-26 12:42:44 +00:00
|
|
|
short_description: Allows administration of Keycloak client authorization scopes using Keycloak API
|
2023-04-23 12:07:58 +00:00
|
|
|
|
|
|
|
version_added: 6.6.0
|
|
|
|
|
|
|
|
description:
|
2025-01-06 20:31:59 +00:00
|
|
|
- This module allows the administration of Keycloak client Authorization Scopes using the Keycloak REST API. Authorization
|
|
|
|
Scopes are only available if a client has Authorization enabled.
|
|
|
|
- This module requires access to the REST API using OpenID Connect; the user connecting and the realm being used must have
|
|
|
|
the requisite access rights. In a default Keycloak installation, admin-cli and an admin user would work, as would a separate
|
|
|
|
realm definition with the scope tailored to your needs and a user having the expected roles.
|
|
|
|
- The names of module options are snake_cased versions of the camelCase options used by Keycloak. The Authorization Services
|
|
|
|
paths and payloads have not officially been documented by the Keycloak project.
|
|
|
|
U(https://www.puppeteers.net/blog/keycloak-authorization-services-rest-api-paths-and-payload/).
|
2023-04-23 12:07:58 +00:00
|
|
|
attributes:
|
2024-12-26 12:42:44 +00:00
|
|
|
check_mode:
|
|
|
|
support: full
|
|
|
|
diff_mode:
|
|
|
|
support: full
|
|
|
|
action_group:
|
|
|
|
version_added: 10.2.0
|
2023-04-23 12:07:58 +00:00
|
|
|
|
|
|
|
options:
|
2024-12-26 12:42:44 +00:00
|
|
|
state:
|
|
|
|
description:
|
|
|
|
- State of the authorization scope.
|
|
|
|
- On V(present), the authorization scope will be created (or updated if it exists already).
|
|
|
|
- On V(absent), the authorization scope will be removed if it exists.
|
|
|
|
choices: ['present', 'absent']
|
|
|
|
default: 'present'
|
|
|
|
type: str
|
|
|
|
name:
|
|
|
|
description:
|
|
|
|
- Name of the authorization scope to create.
|
|
|
|
type: str
|
|
|
|
required: true
|
|
|
|
display_name:
|
|
|
|
description:
|
|
|
|
- The display name of the authorization scope.
|
|
|
|
type: str
|
|
|
|
required: false
|
|
|
|
icon_uri:
|
|
|
|
description:
|
|
|
|
- The icon URI for the authorization scope.
|
|
|
|
type: str
|
|
|
|
required: false
|
|
|
|
client_id:
|
|
|
|
description:
|
|
|
|
- The C(clientId) of the Keycloak client that should have the authorization scope.
|
|
|
|
- This is usually a human-readable name of the Keycloak client.
|
|
|
|
type: str
|
|
|
|
required: true
|
|
|
|
realm:
|
|
|
|
description:
|
|
|
|
- The name of the Keycloak realm the Keycloak client is in.
|
|
|
|
type: str
|
|
|
|
required: true
|
2023-04-23 12:07:58 +00:00
|
|
|
|
|
|
|
extends_documentation_fragment:
|
2024-12-26 12:42:44 +00:00
|
|
|
- community.general.keycloak
|
|
|
|
- community.general.keycloak.actiongroup_keycloak
|
|
|
|
- community.general.attributes
|
2023-04-23 12:07:58 +00:00
|
|
|
|
|
|
|
author:
|
2024-12-26 12:42:44 +00:00
|
|
|
- Samuli Seppänen (@mattock)
|
|
|
|
"""
|
2023-04-23 12:07:58 +00:00
|
|
|
|
2024-12-26 12:42:44 +00:00
|
|
|
EXAMPLES = r"""
|
2023-04-23 12:07:58 +00:00
|
|
|
- name: Manage Keycloak file:delete authorization scope
|
|
|
|
keycloak_authz_authorization_scope:
|
|
|
|
name: file:delete
|
|
|
|
state: present
|
|
|
|
display_name: File delete
|
|
|
|
client_id: myclient
|
|
|
|
realm: myrealm
|
|
|
|
auth_keycloak_url: http://localhost:8080/auth
|
|
|
|
auth_username: keycloak
|
|
|
|
auth_password: keycloak
|
|
|
|
auth_realm: master
|
2024-12-26 12:42:44 +00:00
|
|
|
"""
|
2023-04-23 12:07:58 +00:00
|
|
|
|
2024-12-26 12:42:44 +00:00
|
|
|
RETURN = r"""
|
2023-04-23 12:07:58 +00:00
|
|
|
msg:
|
2024-12-26 12:42:44 +00:00
|
|
|
description: Message as to what action was taken.
|
|
|
|
returned: always
|
|
|
|
type: str
|
2023-04-23 12:07:58 +00:00
|
|
|
|
|
|
|
end_state:
|
2024-12-26 12:42:44 +00:00
|
|
|
description: Representation of the authorization scope after module execution.
|
|
|
|
returned: on success
|
|
|
|
type: complex
|
|
|
|
contains:
|
|
|
|
id:
|
|
|
|
description: ID of the authorization scope.
|
|
|
|
type: str
|
|
|
|
returned: when O(state=present)
|
|
|
|
sample: a6ab1cf2-1001-40ec-9f39-48f23b6a0a41
|
|
|
|
name:
|
|
|
|
description: Name of the authorization scope.
|
|
|
|
type: str
|
|
|
|
returned: when O(state=present)
|
|
|
|
sample: file:delete
|
|
|
|
display_name:
|
|
|
|
description: Display name of the authorization scope.
|
|
|
|
type: str
|
|
|
|
returned: when O(state=present)
|
|
|
|
sample: File delete
|
|
|
|
icon_uri:
|
|
|
|
description: Icon URI for the authorization scope.
|
|
|
|
type: str
|
|
|
|
returned: when O(state=present)
|
|
|
|
sample: http://localhost/icon.png
|
|
|
|
"""
|
2023-04-23 12:07:58 +00:00
|
|
|
|
|
|
|
from ansible_collections.community.general.plugins.module_utils.identity.keycloak.keycloak import KeycloakAPI, \
|
|
|
|
keycloak_argument_spec, get_token, KeycloakError
|
|
|
|
from ansible.module_utils.basic import AnsibleModule
|
|
|
|
|
|
|
|
|
|
|
|
def main():
|
|
|
|
"""
|
|
|
|
Module execution
|
|
|
|
|
|
|
|
:return:
|
|
|
|
"""
|
|
|
|
argument_spec = keycloak_argument_spec()
|
|
|
|
|
|
|
|
meta_args = dict(
|
|
|
|
state=dict(type='str', default='present',
|
|
|
|
choices=['present', 'absent']),
|
|
|
|
name=dict(type='str', required=True),
|
|
|
|
display_name=dict(type='str', required=False),
|
|
|
|
icon_uri=dict(type='str', required=False),
|
|
|
|
client_id=dict(type='str', required=True),
|
|
|
|
realm=dict(type='str', required=True)
|
|
|
|
)
|
|
|
|
|
|
|
|
argument_spec.update(meta_args)
|
|
|
|
|
|
|
|
module = AnsibleModule(argument_spec=argument_spec,
|
|
|
|
supports_check_mode=True,
|
|
|
|
required_one_of=(
|
|
|
|
[['token', 'auth_realm', 'auth_username', 'auth_password']]),
|
Keycloak modules retry request on authentication error, support refresh token parameter (#9494)
* feat: begin refactor to support refresh token in keycloak modules
* chore: add start of tests for shared token usage
* feat: progress towards supporting refresh token; token introspection not yet working [8857]
* chore: reset to main branch previous state; a different approach is needed [8857]
* feat: add request methods to keycloak class, which will be expanded with retry logic [8857]
* feat: all requests to keycloak use request methods instead of open_url [8857]
* fix: data argument is optional in keycloak request methods [8857]
* feat: add integration test for keycloak module authentication methods [8857]
* chore: refactor get token logic to separate logic using username/pass credentials [8857]
* chore: refactor token request logic further to isolate request logic [8857]
* chore: fix minor lint issues [8857]
* test: add (currently failing) test for request with invalid auth token, valid refresh token [8857]
* chore: allow realm to be provided to role module with refresh_token, without username/pass [8857]
* feat: add retry logic to requests in keycloak module utils [8857]
* chore: rename keycloak module fail_open_url method to fail_request [8857]
* chore: update all keycloak modules to support refresh token param [8857]
* chore: add refresh_token param to keycloak doc_fragments [8857]
* chore: restore dependency between auth_realm and auth_username,auth_password params [8857]
* chore: rearrange module param checks to reduce future pr size [8857]
* chore: remove extra comma [8857]
* chore: update version added for refresh token param [8857]
* chore: add changelog fragment [8857]
* chore: re-add fail_open_url to keycloak module utils for backward compatability [8857]
* fix: do not make a new request to keycloak without reauth when refresh token not provided (#8857)
* fix: only make final auth attempt if username/pass provided, and return exception on failure (#8857)
* fix: make re-auth and retry code more consistent, ensure final exceptions are thrown (#8857)
* test: fix arguments for invalid token, valid refresh token test (#8857)
* feat: catch invalid refresh token errors during re-auth attempt (#8857)
Add test to verify this behaviour works.
* test: improve test coverage, including some unhappy path tests for authentication failures (#8857)
* chore: store auth errors from token request in backwards compatible way (#8857)
* fix: ensure method is still specified for all requests (#8857)
* chore: simplify token request logic (#8857)
* chore: rename functions to request tokens using refresh token or username/password (#8857)
To emphasize their difference from the `get_token` function,
which either gets the token from the module params
*or* makes a request for it.
* doc: add docstrings for new or significantly modified functions (#8857)
* test: repair unit test following change to exception message upon key error during auth request (#8857)
2025-01-26 14:23:39 +00:00
|
|
|
required_together=([['auth_realm', 'auth_username', 'auth_password']]),
|
|
|
|
required_by={'refresh_token': 'auth_realm'},
|
|
|
|
)
|
2023-04-23 12:07:58 +00:00
|
|
|
|
|
|
|
result = dict(changed=False, msg='', end_state={}, diff=dict(before={}, after={}))
|
|
|
|
|
|
|
|
# Obtain access token, initialize API
|
|
|
|
try:
|
|
|
|
connection_header = get_token(module.params)
|
|
|
|
except KeycloakError as e:
|
|
|
|
module.fail_json(msg=str(e))
|
|
|
|
|
|
|
|
kc = KeycloakAPI(module, connection_header)
|
|
|
|
|
|
|
|
# Convenience variables
|
|
|
|
state = module.params.get('state')
|
|
|
|
name = module.params.get('name')
|
|
|
|
display_name = module.params.get('display_name')
|
|
|
|
icon_uri = module.params.get('icon_uri')
|
|
|
|
client_id = module.params.get('client_id')
|
|
|
|
realm = module.params.get('realm')
|
|
|
|
|
|
|
|
# Get the "id" of the client based on the usually more human-readable
|
|
|
|
# "clientId"
|
|
|
|
cid = kc.get_client_id(client_id, realm=realm)
|
|
|
|
if not cid:
|
|
|
|
module.fail_json(msg='Invalid client %s for realm %s' %
|
|
|
|
(client_id, realm))
|
|
|
|
|
|
|
|
# Get current state of the Authorization Scope using its name as the search
|
|
|
|
# filter. This returns False if it is not found.
|
|
|
|
before_authz_scope = kc.get_authz_authorization_scope_by_name(
|
|
|
|
name=name, client_id=cid, realm=realm)
|
|
|
|
|
|
|
|
# Generate a JSON payload for Keycloak Admin API. This is needed for
|
|
|
|
# "create" and "update" operations.
|
|
|
|
desired_authz_scope = {}
|
|
|
|
desired_authz_scope['name'] = name
|
|
|
|
desired_authz_scope['displayName'] = display_name
|
|
|
|
desired_authz_scope['iconUri'] = icon_uri
|
|
|
|
|
|
|
|
# Add "id" to payload for modify operations
|
|
|
|
if before_authz_scope:
|
|
|
|
desired_authz_scope['id'] = before_authz_scope['id']
|
|
|
|
|
|
|
|
# Ensure that undefined (null) optional parameters are presented as empty
|
|
|
|
# strings in the desired state. This makes comparisons with current state
|
|
|
|
# much easier.
|
|
|
|
for k, v in desired_authz_scope.items():
|
|
|
|
if not v:
|
|
|
|
desired_authz_scope[k] = ''
|
|
|
|
|
|
|
|
# Do the above for the current state
|
|
|
|
if before_authz_scope:
|
|
|
|
for k in ['displayName', 'iconUri']:
|
|
|
|
if k not in before_authz_scope:
|
|
|
|
before_authz_scope[k] = ''
|
|
|
|
|
|
|
|
if before_authz_scope and state == 'present':
|
|
|
|
changes = False
|
|
|
|
for k, v in desired_authz_scope.items():
|
|
|
|
if before_authz_scope[k] != v:
|
|
|
|
changes = True
|
|
|
|
# At this point we know we have to update the object anyways,
|
|
|
|
# so there's no need to do more work.
|
|
|
|
break
|
|
|
|
|
|
|
|
if changes:
|
|
|
|
if module._diff:
|
|
|
|
result['diff'] = dict(before=before_authz_scope, after=desired_authz_scope)
|
|
|
|
|
|
|
|
if module.check_mode:
|
|
|
|
result['changed'] = True
|
|
|
|
result['msg'] = 'Authorization scope would be updated'
|
|
|
|
module.exit_json(**result)
|
|
|
|
else:
|
|
|
|
kc.update_authz_authorization_scope(
|
|
|
|
payload=desired_authz_scope, id=before_authz_scope['id'], client_id=cid, realm=realm)
|
|
|
|
result['changed'] = True
|
|
|
|
result['msg'] = 'Authorization scope updated'
|
|
|
|
else:
|
|
|
|
result['changed'] = False
|
|
|
|
result['msg'] = 'Authorization scope not updated'
|
|
|
|
|
|
|
|
result['end_state'] = desired_authz_scope
|
|
|
|
elif not before_authz_scope and state == 'present':
|
|
|
|
if module._diff:
|
|
|
|
result['diff'] = dict(before={}, after=desired_authz_scope)
|
|
|
|
|
|
|
|
if module.check_mode:
|
|
|
|
result['changed'] = True
|
|
|
|
result['msg'] = 'Authorization scope would be created'
|
|
|
|
module.exit_json(**result)
|
|
|
|
else:
|
|
|
|
kc.create_authz_authorization_scope(
|
|
|
|
payload=desired_authz_scope, client_id=cid, realm=realm)
|
|
|
|
result['changed'] = True
|
|
|
|
result['msg'] = 'Authorization scope created'
|
|
|
|
result['end_state'] = desired_authz_scope
|
|
|
|
elif before_authz_scope and state == 'absent':
|
|
|
|
if module._diff:
|
|
|
|
result['diff'] = dict(before=before_authz_scope, after={})
|
|
|
|
|
|
|
|
if module.check_mode:
|
|
|
|
result['changed'] = True
|
|
|
|
result['msg'] = 'Authorization scope would be removed'
|
|
|
|
module.exit_json(**result)
|
|
|
|
else:
|
|
|
|
kc.remove_authz_authorization_scope(
|
|
|
|
id=before_authz_scope['id'], client_id=cid, realm=realm)
|
|
|
|
result['changed'] = True
|
|
|
|
result['msg'] = 'Authorization scope removed'
|
|
|
|
elif not before_authz_scope and state == 'absent':
|
|
|
|
result['changed'] = False
|
|
|
|
else:
|
|
|
|
module.fail_json(msg='Unable to determine what to do with authorization scope %s of client %s in realm %s' % (
|
|
|
|
name, client_id, realm))
|
|
|
|
|
|
|
|
module.exit_json(**result)
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
main()
|