Debian Codegraph @

ansible_collections/community/general/plugins/modules/keycloak_authz_authorization_scope.py

raw
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_authorization_scope
12
13 short_description: Allows administration of Keycloak client authorization scopes using Keycloak API
14
15 version_added: 6.6.0
16
17 description:
18 - This module allows the administration of Keycloak client Authorization Scopes using the Keycloak REST API. Authorization
19 Scopes are only available if a client has Authorization enabled.
20 - This module requires access to the REST API using OpenID Connect; the user connecting and the realm being used must have
21 the requisite access rights. In a default Keycloak installation, admin-cli and an admin user would work, as would a separate
22 realm definition with the scope tailored to your needs and a user having the expected roles.
23 - The names of module options are snake_cased versions of the camelCase options used by Keycloak. The Authorization Services
24 paths and payloads have not officially been documented by the Keycloak project.
25 U(https://www.puppeteers.net/blog/keycloak-authorization-services-rest-api-paths-and-payload/).
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 authorization scope.
38 - On V(present), the authorization scope is created (or updated if it exists already).
39 - On V(absent), the authorization scope is removed if it exists.
40 choices: ['present', 'absent']
41 default: 'present'
42 type: str
43 name:
44 description:
45 - Name of the authorization scope to create.
46 type: str
47 required: true
48 display_name:
49 description:
50 - The display name of the authorization scope.
51 type: str
52 icon_uri:
53 description:
54 - The icon URI for the authorization scope.
55 type: str
56 client_id:
57 description:
58 - The C(clientId) of the Keycloak client that should have the authorization scope.
59 - This is usually a human-readable name of the Keycloak client.
60 type: str
61 required: true
62 realm:
63 description:
64 - The name of the Keycloak realm the Keycloak client is in.
65 type: str
66 required: true
67
68 extends_documentation_fragment:
69 - community.general._keycloak
70 - community.general._keycloak.actiongroup_keycloak
71 - community.general._attributes
72
73 author:
74 - Samuli Seppänen (@mattock)
75 """
76
77 EXAMPLES = r"""
78 - name: Manage Keycloak file:delete authorization scope
79 keycloak_authz_authorization_scope:
80 name: file:delete
81 state: present
82 display_name: File delete
83 client_id: myclient
84 realm: myrealm
85 auth_keycloak_url: http://localhost:8080/auth
86 auth_username: keycloak
87 auth_password: keycloak
88 auth_realm: master
89 """
90
91 RETURN = r"""
92 msg:
93 description: Message as to what action was taken.
94 returned: always
95 type: str
96
97 end_state:
98 description: Representation of the authorization scope after module execution.
99 returned: on success
100 type: dict
101 contains:
102 id:
103 description: ID of the authorization scope.
104 type: str
105 returned: when O(state=present)
106 sample: a6ab1cf2-1001-40ec-9f39-48f23b6a0a41
107 name:
108 description: Name of the authorization scope.
109 type: str
110 returned: when O(state=present)
111 sample: file:delete
112 display_name:
113 description: Display name of the authorization scope.
114 type: str
115 returned: when O(state=present)
116 sample: File delete
117 icon_uri:
118 description: Icon URI for the authorization scope.
119 type: str
120 returned: when O(state=present)
121 sample: http://localhost/icon.png
122 """
123
124 from ansible.module_utils.basic import AnsibleModule
125
126 from ansible_collections.community.general.plugins.module_utils._keycloak import (
127 KeycloakAPI,
128 KeycloakError,
129 get_token,
130 keycloak_argument_spec,
131 )
132
133
134 def main():
135 """
136 Module execution
137
138 :return:
139 """
140 argument_spec = keycloak_argument_spec()
141
142 meta_args = dict(
143 state=dict(type="str", default="present", choices=["present", "absent"]),
144 name=dict(type="str", required=True),
145 display_name=dict(type="str"),
146 icon_uri=dict(type="str"),
147 client_id=dict(type="str", required=True),
148 realm=dict(type="str", required=True),
149 )
150
151 argument_spec.update(meta_args)
152
153 module = AnsibleModule(
154 argument_spec=argument_spec,
155 supports_check_mode=True,
156 required_one_of=(
157 [["token", "auth_realm", "auth_username", "auth_password", "auth_client_id", "auth_client_secret"]]
158 ),
159 required_together=([["auth_username", "auth_password"]]),
160 required_by={"refresh_token": "auth_realm"},
161 )
162
163 result = dict(changed=False, msg="", end_state={}, diff=dict(before={}, after={}))
164
165 # Obtain access token, initialize API
166 try:
167 connection_header = get_token(module.params)
168 except KeycloakError as e:
169 module.fail_json(msg=str(e))
170
171 kc = KeycloakAPI(module, connection_header)
172
173 # Convenience variables
174 state = module.params.get("state")
175 name = module.params.get("name")
176 display_name = module.params.get("display_name")
177 icon_uri = module.params.get("icon_uri")
178 client_id = module.params.get("client_id")
179 realm = module.params.get("realm")
180
181 # Get the "id" of the client based on the usually more human-readable
182 # "clientId"
183 cid = kc.get_client_id(client_id, realm=realm)
184 if not cid:
185 module.fail_json(msg=f"Invalid client {client_id} for realm {realm}")
186
187 # Get current state of the Authorization Scope using its name as the search
188 # filter. This returns False if it is not found.
189 before_authz_scope = kc.get_authz_authorization_scope_by_name(name=name, client_id=cid, realm=realm)
190
191 # Generate a JSON payload for Keycloak Admin API. This is needed for
192 # "create" and "update" operations.
193 desired_authz_scope = {}
194 desired_authz_scope["name"] = name
195 desired_authz_scope["displayName"] = display_name
196 desired_authz_scope["iconUri"] = icon_uri
197
198 # Add "id" to payload for modify operations
199 if before_authz_scope:
200 desired_authz_scope["id"] = before_authz_scope["id"]
201
202 # Ensure that undefined (null) optional parameters are presented as empty
203 # strings in the desired state. This makes comparisons with current state
204 # much easier.
205 for k, v in desired_authz_scope.items():
206 if not v:
207 desired_authz_scope[k] = ""
208
209 # Do the above for the current state
210 if before_authz_scope:
211 for k in ["displayName", "iconUri"]:
212 if k not in before_authz_scope:
213 before_authz_scope[k] = ""
214
215 if before_authz_scope and state == "present":
216 changes = False
217 for k, v in desired_authz_scope.items():
218 if before_authz_scope[k] != v:
219 changes = True
220 # At this point we know we have to update the object anyways,
221 # so there's no need to do more work.
222 break
223
224 if changes:
225 if module._diff:
226 result["diff"] = dict(before=before_authz_scope, after=desired_authz_scope)
227
228 if module.check_mode:
229 result["changed"] = True
230 result["msg"] = "Authorization scope would be updated"
231 module.exit_json(**result)
232 else:
233 kc.update_authz_authorization_scope(
234 payload=desired_authz_scope, id=before_authz_scope["id"], client_id=cid, realm=realm
235 )
236 result["changed"] = True
237 result["msg"] = "Authorization scope updated"
238 else:
239 result["changed"] = False
240 result["msg"] = "Authorization scope not updated"
241
242 result["end_state"] = desired_authz_scope
243 elif not before_authz_scope and state == "present":
244 if module._diff:
245 result["diff"] = dict(before={}, after=desired_authz_scope)
246
247 if module.check_mode:
248 result["changed"] = True
249 result["msg"] = "Authorization scope would be created"
250 module.exit_json(**result)
251 else:
252 kc.create_authz_authorization_scope(payload=desired_authz_scope, client_id=cid, realm=realm)
253 result["changed"] = True
254 result["msg"] = "Authorization scope created"
255 result["end_state"] = desired_authz_scope
256 elif before_authz_scope and state == "absent":
257 if module._diff:
258 result["diff"] = dict(before=before_authz_scope, after={})
259
260 if module.check_mode:
261 result["changed"] = True
262 result["msg"] = "Authorization scope would be removed"
263 module.exit_json(**result)
264 else:
265 kc.remove_authz_authorization_scope(id=before_authz_scope["id"], client_id=cid, realm=realm)
266 result["changed"] = True
267 result["msg"] = "Authorization scope removed"
268 elif not before_authz_scope and state == "absent":
269 result["changed"] = False
270 else:
271 module.fail_json(
272 msg=f"Unable to determine what to do with authorization scope {name} of client {client_id} in realm {realm}"
273 )
274
275 module.exit_json(**result)
276
277
278 if __name__ == "__main__":
279 main()