| 1 |
#!/usr/bin/python |
| 2 |
|
| 3 |
# Copyright (c) 2017, Eike Frost <[email protected]> |
| 4 |
# Copyright (c) 2021, Christophe Gilles <[email protected]> |
| 5 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or |
| 6 |
# https://www.gnu.org/licenses/gpl-3.0.txt) |
| 7 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 8 |
from __future__ import annotations |
| 9 |
|
| 10 |
DOCUMENTATION = r""" |
| 11 |
module: keycloak_authz_permission |
| 12 |
|
| 13 |
version_added: 7.2.0 |
| 14 |
|
| 15 |
short_description: Allows administration of Keycloak client authorization permissions using Keycloak API |
| 16 |
|
| 17 |
description: |
| 18 |
- This module allows the administration of Keycloak client authorization permissions using the Keycloak REST API. Authorization |
| 19 |
permissions are only available if a client has Authorization enabled. |
| 20 |
- There are some peculiarities in JSON paths and payloads for authorization permissions. In particular POST and PUT operations |
| 21 |
are targeted at permission endpoints, whereas GET requests go to policies endpoint. To make matters more interesting the |
| 22 |
JSON responses from GET requests return data in a different format than what is expected for POST and PUT. The end result |
| 23 |
is that it is not possible to detect changes to things like policies, scopes or resources - at least not without a large |
| 24 |
number of additional API calls. Therefore this module always updates authorization permissions instead of attempting to |
| 25 |
determine if changes are truly needed. |
| 26 |
- This module requires access to the REST API using OpenID Connect; the user connecting and the realm being used must have |
| 27 |
the requisite access rights. In a default Keycloak installation, admin-cli and an admin user would work, as would a separate |
| 28 |
realm definition with the scope tailored to your needs and a user having the expected roles. |
| 29 |
- The names of module options are snake_cased versions of the camelCase options used by Keycloak. The Authorization Services |
| 30 |
paths and payloads have not officially been documented by the Keycloak project. |
| 31 |
U(https://www.puppeteers.net/blog/keycloak-authorization-services-rest-api-paths-and-payload/). |
| 32 |
attributes: |
| 33 |
check_mode: |
| 34 |
support: full |
| 35 |
diff_mode: |
| 36 |
support: none |
| 37 |
action_group: |
| 38 |
version_added: 10.2.0 |
| 39 |
|
| 40 |
options: |
| 41 |
state: |
| 42 |
description: |
| 43 |
- State of the authorization permission. |
| 44 |
- On V(present), the authorization permission is created (or updated if it exists already). |
| 45 |
- On V(absent), the authorization permission is removed if it exists. |
| 46 |
choices: ['present', 'absent'] |
| 47 |
default: 'present' |
| 48 |
type: str |
| 49 |
name: |
| 50 |
description: |
| 51 |
- Name of the authorization permission to create. |
| 52 |
type: str |
| 53 |
required: true |
| 54 |
description: |
| 55 |
description: |
| 56 |
- The description of the authorization permission. |
| 57 |
type: str |
| 58 |
permission_type: |
| 59 |
description: |
| 60 |
- The type of authorization permission. |
| 61 |
- On V(scope) create a scope-based permission. |
| 62 |
- On V(resource) create a resource-based permission. |
| 63 |
type: str |
| 64 |
required: true |
| 65 |
choices: |
| 66 |
- resource |
| 67 |
- scope |
| 68 |
decision_strategy: |
| 69 |
description: |
| 70 |
- The decision strategy to use with this permission. |
| 71 |
type: str |
| 72 |
default: UNANIMOUS |
| 73 |
choices: |
| 74 |
- UNANIMOUS |
| 75 |
- AFFIRMATIVE |
| 76 |
- CONSENSUS |
| 77 |
resources: |
| 78 |
description: |
| 79 |
- Resource names to attach to this permission. |
| 80 |
- Scope-based permissions can only include one resource. |
| 81 |
- Resource-based permissions can include multiple resources. |
| 82 |
type: list |
| 83 |
elements: str |
| 84 |
default: [] |
| 85 |
scopes: |
| 86 |
description: |
| 87 |
- Scope names to attach to this permission. |
| 88 |
- Resource-based permissions cannot have scopes attached to them. |
| 89 |
type: list |
| 90 |
elements: str |
| 91 |
default: [] |
| 92 |
policies: |
| 93 |
description: |
| 94 |
- Policy names to attach to this permission. |
| 95 |
type: list |
| 96 |
elements: str |
| 97 |
default: [] |
| 98 |
client_id: |
| 99 |
description: |
| 100 |
- The clientId of the keycloak client that should have the authorization scope. |
| 101 |
- This is usually a human-readable name of the Keycloak client. |
| 102 |
type: str |
| 103 |
required: true |
| 104 |
realm: |
| 105 |
description: |
| 106 |
- The name of the Keycloak realm the Keycloak client is in. |
| 107 |
type: str |
| 108 |
required: true |
| 109 |
|
| 110 |
extends_documentation_fragment: |
| 111 |
- community.general._keycloak |
| 112 |
- community.general._keycloak.actiongroup_keycloak |
| 113 |
- community.general._attributes |
| 114 |
|
| 115 |
author: |
| 116 |
- Samuli Seppänen (@mattock) |
| 117 |
""" |
| 118 |
|
| 119 |
EXAMPLES = r""" |
| 120 |
- name: Manage scope-based Keycloak authorization permission |
| 121 |
community.general.keycloak_authz_permission: |
| 122 |
name: ScopePermission |
| 123 |
state: present |
| 124 |
description: Scope permission |
| 125 |
permission_type: scope |
| 126 |
scopes: |
| 127 |
- file:delete |
| 128 |
policies: |
| 129 |
- Default Policy |
| 130 |
client_id: myclient |
| 131 |
realm: myrealm |
| 132 |
auth_keycloak_url: http://localhost:8080/auth |
| 133 |
auth_username: keycloak |
| 134 |
auth_password: keycloak |
| 135 |
auth_realm: master |
| 136 |
|
| 137 |
- name: Manage resource-based Keycloak authorization permission |
| 138 |
community.general.keycloak_authz_permission: |
| 139 |
name: ResourcePermission |
| 140 |
state: present |
| 141 |
description: Resource permission |
| 142 |
permission_type: resource |
| 143 |
resources: |
| 144 |
- Default Resource |
| 145 |
policies: |
| 146 |
- Default Policy |
| 147 |
client_id: myclient |
| 148 |
realm: myrealm |
| 149 |
auth_keycloak_url: http://localhost:8080/auth |
| 150 |
auth_username: keycloak |
| 151 |
auth_password: keycloak |
| 152 |
auth_realm: master |
| 153 |
""" |
| 154 |
|
| 155 |
RETURN = r""" |
| 156 |
msg: |
| 157 |
description: Message as to what action was taken. |
| 158 |
returned: always |
| 159 |
type: str |
| 160 |
|
| 161 |
end_state: |
| 162 |
description: Representation of the authorization permission after module execution. |
| 163 |
returned: on success |
| 164 |
type: dict |
| 165 |
contains: |
| 166 |
id: |
| 167 |
description: ID of the authorization permission. |
| 168 |
type: str |
| 169 |
returned: when O(state=present) |
| 170 |
sample: 9da05cd2-b273-4354-bbd8-0c133918a454 |
| 171 |
name: |
| 172 |
description: Name of the authorization permission. |
| 173 |
type: str |
| 174 |
returned: when O(state=present) |
| 175 |
sample: ResourcePermission |
| 176 |
description: |
| 177 |
description: Description of the authorization permission. |
| 178 |
type: str |
| 179 |
returned: when O(state=present) |
| 180 |
sample: Resource Permission |
| 181 |
type: |
| 182 |
description: Type of the authorization permission. |
| 183 |
type: str |
| 184 |
returned: when O(state=present) |
| 185 |
sample: resource |
| 186 |
decisionStrategy: |
| 187 |
description: The decision strategy to use. |
| 188 |
type: str |
| 189 |
returned: when O(state=present) |
| 190 |
sample: UNANIMOUS |
| 191 |
logic: |
| 192 |
description: The logic used for the permission (part of the payload, but has a fixed value). |
| 193 |
type: str |
| 194 |
returned: when O(state=present) |
| 195 |
sample: POSITIVE |
| 196 |
resources: |
| 197 |
description: IDs of resources attached to this permission. |
| 198 |
type: list |
| 199 |
returned: when O(state=present) |
| 200 |
sample: |
| 201 |
- 49e052ff-100d-4b79-a9dd-52669ed3c11d |
| 202 |
scopes: |
| 203 |
description: IDs of scopes attached to this permission. |
| 204 |
type: list |
| 205 |
returned: when O(state=present) |
| 206 |
sample: |
| 207 |
- 9da05cd2-b273-4354-bbd8-0c133918a454 |
| 208 |
policies: |
| 209 |
description: IDs of policies attached to this permission. |
| 210 |
type: list |
| 211 |
returned: when O(state=present) |
| 212 |
sample: |
| 213 |
- 9da05cd2-b273-4354-bbd8-0c133918a454 |
| 214 |
""" |
| 215 |
|
| 216 |
from ansible.module_utils.basic import AnsibleModule |
| 217 |
|
| 218 |
from ansible_collections.community.general.plugins.module_utils._keycloak import ( |
| 219 |
KeycloakAPI, |
| 220 |
KeycloakError, |
| 221 |
get_token, |
| 222 |
keycloak_argument_spec, |
| 223 |
) |
| 224 |
|
| 225 |
|
| 226 |
def main(): |
| 227 |
""" |
| 228 |
Module execution |
| 229 |
|
| 230 |
:return: |
| 231 |
""" |
| 232 |
argument_spec = keycloak_argument_spec() |
| 233 |
|
| 234 |
meta_args = dict( |
| 235 |
state=dict(type="str", default="present", choices=["present", "absent"]), |
| 236 |
name=dict(type="str", required=True), |
| 237 |
description=dict(type="str"), |
| 238 |
permission_type=dict(type="str", choices=["scope", "resource"], required=True), |
| 239 |
decision_strategy=dict(type="str", default="UNANIMOUS", choices=["UNANIMOUS", "AFFIRMATIVE", "CONSENSUS"]), |
| 240 |
resources=dict(type="list", elements="str", default=[]), |
| 241 |
scopes=dict(type="list", elements="str", default=[]), |
| 242 |
policies=dict(type="list", elements="str", default=[]), |
| 243 |
client_id=dict(type="str", required=True), |
| 244 |
realm=dict(type="str", required=True), |
| 245 |
) |
| 246 |
|
| 247 |
argument_spec.update(meta_args) |
| 248 |
|
| 249 |
module = AnsibleModule( |
| 250 |
argument_spec=argument_spec, |
| 251 |
supports_check_mode=True, |
| 252 |
required_one_of=( |
| 253 |
[["token", "auth_realm", "auth_username", "auth_password", "auth_client_id", "auth_client_secret"]] |
| 254 |
), |
| 255 |
required_together=([["auth_username", "auth_password"]]), |
| 256 |
required_by={"refresh_token": "auth_realm"}, |
| 257 |
) |
| 258 |
|
| 259 |
# Convenience variables |
| 260 |
state = module.params.get("state") |
| 261 |
name = module.params.get("name") |
| 262 |
description = module.params.get("description") |
| 263 |
permission_type = module.params.get("permission_type") |
| 264 |
decision_strategy = module.params.get("decision_strategy") |
| 265 |
realm = module.params.get("realm") |
| 266 |
client_id = module.params.get("client_id") |
| 267 |
realm = module.params.get("realm") |
| 268 |
resources = module.params.get("resources") |
| 269 |
scopes = module.params.get("scopes") |
| 270 |
policies = module.params.get("policies") |
| 271 |
|
| 272 |
if permission_type == "scope" and state == "present": |
| 273 |
if scopes == []: |
| 274 |
module.fail_json(msg="Scopes need to defined when permission type is set to scope!") |
| 275 |
if len(resources) > 1: |
| 276 |
module.fail_json(msg="Only one resource can be defined for a scope permission!") |
| 277 |
|
| 278 |
if permission_type == "resource" and state == "present": |
| 279 |
if resources == []: |
| 280 |
module.fail_json(msg="A resource need to defined when permission type is set to resource!") |
| 281 |
if scopes != []: |
| 282 |
module.fail_json(msg="Scopes cannot be defined when permission type is set to resource!") |
| 283 |
|
| 284 |
result = dict(changed=False, msg="", end_state={}) |
| 285 |
|
| 286 |
# Obtain access token, initialize API |
| 287 |
try: |
| 288 |
connection_header = get_token(module.params) |
| 289 |
except KeycloakError as e: |
| 290 |
module.fail_json(msg=str(e)) |
| 291 |
|
| 292 |
kc = KeycloakAPI(module, connection_header) |
| 293 |
|
| 294 |
# Get id of the client based on client_id |
| 295 |
cid = kc.get_client_id(client_id, realm=realm) |
| 296 |
if not cid: |
| 297 |
module.fail_json(msg=f"Invalid client {client_id} for realm {realm}") |
| 298 |
|
| 299 |
# Get current state of the permission using its name as the search |
| 300 |
# filter. This returns False if it is not found. |
| 301 |
permission = kc.get_authz_permission_by_name(name=name, client_id=cid, realm=realm) |
| 302 |
|
| 303 |
# Generate a JSON payload for Keycloak Admin API. This is needed for |
| 304 |
# "create" and "update" operations. |
| 305 |
payload = {} |
| 306 |
payload["name"] = name |
| 307 |
payload["description"] = description |
| 308 |
payload["type"] = permission_type |
| 309 |
payload["decisionStrategy"] = decision_strategy |
| 310 |
payload["logic"] = "POSITIVE" |
| 311 |
payload["scopes"] = [] |
| 312 |
payload["resources"] = [] |
| 313 |
payload["policies"] = [] |
| 314 |
|
| 315 |
if permission_type == "scope": |
| 316 |
# Add the resource id, if any, to the payload. While the data type is a |
| 317 |
# list, it is only possible to have one entry in it based on what Keycloak |
| 318 |
# Admin Console does. |
| 319 |
r = False |
| 320 |
resource_scopes = [] |
| 321 |
|
| 322 |
if resources: |
| 323 |
r = kc.get_authz_resource_by_name(resources[0], cid, realm) |
| 324 |
if not r: |
| 325 |
module.fail_json( |
| 326 |
msg=f"Unable to find authorization resource with name {resources[0]} for client {cid} in realm {realm}" |
| 327 |
) |
| 328 |
else: |
| 329 |
payload["resources"].append(r["_id"]) |
| 330 |
|
| 331 |
for rs in r["scopes"]: |
| 332 |
resource_scopes.append(rs["id"]) |
| 333 |
|
| 334 |
# Generate a list of scope ids based on scope names. Fail if the |
| 335 |
# defined resource does not include all those scopes. |
| 336 |
for scope in scopes: |
| 337 |
s = kc.get_authz_authorization_scope_by_name(scope, cid, realm) |
| 338 |
if r and s["id"] not in resource_scopes: |
| 339 |
module.fail_json( |
| 340 |
msg=f"Resource {resources[0]} does not include scope {scope} for client {client_id} in realm {realm}" |
| 341 |
) |
| 342 |
else: |
| 343 |
payload["scopes"].append(s["id"]) |
| 344 |
|
| 345 |
elif permission_type == "resource": |
| 346 |
if resources: |
| 347 |
for resource in resources: |
| 348 |
r = kc.get_authz_resource_by_name(resource, cid, realm) |
| 349 |
if not r: |
| 350 |
module.fail_json( |
| 351 |
msg=f"Unable to find authorization resource with name {resource} for client {cid} in realm {realm}" |
| 352 |
) |
| 353 |
else: |
| 354 |
payload["resources"].append(r["_id"]) |
| 355 |
|
| 356 |
# Add policy ids, if any, to the payload. |
| 357 |
if policies: |
| 358 |
for policy in policies: |
| 359 |
p = kc.get_authz_policy_by_name(policy, cid, realm) |
| 360 |
|
| 361 |
if p: |
| 362 |
payload["policies"].append(p["id"]) |
| 363 |
else: |
| 364 |
module.fail_json( |
| 365 |
msg=f"Unable to find authorization policy with name {policy} for client {client_id} in realm {realm}" |
| 366 |
) |
| 367 |
|
| 368 |
# Add "id" to payload for update operations |
| 369 |
if permission: |
| 370 |
payload["id"] = permission["id"] |
| 371 |
|
| 372 |
# Handle the special case where the user attempts to change an already |
| 373 |
# existing permission's type - something that can't be done without a |
| 374 |
# full delete -> (re)create cycle. |
| 375 |
if permission["type"] != payload["type"]: |
| 376 |
module.fail_json( |
| 377 |
msg=( |
| 378 |
f"Modifying the type of permission (scope/resource) is not supported: " |
| 379 |
f"permission {permission['id']} of client {cid} in realm {realm} unchanged" |
| 380 |
) |
| 381 |
) |
| 382 |
|
| 383 |
# Updating an authorization permission is tricky for several reasons. |
| 384 |
# Firstly, the current permission is retrieved using a _policy_ endpoint, |
| 385 |
# not from a permission endpoint. Also, the data that is returned is in a |
| 386 |
# different format than what is expected by the payload. So, comparing the |
| 387 |
# current state attribute by attribute to the payload is not possible. For |
| 388 |
# example the data contains a JSON object "config" which may contain the |
| 389 |
# authorization type, but which is no required in the payload. Moreover, |
| 390 |
# information about resources, scopes and policies is _not_ present in the |
| 391 |
# data. So, there is no way to determine if any of those fields have |
| 392 |
# changed. Therefore the best options we have are |
| 393 |
# |
| 394 |
# a) Always apply the payload without checking the current state |
| 395 |
# b) Refuse to make any changes to any settings (only support create and delete) |
| 396 |
# |
| 397 |
# The approach taken here is a). |
| 398 |
# |
| 399 |
if permission and state == "present": |
| 400 |
if module.check_mode: |
| 401 |
result["msg"] = "Notice: unable to check current resources, scopes and policies for permission. \ |
| 402 |
Would apply desired state without checking the current state." |
| 403 |
else: |
| 404 |
kc.update_authz_permission( |
| 405 |
payload=payload, permission_type=permission_type, id=permission["id"], client_id=cid, realm=realm |
| 406 |
) |
| 407 |
result["msg"] = "Notice: unable to check current resources, scopes and policies for permission. \ |
| 408 |
Applying desired state without checking the current state." |
| 409 |
|
| 410 |
# Assume that something changed, although we don't know if that is the case. |
| 411 |
result["changed"] = True |
| 412 |
result["end_state"] = payload |
| 413 |
elif not permission and state == "present": |
| 414 |
if module.check_mode: |
| 415 |
result["msg"] = "Would create permission" |
| 416 |
else: |
| 417 |
kc.create_authz_permission(payload=payload, permission_type=permission_type, client_id=cid, realm=realm) |
| 418 |
result["msg"] = "Permission created" |
| 419 |
|
| 420 |
result["changed"] = True |
| 421 |
result["end_state"] = payload |
| 422 |
elif permission and state == "absent": |
| 423 |
if module.check_mode: |
| 424 |
result["msg"] = "Would remove permission" |
| 425 |
else: |
| 426 |
kc.remove_authz_permission(id=permission["id"], client_id=cid, realm=realm) |
| 427 |
result["msg"] = "Permission removed" |
| 428 |
|
| 429 |
result["changed"] = True |
| 430 |
|
| 431 |
elif not permission and state == "absent": |
| 432 |
result["changed"] = False |
| 433 |
else: |
| 434 |
module.fail_json( |
| 435 |
msg=f"Unable to determine what to do with permission {name} of client {client_id} in realm {realm}" |
| 436 |
) |
| 437 |
|
| 438 |
module.exit_json(**result) |
| 439 |
|
| 440 |
|
| 441 |
if __name__ == "__main__": |
| 442 |
main() |