Debian Codegraph @

ansible_collections/community/okd/plugins/module_utils/openshift_adm_prune_auth.py

raw
1 #!/usr/bin/env python
2
3 from __future__ import absolute_import, division, print_function
4
5 __metaclass__ = type
6
7 from ansible.module_utils._text import to_native
8
9 from ansible_collections.community.okd.plugins.module_utils.openshift_common import (
10 AnsibleOpenshiftModule,
11 )
12
13 try:
14 from kubernetes import client
15 from kubernetes.dynamic.exceptions import DynamicApiError, NotFoundError
16 except ImportError:
17 pass
18
19
20 class OpenShiftAdmPruneAuth(AnsibleOpenshiftModule):
21 def __init__(self, **kwargs):
22 super(OpenShiftAdmPruneAuth, self).__init__(**kwargs)
23
24 def prune_resource_binding(
25 self, kind, api_version, ref_kind, ref_namespace_names, propagation_policy=None
26 ):
27 resource = self.find_resource(kind=kind, api_version=api_version, fail=True)
28 candidates = []
29 for ref_namespace, ref_name in ref_namespace_names:
30 try:
31 result = resource.get(name=None, namespace=ref_namespace)
32 result = result.to_dict()
33 result = result.get("items") if "items" in result else [result]
34 for obj in result:
35 namespace = obj["metadata"].get("namespace", None)
36 name = obj["metadata"].get("name")
37 if ref_kind and obj["roleRef"]["kind"] != ref_kind:
38 # skip this binding as the roleRef.kind does not match
39 continue
40 if obj["roleRef"]["name"] == ref_name:
41 # select this binding as the roleRef.name match
42 candidates.append((namespace, name))
43 except NotFoundError:
44 continue
45 except DynamicApiError as exc:
46 msg = "Failed to get {kind} resource due to: {msg}".format(
47 kind=kind, msg=exc.body
48 )
49 self.fail_json(msg=msg)
50 except Exception as e:
51 msg = "Failed to get {kind} due to: {msg}".format(
52 kind=kind, msg=to_native(e)
53 )
54 self.fail_json(msg=msg)
55
56 if len(candidates) == 0 or self.check_mode:
57 return [y if x is None else x + "/" + y for x, y in candidates]
58
59 delete_options = client.V1DeleteOptions()
60 if propagation_policy:
61 delete_options.propagation_policy = propagation_policy
62
63 for namespace, name in candidates:
64 try:
65 result = resource.delete(
66 name=name, namespace=namespace, body=delete_options
67 )
68 except DynamicApiError as exc:
69 msg = "Failed to delete {kind} {namespace}/{name} due to: {msg}".format(
70 kind=kind, namespace=namespace, name=name, msg=exc.body
71 )
72 self.fail_json(msg=msg)
73 except Exception as e:
74 msg = "Failed to delete {kind} {namespace}/{name} due to: {msg}".format(
75 kind=kind, namespace=namespace, name=name, msg=to_native(e)
76 )
77 self.fail_json(msg=msg)
78 return [y if x is None else x + "/" + y for x, y in candidates]
79
80 def update_resource_binding(self, ref_kind, ref_names, namespaced=False):
81 kind = "ClusterRoleBinding"
82 api_version = "rbac.authorization.k8s.io/v1"
83 if namespaced:
84 kind = "RoleBinding"
85 resource = self.find_resource(kind=kind, api_version=api_version, fail=True)
86 result = resource.get(name=None, namespace=None).to_dict()
87 result = result.get("items") if "items" in result else [result]
88
89 if len(result) == 0:
90 return [], False
91
92 def _update_user_group(binding_namespace, subjects):
93 users, groups = [], []
94 for x in subjects:
95 if x["kind"] == "User":
96 users.append(x["name"])
97 elif x["kind"] == "Group":
98 groups.append(x["name"])
99 elif x["kind"] == "ServiceAccount":
100 namespace = binding_namespace
101 if x.get("namespace") is not None:
102 namespace = x.get("namespace")
103 if namespace is not None:
104 users.append(
105 "system:serviceaccount:%s:%s" % (namespace, x["name"])
106 )
107 return users, groups
108
109 candidates = []
110 changed = False
111 for item in result:
112 subjects = item.get("subjects", [])
113 retainedSubjects = [
114 x for x in subjects if x["kind"] == ref_kind and x["name"] in ref_names
115 ]
116 if len(subjects) != len(retainedSubjects):
117 updated_binding = item
118 updated_binding["subjects"] = retainedSubjects
119 binding_namespace = item["metadata"].get("namespace", None)
120 (
121 updated_binding["userNames"],
122 updated_binding["groupNames"],
123 ) = _update_user_group(binding_namespace, retainedSubjects)
124 candidates.append(
125 binding_namespace + "/" + item["metadata"]["name"]
126 if binding_namespace
127 else item["metadata"]["name"]
128 )
129 changed = True
130 if not self.check_mode:
131 try:
132 resource.apply(updated_binding, namespace=binding_namespace)
133 except DynamicApiError as exc:
134 msg = "Failed to apply object due to: {0}".format(exc.body)
135 self.fail_json(msg=msg)
136 return candidates, changed
137
138 def update_security_context(self, ref_names, key):
139 params = {
140 "kind": "SecurityContextConstraints",
141 "api_version": "security.openshift.io/v1",
142 }
143 sccs = self.kubernetes_facts(**params)
144 if not sccs["api_found"]:
145 self.fail_json(msg=sccs["msg"])
146 sccs = sccs.get("resources")
147
148 candidates = []
149 changed = False
150 resource = self.find_resource(
151 kind="SecurityContextConstraints", api_version="security.openshift.io/v1"
152 )
153 for item in sccs:
154 subjects = item.get(key, [])
155 retainedSubjects = [x for x in subjects if x not in ref_names]
156 if len(subjects) != len(retainedSubjects):
157 candidates.append(item["metadata"]["name"])
158 changed = True
159 if not self.check_mode:
160 upd_sec_ctx = item
161 upd_sec_ctx.update({key: retainedSubjects})
162 try:
163 resource.apply(upd_sec_ctx, namespace=None)
164 except DynamicApiError as exc:
165 msg = "Failed to apply object due to: {0}".format(exc.body)
166 self.fail_json(msg=msg)
167 return candidates, changed
168
169 def auth_prune_roles(self):
170 params = {
171 "kind": "Role",
172 "api_version": "rbac.authorization.k8s.io/v1",
173 "namespace": self.params.get("namespace"),
174 }
175 for attr in ("name", "label_selectors"):
176 if self.params.get(attr):
177 params[attr] = self.params.get(attr)
178
179 result = self.kubernetes_facts(**params)
180 if not result["api_found"]:
181 self.fail_json(msg=result["msg"])
182
183 roles = result.get("resources")
184 if len(roles) == 0:
185 self.exit_json(
186 changed=False,
187 msg="No candidate rolebinding to prune from namespace %s."
188 % self.params.get("namespace"),
189 )
190
191 ref_roles = [(x["metadata"]["namespace"], x["metadata"]["name"]) for x in roles]
192 candidates = self.prune_resource_binding(
193 kind="RoleBinding",
194 api_version="rbac.authorization.k8s.io/v1",
195 ref_kind="Role",
196 ref_namespace_names=ref_roles,
197 propagation_policy="Foreground",
198 )
199 if len(candidates) == 0:
200 self.exit_json(changed=False, role_binding=candidates)
201
202 self.exit_json(changed=True, role_binding=candidates)
203
204 def auth_prune_clusterroles(self):
205 params = {"kind": "ClusterRole", "api_version": "rbac.authorization.k8s.io/v1"}
206 for attr in ("name", "label_selectors"):
207 if self.params.get(attr):
208 params[attr] = self.params.get(attr)
209
210 result = self.kubernetes_facts(**params)
211 if not result["api_found"]:
212 self.fail_json(msg=result["msg"])
213
214 clusterroles = result.get("resources")
215 if len(clusterroles) == 0:
216 self.exit_json(
217 changed=False, msg="No clusterroles found matching input criteria."
218 )
219
220 ref_clusterroles = [(None, x["metadata"]["name"]) for x in clusterroles]
221
222 # Prune ClusterRoleBinding
223 candidates_cluster_binding = self.prune_resource_binding(
224 kind="ClusterRoleBinding",
225 api_version="rbac.authorization.k8s.io/v1",
226 ref_kind=None,
227 ref_namespace_names=ref_clusterroles,
228 )
229
230 # Prune Role Binding
231 candidates_namespaced_binding = self.prune_resource_binding(
232 kind="RoleBinding",
233 api_version="rbac.authorization.k8s.io/v1",
234 ref_kind="ClusterRole",
235 ref_namespace_names=ref_clusterroles,
236 )
237
238 self.exit_json(
239 changed=True,
240 cluster_role_binding=candidates_cluster_binding,
241 role_binding=candidates_namespaced_binding,
242 )
243
244 def list_groups(self, params=None):
245 options = {"kind": "Group", "api_version": "user.openshift.io/v1"}
246 if params:
247 for attr in ("name", "label_selectors"):
248 if params.get(attr):
249 options[attr] = params.get(attr)
250 return self.kubernetes_facts(**options)
251
252 def auth_prune_users(self):
253 params = {"kind": "User", "api_version": "user.openshift.io/v1"}
254 for attr in ("name", "label_selectors"):
255 if self.params.get(attr):
256 params[attr] = self.params.get(attr)
257
258 users = self.kubernetes_facts(**params)
259 if len(users) == 0:
260 self.exit_json(
261 changed=False,
262 msg="No resource type 'User' found matching input criteria.",
263 )
264
265 names = [x["metadata"]["name"] for x in users]
266 changed = False
267 # Remove the user role binding
268 rolebinding, changed_role = self.update_resource_binding(
269 ref_kind="User", ref_names=names, namespaced=True
270 )
271 changed = changed or changed_role
272 # Remove the user cluster role binding
273 clusterrolesbinding, changed_cr = self.update_resource_binding(
274 ref_kind="User", ref_names=names
275 )
276 changed = changed or changed_cr
277
278 # Remove the user from security context constraints
279 sccs, changed_sccs = self.update_security_context(names, "users")
280 changed = changed or changed_sccs
281
282 # Remove the user from groups
283 groups = self.list_groups()
284 deleted_groups = []
285 resource = self.find_resource(kind="Group", api_version="user.openshift.io/v1")
286 for grp in groups:
287 subjects = grp.get("users", [])
288 retainedSubjects = [x for x in subjects if x not in names]
289 if len(subjects) != len(retainedSubjects):
290 deleted_groups.append(grp["metadata"]["name"])
291 changed = True
292 if not self.check_mode:
293 upd_group = grp
294 upd_group.update({"users": retainedSubjects})
295 try:
296 resource.apply(upd_group, namespace=None)
297 except DynamicApiError as exc:
298 msg = "Failed to apply object due to: {0}".format(exc.body)
299 self.fail_json(msg=msg)
300
301 # Remove the user's OAuthClientAuthorizations
302 oauth = self.kubernetes_facts(
303 kind="OAuthClientAuthorization", api_version="oauth.openshift.io/v1"
304 )
305 deleted_auths = []
306 resource = self.find_resource(
307 kind="OAuthClientAuthorization", api_version="oauth.openshift.io/v1"
308 )
309 for authorization in oauth:
310 if authorization.get("userName", None) in names:
311 auth_name = authorization["metadata"]["name"]
312 deleted_auths.append(auth_name)
313 changed = True
314 if not self.check_mode:
315 try:
316 resource.delete(
317 name=auth_name,
318 namespace=None,
319 body=client.V1DeleteOptions(),
320 )
321 except DynamicApiError as exc:
322 msg = "Failed to delete OAuthClientAuthorization {name} due to: {msg}".format(
323 name=auth_name, msg=exc.body
324 )
325 self.fail_json(msg=msg)
326 except Exception as e:
327 msg = "Failed to delete OAuthClientAuthorization {name} due to: {msg}".format(
328 name=auth_name, msg=to_native(e)
329 )
330 self.fail_json(msg=msg)
331
332 self.exit_json(
333 changed=changed,
334 cluster_role_binding=clusterrolesbinding,
335 role_binding=rolebinding,
336 security_context_constraints=sccs,
337 authorization=deleted_auths,
338 group=deleted_groups,
339 )
340
341 def auth_prune_groups(self):
342 groups = self.list_groups(params=self.params)
343 if len(groups) == 0:
344 self.exit_json(
345 changed=False,
346 result="No resource type 'Group' found matching input criteria.",
347 )
348
349 names = [x["metadata"]["name"] for x in groups]
350
351 changed = False
352 # Remove the groups role binding
353 rolebinding, changed_role = self.update_resource_binding(
354 ref_kind="Group", ref_names=names, namespaced=True
355 )
356 changed = changed or changed_role
357 # Remove the groups cluster role binding
358 clusterrolesbinding, changed_cr = self.update_resource_binding(
359 ref_kind="Group", ref_names=names
360 )
361 changed = changed or changed_cr
362 # Remove the groups security context constraints
363 sccs, changed_sccs = self.update_security_context(names, "groups")
364 changed = changed or changed_sccs
365
366 self.exit_json(
367 changed=changed,
368 cluster_role_binding=clusterrolesbinding,
369 role_binding=rolebinding,
370 security_context_constraints=sccs,
371 )
372
373 def execute_module(self):
374 auth_prune = {
375 "roles": self.auth_prune_roles,
376 "clusterroles": self.auth_prune_clusterroles,
377 "users": self.auth_prune_users,
378 "groups": self.auth_prune_groups,
379 }
380 auth_prune[self.params.get("resource")]()