community.general/plugins/modules/keycloak_realm_keys_metadat...

135 lines
3.7 KiB
Python
Raw Normal View History

#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) Ansible project
# 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
DOCUMENTATION = r"""
module: keycloak_realm_keys_metadata_info
short_description: Allows obtaining Keycloak realm keys metadata using Keycloak API
version_added: 9.3.0
description:
- This module allows you to get Keycloak realm keys metadata using the Keycloak REST API.
- The names of module options are snake_cased versions of the camelCase ones found in the Keycloak API and its documentation
at U(https://www.keycloak.org/docs-api/latest/rest-api/index.html).
attributes:
action_group:
version_added: 10.2.0
options:
realm:
type: str
description:
- They Keycloak realm to fetch keys metadata.
default: 'master'
extends_documentation_fragment:
- community.general.keycloak
- community.general.keycloak.actiongroup_keycloak
- community.general.attributes
- community.general.attributes.info_module
author:
- Thomas Bach (@thomasbach-dev)
"""
EXAMPLES = r"""
- name: Fetch Keys metadata
community.general.keycloak_realm_keys_metadata_info:
auth_keycloak_url: https://auth.example.com/auth
auth_realm: master
auth_username: USERNAME
auth_password: PASSWORD
realm: MyCustomRealm
delegate_to: localhost
register: keycloak_keys_metadata
- name: Write the Keycloak keys certificate into a file
ansible.builtin.copy:
dest: /tmp/keycloak.cert
content: |
{{ keys_metadata['keycloak_keys_metadata']['keys']
| selectattr('algorithm', 'equalto', 'RS256')
| map(attribute='certificate')
| first
}}
delegate_to: localhost
"""
RETURN = r"""
msg:
description: Message as to what action was taken.
returned: always
type: str
keys_metadata:
description:
- Representation of the realm keys metadata (see U(https://www.keycloak.org/docs-api/latest/rest-api/index.html#KeysMetadataRepresentation)).
returned: always
type: dict
contains:
active:
description: A mapping (that is, a dict) from key algorithms to UUIDs.
type: dict
returned: always
keys:
description: A list of dicts providing detailed information on the keys.
type: list
elements: dict
returned: always
"""
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.community.general.plugins.module_utils.identity.keycloak.keycloak import (
KeycloakAPI, KeycloakError, get_token, keycloak_argument_spec)
def main():
argument_spec = keycloak_argument_spec()
meta_args = dict(
realm=dict(default="master"),
)
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'},
)
result = dict(changed=False, msg="", keys_metadata="")
# 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)
realm = module.params.get("realm")
keys_metadata = kc.get_realm_keys_metadata_by_id(realm=realm)
result["keys_metadata"] = keys_metadata
result["msg"] = "Get realm keys metadata successful for ID {realm}".format(
realm=realm
)
module.exit_json(**result)
if __name__ == "__main__":
main()