Debian Codegraph @

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

raw
1 #!/usr/bin/env python
2
3 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
4
5
6 from __future__ import absolute_import, division, print_function
7
8 __metaclass__ = type
9
10
11 from datetime import datetime
12
13 from ansible.module_utils.parsing.convert_bool import boolean
14 from ansible.module_utils._text import to_native
15 from ansible.module_utils.basic import missing_required_lib
16
17 from ansible_collections.community.okd.plugins.module_utils.openshift_ldap import (
18 validate_ldap_sync_config,
19 ldap_split_host_port,
20 OpenshiftLDAPRFC2307,
21 OpenshiftLDAPActiveDirectory,
22 OpenshiftLDAPAugmentedActiveDirectory,
23 )
24
25 try:
26 import ldap
27
28 HAS_PYTHON_LDAP = True
29 PYTHON_LDAP_ERROR = None
30 except ImportError as e:
31 HAS_PYTHON_LDAP = False
32 PYTHON_LDAP_ERROR = e
33
34 from ansible_collections.community.okd.plugins.module_utils.openshift_common import (
35 AnsibleOpenshiftModule,
36 )
37
38 try:
39 from kubernetes.dynamic.exceptions import DynamicApiError
40 except ImportError as e:
41 pass
42
43
44 LDAP_OPENSHIFT_HOST_LABEL = "openshift.io/ldap.host"
45 LDAP_OPENSHIFT_URL_ANNOTATION = "openshift.io/ldap.url"
46 LDAP_OPENSHIFT_UID_ANNOTATION = "openshift.io/ldap.uid"
47 LDAP_OPENSHIFT_SYNCTIME_ANNOTATION = "openshift.io/ldap.sync-time"
48
49
50 def connect_to_ldap(
51 module, server_uri, bind_dn=None, bind_pw=None, insecure=True, ca_file=None
52 ):
53 if insecure:
54 ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER)
55 elif ca_file:
56 ldap.set_option(ldap.OPT_X_TLS_CACERTFILE, ca_file)
57 try:
58 connection = ldap.initialize(server_uri)
59 connection.set_option(ldap.OPT_REFERRALS, 0)
60
61 connection.simple_bind_s(bind_dn, bind_pw)
62 return connection
63 except ldap.LDAPError as e:
64 module.fail_json(
65 msg="Cannot bind to the LDAP server '{0}' due to: {1}".format(server_uri, e)
66 )
67
68
69 def validate_group_annotation(definition, host_ip):
70 name = definition["metadata"]["name"]
71 # Validate LDAP URL Annotation
72 annotate_url = (
73 definition["metadata"].get("annotations", {}).get(LDAP_OPENSHIFT_URL_ANNOTATION)
74 )
75 if host_ip:
76 if not annotate_url:
77 return "group '{0}' marked as having been synced did not have an '{1}' annotation".format(
78 name, LDAP_OPENSHIFT_URL_ANNOTATION
79 )
80 elif annotate_url != host_ip:
81 return "group '{0}' was not synchronized from: '{1}'".format(name, host_ip)
82 # Validate LDAP UID Annotation
83 annotate_uid = definition["metadata"]["annotations"].get(
84 LDAP_OPENSHIFT_UID_ANNOTATION
85 )
86 if not annotate_uid:
87 return "group '{0}' marked as having been synced did not have an '{1}' annotation".format(
88 name, LDAP_OPENSHIFT_UID_ANNOTATION
89 )
90 return None
91
92
93 class OpenshiftLDAPGroups(object):
94 kind = "Group"
95 version = "user.openshift.io/v1"
96
97 def __init__(self, module):
98 self.module = module
99 self.cache = {}
100 self.__group_api = None
101
102 @property
103 def k8s_group_api(self):
104 if not self.__group_api:
105 params = dict(kind=self.kind, api_version=self.version, fail=True)
106 self.__group_api = self.module.find_resource(**params)
107 return self.__group_api
108
109 def get_group_info(self, return_list=False, **kwargs):
110 params = dict(
111 kind=self.kind,
112 api_version=self.version,
113 )
114 params.update(kwargs)
115 result = self.module.kubernetes_facts(**params)
116 if len(result["resources"]) == 0:
117 return None
118 if len(result["resources"]) == 1 and not return_list:
119 return result["resources"][0]
120 else:
121 return result["resources"]
122
123 def list_groups(self):
124 allow_groups = self.module.params.get("allow_groups")
125 deny_groups = self.module.params.get("deny_groups")
126 name_mapping = self.module.config.get("groupUIDNameMapping")
127
128 if name_mapping and (allow_groups or deny_groups):
129
130 def _map_group_names(groups):
131 return [name_mapping.get(value, value) for value in groups]
132
133 allow_groups = _map_group_names(allow_groups)
134 deny_groups = _map_group_names(deny_groups)
135
136 host = self.module.host
137 netlocation = self.module.netlocation
138 groups = []
139 if allow_groups:
140 missing = []
141 for grp in allow_groups:
142 if grp in deny_groups:
143 continue
144 resource = self.get_group_info(name=grp)
145 if not resource:
146 missing.append(grp)
147 continue
148 groups.append(resource)
149
150 if missing:
151 self.module.fail_json(
152 msg="The following groups were not found: %s" % "".join(missing)
153 )
154 else:
155 label_selector = "%s=%s" % (LDAP_OPENSHIFT_HOST_LABEL, host)
156 resources = self.get_group_info(
157 label_selectors=[label_selector], return_list=True
158 )
159 if not resources:
160 return (
161 None,
162 "Unable to find Group matching label selector '%s'"
163 % label_selector,
164 )
165 groups = resources
166 if deny_groups:
167 groups = [
168 item
169 for item in groups
170 if item["metadata"]["name"] not in deny_groups
171 ]
172
173 uids = []
174 for grp in groups:
175 err = validate_group_annotation(grp, netlocation)
176 if err and allow_groups:
177 # We raise an error for group part of the allow_group not matching LDAP sync criteria
178 return None, err
179 group_uid = grp["metadata"]["annotations"].get(
180 LDAP_OPENSHIFT_UID_ANNOTATION
181 )
182 self.cache[group_uid] = grp
183 uids.append(group_uid)
184 return uids, None
185
186 def get_group_name_for_uid(self, group_uid):
187 if group_uid not in self.cache:
188 return None, "No mapping found for Group uid: %s" % group_uid
189 return self.cache[group_uid]["metadata"]["name"], None
190
191 def make_openshift_group(self, group_uid, group_name, usernames):
192 group = self.get_group_info(name=group_name)
193 if not group:
194 group = {
195 "apiVersion": "user.openshift.io/v1",
196 "kind": "Group",
197 "metadata": {
198 "name": group_name,
199 "labels": {LDAP_OPENSHIFT_HOST_LABEL: self.module.host},
200 "annotations": {
201 LDAP_OPENSHIFT_URL_ANNOTATION: self.module.netlocation,
202 LDAP_OPENSHIFT_UID_ANNOTATION: group_uid,
203 },
204 },
205 }
206
207 # Make sure we aren't taking over an OpenShift group that is already related to a different LDAP group
208 ldaphost_label = (
209 group["metadata"].get("labels", {}).get(LDAP_OPENSHIFT_HOST_LABEL)
210 )
211 if not ldaphost_label or ldaphost_label != self.module.host:
212 return (
213 None,
214 "Group %s: %s label did not match sync host: wanted %s, got %s"
215 % (
216 group_name,
217 LDAP_OPENSHIFT_HOST_LABEL,
218 self.module.host,
219 ldaphost_label,
220 ),
221 )
222
223 ldapurl_annotation = (
224 group["metadata"].get("annotations", {}).get(LDAP_OPENSHIFT_URL_ANNOTATION)
225 )
226 if not ldapurl_annotation or ldapurl_annotation != self.module.netlocation:
227 return (
228 None,
229 "Group %s: %s annotation did not match sync host: wanted %s, got %s"
230 % (
231 group_name,
232 LDAP_OPENSHIFT_URL_ANNOTATION,
233 self.module.netlocation,
234 ldapurl_annotation,
235 ),
236 )
237
238 ldapuid_annotation = (
239 group["metadata"].get("annotations", {}).get(LDAP_OPENSHIFT_UID_ANNOTATION)
240 )
241 if not ldapuid_annotation or ldapuid_annotation != group_uid:
242 return (
243 None,
244 "Group %s: %s annotation did not match LDAP UID: wanted %s, got %s"
245 % (
246 group_name,
247 LDAP_OPENSHIFT_UID_ANNOTATION,
248 group_uid,
249 ldapuid_annotation,
250 ),
251 )
252
253 # Overwrite Group Users data
254 group["users"] = usernames
255 group["metadata"]["annotations"][
256 LDAP_OPENSHIFT_SYNCTIME_ANNOTATION
257 ] = datetime.now().isoformat()
258 return group, None
259
260 def create_openshift_groups(self, groups: list):
261 diffs = []
262 results = []
263 changed = False
264 for definition in groups:
265 name = definition["metadata"]["name"]
266 existing = self.get_group_info(name=name)
267 if not self.module.check_mode:
268 method = "patch" if existing else "create"
269 try:
270 if existing:
271 definition = self.k8s_group_api.patch(definition).to_dict()
272 else:
273 definition = self.k8s_group_api.create(definition).to_dict()
274 except DynamicApiError as exc:
275 self.module.fail_json(
276 msg="Failed to %s Group '%s' due to: %s"
277 % (method, name, exc.body)
278 )
279 except Exception as exc:
280 self.module.fail_json(
281 msg="Failed to %s Group '%s' due to: %s"
282 % (method, name, to_native(exc))
283 )
284 equals = False
285 if existing:
286 equals, diff = self.module.diff_objects(existing, definition)
287 diffs.append(diff)
288 changed = changed or not equals
289 results.append(definition)
290 return results, diffs, changed
291
292 def delete_openshift_group(self, name: str):
293 result = dict(kind=self.kind, apiVersion=self.version, metadata=dict(name=name))
294 if not self.module.check_mode:
295 try:
296 result = self.k8s_group_api.delete(name=name).to_dict()
297 except DynamicApiError as exc:
298 self.module.fail_json(
299 msg="Failed to delete Group '{0}' due to: {1}".format(
300 name, exc.body
301 )
302 )
303 except Exception as exc:
304 self.module.fail_json(
305 msg="Failed to delete Group '{0}' due to: {1}".format(
306 name, to_native(exc)
307 )
308 )
309 return result
310
311
312 class OpenshiftGroupsSync(AnsibleOpenshiftModule):
313 def __init__(self, **kwargs):
314 super(OpenshiftGroupsSync, self).__init__(**kwargs)
315 self.__k8s_group_api = None
316 self.__ldap_connection = None
317 self.host = None
318 self.port = None
319 self.netlocation = None
320 self.scheme = None
321 self.config = self.params.get("sync_config")
322
323 if not HAS_PYTHON_LDAP:
324 self.fail_json(
325 msg=missing_required_lib("python-ldap"),
326 error=to_native(PYTHON_LDAP_ERROR),
327 )
328
329 @property
330 def k8s_group_api(self):
331 if not self.__k8s_group_api:
332 params = dict(kind="Group", api_version="user.openshift.io/v1", fail=True)
333 self.__k8s_group_api = self.find_resource(**params)
334 return self.__k8s_group_api
335
336 @property
337 def hostIP(self):
338 return self.netlocation
339
340 @property
341 def connection(self):
342 if not self.__ldap_connection:
343 # Create connection object
344 params = dict(
345 module=self,
346 server_uri=self.config.get("url"),
347 bind_dn=self.config.get("bindDN"),
348 bind_pw=self.config.get("bindPassword"),
349 insecure=boolean(self.config.get("insecure")),
350 ca_file=self.config.get("ca"),
351 )
352 self.__ldap_connection = connect_to_ldap(**params)
353 return self.__ldap_connection
354
355 def close_connection(self):
356 if self.__ldap_connection:
357 self.__ldap_connection.unbind_s()
358 self.__ldap_connection = None
359
360 def exit_json(self, **kwargs):
361 self.close_connection()
362 self.module.exit_json(**kwargs)
363
364 def fail_json(self, **kwargs):
365 self.close_connection()
366 self.module.fail_json(**kwargs)
367
368 def get_syncer(self):
369 syncer = None
370 if "rfc2307" in self.config:
371 syncer = OpenshiftLDAPRFC2307(self.config, self.connection)
372 elif "activeDirectory" in self.config:
373 syncer = OpenshiftLDAPActiveDirectory(self.config, self.connection)
374 elif "augmentedActiveDirectory" in self.config:
375 syncer = OpenshiftLDAPAugmentedActiveDirectory(self.config, self.connection)
376 else:
377 msg = "No schema-specific config was found, should be one of 'rfc2307', 'activeDirectory', 'augmentedActiveDirectory'"
378 self.fail_json(msg=msg)
379 return syncer
380
381 def synchronize(self):
382 sync_group_type = self.module.params.get("type")
383
384 groups_uids = []
385 ldap_openshift_group = OpenshiftLDAPGroups(module=self)
386
387 # Get Synchronize object
388 syncer = self.get_syncer()
389
390 # Determine what to sync : list groups
391 if sync_group_type == "openshift":
392 groups_uids, err = ldap_openshift_group.list_groups()
393 if err:
394 self.fail_json(msg="Failed to list openshift groups", errors=err)
395 else:
396 # List LDAP Group to synchronize
397 groups_uids = self.params.get("allow_groups")
398 if not groups_uids:
399 groups_uids, err = syncer.list_groups()
400 if err:
401 self.module.fail_json(msg=err)
402 deny_groups = self.params.get("deny_groups")
403 if deny_groups:
404 groups_uids = [uid for uid in groups_uids if uid not in deny_groups]
405
406 openshift_groups = []
407 for uid in groups_uids:
408 # Get membership data
409 member_entries, err = syncer.extract_members(uid)
410 if err:
411 self.fail_json(msg=err)
412
413 # Determine usernames for members entries
414 usernames = []
415 for entry in member_entries:
416 name, err = syncer.get_username_for_entry(entry)
417 if err:
418 self.exit_json(
419 msg="Unable to determine username for entry %s: %s"
420 % (entry, err)
421 )
422 if isinstance(name, list):
423 usernames.extend(name)
424 else:
425 usernames.append(name)
426 # Get group name
427 if sync_group_type == "openshift":
428 group_name, err = ldap_openshift_group.get_group_name_for_uid(uid)
429 else:
430 group_name, err = syncer.get_group_name_for_uid(uid)
431 if err:
432 self.exit_json(msg=err)
433
434 # Make Openshift group
435 group, err = ldap_openshift_group.make_openshift_group(
436 uid, group_name, usernames
437 )
438 if err:
439 self.fail_json(msg=err)
440 openshift_groups.append(group)
441
442 # Create Openshift Groups
443 results, diffs, changed = ldap_openshift_group.create_openshift_groups(
444 openshift_groups
445 )
446 self.module.exit_json(changed=True, groups=results)
447
448 def prune(self):
449 ldap_openshift_group = OpenshiftLDAPGroups(module=self)
450 groups_uids, err = ldap_openshift_group.list_groups()
451 if err:
452 self.fail_json(msg="Failed to list openshift groups", errors=err)
453
454 # Get Synchronize object
455 syncer = self.get_syncer()
456
457 changed = False
458 groups = []
459 for uid in groups_uids:
460 # Check if LDAP group exist
461 exists, err = syncer.is_ldapgroup_exists(uid)
462 if err:
463 msg = "Error determining LDAP group existence for group %s: %s" % (
464 uid,
465 err,
466 )
467 self.module.fail_json(msg=msg)
468
469 if exists:
470 continue
471
472 # if the LDAP entry that was previously used to create the group doesn't exist, prune it
473 group_name, err = ldap_openshift_group.get_group_name_for_uid(uid)
474 if err:
475 self.module.fail_json(msg=err)
476
477 # Delete Group
478 result = ldap_openshift_group.delete_openshift_group(group_name)
479 groups.append(result)
480 changed = True
481
482 self.exit_json(changed=changed, groups=groups)
483
484 def execute_module(self):
485 # validate LDAP sync configuration
486 error = validate_ldap_sync_config(self.config)
487 if error:
488 self.fail_json(msg="Invalid LDAP Sync config: %s" % error)
489
490 # Split host/port
491 if self.config.get("url"):
492 result, error = ldap_split_host_port(self.config.get("url"))
493 if error:
494 self.fail_json(
495 msg="Failed to parse url='{0}': {1}".format(
496 self.config.get("url"), error
497 )
498 )
499 self.netlocation, self.host, self.port = (
500 result["netlocation"],
501 result["host"],
502 result["port"],
503 )
504 self.scheme = result["scheme"]
505
506 if self.params.get("state") == "present":
507 self.synchronize()
508 else:
509 self.prune()