Add a keycloak module to query keys metadata (#8605)

* feat(keycloak): module to query keys metadata

* chore: add thomasbach-dev as maintainer in team_keycloak

* test: adding a unit test for keycloak_real_keys_metadata_info module

* fixup! feat(keycloak): module to query keys metadata
This commit is contained in:
Thomas Bach 2024-08-01 17:10:11 +02:00 committed by GitHub
commit 229ed6dad9
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 349 additions and 1 deletions

View file

@ -19,6 +19,7 @@ from ansible.module_utils.common.text.converters import to_native, to_text
URL_REALM_INFO = "{url}/realms/{realm}"
URL_REALMS = "{url}/admin/realms"
URL_REALM = "{url}/admin/realms/{realm}"
URL_REALM_KEYS_METADATA = "{url}/admin/realms/{realm}/keys"
URL_TOKEN = "{url}/realms/{realm}/protocol/openid-connect/token"
URL_CLIENT = "{url}/admin/realms/{realm}/clients/{id}"
@ -306,6 +307,37 @@ class KeycloakAPI(object):
self.module.fail_json(msg='Could not obtain realm %s: %s' % (realm, str(e)),
exception=traceback.format_exc())
def get_realm_keys_metadata_by_id(self, realm='master'):
"""Obtain realm public info by id
:param realm: realm id
:return: None, or a 'KeysMetadataRepresentation'
(https://www.keycloak.org/docs-api/latest/rest-api/index.html#KeysMetadataRepresentation)
-- a dict containing the keys 'active' and 'keys', the former containing a mapping
from algorithms to key-ids, the latter containing a list of dicts with key
information.
"""
realm_keys_metadata_url = URL_REALM_KEYS_METADATA.format(url=self.baseurl, realm=realm)
try:
return json.loads(to_native(open_url(realm_keys_metadata_url, method='GET', http_agent=self.http_agent, headers=self.restheaders,
timeout=self.connection_timeout,
validate_certs=self.validate_certs).read()))
except HTTPError as e:
if e.code == 404:
return None
else:
self.fail_open_url(e, msg='Could not obtain realm %s: %s' % (realm, str(e)),
exception=traceback.format_exc())
except ValueError as e:
self.module.fail_json(msg='API returned incorrect JSON when trying to obtain realm %s: %s' % (realm, str(e)),
exception=traceback.format_exc())
except Exception as e:
self.module.fail_json(msg='Could not obtain realm %s: %s' % (realm, str(e)),
exception=traceback.format_exc())
def get_realm_by_id(self, realm='master'):
""" Obtain realm representation by id

View file

@ -0,0 +1,133 @@
#!/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 = """
---
module: keycloak_realm_keys_metadata_info
short_description: Allows obtaining Keycloak realm keys metadata via Keycloak API
version_added: 9.3.0
description:
- This module allows you to get Keycloak realm keys metadata via 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).
options:
realm:
type: str
description:
- They Keycloak realm to fetch keys metadata.
default: 'master'
extends_documentation_fragment:
- community.general.keycloak
- community.general.attributes
- community.general.attributes.info_module
author:
- Thomas Bach (@thomasbach-dev)
"""
EXAMPLES = """
- 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 = """
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"]]),
required_together=([["auth_realm", "auth_username", "auth_password"]]),
)
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()