id
int64
0
458k
file_name
stringlengths
4
119
file_path
stringlengths
14
227
content
stringlengths
24
9.96M
size
int64
24
9.96M
language
stringclasses
1 value
extension
stringclasses
14 values
total_lines
int64
1
219k
avg_line_length
float64
2.52
4.63M
max_line_length
int64
5
9.91M
alphanum_fraction
float64
0
1
repo_name
stringlengths
7
101
repo_stars
int64
100
139k
repo_forks
int64
0
26.4k
repo_open_issues
int64
0
2.27k
repo_license
stringclasses
12 values
repo_extraction_date
stringclasses
433 values
16,500
service_plugin.py
freeipa_freeipa/ipatests/test_xmlrpc/tracker/service_plugin.py
# -*- coding: utf-8 -*- # # Copyright (C) 2016 FreeIPA Contributors see COPYING for license # import six from ipalib import api from ipatests.test_xmlrpc.tracker.base import Tracker from ipatests.test_xmlrpc.tracker.kerberos_aliases import KerberosAliasMixin from ipatests.test_xmlrpc.xmlrpc_test import fuzzy_uuid from ipatests.test_xmlrpc import objectclasses from ipatests.util import assert_deepequal from ipapython.dn import DN if six.PY3: unicode = str class ServiceTracker(KerberosAliasMixin, Tracker): """ Tracker class for service plugin So far does not include methods for these commands: service-add-host service-remove-host service-allow-retrieve-keytab service-disallow-retrieve-keytab service-allow-create-keytab service-disallow-create-keytab service-disable service-add-cert service-remove-cert """ retrieve_keys = { u'dn', u'krbprincipalname', u'usercertificate', u'has_keytab', u'ipakrbauthzdata', u'ipaallowedtoperform', u'subject', u'managedby', u'serial_number', u'serial_number_hex', u'issuer', u'valid_not_before', u'valid_not_after', u'sha1_fingerprint', u'sha256_fingerprint', u'krbprincipalauthind', u'managedby_host', u'krbcanonicalname'} retrieve_all_keys = retrieve_keys | { u'ipaKrbPrincipalAlias', u'ipaUniqueID', u'krbExtraData', u'krbLastPwdChange', u'krbLoginFailedCount', u'memberof', u'objectClass', u'ipakrbrequirespreauth', u'krbpwdpolicyreference', u'ipakrbokasdelegate', u'ipakrboktoauthasdelegate'} create_keys = (retrieve_keys | {u'objectclass', u'ipauniqueid'}) - { u'usercertificate', u'has_keytab'} update_keys = retrieve_keys - {u'dn', u'has_keytab'} def __init__(self, name, host_fqdn, options=None): super(ServiceTracker, self).__init__(default_version=None) self._name = u"{0}/{1}@{2}".format(name, host_fqdn, api.env.realm) self.dn = DN( ('krbprincipalname', self.name), api.env.container_service, api.env.basedn) self.host_fqdn = host_fqdn self.options = options or {} @property def name(self): return self._name def make_create_command(self, force=True): """ Make function that creates a service """ return self.make_command('service_add', self.name, force=force, **self.options) def make_delete_command(self): """ Make function that deletes a service """ return self.make_command('service_del', self.name) def make_retrieve_command(self, all=False, raw=False): """ Make function that retrieves a service """ return self.make_command('service_show', self.name, all=all) def make_find_command(self, *args, **kwargs): """ Make function that searches for a service""" return self.make_command('service_find', *args, **kwargs) def make_update_command(self, updates): """ Make function that updates a service """ return self.make_command('service_mod', self.name, **updates) def make_disable_command(self): """ make command that disables the service principal """ return self.make_command('service_disable', self.name) def create(self, force=True): """Helper function to create an entry and check the result""" self.ensure_missing() self.track_create() command = self.make_create_command(force=force) result = command() self.check_create(result) def track_create(self, **options): """ Update expected state for service creation """ self.attrs = { u'dn': self.dn, u'krbprincipalname': [u'{0}'.format(self.name)], u'objectclass': objectclasses.service, u'ipauniqueid': [fuzzy_uuid], u'managedby_host': [self.host_fqdn], u'krbcanonicalname': [u'{0}'.format(self.name)], u'has_keytab': False, u'ipakrboktoauthasdelegate': False, u'krbpwdpolicyreference': [DN( u'cn=Default Service Password Policy', self.api.env.container_service, self.api.env.basedn, )], } for key in self.options: self.attrs[key] = [self.options[key]] self.exists = True def check_create(self, result): """ Check service-add command result """ assert_deepequal({ u'value': u'{0}'.format(self.name), u'summary': u'Added service "{0}"'.format(self.name), u'result': self.filter_attrs(self.create_keys) }, result) def check_delete(self, result): """ Check service-del command result """ assert_deepequal({ u'value': [u'{0}'.format(self.name)], u'summary': u'Deleted service "{0}"'.format(self.name), u'result': {u'failed': []} }, result) def check_retrieve(self, result, all=False, raw=False): """ Check service-show command result """ if all: expected = self.filter_attrs(self.retrieve_all_keys) else: expected = self.filter_attrs(self.retrieve_keys) assert_deepequal({ u'value': u'{0}'.format(self.name), u'summary': None, u'result': expected, }, result) def check_find(self, result, all=False, raw=False): """ Check service-find command result """ if all: expected = self.filter_attrs(self.retrieve_all_keys) else: expected = self.filter_attrs(self.retrieve_keys) assert_deepequal({ u'count': 1, u'truncated': False, u'summary': u'1 service matched', u'result': [expected] }, result) def check_update(self, result, extra_keys=()): """ Check service-mod command result """ assert_deepequal({ u'value': u'{0}'.format(self.name), u'summary': u'Modified service "{0}"'.format(self.name), u'result': self.filter_attrs(self.update_keys | set(extra_keys)) }, result) # Kerberos aliases methods def _make_add_alias_cmd(self): return self.make_command('service_add_principal', self.name) def _make_remove_alias_cmd(self): return self.make_command('service_remove_principal', self.name)
6,487
Python
.py
149
34.516779
76
0.621592
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,501
ca_plugin.py
freeipa_freeipa/ipatests/test_xmlrpc/tracker/ca_plugin.py
# # Copyright (C) 2016 FreeIPA Contributors see COPYING for license # from __future__ import absolute_import import six from ipapython.dn import DN from ipatests.test_xmlrpc.tracker.base import Tracker, EnableTracker from ipatests.util import assert_deepequal from ipatests.test_xmlrpc.xmlrpc_test import ( fuzzy_issuer, fuzzy_caid, fuzzy_base64, fuzzy_sequence_of, fuzzy_bytes, ) from ipatests.test_xmlrpc import objectclasses if six.PY3: unicode = str class CATracker(Tracker, EnableTracker): """Implementation of a Tracker class for CA plugin.""" ldap_keys = { 'dn', 'cn', 'ipacaid', 'ipacasubjectdn', 'ipacaissuerdn', 'description', 'ipacarandomserialnumberversion', } cert_keys = { 'certificate', } cert_all_keys = { 'certificate_chain', } find_keys = ldap_keys find_all_keys = {'objectclass'} | ldap_keys retrieve_keys = ldap_keys | cert_keys retrieve_all_keys = {'objectclass'} | retrieve_keys | cert_all_keys create_keys = {'objectclass'} | retrieve_keys update_keys = ldap_keys - {'dn'} def __init__(self, name, subject, desc=u"Test generated CA", default_version=None, auto_disable_for_delete=True): super(CATracker, self).__init__(default_version=default_version) self.attrs = {} self.ipasubjectdn = subject self.description = desc self.dn = DN(('cn', name), self.api.env.container_ca, self.api.env.basedn) # Whether to run ca-disable automatically before deleting the CA. self.auto_disable_for_delete = auto_disable_for_delete def make_create_command(self): """Make function that creates the plugin entry object.""" return self.make_command( 'ca_add', self.name, ipacasubjectdn=self.ipasubjectdn, description=self.description ) def check_create(self, result): assert_deepequal(dict( value=self.name, summary=u'Created CA "{}"'.format(self.name), result=dict(self.filter_attrs(self.create_keys)) ), result) def track_create(self): self.attrs = dict( dn=unicode(self.dn), cn=[self.name], description=[self.description], ipacasubjectdn=[self.ipasubjectdn], ipacaissuerdn=[fuzzy_issuer], ipacaid=[fuzzy_caid], certificate=fuzzy_base64, certificate_chain=fuzzy_sequence_of(fuzzy_bytes), objectclass=objectclasses.ca ) if self.description == 'IPA CA': self.attrs['ipacarandomserialnumberversion'] = ('0',) self.exists = True def make_disable_command(self): return self.make_command('ca_disable', self.name) def check_disable(self, result): assert_deepequal(dict( result=True, value=self.name, summary=f'Disabled CA "{self.name}"', ), result) def make_delete_command(self): """Make function that deletes the plugin entry object.""" if self.auto_disable_for_delete: def disable_then_delete(): self.make_command('ca_disable', self.name)() return self.make_command('ca_del', self.name)() return disable_then_delete else: return self.make_command('ca_del', self.name) def check_delete(self, result): assert_deepequal(dict( value=[self.name], summary=u'Deleted CA "{}"'.format(self.name), result=dict(failed=[]) ), result) def make_retrieve_command(self, all=False, raw=False, **options): """Make function that retrieves the entry using ${CMD}_show""" return self.make_command('ca_show', self.name, all=all, raw=raw, **options) def check_retrieve(self, result, all=False, raw=False): """Check the plugin's `show` command result""" if all: expected = self.filter_attrs(self.retrieve_all_keys) else: expected = self.filter_attrs(self.retrieve_keys) assert_deepequal(dict( value=self.name, summary=None, result=expected ), result) def make_find_command(self, *args, **kwargs): """Make function that finds the entry using ${CMD}_find Note that the name (or other search terms) needs to be specified in arguments. """ return self.make_command('ca_find', *args, **kwargs) def check_find(self, result, all=False, raw=False): """Check the plugin's `find` command result""" if all: expected = self.filter_attrs(self.find_all_keys) else: expected = self.filter_attrs(self.find_keys) assert_deepequal(dict( count=1, truncated=False, summary=u'1 CA matched', result=[expected] ), result) def make_update_command(self, updates): """Make function that modifies the entry using ${CMD}_mod""" return self.make_command('ca_mod', self.name, **updates) def check_update(self, result, extra_keys=()): """Check the plugin's `find` command result""" assert_deepequal(dict( value=self.name, summary=u'Modified CA "{}"'.format(self.name), result=self.filter_attrs(self.update_keys | set(extra_keys)) ), result)
5,526
Python
.py
140
30.342857
73
0.610075
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,502
automember_plugin.py
freeipa_freeipa/ipatests/test_xmlrpc/tracker/automember_plugin.py
# # Copyright (C) 2015 FreeIPA Contributors see COPYING for license # from ipatests.test_xmlrpc import objectclasses from ipatests.test_xmlrpc.xmlrpc_test import ( fuzzy_uuid, fuzzy_automember_message, fuzzy_automember_dn) from ipatests.test_xmlrpc.tracker.base import Tracker from ipatests.util import assert_deepequal from ipalib import api from ipapython.dn import DN class AutomemberTracker(Tracker): """ Class for tracking automembers """ retrieve_keys = {u'dn', u'cn', u'member_host', u'description', u'member_automember', u'memberindirect_host', u'automemberinclusiveregex', u'automemberexclusiveregex', u'automembertargetgroup'} retrieve_all_keys = retrieve_keys | {u'objectclass', u'automembertargetgroup'} create_keys = retrieve_all_keys update_keys = retrieve_keys - {u'dn'} add_member_keys = retrieve_keys | {u'member_host'} add_condition_keys = retrieve_keys - {u'dn'} |\ {u'automemberinclusiveregex', u'automembertargetgroup'} add_condition_negative_keys = {u'automemberinclusiveregex'} def __init__(self, groupname, membertype, description=u'Automember desc'): super(AutomemberTracker, self).__init__(default_version=None) self.cn = groupname self.description = description self.membertype = membertype self.dn = DN(('cn', self.cn), ('cn', self.membertype.title()), ('cn', 'automember'), ('cn', 'etc'), api.env.basedn) def make_create_command(self, *args, **kwargs): """ Make function that creates an automember using 'automember-add' """ return self.make_command('automember_add', self.cn, description=self.description, type=self.membertype, *args, **kwargs) def make_delete_command(self): """ Make function that deletes an automember using 'automember-del' """ return self.make_command('automember_del', self.cn, **dict(type=self.membertype)) def make_retrieve_command(self, all=False, raw=False, membertype=None): """ Make function that retrieves an automember using 'automember-show' """ if membertype is None: membertype = self.membertype return self.make_command('automember_show', self.cn, type=membertype) def make_find_command(self, *args, **kwargs): """ Make function that searches for an automember using 'automember-find' """ return self.make_command('automember_find', self.cn, type=self.membertype) def make_update_command(self, updates): """ Make function that updates an automember using 'automember-mod' """ return self.make_command('automember_mod', self.cn, type=self.membertype, **updates) def make_add_member_command(self, options={}): """ Make function that adds a member to an automember """ return self.make_command('automember_add_member', self.cn, **options) def make_remove_member_command(self, options={}): """ Make function that removes a member from an automember """ return self.make_command('automember_remove_member', self.cn, **options) def make_rebuild_command(self, *args, **kwargs): """ Make function that issues automember_rebuild. This function can be executed with arbitrary automember tracker """ return self.make_command('automember_rebuild', *args, **kwargs) def make_add_condition_command(self, *args, **kwargs): """ Make function that issues automember_add_condition """ return self.make_command('automember_add_condition', self.cn, *args, **kwargs) def make_remove_condition_command(self, *args, **kwargs): """ Make function that issues automember_remove_condition """ return self.make_command('automember_remove_condition', self.cn, *args, **kwargs) def track_create(self): """ Updates expected state for automember creation""" self.attrs = dict( dn=self.dn, mepmanagedentry=[DN(('cn', self.cn), ('cn', 'ng'), ('cn', 'alt'), api.env.basedn)], cn=[self.cn], description=[self.description], ipauniqueid=[fuzzy_uuid], objectclass=objectclasses.automember, automembertargetgroup=[DN(('cn', self.cn), ('cn', self.membertype + 's'), ('cn', 'accounts'), api.env.basedn)] ) self.exists = True def add_member(self, options): """ Add a member host to automember and perform check """ if u'group' in options: try: self.attrs[u'group'] =\ self.attrs[u'group'] + [options[u'group']] except KeyError: self.attrs[u'group'] = [options[u'group']] # search for hosts in the target automember and # add them as memberindirect hosts elif u'hostgroup' in options: try: self.attrs[u'hostgroup'] =\ self.attrs[u'hostgroup'] + [options[u'hostgroup']] except KeyError: self.attrs[u'hostgroup'] = [options[u'hostgroup']] command = self.make_add_member_command(options) result = command() self.check_add_member(result) def remove_member(self, options): """ Remove a member host from automember and perform check """ if u'host' in options: self.attrs[u'member_host'].remove(options[u'host']) elif u'automember' in options: self.attrs[u'member_automember'].remove(options[u'automember']) try: if not self.attrs[u'member_host']: del self.attrs[u'member_host'] except KeyError: pass try: if not self.attrs[u'member_automember']: del self.attrs[u'member_automember'] except KeyError: pass command = self.make_remove_member_command(options) result = command() self.check_remove_member(result) def update(self, updates, expected_updates=None): """Helper function to update this user and check the result Overriding Tracker method for setting self.attrs correctly; * most attributes stores its value in list * the rest can be overridden by expected_updates * allow deleting parametrs if update value is None """ if expected_updates is None: expected_updates = {} self.ensure_exists() command = self.make_update_command(updates) result = command() for key, value in updates.items(): if value is None: del self.attrs[key] else: self.attrs[key] = [value] for key, value in expected_updates.items(): if value is None: del self.attrs[key] else: self.attrs[key] = value self.check_update( result, extra_keys=set(updates.keys()) | set(expected_updates.keys()) ) def add_condition(self, key, type, inclusiveregex): """ Add a condition with given inclusive regex and check for result. Only one condition can be added. For more specific uses please use make_add_condition_command instead. """ command = self.make_add_condition_command( key=key, type=type, automemberinclusiveregex=inclusiveregex) self.attrs['automemberinclusiveregex'] = [u'%s=%s' % (key, inclusiveregex[0])] result = command() self.check_add_condition(result) def add_condition_exclusive(self, key, type, exclusiveregex): """ Add a condition with given exclusive regex and check for result. Only one condition can be added. For more specific uses please use make_add_condition_command instead. """ command = self.make_add_condition_command( key=key, type=type, automemberexclusiveregex=exclusiveregex) self.attrs['automemberexclusiveregex'] = [u'%s=%s' % (key, exclusiveregex[0])] result = command() self.check_add_condition(result) def rebuild(self, no_wait=False): """ Rebuild automember conditions and check for result """ command = self.make_rebuild_command(type=self.membertype, no_wait=no_wait) result = command() self.check_rebuild(result, no_wait=no_wait) def check_rebuild(self, result, no_wait=False): """ Check result of automember_rebuild command """ if no_wait is False: assert_deepequal(dict( value=None, result=dict(), summary=fuzzy_automember_message ), result) else: assert_deepequal(dict( value=None, result=dict(dn=fuzzy_automember_dn), summary=u'Automember rebuild membership task started' ), result) def check_add_condition(self, result): """ Check result of automember_add_condition command """ assert_deepequal(dict( value=self.cn, summary=u'Added condition(s) to "%s"' % self.cn, completed=1, failed=dict( failed=dict(automemberinclusiveregex=tuple(), automemberexclusiveregex=tuple(), ) ), result=self.filter_attrs(self.add_condition_keys) ), result) def check_add_condition_negative(self, result): """ Check result of automember_add_condition command when the operation didn't add anything. """ assert_deepequal(dict( value=self.cn, summary=u'Added condition(s) to "%s"' % self.cn, completed=0, failed=dict( failed=dict(automemberinclusiveregex=tuple(), automemberexclusiveregex=tuple(), ) ), result=self.filter_attrs(self.add_condition_negative_keys) ), result) def check_create(self, result): """ Checks 'automember_add' command result """ assert_deepequal(dict( value=self.cn, summary=u'Added automember rule "%s"' % self.cn, result=self.filter_attrs(self.create_keys) ), result) def check_delete(self, result): """ Checks 'automember_del' command result """ assert_deepequal(dict( value=[self.cn], summary=u'Deleted automember rule "%s"' % self.cn, result=dict(failed=[]), ), result) def check_retrieve(self, result, all=False, raw=False): """ Checks 'automember_show' command result """ if all: expected = self.filter_attrs(self.retrieve_all_keys) else: expected = self.filter_attrs(self.retrieve_keys) assert_deepequal(dict( value=self.cn, summary=None, result=expected ), result) def check_find(self, result, all=False, raw=False): """ Checks 'automember_find' command result """ if all: expected = self.filter_attrs(self.retrieve_all_keys) else: expected = self.filter_attrs(self.retrieve_keys) assert_deepequal(dict( count=1, truncated=False, summary=u'1 rules matched', result=[expected], ), result) def check_update(self, result, extra_keys={}): """ Checks 'automember_mod' command result """ assert_deepequal(dict( value=self.cn, summary=u'Modified automember rule "%s"' % self.cn, result=self.filter_attrs(self.update_keys | set(extra_keys)) ), result) def check_add_member(self, result): """ Checks 'automember_add_member' command result """ assert_deepequal(dict( completed=1, failed={u'member': {u'host': (), u'automember': ()}}, result=self.filter_attrs(self.add_member_keys) ), result) def check_add_member_negative(self, result, options): """ Checks 'automember_add_member' command result when expected result is failure of the operation""" expected = dict( completed=0, failed={u'member': {u'automember': (), u'user': ()}}, result=self.filter_attrs(self.add_member_keys) ) if u'host' in options: expected[u'failed'][u'member'][u'host'] = [( options[u'host'], u'no such entry')] elif u'automember' in options: expected[u'failed'][u'member'][u'automember'] = [( options[u'automember'], u'no such entry')] assert_deepequal(expected, result) def check_remove_member_negative(self, result, options): """ Checks 'automember_remove_member' command result when expected result is failure of the operation""" expected = dict( completed=0, failed={u'member': {u'automember': (), u'host': ()}}, result=self.filter_attrs(self.add_member_keys) ) if u'user' in options: expected[u'failed'][u'member'][u'host'] = [( options[u'user'], u'This entry is not a member')] elif u'automember' in options: expected[u'failed'][u'member'][u'automember'] = [( options[u'automember'], u'This entry is not a member')] assert_deepequal(expected, result) def check_remove_member(self, result): """ Checks 'automember_remove_member' command result """ self.check_add_member(result)
14,264
Python
.py
304
34.796053
79
0.583639
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,503
certmapdata.py
freeipa_freeipa/ipatests/test_xmlrpc/tracker/certmapdata.py
# # Copyright (C) 2015 FreeIPA Contributors see COPYING for license # import base64 from cryptography import x509 from cryptography.hazmat.backends import default_backend import pytest from ipalib.errors import MutuallyExclusiveError, RequirementError from ipapython.dn import DN from ipatests.util import assert_deepequal class CertmapdataMixin: certmapdata_options = {u'issuer', u'subject', u'certificate', u'ipacertmapdata'} def _data_from_options(self, **options): issuer = None subject = None if not self.certmapdata_options & set(options): raise RequirementError(name=u'certmapdata') if ({u'issuer', u'subject'} & set(options) and {u'ipacertmapdata', u'certificate'} & set(options)): raise MutuallyExclusiveError(reason=u'Mutually exclusive options ' u'provided at the same time.') if u'issuer' in options and u'subject' not in options: raise RequirementError(name=u'subject') if u'subject' in options and u'issuer' not in options: raise RequirementError(name=u'issuer') if {u'ipacertmapdata', u'certificate'} & set(options): try: data = options[u'ipacertmapdata'] except KeyError: data = [] else: if not isinstance(data, list): data = [data] try: certs = options[u'certificate'] except KeyError: certs = [] else: if not isinstance(certs, list): certs = [certs] for cert in certs: cert = x509.load_der_x509_certificate( base64.b64decode(cert), backend=default_backend() ) issuer = DN(cert.issuer).x500_text() subject = DN(cert.subject).x500_text() data.append( u'X509:<I>{i}<S>{s}'.format(i=issuer, s=subject) ) else: issuer = DN(options[u'issuer']).x500_text() subject = DN(options[u'subject']).x500_text() data = [u'X509:<I>{i}<S>{s}'.format(i=issuer, s=subject)] return set(data) def _make_add_certmap(self): raise NotImplementedError("_make_add_certmap method must be " "implemented in instance.") def _make_remove_certmap(self): raise NotImplementedError("_make_remove_certmap method must be " "implemented in instance.") def add_certmap(self, **kwargs): cmd = self._make_add_certmap() try: expected_certmapdata = self._data_from_options(**kwargs) except Exception as e: with pytest.raises(type(e)): cmd(**kwargs) else: result = cmd(**kwargs) self.attrs.setdefault(u'ipacertmapdata', []).extend( expected_certmapdata) expected = dict( summary=(u'Added certificate mappings to user ' u'"{}"'.format(self.name)), value=self.name, result=dict( uid=(self.name,), ), ) if self.attrs[u'ipacertmapdata']: expected[u'result'][u'ipacertmapdata'] = ( self.attrs[u'ipacertmapdata']) assert_deepequal(expected, result) def remove_certmap(self, **kwargs): cmd = self._make_remove_certmap() try: expected_certmapdata = self._data_from_options(**kwargs) except Exception as e: with pytest.raises(type(e)): cmd(**kwargs) else: result = cmd(**kwargs) for data in expected_certmapdata: self.attrs[u'ipacertmapdata'].remove(data) expected = dict( summary=(u'Removed certificate mappings from user ' u'"{}"'.format(self.name)), value=self.name, result=dict( uid=(self.name,), ), ) if self.attrs[u'ipacertmapdata']: expected[u'result'][u'ipacertmapdata'] = ( self.attrs[u'ipacertmapdata']) assert_deepequal(expected, result)
4,484
Python
.py
108
27.851852
78
0.533686
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,504
host_plugin.py
freeipa_freeipa/ipatests/test_xmlrpc/tracker/host_plugin.py
# # Copyright (C) 2015 FreeIPA Contributors see COPYING for license # from __future__ import print_function from ipapython.dn import DN from ipatests.test_xmlrpc.tracker.base import Tracker from ipatests.test_xmlrpc.tracker.kerberos_aliases import KerberosAliasMixin from ipatests.test_xmlrpc.xmlrpc_test import fuzzy_uuid from ipatests.test_xmlrpc import objectclasses from ipatests.util import assert_deepequal from ipalib import errors class HostTracker(KerberosAliasMixin, Tracker): """Wraps and tracks modifications to a Host object Implements the helper functions for host plugin. The HostTracker object stores information about the host, e.g. ``fqdn`` and ``dn``. """ retrieve_keys = { 'dn', 'fqdn', 'description', 'l', 'krbcanonicalname', 'krbprincipalname', 'managedby_host', 'has_keytab', 'has_password', 'issuer', 'serial_number', 'serial_number_hex', 'sha1_fingerprint', 'sha256_fingerprint', 'subject', 'usercertificate', 'valid_not_after', 'valid_not_before', 'macaddress', 'sshpubkeyfp', 'ipaallowedtoperform_read_keys_user', 'memberof_hostgroup', 'memberofindirect_hostgroup', 'ipaallowedtoperform_read_keys_group', 'ipaallowedtoperform_read_keys_host', 'ipaallowedtoperform_read_keys_hostgroup', 'ipaallowedtoperform_write_keys_user', 'ipaallowedtoperform_write_keys_group', 'ipaallowedtoperform_write_keys_host', 'ipaallowedtoperform_write_keys_hostgroup'} retrieve_all_keys = retrieve_keys | { u'cn', u'ipakrbokasdelegate', u'ipakrbrequirespreauth', u'ipauniqueid', u'krbcanonicalname', u'managing_host', u'objectclass', u'serverhostname', u'ipakrboktoauthasdelegate', u'krbpwdpolicyreference'} create_keys = retrieve_keys | {'objectclass', 'ipauniqueid', 'randompassword'} update_keys = retrieve_keys - {'dn'} managedby_keys = retrieve_keys - {'has_keytab', 'has_password'} allowedto_keys = retrieve_keys - {'has_keytab', 'has_password'} find_keys = retrieve_keys - { 'has_keytab', 'has_password', 'memberof_hostgroup', 'memberofindirect_hostgroup', 'managedby_host', } find_all_keys = retrieve_all_keys - {'has_keytab', 'has_password'} def __init__(self, name, fqdn=None, default_version=None): super(HostTracker, self).__init__(default_version=default_version) self.shortname = name if fqdn: self.fqdn = fqdn else: self.fqdn = u'%s.%s' % (name, self.api.env.domain) self.dn = DN(('fqdn', self.fqdn), 'cn=computers', 'cn=accounts', self.api.env.basedn) self.description = u'Test host <%s>' % name self.location = u'Undisclosed location <%s>' % name def make_create_command(self, force=True): """Make function that creates this host using host_add""" return self.make_command('host_add', self.fqdn, description=self.description, l=self.location, force=force) def make_delete_command(self): """Make function that deletes the host using host_del""" return self.make_command('host_del', self.fqdn) def make_retrieve_command(self, all=False, raw=False): """Make function that retrieves the host using host_show""" return self.make_command('host_show', self.fqdn, all=all, raw=raw) def make_find_command(self, *args, **kwargs): """Make function that finds hosts using host_find Note that the fqdn (or other search terms) needs to be specified in arguments. """ return self.make_command('host_find', *args, **kwargs) def make_update_command(self, updates): """Make function that modifies the host using host_mod""" return self.make_command('host_mod', self.fqdn, **updates) def create(self, force=True): """Helper function to create an entry and check the result""" self.ensure_missing() self.track_create() command = self.make_create_command(force=force) result = command() self.check_create(result) def track_create(self): """Update expected state for host creation""" self.attrs = dict( dn=self.dn, fqdn=[self.fqdn], description=[self.description], l=[self.location], krbprincipalname=[u'host/%s@%s' % (self.fqdn, self.api.env.realm)], krbcanonicalname=[u'host/%s@%s' % (self.fqdn, self.api.env.realm)], objectclass=objectclasses.host, ipauniqueid=[fuzzy_uuid], managedby_host=[self.fqdn], has_keytab=False, has_password=False, cn=[self.fqdn], ipakrbokasdelegate=False, ipakrbrequirespreauth=True, managing_host=[self.fqdn], serverhostname=[self.shortname], ipakrboktoauthasdelegate=False, krbpwdpolicyreference=[DN( u'cn=Default Host Password Policy', self.api.env.container_host, self.api.env.basedn, )], ) self.exists = True def check_create(self, result): """Check `host_add` command result""" assert_deepequal(dict( value=self.fqdn, summary=u'Added host "%s"' % self.fqdn, result=self.filter_attrs(self.create_keys), ), result) def check_delete(self, result): """Check `host_del` command result""" assert_deepequal(dict( value=[self.fqdn], summary=u'Deleted host "%s"' % self.fqdn, result=dict(failed=[]), ), result) def check_retrieve(self, result, all=False, raw=False): """Check `host_show` command result""" if all: expected = self.filter_attrs(self.retrieve_all_keys) else: expected = self.filter_attrs(self.retrieve_keys) assert_deepequal(dict( value=self.fqdn, summary=None, result=expected, ), result) def check_find(self, result, all=False, raw=False): """Check `host_find` command result""" if all: expected = self.filter_attrs(self.find_all_keys) else: expected = self.filter_attrs(self.find_keys) assert_deepequal(dict( count=1, truncated=False, summary=u'1 host matched', result=[expected], ), result) def check_update(self, result, extra_keys=()): """Check `host_update` command result""" assert_deepequal(dict( value=self.fqdn, summary=u'Modified host "%s"' % self.fqdn, result=self.filter_attrs(self.update_keys | set(extra_keys)) ), result) def add_finalizer_certcleanup(self, request): """ Fixture to cleanup certificate from local host """ cleanup_command = self.make_update_command( updates={'usercertificate':''}) def cleanup(): try: cleanup_command() except errors.EmptyModlist: pass request.addfinalizer(cleanup) # Kerberos aliases methods def _make_add_alias_cmd(self): return self.make_command('host_add_principal', self.name) def _make_remove_alias_cmd(self): return self.make_command('host_remove_principal', self.name)
7,594
Python
.py
173
34.092486
79
0.6168
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,505
location_plugin.py
freeipa_freeipa/ipatests/test_xmlrpc/tracker/location_plugin.py
# # Copyright (C) 2016 FreeIPA Contributors see COPYING for license # from __future__ import absolute_import import six from ipapython.dn import DN from ipapython.dnsutil import DNSName from ipatests.util import assert_deepequal from ipatests.test_xmlrpc.tracker.base import Tracker if six.PY3: unicode = str class LocationTracker(Tracker): """Tracker for IPA Location tests""" retrieve_keys = { 'idnsname', 'description', 'dn', 'servers_server', 'dns_server'} retrieve_all_keys = retrieve_keys | {'objectclass'} create_keys = {'idnsname', 'description', 'dn', 'objectclass'} find_keys = {'idnsname', 'description', 'dn',} find_all_keys = find_keys | {'objectclass'} update_keys = {'idnsname', 'description'} def __init__(self, name, description=u"Location description"): super(LocationTracker, self).__init__(default_version=None) # ugly hack to allow testing invalid inputs try: self.idnsname_obj = DNSName(name) except Exception: self.idnsname_obj = DNSName(u"placeholder-for-invalid-value") self.idnsname = name self.description = description self.dn = DN( ('idnsname', self.idnsname_obj.ToASCII()), 'cn=locations', 'cn=etc', self.api.env.basedn ) self.servers = {} def make_create_command(self): """Make function that creates this location using location-add""" return self.make_command( 'location_add', self.idnsname, description=self.description, ) def make_delete_command(self): """Make function that removes this location using location-del""" return self.make_command('location_del', self.idnsname) def make_retrieve_command(self, all=False, raw=False): """Make function that retrieves this location using location-show""" return self.make_command( 'location_show', self.idnsname, all=all, raw=raw ) def make_find_command(self, *args, **kwargs): """Make function that finds locations using location-find""" return self.make_command('location_find', *args, **kwargs) def make_update_command(self, updates): """Make function that modifies the location using location-mod""" return self.make_command('location_mod', self.idnsname, **updates) def track_create(self): """Update expected state for location creation""" self.attrs = dict( dn=self.dn, idnsname=[self.idnsname_obj], description=[self.description], objectclass=[u'top', u'ipaLocationObject'], ) self.exists = True def check_create(self, result): """Check `location-add` command result""" assert_deepequal(dict( value=self.idnsname_obj, summary=u'Added IPA location "{loc}"'.format(loc=self.idnsname), result=self.filter_attrs(self.create_keys) ), result) def check_delete(self, result): """Check `location-del` command result""" assert_deepequal(dict( value=[self.idnsname_obj], summary=u'Deleted IPA location "{loc}"'.format(loc=self.idnsname), result=dict(failed=[]), ), result) def check_retrieve(self, result, all=False, raw=False): """Check `location-show` command result""" if all: expected = self.filter_attrs(self.retrieve_all_keys) else: expected = self.filter_attrs(self.retrieve_keys) assert_deepequal(dict( value=self.idnsname_obj, summary=None, result=expected, servers=self.servers, ), result) def check_find(self, result, all=False, raw=False): """Check `location-find` command result""" if all: expected = self.filter_attrs(self.find_all_keys) else: expected = self.filter_attrs(self.find_keys) assert_deepequal(dict( count=1, truncated=False, summary=u'1 IPA location matched', result=[expected], ), result) def check_update(self, result, extra_keys=()): """Check `location-update` command result""" assert_deepequal(dict( value=self.idnsname_obj, summary=u'Modified IPA location "{loc}"'.format(loc=self.idnsname), result=self.filter_attrs(self.update_keys | set(extra_keys)) ), result) def add_server_to_location( self, server_name, weight=100, relative_weight=u"100.0%"): self.attrs.setdefault('servers_server', []).append(server_name) self.attrs.setdefault('dns_server', []).append(server_name) self.servers[server_name] = { 'cn': [server_name], 'ipaserviceweight': [unicode(weight)], 'service_relative_weight': [relative_weight], 'enabled_role_servrole': lambda other: True } def remove_server_from_location(self, server_name): if 'servers_server' in self.attrs: try: self.attrs['servers_server'].remove(server_name) self.attrs['dns_server'].remove(server_name) except ValueError: pass else: if not self.attrs['servers_server']: del self.attrs['servers_server'] if not self.attrs['dns_server']: del self.attrs['dns_server'] try: del self.servers[server_name] except KeyError: pass
5,622
Python
.py
134
32.365672
79
0.61226
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,506
group_plugin.py
freeipa_freeipa/ipatests/test_xmlrpc/tracker/group_plugin.py
# # Copyright (C) 2015 FreeIPA Contributors see COPYING for license # from ipatests.test_xmlrpc import objectclasses from ipatests.test_xmlrpc.xmlrpc_test import fuzzy_digits, fuzzy_uuid from ipatests.test_xmlrpc.xmlrpc_test import fuzzy_user_or_group_sid from ipatests.test_xmlrpc.xmlrpc_test import fuzzy_set_optional_oc from ipatests.test_xmlrpc.tracker.base import Tracker from ipatests.util import assert_deepequal, get_group_dn class GroupTracker(Tracker): """ Class for host plugin like tests """ retrieve_keys = { 'dn', 'cn', 'gidnumber', 'member_user', 'member_group', 'member_service', 'description', 'memberof_group', 'memberofindirect_group', 'memberindirect_group', 'memberindirect_user', 'memberindirect_service', 'membermanager_group', 'membermanager_user', 'member_idoverrideuser', 'memberindirect_idoverrideuser', 'idoverrideuser' } retrieve_all_keys = retrieve_keys | {u'ipauniqueid', u'objectclass', 'ipantsecurityidentifier'} create_keys = retrieve_all_keys - {u'ipantsecurityidentifier'} update_keys = retrieve_keys - {u'dn'} add_member_keys = retrieve_keys | {u'description'} def __init__(self, name, description=u'Group desc'): super(GroupTracker, self).__init__(default_version=None) self.cn = name self.description = description self.dn = get_group_dn(self.cn) def make_create_command(self, nonposix=False, external=False, *args, **kwargs): """ Make function that creates a group using 'group-add' """ return self.make_command('group_add', self.cn, description=self.description, nonposix=nonposix, external=external, *args, **kwargs) def make_delete_command(self): """ Make function that deletes a group using 'group-del' """ return self.make_command('group_del', self.cn) def make_retrieve_command(self, all=False, raw=False): """ Make function that retrieves a group using 'group-show' """ return self.make_command('group_show', self.cn, all=all) def make_find_command(self, *args, **kwargs): """ Make function that searches for a group using 'group-find' """ return self.make_command('group_find', *args, **kwargs) def make_update_command(self, updates): """ Make function that updates a group using 'group-mod' """ return self.make_command('group_mod', self.cn, **updates) def make_add_member_command(self, options={}): """ Make function that adds a member to a group """ self.adds = options return self.make_command('group_add_member', self.cn, **options) def make_remove_member_command(self, options={}): """ Make function that removes a member from a group """ return self.make_command('group_remove_member', self.cn, **options) def make_detach_command(self): """ Make function that detaches a managed group using 'group-detach' """ self.exists = True return self.make_command('group_detach', self.cn) def make_add_member_manager_command(self, options={}): return self.make_command( 'group_add_member_manager', self.cn, **options ) def make_remove_member_manager_command(self, options={}): return self.make_command( 'group_remove_member_manager', self.cn, **options ) def track_create(self): """ Updates expected state for group creation""" self.attrs = dict( dn=get_group_dn(self.cn), cn=[self.cn], description=[self.description], gidnumber=[fuzzy_digits], ipauniqueid=[fuzzy_uuid], objectclass=fuzzy_set_optional_oc( objectclasses.posixgroup, 'ipantgroupattrs'), ipantsecurityidentifier=[fuzzy_user_or_group_sid], ) self.exists = True def update(self, updates, expected_updates=None): """Helper function to update the group and check the result Overriding Tracker method for setting self.attrs correctly; * most attributes stores its value in list * the rest can be overridden by expected_updates * allow deleting parametrs if update value is None """ if expected_updates is None: expected_updates = {} self.ensure_exists() command = self.make_update_command(updates) result = command() for key, value in updates.items(): if value is None: del self.attrs[key] else: self.attrs[key] = [value] for key, value in expected_updates.items(): if value is None: del self.attrs[key] else: self.attrs[key] = value self.check_update( result, extra_keys=set(updates.keys()) | set(expected_updates.keys()) ) def add_member(self, options): """ Add a member (group OR user OR service OR idoverrideuser) and performs check """ if u'user' in options: try: self.attrs[u'member_user'] =\ self.attrs[u'member_user'] + [options[u'user']] except KeyError: self.attrs[u'member_user'] = [options[u'user']] elif u'group' in options: try: self.attrs[u'member_group'] =\ self.attrs[u'member_group'] + [options[u'group']] except KeyError: self.attrs[u'member_group'] = [options[u'group']] elif u'service' in options: try: self.attrs[u'member_service'] =\ self.attrs[u'member_service'] + [options[u'service']] except KeyError: self.attrs[u'member_service'] = [options[u'service']] elif u'idoverrideuser' in options: try: self.attrs[u'member_idoverrideuser'] =\ self.attrs[u'member_idoverrideuser'] + \ [options[u'idoverrideuser']] except KeyError: self.attrs[u'member_idoverrideuser'] =\ [options[u'idoverrideuser']] command = self.make_add_member_command(options) result = command() self.check_add_member(result) def remove_member(self, options): """ Remove a member (group OR user) and performs check """ if u'user' in options: self.attrs[u'member_user'].remove(options[u'user']) elif u'group' in options: self.attrs[u'member_group'].remove(options[u'group']) elif u'service' in options: self.attrs[u'member_service'].remove(options[u'service']) try: if not self.attrs[u'member_user']: del self.attrs[u'member_user'] except KeyError: pass try: if not self.attrs[u'member_group']: del self.attrs[u'member_group'] except KeyError: pass try: if not self.attrs[u'member_service']: del self.attrs[u'member_service'] except KeyError: pass try: if not self.attrs[u'member_idoverrideuser']: del self.attrs[u'member_idoverrideuser'] except KeyError: pass command = self.make_remove_member_command(options) result = command() self.check_remove_member(result) def add_member_manager(self, options): """Add a member manager (user or group) and perform checks""" if "user" in options: members = self.attrs.setdefault("membermanager_user", []) members.append(options["user"]) elif "group" in options: members = self.attrs.setdefault("membermanager_group", []) members.append(options["group"]) command = self.make_add_member_manager_command(options) result = command() self.check_add_member_manager(result) def remove_member_manager(self, options): if "user" in options: members = self.attrs["membermanager_user"] members.remove(options["user"]) if not members: self.attrs.pop("membermanager_user") elif "group" in options: members = self.attrs["membermanager_group"] members.remove(options["group"]) if not members: self.attrs.pop("membermanager_group") command = self.make_remove_member_manager_command(options) result = command() self.check_remove_member_manager(result) def retrieve(self, all=False, raw=False): command = self.make_retrieve_command(all=all, raw=raw) result = command() self.check_retrieve(result, all=all, raw=raw) def check_create(self, result): """ Checks 'group_add' command result """ assert_deepequal(dict( value=self.cn, summary=u'Added group "%s"' % self.cn, result=self.filter_attrs(self.create_keys) ), result) def check_delete(self, result): """ Checks 'group_del' command result """ assert_deepequal(dict( value=[self.cn], summary=u'Deleted group "%s"' % self.cn, result=dict(failed=[]), ), result) def check_retrieve(self, result, all=False, raw=False): """ Checks 'group_show' command result """ if all: expected = self.filter_attrs(self.retrieve_all_keys) else: expected = self.filter_attrs(self.retrieve_keys) assert_deepequal(dict( value=self.cn, summary=None, result=expected ), result) def check_find(self, result, all=False, raw=False): """ Checks 'group_find' command result """ if all: expected = self.filter_attrs(self.retrieve_all_keys) else: expected = self.filter_attrs(self.retrieve_keys) assert_deepequal(dict( count=1, truncated=False, summary=u'1 group matched', result=[expected], ), result) def check_update(self, result, extra_keys={}): """ Checks 'group_mod' command result """ assert_deepequal(dict( value=self.cn, summary=u'Modified group "%s"' % self.cn, result=self.filter_attrs(self.update_keys | set(extra_keys)) ), result) def check_add_member(self, result): """ Checks 'group_add_member' command result """ assert_deepequal(dict( completed=1, failed={u'member': {u'group': (), u'user': (), u'service': (), u'idoverrideuser': ()}}, result=self.filter_attrs(self.add_member_keys) ), result) def check_add_member_negative(self, result, options={}): """ Checks 'group_add_member' command result when expected result is failure of the operation""" expected = dict( completed=0, failed={u'member': {u'group': (), u'user': (), u'service': (), u'idoverrideuser': ()}}, result=self.filter_attrs(self.add_member_keys) ) if not options: try: options = self.adds except NameError: pass if u'user' in options: expected[u'failed'][u'member'][u'user'] = [( options[u'user'], u'no such entry')] elif u'group' in options: expected[u'failed'][u'member'][u'group'] = [( options[u'group'], u'no such entry')] elif u'service' in options: expected[u'failed'][u'member'][u'service'] = [( options[u'service'], u'no such entry')] elif u'idoverrideuser' in options: expected[u'failed'][u'member'][u'idoverrideuser'] = [( options[u'idoverrideuser'], u'no such entry')] assert_deepequal(expected, result) def check_remove_member_negative(self, result, options): """ Checks 'group_remove_member' command result when expected result is failure of the operation""" expected = dict( completed=0, failed={u'member': {u'group': (), u'user': (), u'service': (), u'idoverrideuser': ()}}, result=self.filter_attrs(self.add_member_keys) ) if u'user' in options: expected[u'failed'][u'member'][u'user'] = [( options[u'user'], u'This entry is not a member')] elif u'group' in options: expected[u'failed'][u'member'][u'group'] = [( options[u'group'], u'This entry is not a member')] elif u'service' in options: expected[u'failed'][u'member'][u'service'] = [( options[u'service'], u'This entry is not a member')] elif u'idoverrideuser' in options: expected[u'failed'][u'member'][u'idoverrideuser'] = [( options[u'service'], u'This entry is not a member')] assert_deepequal(expected, result) def check_remove_member(self, result): """ Checks 'group_remove_member' command result """ self.check_add_member(result) def check_add_member_manager(self, result): assert_deepequal(dict( completed=1, failed={'membermanager': {'group': (), 'user': ()}}, result=self.filter_attrs(self.add_member_keys) ), result) def check_remove_member_manager(self, result): self.check_add_member_manager(result) def check_detach(self, result): """ Checks 'group_detach' command result """ assert_deepequal(dict( value=self.cn, summary=u'Detached group "%s" from user "%s"' % ( self.cn, self.cn), result=True ), result)
14,193
Python
.py
321
32.981308
75
0.579366
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,507
idp_plugin.py
freeipa_freeipa/ipatests/test_xmlrpc/tracker/idp_plugin.py
# # Copyright (C) 2021 FreeIPA Contributors see COPYING for license # from ipalib import api from ipapython.dn import DN from ipatests.test_xmlrpc.tracker.base import Tracker from ipatests.test_xmlrpc import objectclasses from ipatests.util import assert_deepequal class IdpTracker(Tracker): """Class for ipd tests""" retrieve_keys = { 'dn', 'cn', 'ipaidpauthendpoint', 'ipaidpdevauthendpoint', 'ipaidpuserinfoendpoint', 'ipaidpkeysendpoint', 'ipaidptokenendpoint', 'ipaidpissuerurl', 'ipaidpclientid', 'ipaidpscope', 'ipaidpsub'} retrieve_all_keys = retrieve_keys | { 'objectclass', 'ipaidpclientsecret' } create_keys = retrieve_all_keys update_keys = retrieve_keys - {'dn'} find_keys = retrieve_keys find_all_keys = retrieve_all_keys primary_keys = {'cn', 'dn'} def __init__(self, cn, **kwargs): super(IdpTracker, self).__init__(default_version=None) self.cn = cn self.dn = DN(('cn', cn), api.env.container_idp, api.env.basedn) self.kwargs = kwargs def make_create_command(self): """ Make function that creates an idp using idp-add """ return self.make_command('idp_add', self.cn, **self.kwargs) def track_create(self): """ Update expected state for idp creation """ self.attrs = dict( dn=self.dn, cn=[self.cn], objectclass=objectclasses.idp, ) for key, value in self.kwargs.items(): if key == 'ipaidpclientsecret': self.attrs[key] = [value.encode('utf-8')] continue if type(value) is not list: self.attrs[key] = [value] else: self.attrs[key] = value self.exists = True def check_create(self, result, extra_keys=()): """ Check idp-add command result """ expected = self.filter_attrs(self.create_keys | set(extra_keys)) assert_deepequal( dict( value=self.cn, summary='Added Identity Provider reference "%s"' % self.cn, result=self.filter_attrs(expected), ), result) def make_delete_command(self): """ Make function that deletes an idp using idp-del """ return self.make_command('idp_del', self.cn) def check_delete(self, result): """ Check idp-del command result """ assert_deepequal( dict( value=[self.cn], summary='Deleted Identity Provider reference "%s"' % self.cn, result=dict(failed=[]), ), result) def make_retrieve_command(self, all=False, raw=False): """ Make function that retrieves an idp using idp-show """ return self.make_command('idp_show', self.cn, all=all) def check_retrieve(self, result, all=False, raw=False): """ Check idp-show command result """ if all: expected = self.filter_attrs(self.retrieve_all_keys) else: expected = self.filter_attrs(self.retrieve_keys) assert_deepequal(dict( value=self.cn, summary=None, result=expected, ), result) def make_find_command(self, *args, **kwargs): """ Make function that finds idp using idp-find """ return self.make_command('idp_find', *args, **kwargs) def check_find(self, result, all=False, raw=False, pkey_only=False): """ Check idp-find command result """ if all: expected = self.filter_attrs(self.find_all_keys) elif pkey_only: expected = self.filter_attrs(self.primary_keys) else: expected = self.filter_attrs(self.find_keys) assert_deepequal(dict( count=1, truncated=False, summary='1 Identity Provider reference matched', result=[expected], ), result) def make_update_command(self, updates): """ Make function that updates an idp using idp_mod """ return self.make_command('idp_mod', self.cn, **updates) def update(self, updates, expected_updates=None): """Helper function to update this idp and check the result Overriding Tracker method for setting self.attrs correctly; * most attributes stores its value in list * the rest can be overridden by expected_updates * allow deleting parameters if update value is None """ if expected_updates is None: expected_updates = {} self.ensure_exists() command = self.make_update_command(updates) result = command() for key, value in updates.items(): if value is None or value == '': del self.attrs[key] elif key == 'rename': self.attrs['cn'] = [value] else: if type(value) is list: self.attrs[key] = value else: self.attrs[key] = [value] for key, value in expected_updates.items(): if value is None or value == '': del self.attrs[key] else: self.attrs[key] = value self.check_update( result, extra_keys=set(updates.keys()) | set(expected_updates.keys()) ) if 'rename' in updates: self.cn = self.attrs['cn'][0] def check_update(self, result, extra_keys=()): """ Check idp-mod command result """ expected = self.filter_attrs(self.update_keys | set(extra_keys)) assert_deepequal(dict( value=self.cn, summary='Modified Identity Provider reference "%s"' % self.cn, result=expected ), result)
5,796
Python
.py
142
30.697183
77
0.586385
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,508
base.py
freeipa_freeipa/ipatests/test_xmlrpc/tracker/base.py
# # Copyright (C) 2015 FreeIPA Contributors see COPYING for license # """ Implements a base class to track changes to an LDAP object. """ from __future__ import print_function import functools from ipalib import api, errors from ipapython.dn import DN from ipapython.version import API_VERSION from ipatests.util import Fuzzy class BaseTracker: _override_me_msg = "This method needs to be overridden in a subclass" def __init__(self, default_version=None): self.api = api self.default_version = default_version or API_VERSION self._dn = None self.attrs = {} @property def dn(self): """A property containing the distinguished name of the entry.""" if not self._dn: raise ValueError('The DN must be set in the init method.') return self._dn @dn.setter def dn(self, value): if not (isinstance(value, DN) or isinstance(value, Fuzzy)): raise ValueError('The value must be an instance of DN or Fuzzy.') self._dn = value @property def rdn(self): return self.dn[0] @property def name(self): """Property holding the name of the entry in LDAP. This property is computed in runtime. """ return self.rdn.value def filter_attrs(self, keys): """Return a dict of expected attrs, filtered by the given keys""" if not self.attrs: raise RuntimeError('The tracker instance has no attributes.') return {k: v for k, v in self.attrs.items() if k in keys} def run_command(self, name, *args, **options): """Run the given IPA command Logs the command using print for easier debugging """ cmd = self.api.Command[name] options.setdefault('version', self.default_version) args_repr = ', '.join( [repr(a) for a in args] + ['%s=%r' % item for item in list(options.items())]) try: result = cmd(*args, **options) except Exception as e: print('Ran command: %s(%s): %s: %s' % (cmd, args_repr, type(e).__name__, e)) raise else: print('Ran command: %s(%s): OK' % (cmd, args_repr)) return result def make_command(self, name, *args, **options): """Make a functools.partial function to run the given command""" return functools.partial(self.run_command, name, *args, **options) def make_fixture(self, request): """Make fixture for the tracker Don't do anything here. """ return self class RetrievalTracker(BaseTracker): retrieve_keys = None retrieve_all_keys = None def make_retrieve_command(self, all=False, raw=False): """Make function that retrieves the entry using ${CMD}_show""" raise NotImplementedError(self._override_me_msg) def check_retrieve(self, result, all=False, raw=False): """Check the plugin's `show` command result""" raise NotImplementedError(self._override_me_msg) def retrieve(self, all=False, raw=False): """Helper function to retrieve an entry and check the result""" command = self.make_retrieve_command(all=all, raw=raw) result = command() self.check_retrieve(result, all=all, raw=raw) class SearchTracker(BaseTracker): def make_find_command(self, *args, **kwargs): """Make function that finds the entry using ${CMD}_find Note that the name (or other search terms) needs to be specified in arguments. """ raise NotImplementedError(self._override_me_msg) def check_find(self, result, all=False, raw=False): """Check the plugin's `find` command result""" raise NotImplementedError(self._override_me_msg) def find(self, all=False, raw=False): """Helper function to search for this hosts and check the result""" command = self.make_find_command(self.name, all=all, raw=raw) result = command() self.check_find(result, all=all, raw=raw) class ModificationTracker(BaseTracker): update_keys = None singlevalue_keys = None def make_update_command(self, updates): """Make function that modifies the entry using ${CMD}_mod""" raise NotImplementedError(self._override_me_msg) def check_update(self, result, extra_keys=()): """Check the plugin's `mod` command result""" raise NotImplementedError(self._override_me_msg) def update(self, updates, expected_updates=None): """Helper function to update this hosts and check the result The ``updates`` are used as options to the *_mod command, and the self.attrs is updated with this dict. Additionally, self.attrs is updated with ``expected_updates``. """ if expected_updates is None: expected_updates = {} command = self.make_update_command(updates) result = command() self.attrs.update(updates) self.attrs.update(expected_updates) self.attrs = {k: v for k, v in self.attrs.items() if v is not None} self.check_update( result, extra_keys=set(updates.keys()) | set(expected_updates.keys()) ) class CreationTracker(BaseTracker): create_keys = None def __init__(self, default_version=None): super(CreationTracker, self).__init__(default_version=default_version) self.exists = False def make_create_command(self): """Make function that creates the plugin entry object.""" raise NotImplementedError(self._override_me_msg) def track_create(self): """Update expected state for host creation The method should look similar to the following example of host plugin. self.attrs = dict( dn=self.dn, fqdn=[self.fqdn], description=[self.description], ... # all required attributes ) self.exists = True """ raise NotImplementedError(self._override_me_msg) def check_create(self, result): """Check plugin's add command result""" raise NotImplementedError(self._override_me_msg) def create(self): """Helper function to create an entry and check the result""" self.track_create() command = self.make_create_command() result = command() self.check_create(result) def ensure_exists(self): """If the entry does not exist (according to tracker state), create it """ if not self.exists: self.create() def make_delete_command(self): """Make function that deletes the plugin entry object.""" raise NotImplementedError(self._override_me_msg) def track_delete(self): """Update expected state for host deletion""" self.exists = False self.attrs = {} def check_delete(self, result): """Check plugin's `del` command result""" raise NotImplementedError(self._override_me_msg) def delete(self): """Helper function to delete a host and check the result""" self.track_delete() command = self.make_delete_command() result = command() self.check_delete(result) def ensure_missing(self): """If the entry exists (according to tracker state), delete it """ if self.exists: self.delete() def make_fixture(self, request): """Make a pytest fixture for this tracker The fixture ensures the plugin entry does not exist before and after the tests that use it. """ del_command = self.make_delete_command() try: del_command() except errors.NotFound: pass def cleanup(): existed = self.exists try: del_command() except errors.NotFound: if existed: raise self.exists = False request.addfinalizer(cleanup) return super(CreationTracker, self).make_fixture(request) class EnableTracker(BaseTracker): def __init__(self, default_version=None, enabled=True): super(EnableTracker, self).__init__(default_version=default_version) self.original_enabled = enabled self.enabled = enabled def make_enable_command(self): """Make function that enables the entry using ${CMD}_enable""" raise NotImplementedError(self._override_me_msg) def enable(self): self.enabled = True command = self.make_enable_command() result = command() self.check_enable(result) def check_enable(self, result): """Check the plugin's `enable` command result""" raise NotImplementedError(self._override_me_msg) def make_disable_command(self): """Make function that disables the entry using ${CMD}_disable""" raise NotImplementedError(self._override_me_msg) def disable(self): self.enabled = False command = self.make_disable_command() result = command() self.check_disable(result) def check_disable(self, result): """Check the plugin's `disable` command result""" raise NotImplementedError(self._override_me_msg) def make_fixture(self, request): """Make a pytest fixture for this tracker The fixture ensures the plugin entry is in the same state (enabled/disabled) after the test as it was before it. """ def cleanup(): if isinstance(self, CreationTracker): # special case: if it already got deleted there is # nothing to enable or disable return if self.original_enabled != self.enabled: if self.original_enabled: command = self.make_enable_command() else: command = self.make_disable_command() command() request.addfinalizer(cleanup) return super(EnableTracker, self).make_fixture(request) class ConfigurationTracker(RetrievalTracker, ModificationTracker): def make_fixture(self, request): """Make a pytest fixture for this tracker Make sure that the state of entry in the end is the same it was in the begining. """ retrieve = self.make_retrieve_command(all=True) res = retrieve()['result'] original_state = {} for k, v in res.items(): if k in self.update_keys: original_state[k] = v[0] if k in self.singlevalue_keys else v def revert(): update = self.make_update_command(original_state) try: update() except errors.EmptyModlist: # ignore no change pass request.addfinalizer(revert) return super(ConfigurationTracker, self).make_fixture(request) class Tracker(RetrievalTracker, SearchTracker, ModificationTracker, CreationTracker): """Wraps and tracks modifications to a plugin LDAP entry object Stores a copy of state of a plugin entry object and allows checking that the state in the database is the same as expected. This allows creating independent tests: the individual tests check that the relevant changes have been made. At the same time the entry doesn't need to be recreated and cleaned up for each test. Two attributes are used for tracking: ``exists`` (true if the entry is supposed to exist) and ``attrs`` (a dict of LDAP attributes that are expected to be returned from IPA commands). For commonly used operations, there is a helper method, e.g. ``create``, ``update``, or ``find``, that does these steps: * ensure the entry exists (or does not exist, for "create") * store the expected modifications * get the IPA command to run, and run it * check that the result matches the expected state Tests that require customization of these steps are expected to do them manually, using lower-level methods. Especially the first step (ensure the entry exists) is important for achieving independent tests. The Tracker object also stores information about the entry, e.g. ``dn``, ``rdn`` and ``name`` which is derived from DN property. To use this class, the programer must subclass it and provide the implementation of following methods: * make_*_command -- implementing the API call for particular plugin and operation (add, delete, ...) These methods should use the make_command method * check_* commands -- an assertion for a plugin command (CRUD) * track_create -- to make an internal representation of the entry Apart from overriding these methods, the subclass must provide the distinguished name of the entry in `self.dn` property. It is also required to override the class variables defining the sets of ldap attributes/keys for these operations specific to the plugin being implemented. Take the host plugin test for an example. The implementation of these methods is not strictly enforced. A missing method will cause a NotImplementedError during runtime as a result. """
13,440
Python
.py
307
34.925081
78
0.64134
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,509
certprofile_plugin.py
freeipa_freeipa/ipatests/test_xmlrpc/tracker/certprofile_plugin.py
# -*- coding: utf-8 -*- # # Copyright (C) 2015 FreeIPA Contributors see COPYING for license # import os import six from ipapython.dn import DN from ipatests.test_xmlrpc.tracker.base import Tracker from ipatests.test_xmlrpc import objectclasses from ipatests.util import assert_deepequal if six.PY3: unicode = str class CertprofileTracker(Tracker): """Tracker class for certprofile plugin. """ retrieve_keys = { 'dn', 'cn', 'description', 'ipacertprofilestoreissued' } retrieve_all_keys = retrieve_keys | {'objectclass'} create_keys = retrieve_keys | {'objectclass'} update_keys = retrieve_keys - {'dn'} managedby_keys = retrieve_keys allowedto_keys = retrieve_keys def __init__(self, name, store=False, desc='dummy description', profile=None, default_version=None): super(CertprofileTracker, self).__init__( default_version=default_version ) self.store = store self.description = desc self._profile_path = profile self.dn = DN(('cn', name), 'cn=certprofiles', 'cn=ca', self.api.env.basedn) @property def profile(self): if not self._profile_path: return None if os.path.isabs(self._profile_path): path = self._profile_path else: path = os.path.join(os.path.dirname(__file__), self._profile_path) with open(path, 'r') as f: content = f.read() return unicode(content) def make_create_command(self, extra_lines=None): """ :param extra_lines: list of extra lines to append to profile config. """ if extra_lines is None: extra_lines = [] if not self.profile: raise RuntimeError('Tracker object without path to profile ' 'cannot be used to create profile entry.') return self.make_command('certprofile_import', self.name, description=self.description, ipacertprofilestoreissued=self.store, file=u'\n'.join([self.profile] + extra_lines)) def check_create(self, result): assert_deepequal(dict( value=self.name, summary=u'Imported profile "{}"'.format(self.name), result=dict(self.filter_attrs(self.create_keys)) ), result) def track_create(self): self.attrs = dict( dn=unicode(self.dn), cn=[self.name], description=[self.description], ipacertprofilestoreissued=[self.store], objectclass=objectclasses.certprofile ) self.exists = True def make_delete_command(self): return self.make_command('certprofile_del', self.name) def check_delete(self, result): assert_deepequal(dict( value=[self.name], # correctly a list? summary=u'Deleted profile "{}"'.format(self.name), result=dict(failed=[]), ), result) def make_retrieve_command(self, all=False, raw=False, **options): return self.make_command('certprofile_show', self.name, all=all, raw=raw, **options) def check_retrieve(self, result, all=False, raw=False): if all: expected = self.filter_attrs(self.retrieve_all_keys) else: expected = self.filter_attrs(self.retrieve_keys) assert_deepequal(dict( value=self.name, summary=None, result=expected, ), result) def make_find_command(self, *args, **kwargs): return self.make_command('certprofile_find', *args, **kwargs) def check_find(self, result, all=False, raw=False): if all: expected = self.filter_attrs(self.retrieve_all_keys) else: expected = self.filter_attrs(self.retrieve_keys) assert_deepequal(dict( count=1, truncated=False, summary=u'1 profile matched', result=[expected] ), result) def make_update_command(self, updates): return self.make_command('certprofile_mod', self.name, **updates) def check_update(self, result, extra_keys=()): assert_deepequal(dict( value=self.name, summary=u'Modified Certificate Profile "{}"'.format(self.name), result=self.filter_attrs(self.update_keys | set(extra_keys)) ), result)
4,565
Python
.py
115
29.530435
79
0.59534
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,510
sudocmdgroup_plugin.py
freeipa_freeipa/ipatests/test_xmlrpc/tracker/sudocmdgroup_plugin.py
# # Copyright (C) 2015 FreeIPA Contributors see COPYING for license # from ipatests.test_xmlrpc import objectclasses from ipatests.test_xmlrpc.xmlrpc_test import fuzzy_uuid from ipatests.test_xmlrpc.tracker.base import Tracker from ipatests.util import assert_deepequal from ipalib import api from ipapython.dn import DN class SudoCmdGroupTracker(Tracker): """ Class for tracking sudocmdgroups """ retrieve_keys = {u'dn', u'cn', u'member_sudocmd', u'description', u'member_sudocmdgroup'} retrieve_all_keys = retrieve_keys | {u'ipauniqueid', u'objectclass', u'mepmanagedentry'} create_keys = retrieve_all_keys update_keys = retrieve_keys - {u'dn'} add_member_keys = retrieve_keys | {u'member_sudocmd'} find_keys = { u'dn', u'cn', u'description', u'member_sudocmdgroup'} find_all_keys = find_keys | { u'ipauniqueid', u'objectclass', u'mepmanagedentry'} def __init__(self, name, description=u'SudoCmdGroup desc'): super(SudoCmdGroupTracker, self).__init__(default_version=None) self.cn = name self.description = description self.dn = DN(('cn', self.cn), ('cn', 'sudocmdgroups'), ('cn', 'sudo'), api.env.basedn) def make_create_command(self, *args, **kwargs): """ Make function that creates a sudocmdgroup using 'sudocmdgroup-add' """ return self.make_command('sudocmdgroup_add', self.cn, description=self.description, *args, **kwargs) def make_delete_command(self): """ Make function that deletes a sudocmdgroup using 'sudocmdgroup-del' """ return self.make_command('sudocmdgroup_del', self.cn) def make_retrieve_command(self, all=False, raw=False): """ Make function that retrieves a sudocmdgroup using 'sudocmdgroup-show' """ return self.make_command('sudocmdgroup_show', self.cn, all=all) def make_find_command(self, *args, **kwargs): """ Make function that searches for a sudocmdgroup using 'sudocmdgroup-find' """ return self.make_command('sudocmdgroup_find', *args, **kwargs) def make_update_command(self, updates): """ Make function that updates a sudocmdgroup using 'sudocmdgroup-mod' """ return self.make_command('sudocmdgroup_mod', self.cn, **updates) def make_add_member_command(self, options={}): """ Make function that adds a member to a sudocmdgroup """ return self.make_command('sudocmdgroup_add_member', self.cn, **options) def make_remove_member_command(self, options={}): """ Make function that removes a member from a sudocmdgroup """ return self.make_command('sudocmdgroup_remove_member', self.cn, **options) def track_create(self): """ Updates expected state for sudocmdgroup creation""" self.attrs = dict( dn=self.dn, cn=[self.cn], description=[self.description], ipauniqueid=[fuzzy_uuid], objectclass=objectclasses.sudocmdgroup, ) self.exists = True def add_member(self, options): """ Add a member sudocmd to sudocmdgroup and perform check """ try: self.attrs[u'member_sudocmd'] =\ self.attrs[u'member_sudocmd'] + [options[u'sudocmd']] except KeyError: self.attrs[u'member_sudocmd'] = [options[u'sudocmd']] command = self.make_add_member_command(options) result = command() self.check_add_member(result) def remove_member(self, options): """ Remove a member sudocmd from sudocmdgroup and perform check """ self.attrs[u'member_sudocmd'].remove(options[u'sudocmd']) try: if not self.attrs[u'member_sudocmd']: del self.attrs[u'member_sudocmd'] except KeyError: pass command = self.make_remove_member_command(options) result = command() self.check_remove_member(result) def update(self, updates, expected_updates=None): """Helper function to update and check the result Overriding Tracker method for setting self.attrs correctly; * most attributes stores its value in list * the rest can be overridden by expected_updates * allow deleting parametrs if update value is None """ if expected_updates is None: expected_updates = {} self.ensure_exists() command = self.make_update_command(updates) result = command() for key, value in updates.items(): if value is None: del self.attrs[key] else: self.attrs[key] = [value] for key, value in expected_updates.items(): if value is None: del self.attrs[key] else: self.attrs[key] = value self.check_update( result, extra_keys=set(updates.keys()) | set(expected_updates.keys()) ) def check_create(self, result): """ Checks 'sudocmdgroup_add' command result """ assert_deepequal(dict( value=self.cn, summary=u'Added Sudo Command Group "%s"' % self.cn, result=self.filter_attrs(self.create_keys) ), result) def check_delete(self, result): """ Checks 'sudocmdgroup_del' command result """ assert_deepequal(dict( value=[self.cn], summary=u'Deleted Sudo Command Group "%s"' % self.cn, result=dict(failed=[]), ), result) def check_retrieve(self, result, all=False, raw=False): """ Checks 'sudocmdgroup_show' command result """ if all: expected = self.filter_attrs(self.retrieve_all_keys) else: expected = self.filter_attrs(self.retrieve_keys) assert_deepequal(dict( value=self.cn, summary=None, result=expected ), result) def check_find(self, result, all=False, raw=False): """ Checks 'sudocmdgroup_find' command result """ if all: expected = self.filter_attrs(self.find_all_keys) else: expected = self.filter_attrs(self.find_keys) assert_deepequal(dict( count=1, truncated=False, summary=u'1 Sudo Command Group matched', result=[expected], ), result) def check_update(self, result, extra_keys={}): """ Checks 'sudocmdgroup_mod' command result """ assert_deepequal(dict( value=self.cn, summary=u'Modified Sudo Command Group "%s"' % self.cn, result=self.filter_attrs(self.update_keys | set(extra_keys)) ), result) def check_add_member(self, result): """ Checks 'sudocmdgroup_add_member' command result """ assert_deepequal(dict( completed=1, failed={u'member': {u'sudocmd': ()}}, result=self.filter_attrs(self.add_member_keys) ), result) def check_add_member_negative(self, result, options): """ Checks 'sudocmdgroup_add_member' command result when expected result is failure of the operation""" expected = dict( completed=0, failed={u'member': {u'sudocmd': ()}}, result=self.filter_attrs(self.add_member_keys) ) expected[u'failed'][u'member'][u'sudocmd'] = [( options[u'sudocmd'], u'no such entry')] assert_deepequal(expected, result) def check_remove_member_negative(self, result, options): """ Checks 'sudocmdgroup_remove_member' command result when expected result is failure of the operation""" expected = dict( completed=0, failed={u'member': {u'sudocmd': ()}}, result=self.filter_attrs(self.add_member_keys) ) expected[u'failed'][u'member'][u'sudocmd'] = [( options[u'sudocmd'], u'This entry is not a member')] assert_deepequal(expected, result) def check_remove_member(self, result): """ Checks 'sudocmdgroup_remove_member' command result """ self.check_add_member(result)
8,404
Python
.py
190
33.9
79
0.603866
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,511
passkey_plugin.py
freeipa_freeipa/ipatests/test_xmlrpc/tracker/passkey_plugin.py
# # Copyright (C) 2022 FreeIPA Contributors see COPYING for license # from ipapython.dn import DN from ipatests.test_xmlrpc import objectclasses from ipatests.test_xmlrpc.tracker.base import ConfigurationTracker from ipatests.test_xmlrpc.xmlrpc_test import fuzzy_string from ipatests.util import assert_deepequal class PasskeyconfigTracker(ConfigurationTracker): retrieve_keys = { 'dn', 'iparequireuserverification', } retrieve_all_keys = retrieve_keys | { 'cn', 'objectclass', 'aci', } update_keys = retrieve_keys - {'dn'} singlevalue_keys = {'iparequireuserverification'} def __init__(self, default_version=None): super(PasskeyconfigTracker, self).__init__( default_version=default_version) self.attrs = { 'dn': DN(self.api.env.container_passkey, self.api.env.basedn), 'cn': [self.api.env.container_passkey[0].value], 'objectclass': objectclasses.passkeyconfig, 'aci': [fuzzy_string], 'iparequireuserverif': self.api.Command.passkeyconfig_show( )['result']['iparequireuserverification'], } def make_update_command(self, updates): return self.make_command('passkeyconfig_mod', **updates) def check_update(self, result, extra_keys=()): assert_deepequal( dict( value=None, summary=None, result=self.filter_attrs(self.update_keys | set(extra_keys)), ), result ) def make_retrieve_command(self, all=False, raw=False): return self.make_command('passkeyconfig_show', all=all, raw=raw) def check_retrieve(self, result, all=False, raw=False): if all: expected = self.filter_attrs(self.retrieve_all_keys) else: expected = self.filter_attrs(self.retrieve_keys) assert_deepequal( dict( value=None, summary=None, result=expected, ), result ) class PasskeyMixin: def _make_add_passkey(self): raise NotImplementedError("_make_add_passkey method must be " "implemented in instance.") def _make_remove_passkey(self): raise NotImplementedError("_make_remove_passkey method must be " "implemented in instance.") def add_passkey(self, **kwargs): cmd = self._make_add_passkey() result = cmd(**kwargs) data = kwargs.get('ipapasskey', []) if not isinstance(data, list): data = [data] self.attrs.setdefault('ipapasskey', []).extend(data) expected = dict( summary=('Added passkey mappings to user ' '"{}"'.format(self.name)), value=self.name, result=dict( uid=(self.name,), ), ) if self.attrs['ipapasskey']: expected['result']['ipapasskey'] = ( self.attrs['ipapasskey']) assert_deepequal(expected, result) def remove_passkey(self, **kwargs): cmd = self._make_remove_passkey() result = cmd(**kwargs) data = kwargs.get('ipapasskey', []) if not isinstance(data, list): data = [data] for key in data: self.attrs['ipapasskey'].remove(key) expected = dict( summary=('Removed passkey mappings from user ' '"{}"'.format(self.name)), value=self.name, result=dict( uid=(self.name,), ), ) if self.attrs['ipapasskey']: expected['result']['ipapasskey'] = ( self.attrs['ipapasskey']) assert_deepequal(expected, result)
3,860
Python
.py
103
26.990291
77
0.574183
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,512
caacl_plugin.py
freeipa_freeipa/ipatests/test_xmlrpc/tracker/caacl_plugin.py
# # Copyright (C) 2015 FreeIPA Contributors see COPYING for license # from ipalib import errors from ipatests.util import assert_deepequal from ipatests.test_xmlrpc.xmlrpc_test import (fuzzy_caacldn, fuzzy_uuid, fuzzy_ipauniqueid) from ipatests.test_xmlrpc import objectclasses from ipatests.test_xmlrpc.tracker.base import Tracker class CAACLTracker(Tracker): """Tracker class for CA ACL LDAP object. The class implements methods required by the base class to help with basic CRUD operations. Methods for adding and deleting actual member entries into an ACL do not have check methods as these would make the class unnecessarily complicated. The checks are implemented as a standalone test suite. However, this makes the test crucial in debugging more complicated test cases. Since the add/remove operation won't be checked right away by the tracker, a problem in this operation may propagate into more complicated test case. It is possible to pass a list of member uids to these methods. The test uses instances of Fuzzy class to compare results as they are in the UUID format. The dn and rdn properties were modified to reflect this as well. """ member_keys = { u'memberuser_user', u'memberuser_group', u'memberhost_host', u'memberhost_hostgroup', u'memberservice_service', u'ipamembercertprofile_certprofile', u'ipamemberca_ca'} category_keys = { u'ipacacategory', u'ipacertprofilecategory', u'usercategory', u'hostcategory', u'servicecategory'} retrieve_keys = { u'dn', u'cn', u'description', u'ipaenabledflag', u'ipamemberca', u'ipamembercertprofile', u'memberuser', u'memberhost', u'memberservice'} | member_keys | category_keys retrieve_all_keys = retrieve_keys | {u'objectclass', u'ipauniqueid'} create_keys = {u'dn', u'cn', u'description', u'ipacertprofilecategory', u'usercategory', u'hostcategory', u'ipacacategory', u'servicecategory', u'ipaenabledflag', u'objectclass', u'ipauniqueid'} update_keys = retrieve_keys - {"dn"} def __init__(self, name, ipacertprofile_category=None, user_category=None, service_category=None, host_category=None, ipaca_category=None, description=None, default_version=None): super(CAACLTracker, self).__init__(default_version=default_version) self._name = name self.description = description self._categories = dict( ipacertprofilecategory=ipacertprofile_category, ipacacategory=ipaca_category, usercategory=user_category, servicecategory=service_category, hostcategory=host_category) self.dn = fuzzy_caacldn @property def name(self): return self._name @property def rdn(self): return fuzzy_ipauniqueid @property def categories(self): """To be used in track_create""" return {cat: v for cat, v in self._categories.items() if v} @property def create_categories(self): """ Return the categories set on create. Unused categories are left out. """ return {cat: [v] for cat, v in self.categories.items() if v} def make_create_command(self): return self.make_command(u'caacl_add', self.name, description=self.description, **self.categories) def check_create(self, result): assert_deepequal(dict( value=self.name, summary=u'Added CA ACL "{}"'.format(self.name), result=dict(self.filter_attrs(self.create_keys)) ), result) def track_create(self): self.attrs = dict( dn=self.dn, ipauniqueid=[fuzzy_uuid], cn=[self.name], objectclass=objectclasses.caacl, ipaenabledflag=[True]) self.attrs.update(self.create_categories) if self.description: self.attrs.update({"description": [self.description]}) self.exists = True def make_delete_command(self): return self.make_command('caacl_del', self.name) def check_delete(self, result): assert_deepequal(dict( value=[self.name], summary=u'Deleted CA ACL "{}"'.format(self.name), result=dict(failed=[]) ), result) def make_retrieve_command(self, all=False, raw=False): return self.make_command('caacl_show', self.name, all=all, raw=raw) def check_retrieve(self, result, all=False, raw=False): if all: expected = self.filter_attrs(self.retrieve_all_keys) else: expected = self.filter_attrs(self.retrieve_keys) assert_deepequal(dict( value=self.name, summary=None, result=expected ), result) def make_find_command(self, *args, **kwargs): return self.make_command('caacl_find', *args, **kwargs) def check_find(self, result, all=False, raw=False): if all: expected = self.filter_attrs(self.retrieve_all_keys) else: expected = self.filter_attrs(self.retrieve_keys) assert_deepequal(dict( count=1, truncated=False, summary=u'1 CA ACL matched', result=[expected] ), result) def make_update_command(self, updates): return self.make_command('caacl_mod', self.name, **updates) def update(self, updates, expected_updates=None): """If removing a category, delete it from tracker as well""" # filter out empty categories and track changes filtered_updates = dict() for key, value in updates.items(): if key in self.category_keys: if not value: del self.attrs[key] else: # if there is a value, prepare the pair for update filtered_updates.update({key: value}) else: filtered_updates.update({key: value}) if expected_updates is None: expected_updates = {} command = self.make_update_command(updates) try: result = command() except errors.EmptyModlist: pass else: self.attrs.update(filtered_updates) self.attrs.update(expected_updates) self.check_update(result, extra_keys=set(self.update_keys) | set(expected_updates.keys())) def check_update(self, result, extra_keys=()): assert_deepequal(dict( value=self.name, summary=u'Modified CA ACL "{}"'.format(self.name), result=self.filter_attrs(self.update_keys | set(extra_keys)) ), result) # Helper methods for caacl subcommands. The check methods will be # implemented in standalone test # # The methods implemented here will be: # caacl_{add,remove}_{host, service, certprofile, user, ca} def _add_acl_component(self, command_name, keys, track): """ Add a resource into ACL rule and track it. command_name - the name in the API keys = { 'tracker_attr': { 'api_key': 'value' } } e.g. keys = { 'memberhost_host': { 'host': 'hostname' }, 'memberhost_hostgroup': { 'hostgroup': 'hostgroup_name' } } """ if not self.exists: raise errors.NotFound(reason="The tracked entry doesn't exist.") command = self.make_command(command_name, self.name) command_options = dict() # track for tracker_attr in keys: api_options = keys[tracker_attr] if track: for option in api_options: try: if type(option) in (list, tuple): self.attrs[tracker_attr].extend(api_options[option]) else: self.attrs[tracker_attr].append(api_options[option]) except KeyError: if type(option) in (list, tuple): self.attrs[tracker_attr] = api_options[option] else: self.attrs[tracker_attr] = [api_options[option]] # prepare options for the command call command_options.update(api_options) return command(**command_options) def _remove_acl_component(self, command_name, keys, track): """ Remove a resource from ACL rule and track it. command_name - the name in the API keys = { 'tracker_attr': { 'api_key': 'value' } } e.g. keys = { 'memberhost_host': { 'host': 'hostname' }, 'memberhost_hostgroup': { 'hostgroup': 'hostgroup_name' } } """ command = self.make_command(command_name, self.name) command_options = dict() for tracker_attr in keys: api_options = keys[tracker_attr] if track: for option in api_options: if type(option) in (list, tuple): for item in option: self.attrs[tracker_attr].remove(item) else: self.attrs[tracker_attr].remove(api_options[option]) if len(self.attrs[tracker_attr]) == 0: del self.attrs[tracker_attr] command_options.update(api_options) return command(**command_options) def add_host(self, host=None, hostgroup=None, track=True): """Associates an host or hostgroup entry with the ACL. The command takes an unicode string with the name of the entry (RDN). It is the responsibility of a test writer to provide the correct value, object type as the method does not verify whether the entry exists. The method can add only one entry of each type in one call. """ options = { u'memberhost_host': {u'host': host}, u'memberhost_hostgroup': {u'hostgroup': hostgroup}} return self._add_acl_component(u'caacl_add_host', options, track) def remove_host(self, host=None, hostgroup=None, track=True): options = { u'memberhost_host': {u'host': host}, u'memberhost_hostgroup': {u'hostgroup': hostgroup}} return self._remove_acl_component(u'caacl_remove_host', options, track) def add_user(self, user=None, group=None, track=True): options = { u'memberuser_user': {u'user': user}, u'memberuser_group': {u'group': group}} return self._add_acl_component(u'caacl_add_user', options, track) def remove_user(self, user=None, group=None, track=True): options = { u'memberuser_user': {u'user': user}, u'memberuser_group': {u'group': group}} return self._remove_acl_component(u'caacl_remove_user', options, track) def add_service(self, service=None, track=True): options = { u'memberservice_service': {u'service': service}} return self._add_acl_component(u'caacl_add_service', options, track) def remove_service(self, service=None, track=True): options = { u'memberservice_service': {u'service': service}} return self._remove_acl_component(u'caacl_remove_service', options, track) def add_profile(self, certprofile=None, track=True): options = { u'ipamembercertprofile_certprofile': {u'certprofile': certprofile}} return self._add_acl_component(u'caacl_add_profile', options, track) def remove_profile(self, certprofile=None, track=True): options = { u'ipamembercertprofile_certprofile': {u'certprofile': certprofile}} return self._remove_acl_component(u'caacl_remove_profile', options, track) def add_ca(self, ca=None, track=True): options = { u'ipamemberca_ca': {u'ca': ca}} return self._add_acl_component(u'caacl_add_ca', options, track) def remove_ca(self, ca=None, track=True): options = { u'ipamemberca_ca': {u'ca': ca}} return self._remove_acl_component(u'caacl_remove_ca', options, track) def enable(self): command = self.make_command(u'caacl_enable', self.name) self.attrs.update({u'ipaenabledflag': [True]}) command() def disable(self): command = self.make_command(u'caacl_disable', self.name) self.attrs.update({u'ipaenabledflag': [False]}) command()
13,270
Python
.py
304
31.993421
82
0.585803
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,513
idview_plugin.py
freeipa_freeipa/ipatests/test_xmlrpc/tracker/idview_plugin.py
# # Copyright (C) 2016 FreeIPA Contributors see COPYING for license # from ipalib import api from ipapython.dn import DN from ipatests.test_xmlrpc.tracker.base import Tracker from ipatests.util import assert_deepequal from ipatests.test_xmlrpc import objectclasses import six if six.PY3: unicode = str class IdviewTracker(Tracker): """Class for idview tests""" retrieve_keys = { u'cn' } retrieve_all_keys = retrieve_keys | { u'description', u'objectclass', u'dn' } create_keys = retrieve_all_keys find_all_keys = retrieve_all_keys def del_cert_from_idoverrideuser(self, username, cert): result = api.Command.idoverrideuser_remove_cert( self.cn, username, usercertificate=cert ) return dict( usercertificate=result['result'].get('usercertificate', []), value=result.get('value'), summary=result.get('summary') ) def add_cert_to_idoverrideuser(self, username, cert): result = api.Command.idoverrideuser_add_cert( self.cn, username, usercertificate=cert ) return dict( usercertificate=result['result'].get('usercertificate', []), value=result.get('value'), summary=result.get('summary') ) def __init__(self, cn, **kwargs): super(IdviewTracker, self).__init__(default_version=None) self.cn = cn self.dn = DN(('cn', cn), api.env.container_views, api.env.basedn) self.kwargs = kwargs def make_create_command(self): return self.make_command( 'idview_add', self.cn, **self.kwargs ) def make_delete_command(self): return self.make_command( 'idview_del', self.cn, **self.kwargs ) def make_retrieve_command(self, all=False, raw=False): """ Make function that retrieves a idview using idview-show """ return self.make_command('idview_show', self.cn, all=all) def make_find_command(self, *args, **kwargs): """ Make function that finds idview using idview-find """ return self.make_command('idview_find', *args, **kwargs) def make_update_command(self, updates): """ Make function that updates idview using idview-mod """ return self.make_command('idview_mod', self.cn, **updates) def track_create(self): self.attrs = dict( cn=(self.cn,), dn=unicode(self.dn), idoverrideusers=[], objectclass=objectclasses.idview ) if 'description' in self.kwargs: self.attrs['description'] = self.kwargs['description'] self.exists = True def make_add_idoverrideuser_command(self, username, options=None): options = options or {} """ Make function that adds a member to a group """ return self.make_command('idoverrideuser_add', self.cn, username, **options) def idoverrideuser_add(self, user): command = self.make_add_idoverrideuser_command(user.name) result = command() self.attrs['idoverrideusers'].append(result['value']) self.check_idoverrideuser_add(result, user) def check_create(self, result, extra_keys=()): """ Check 'user-add' command result """ expected = self.filter_attrs(self.create_keys | set(extra_keys)) assert_deepequal(dict( summary=u'Added ID View "%s"' % self.cn, result=self.filter_attrs(expected), value=self.cn ), result) def check_idoverrideuser_add(self, result, user): """ Checks 'group_add_member' command result """ assert_deepequal( u'Added User ID override "%s"' % user.name, result['summary'] )
3,823
Python
.py
95
31.6
73
0.621257
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,514
user_plugin.py
freeipa_freeipa/ipatests/test_xmlrpc/tracker/user_plugin.py
# # Copyright (C) 2015 FreeIPA Contributors see COPYING for license # from ipalib import api, errors from ipaplatform.constants import constants as platformconstants from ipapython.dn import DN import six from ipatests.util import assert_deepequal, get_group_dn from ipatests.test_xmlrpc import objectclasses from ipatests.test_xmlrpc.xmlrpc_test import ( fuzzy_set_optional_oc, fuzzy_digits, fuzzy_uuid, fuzzy_user_or_group_sid, raises_exact) from ipatests.test_xmlrpc.tracker.base import Tracker from ipatests.test_xmlrpc.tracker.kerberos_aliases import KerberosAliasMixin from ipatests.test_xmlrpc.tracker.certmapdata import CertmapdataMixin from ipatests.test_xmlrpc.tracker.passkey_plugin import PasskeyMixin if six.PY3: unicode = str class UserTracker(PasskeyMixin, CertmapdataMixin, KerberosAliasMixin, Tracker): """ Class for host plugin like tests """ retrieve_keys = { u'dn', u'uid', u'givenname', u'sn', u'homedirectory', u'loginshell', u'uidnumber', u'gidnumber', u'mail', u'ou', u'telephonenumber', u'title', u'memberof', u'nsaccountlock', u'memberofindirect', u'ipauserauthtype', u'userclass', u'ipatokenradiusconfiglink', u'ipatokenradiususername', u'krbprincipalexpiration', u'usercertificate;binary', u'has_keytab', u'has_password', u'memberof_group', u'sshpubkeyfp', u'krbcanonicalname', 'krbprincipalname' } retrieve_all_keys = retrieve_keys | { u'usercertificate', u'street', u'postalcode', u'facsimiletelephonenumber', u'carlicense', u'ipasshpubkey', u'l', u'mobile', u'krbextradata', u'krblastpwdchange', u'krbpasswordexpiration', u'pager', u'st', u'manager', u'cn', u'ipauniqueid', u'objectclass', u'mepmanagedentry', u'displayname', u'gecos', u'initials', u'preserved', 'ipantsecurityidentifier'} retrieve_preserved_keys = (retrieve_keys - {u'memberof_group'}) | { u'preserved'} retrieve_preserved_all_keys = retrieve_all_keys - {u'memberof_group'} create_keys = retrieve_all_keys | { u'krbextradata', u'krbpasswordexpiration', u'krblastpwdchange', u'krbprincipalkey', u'userpassword', u'randompassword'} create_keys = create_keys - {u'nsaccountlock'} create_keys = create_keys - {'ipantsecurityidentifier'} update_keys = retrieve_keys - {u'dn'} activate_keys = retrieve_keys find_keys = retrieve_keys - { u'mepmanagedentry', u'memberof_group', u'has_keytab', u'has_password', u'manager', } find_all_keys = retrieve_all_keys - { u'has_keytab', u'has_password' } primary_keys = {u'uid', u'dn'} def __init__(self, name=None, givenname=None, sn=None, **kwargs): """ Check for non-empty unicode string for the required attributes in the init method """ if not (isinstance(givenname, str) and givenname): raise ValueError( "Invalid first name provided: {!r}".format(givenname) ) if not (isinstance(sn, str) and sn): raise ValueError("Invalid second name provided: {!r}".format(sn)) super(UserTracker, self).__init__(default_version=None) self.uid = unicode(name) self.givenname = unicode(givenname) self.sn = unicode(sn) self.dn = DN(('uid', self.uid), api.env.container_user, api.env.basedn) self.kwargs = kwargs def make_create_command(self, force=None): """ Make function that creates a user using user-add with all set of attributes and with minimal values, where uid is not specified """ if self.uid is not None: return self.make_command( 'user_add', self.uid, givenname=self.givenname, sn=self.sn, **self.kwargs ) else: return self.make_command( 'user_add', givenname=self.givenname, sn=self.sn, **self.kwargs ) def make_delete_command(self, no_preserve=True, preserve=False): """ Make function that deletes a user using user-del Arguments 'preserve' and 'no_preserve' represent implemented options --preserve and --no-preserve of user-del command, which are mutually exclusive. If --preserve=True and --no-preserve=False, the user is moved to deleted container. If --preserve=True and --no-preserve=True, an error is raised. If --preserve=False and --no-preserver=True, user is deleted. """ if preserve and not no_preserve: # --preserve=True and --no-preserve=False - user is moved to # another container, hence it is necessary to change some user # attributes self.attrs[u'dn'] = DN( ('uid', self.uid), api.env.container_deleteuser, api.env.basedn ) self.attrs[u'objectclass'] = objectclasses.user_base \ + ['ipantuserattrs'] return self.make_command( 'user_del', self.uid, no_preserve=no_preserve, preserve=preserve ) def make_retrieve_command(self, all=False, raw=False): """ Make function that retrieves a user using user-show """ return self.make_command('user_show', self.uid, all=all) def make_find_command(self, *args, **kwargs): """ Make function that finds user using user-find """ return self.make_command('user_find', *args, **kwargs) def make_update_command(self, updates): """ Make function that updates user using user-mod """ return self.make_command('user_mod', self.uid, **updates) def make_undelete_command(self): """ Make function that activates preserved user using user-undel """ return self.make_command('user_undel', self.uid) def make_enable_command(self): """ Make function that enables user using user-enable """ return self.make_command('user_enable', self.uid) def make_disable_command(self): """ Make function that disables user using user-disable """ return self.make_command('user_disable', self.uid) def make_stage_command(self): """ Make function that restores preserved user by moving it to staged container """ return self.make_command('user_stage', self.uid) def make_group_add_member_command(self, *args, **kwargs): return self.make_command('group_add_member', *args, **kwargs) def track_create(self): """ Update expected state for user creation """ self.attrs = dict( dn=self.dn, uid=[self.uid], givenname=[self.givenname], sn=[self.sn], homedirectory=[u'/home/%s' % self.uid], displayname=[u'%s %s' % (self.givenname, self.sn)], cn=[u'%s %s' % (self.givenname, self.sn)], initials=[u'%s%s' % (self.givenname[0], self.sn[0])], objectclass=fuzzy_set_optional_oc( objectclasses.user, 'ipantuserattrs'), description=[u'__no_upg__'], ipauniqueid=[fuzzy_uuid], uidnumber=[fuzzy_digits], gidnumber=[fuzzy_digits], krbprincipalname=[u'%s@%s' % (self.uid, self.api.env.realm)], krbcanonicalname=[u'%s@%s' % (self.uid, self.api.env.realm)], mail=[u'%s@%s' % (self.uid, self.api.env.domain)], gecos=[u'%s %s' % (self.givenname, self.sn)], loginshell=[platformconstants.DEFAULT_SHELL], has_keytab=False, has_password=False, mepmanagedentry=[get_group_dn(self.uid)], memberof_group=[u'ipausers'], nsaccountlock=[u'false'], ipantsecurityidentifier=[fuzzy_user_or_group_sid], ) for key, value in self.kwargs.items(): if key == "krbprincipalname": try: princ_splitted = value.split("@", maxsplit=1) self.attrs[key] = [ "{}@{}".format( princ_splitted[0].lower(), princ_splitted[1], ) ] except IndexError: # we can provide just principal part self.attrs[key] = [ "{}@{}".format(value.lower(), self.api.env.realm) ] else: if not isinstance(value, list): self.attrs[key] = [value] else: self.attrs[key] = value self.exists = True def update(self, updates, expected_updates=None): """Helper function to update this user and check the result Overriding Tracker method for setting self.attrs correctly; * most attributes stores its value in list * the rest can be overridden by expected_updates * allow deleting parameters if update value is None """ if expected_updates is None: expected_updates = {} self.ensure_exists() command = self.make_update_command(updates) result = command() for key, value in updates.items(): if value is None or value == '': del self.attrs[key] elif key == 'rename': new_principal = u'{0}@{1}'.format(value, self.api.env.realm) self.attrs['uid'] = [value] self.attrs['krbcanonicalname'] = [new_principal] if new_principal not in self.attrs['krbprincipalname']: self.attrs['krbprincipalname'].append(new_principal) else: if type(value) is list: self.attrs[key] = value else: self.attrs[key] = [value] for key, value in expected_updates.items(): if value is None or value == '': del self.attrs[key] else: self.attrs[key] = value self.check_update( result, extra_keys=set(updates.keys()) | set(expected_updates.keys()) ) if 'rename' in updates: self.uid = self.attrs['uid'][0] def check_create(self, result, extra_keys=()): """ Check 'user-add' command result """ expected = self.filter_attrs(self.create_keys | set(extra_keys)) assert_deepequal(dict( value=self.uid, summary=u'Added user "%s"' % self.uid, result=self.filter_attrs(expected), ), result) def check_delete(self, result): """ Check 'user-del' command result """ if u'preserved' in self.attrs and self.attrs[u'preserved']: summary = u'Preserved user "%s"' % self.uid else: summary = u'Deleted user "%s"' % self.uid assert_deepequal(dict( value=[self.uid], summary=summary, result=dict(failed=[]), ), result) def check_retrieve(self, result, all=False, raw=False): """ Check 'user-show' command result """ if u'preserved' in self.attrs and self.attrs[u'preserved']: self.retrieve_all_keys = self.retrieve_preserved_all_keys self.retrieve_keys = self.retrieve_preserved_keys elif u'preserved' not in self.attrs and all: self.attrs[u'preserved'] = False if all: expected = self.filter_attrs(self.retrieve_all_keys) else: expected = self.filter_attrs(self.retrieve_keys) # small override because stageuser-find returns different type # of nsaccountlock value than DS, but overall the value fits # expected result if u'nsaccountlock' in expected: if expected[u'nsaccountlock'] == [u'true']: expected[u'nsaccountlock'] = True elif expected[u'nsaccountlock'] == [u'false']: expected[u'nsaccountlock'] = False assert_deepequal(dict( value=self.uid, summary=None, result=expected, ), result) def check_find(self, result, all=False, raw=False, pkey_only=False, expected_override=None): """ Check 'user-find' command result """ if all: if u'preserved' not in self.attrs: self.attrs.update(preserved=False) expected = self.filter_attrs(self.find_all_keys) elif pkey_only: expected = self.filter_attrs(self.primary_keys) else: expected = self.filter_attrs(self.find_keys) if all and self.attrs[u'preserved']: del expected[u'mepmanagedentry'] if u'nsaccountlock' in expected: if expected[u'nsaccountlock'] == [u'true']: expected[u'nsaccountlock'] = True elif expected[u'nsaccountlock'] == [u'false']: expected[u'nsaccountlock'] = False if expected_override: assert isinstance(expected_override, dict) expected.update(expected_override) assert_deepequal(dict( count=1, truncated=False, summary=u'1 user matched', result=[expected], ), result) def check_find_nomatch(self, result): """ Check 'user-find' command result when no user should be found """ assert_deepequal(dict( count=0, truncated=False, summary=u'0 users matched', result=[], ), result) def check_update(self, result, extra_keys=()): """ Check 'user-mod' command result """ expected = self.filter_attrs(self.update_keys | set(extra_keys)) if expected[u'nsaccountlock'] == [u'true']: expected[u'nsaccountlock'] = True elif expected[u'nsaccountlock'] == [u'false']: expected[u'nsaccountlock'] = False assert_deepequal(dict( value=self.uid, summary=u'Modified user "%s"' % self.uid, result=expected ), result) def check_enable(self, result): """ Check result of enable user operation """ assert_deepequal(dict( value=self.name, summary=u'Enabled user account "%s"' % self.name, result=True ), result) def check_disable(self, result): """ Check result of disable user operation """ assert_deepequal(dict( value=self.name, summary=u'Disabled user account "%s"' % self.name, result=True ), result) def create_from_staged(self, stageduser): """ Copies attributes from staged user - helper function for activation tests """ self.attrs = stageduser.attrs self.uid = stageduser.uid self.givenname = stageduser.givenname self.sn = stageduser.sn self.attrs[u'mepmanagedentry'] = None self.attrs[u'dn'] = self.dn self.attrs[u'ipauniqueid'] = [fuzzy_uuid] self.attrs[u'memberof_group'] = [u'ipausers'] self.attrs[u'mepmanagedentry'] = [u'cn=%s,%s,%s' % ( self.uid, api.env.container_group, api.env.basedn )] self.attrs[u'objectclass'] = objectclasses.user if self.attrs[u'gidnumber'] == [u'-1']: self.attrs[u'gidnumber'] = [fuzzy_digits] if self.attrs[u'uidnumber'] == [u'-1']: self.attrs[u'uidnumber'] = [fuzzy_digits] if u'ipasshpubkey' in self.kwargs: self.attrs[u'ipasshpubkey'] = [str( self.kwargs[u'ipasshpubkey'] )] self.attrs[u'nsaccountlock'] = [u'false'] def check_activate(self, result): """ Check 'stageuser-activate' command result """ expected = dict( value=self.uid, summary=u'Stage user %s activated' % self.uid, result=self.filter_attrs(self.activate_keys)) # small override because stageuser-find returns different # type of nsaccountlock value than DS, but overall the value # fits expected result if expected['result'][u'nsaccountlock'] == [u'true']: expected['result'][u'nsaccountlock'] = True elif expected['result'][u'nsaccountlock'] == [u'false']: expected['result'][u'nsaccountlock'] = False assert_deepequal(expected, result) self.exists = True def check_undel(self, result): """ Check 'user-undel' command result """ assert_deepequal(dict( value=self.uid, summary=u'Undeleted user account "%s"' % self.uid, result=True ), result) def enable(self): """ Enable user account if it was disabled """ if (self.attrs['nsaccountlock'] is True or self.attrs['nsaccountlock'] == [u'true']): self.attrs.update(nsaccountlock=False) result = self.make_enable_command()() self.check_enable(result) def disable(self): """ Disable user account if it was enabled """ if (self.attrs['nsaccountlock'] is False or self.attrs['nsaccountlock'] == [u'false']): self.attrs.update(nsaccountlock=True) result = self.make_disable_command()() self.check_disable(result) def track_delete(self, preserve=False): """Update expected state for host deletion""" if preserve: self.exists = True if u'memberof_group' in self.attrs: del self.attrs[u'memberof_group'] self.attrs[u'nsaccountlock'] = True self.attrs[u'preserved'] = True else: self.exists = False self.attrs = {} def make_preserved_user(self): """ 'Creates' a preserved user necessary for some tests """ self.ensure_exists() self.track_delete(preserve=True) command = self.make_delete_command(no_preserve=False, preserve=True) result = command() self.check_delete(result) def check_attr_preservation(self, expected): """ Verifies that ipaUniqueID, uidNumber and gidNumber are preserved upon reactivation. Also verifies that resulting active user is a member of ipausers group only.""" command = self.make_retrieve_command(all=True) result = command() assert_deepequal(dict( ipauniqueid=result[u'result'][u'ipauniqueid'], uidnumber=result[u'result'][u'uidnumber'], gidnumber=result[u'result'][u'gidnumber'] ), expected) if (u'memberof_group' not in result[u'result'] or result[u'result'][u'memberof_group'] != (u'ipausers',)): assert False def make_fixture_restore(self, request): """Make a pytest fixture for a preserved user that is to be moved to staged area. The fixture ensures the plugin entry does not exist before and after the tests that use it. It takes into account that the preserved user no longer exists after restoring it, therefore the fixture verifies after the tests that the preserved user doesn't exist instead of deleting it. """ del_command = self.make_delete_command() try: del_command() except errors.NotFound: pass def finish(): with raises_exact(errors.NotFound( reason=u'%s: user not found' % self.uid)): del_command() request.addfinalizer(finish) return self def make_admin(self, admin_group=u'admins'): """ Add user to the administrator's group """ result = self.run_command('group_show', admin_group) admin_group_content = result[u'result'][u'member_user'] admin_group_expected = list(admin_group_content) + [self.name] command = self.make_group_add_member_command( admin_group, **dict(user=self.name) ) result = command() assert_deepequal(dict( completed=1, failed=dict( member=dict(group=tuple(), user=tuple(), service=tuple(), idoverrideuser=tuple()) ), result={ 'dn': get_group_dn(admin_group), 'member_user': admin_group_expected, 'gidnumber': [fuzzy_digits], 'cn': [admin_group], 'description': [u'Account administrators group'], }, ), result) # Kerberos aliases methods def _make_add_alias_cmd(self): return self.make_command('user_add_principal', self.name) def _make_remove_alias_cmd(self): return self.make_command('user_remove_principal', self.name) # Certificate identity mapping methods def _make_add_certmap(self): return self.make_command('user_add_certmapdata', self.name) def _make_remove_certmap(self): return self.make_command('user_remove_certmapdata', self.name) # Passkey mapping methods def _make_add_passkey(self): return self.make_command('user_add_passkey', self.name) def _make_remove_passkey(self): return self.make_command('user_remove_passkey', self.name)
21,495
Python
.py
478
34.014644
79
0.592327
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,515
stageuser_plugin.py
freeipa_freeipa/ipatests/test_xmlrpc/tracker/stageuser_plugin.py
# # Copyright (C) 2015 FreeIPA Contributors see COPYING for license # import six from ipalib import api, errors from ipaplatform.constants import constants as platformconstants from ipatests.test_xmlrpc.tracker.base import Tracker from ipatests.test_xmlrpc.tracker.passkey_plugin import PasskeyMixin from ipatests.test_xmlrpc.tracker.kerberos_aliases import KerberosAliasMixin from ipatests.test_xmlrpc import objectclasses from ipatests.test_xmlrpc.xmlrpc_test import ( Fuzzy, fuzzy_string, fuzzy_dergeneralizedtime, raises_exact) from ipatests.util import assert_deepequal from ipapython.dn import DN if six.PY3: unicode = str sshpubkey = (u'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDGAX3xAeLeaJggwTqMjxNwa6X' 'HBUAikXPGMzEpVrlLDCZtv00djsFTBi38PkgxBJVkgRWMrcBsr/35lq7P6w8KGI' 'wA8GI48Z0qBS2NBMJ2u9WQ2hjLN6GdMlo77O0uJY3251p12pCVIS/bHRSq8kHO2' 'No8g7KA9fGGcagPfQH+ee3t7HUkpbQkFTmbPPN++r3V8oVUk5LxbryB3UIIVzNm' 'cSIn3JrXynlvui4MixvrtX6zx+O/bBo68o8/eZD26QrahVbA09fivrn/4h3TM01' '9Eu/c2jOdckfU3cHUV/3Tno5d6JicibyaoDDK7S/yjdn5jhaz8MSEayQvFkZkiF' '0L public key test') sshpubkeyfp = (u'SHA256:cStA9o5TRSARbeketEOooMUMSWRSsArIAXloBZ4vNsE ' 'public key test (ssh-rsa)') class StageUserTracker(PasskeyMixin, KerberosAliasMixin, Tracker): """ Tracker class for staged user LDAP object Implements helper functions for host plugin. StageUserTracker object stores information about the user. """ retrieve_keys = { u'uid', u'givenname', u'sn', u'homedirectory', u'loginshell', u'uidnumber', u'gidnumber', u'mail', u'ou', u'telephonenumber', u'title', u'memberof', u'nsaccountlock', u'memberofindirect', u'ipauserauthtype', u'userclass', u'ipatokenradiusconfiglink', u'ipatokenradiususername', u'krbprincipalexpiration', u'usercertificate', u'dn', u'has_keytab', u'has_password', u'street', u'postalcode', u'facsimiletelephonenumber', u'carlicense', u'ipasshpubkey', u'sshpubkeyfp', u'l', u'st', u'mobile', u'pager', u'krbcanonicalname', u'krbprincipalname'} retrieve_all_keys = retrieve_keys | { u'cn', u'ipauniqueid', u'objectclass', u'description', u'displayname', u'gecos', u'initials', u'manager'} create_keys = retrieve_all_keys | { u'objectclass', u'ipauniqueid', u'randompassword', u'userpassword', u'krbextradata', u'krblastpwdchange', u'krbpasswordexpiration', u'krbprincipalkey'} update_keys = retrieve_keys - {u'dn', u'nsaccountlock'} activate_keys = retrieve_keys | { u'has_keytab', u'has_password', u'nsaccountlock'} find_keys = retrieve_keys - {u'has_keytab', u'has_password'} find_all_keys = retrieve_all_keys - {u'has_keytab', u'has_password'} def __init__(self, name=None, givenname=None, sn=None, **kwargs): """ Check for non-empty unicode string for the required attributes in the init method """ if not (isinstance(givenname, str) and givenname): raise ValueError( "Invalid first name provided: {!r}".format(givenname) ) if not (isinstance(sn, str) and sn): raise ValueError("Invalid second name provided: {!r}".format(sn)) super(StageUserTracker, self).__init__(default_version=None) self.uid = unicode(name) self.givenname = unicode(givenname) self.sn = unicode(sn) self.dn = DN( ('uid', self.uid), api.env.container_stageuser, api.env.basedn) self.kwargs = kwargs def make_create_command(self, options=None): """ Make function that creates a staged user using stageuser-add with all set of attributes and with minimal values, where uid is not specified """ if options is not None: self.kwargs = options if self.uid is not None: return self.make_command( 'stageuser_add', self.uid, givenname=self.givenname, sn=self.sn, **self.kwargs ) else: return self.make_command( 'stageuser_add', givenname=self.givenname, sn=self.sn, **self.kwargs ) def make_delete_command(self): """ Make function that deletes a staged user using stageuser-del """ return self.make_command('stageuser_del', self.uid) def make_retrieve_command(self, all=False, raw=False): """ Make function that retrieves a staged user using stageuser-show """ return self.make_command('stageuser_show', self.uid, all=all) def make_find_command(self, *args, **kwargs): """ Make function that finds staged user using stageuser-find """ return self.make_command('stageuser_find', *args, **kwargs) def make_update_command(self, updates): """ Make function that updates staged user using stageuser-mod """ return self.make_command('stageuser_mod', self.uid, **updates) def make_activate_command(self): """ Make function that activates staged user using stageuser-activate """ return self.make_command('stageuser_activate', self.uid) def track_create(self): """ Update expected state for staged user creation """ self.attrs = dict( dn=self.dn, uid=[self.uid], givenname=[self.givenname], sn=[self.sn], homedirectory=[u'/home/%s' % self.uid], displayname=[u'%s %s' % (self.givenname, self.sn)], cn=[u'%s %s' % (self.givenname, self.sn)], initials=[u'%s%s' % (self.givenname[0], self.sn[0])], objectclass=objectclasses.user_base, description=[u'__no_upg__'], ipauniqueid=[u'autogenerate'], uidnumber=[u'-1'], gidnumber=[u'-1'], krbprincipalname=[u'%s@%s' % (self.uid, self.api.env.realm)], krbcanonicalname=[u'%s@%s' % (self.uid, self.api.env.realm)], mail=[u'%s@%s' % (self.uid, self.api.env.domain)], gecos=[u'%s %s' % (self.givenname, self.sn)], loginshell=[platformconstants.DEFAULT_SHELL], has_keytab=False, has_password=False, nsaccountlock=True, ) for key in self.kwargs: if key == u'krbprincipalname': self.attrs[key] = [u'%s@%s' % ( (self.kwargs[key].split('@'))[0].lower(), (self.kwargs[key].split('@'))[1])] self.attrs[u'krbcanonicalname'] = self.attrs[key] elif key == u'manager': self.attrs[key] = [self.kwargs[key]] elif key == u'ipasshpubkey': self.attrs[u'sshpubkeyfp'] = [sshpubkeyfp] self.attrs[key] = [self.kwargs[key]] elif key in {u'random', u'userpassword'}: self.attrs[u'krbextradata'] = [Fuzzy(type=bytes)] self.attrs[u'krbpasswordexpiration'] = [ fuzzy_dergeneralizedtime] self.attrs[u'krblastpwdchange'] = [fuzzy_dergeneralizedtime] self.attrs[u'krbprincipalkey'] = [Fuzzy(type=bytes)] self.attrs[u'userpassword'] = [Fuzzy(type=bytes)] self.attrs[u'has_keytab'] = True self.attrs[u'has_password'] = True if key == u'random': self.attrs[u'randompassword'] = fuzzy_string else: self.attrs[key] = [self.kwargs[key]] self.exists = True def check_create(self, result, extra_keys=()): """ Check 'stageuser-add' command result """ expected = self.filter_attrs(self.create_keys | set(extra_keys)) assert_deepequal(dict( value=self.uid, summary=u'Added stage user "%s"' % self.uid, result=self.filter_attrs(expected), ), result) def check_delete(self, result): """ Check 'stageuser-del' command result """ assert_deepequal(dict( value=[self.uid], summary=u'Deleted stage user "%s"' % self.uid, result=dict(failed=[]), ), result) def check_retrieve(self, result, all=False, raw=False): """ Check 'stageuser-show' command result """ if all: expected = self.filter_attrs(self.retrieve_all_keys) else: expected = self.filter_attrs(self.retrieve_keys) assert_deepequal(dict( value=self.uid, summary=None, result=expected, ), result) def check_find(self, result, all=False, raw=False): """ Check 'stageuser-find' command result """ if all: expected = self.filter_attrs(self.find_all_keys) else: expected = self.filter_attrs(self.find_keys) assert_deepequal(dict( count=1, truncated=False, summary=u'1 user matched', result=[expected], ), result) def check_find_nomatch(self, result): """ Check 'stageuser-find' command result when no match is expected """ assert_deepequal(dict( count=0, truncated=False, summary=u'0 users matched', result=[], ), result) def check_update(self, result, extra_keys=()): """ Check 'stageuser-mod' command result """ assert_deepequal(dict( value=self.uid, summary=u'Modified stage user "%s"' % self.uid, result=self.filter_attrs(self.update_keys | set(extra_keys)) ), result) def check_restore_preserved(self, result): assert_deepequal(dict( value=[self.uid], summary=u'Staged user account "%s"' % self.uid, result=dict(failed=[]), ), result) def make_fixture_activate(self, request): """Make a pytest fixture for a staged user that is to be activated The fixture ensures the plugin entry does not exist before and after the tests that use it. It takes into account that the staged user no longer exists after activation, therefore the fixture verifies after the tests that the staged user doesn't exist instead of deleting it. """ del_command = self.make_delete_command() try: del_command() except errors.NotFound: pass def finish(): with raises_exact(errors.NotFound( reason=u'%s: stage user not found' % self.uid)): del_command() request.addfinalizer(finish) return self def create_from_preserved(self, user): """ Copies values from preserved user - helper function for restoration tests """ self.attrs = user.attrs self.uid = user.uid self.givenname = user.givenname self.sn = user.sn self.dn = DN( ('uid', self.uid), api.env.container_stageuser, api.env.basedn) self.attrs[u'dn'] = self.dn def _make_add_alias_cmd(self): return self.make_command('stageuser_add_principal', self.name) def _make_remove_alias_cmd(self): return self.make_command('stageuser_remove_principal', self.name) # Passkey mapping methods def _make_add_passkey(self): return self.make_command('stageuser_add_passkey', self.name) def _make_remove_passkey(self): return self.make_command('stageuser_remove_passkey', self.name)
11,639
Python
.py
249
36.349398
79
0.614157
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,516
hostgroup_plugin.py
freeipa_freeipa/ipatests/test_xmlrpc/tracker/hostgroup_plugin.py
# # Copyright (C) 2015 FreeIPA Contributors see COPYING for license # from ipatests.test_xmlrpc import objectclasses from ipatests.test_xmlrpc.xmlrpc_test import fuzzy_uuid from ipatests.test_xmlrpc.tracker.base import Tracker from ipatests.util import assert_deepequal from ipalib import api from ipapython.dn import DN class HostGroupTracker(Tracker): """ Class for tracking hostgroups """ retrieve_keys = {u'dn', u'cn', u'member_host', u'description', u'member_hostgroup', u'memberindirect_host'} retrieve_all_keys = retrieve_keys | {u'ipauniqueid', u'objectclass', u'mepmanagedentry'} create_keys = retrieve_all_keys update_keys = retrieve_keys - {u'dn'} add_member_keys = retrieve_keys | {u'member_host'} find_keys = { u'dn', u'cn', u'description', } find_all_keys = { u'dn', u'cn', u'member_host', u'description', u'member_hostgroup', u'memberindirect_host', u'ipauniqueid', u'objectclass', u'mepmanagedentry', } def __init__(self, name, description=u'HostGroup desc'): super(HostGroupTracker, self).__init__(default_version=None) self.cn = name self.description = description self.dn = DN(('cn', self.cn), ('cn', 'hostgroups'), ('cn', 'accounts'), api.env.basedn) def make_create_command(self, force=True, *args, **kwargs): """ Make function that creates a hostgroup using 'hostgroup-add' """ return self.make_command('hostgroup_add', self.cn, description=self.description, *args, **kwargs) def make_delete_command(self): """ Make function that deletes a hostgroup using 'hostgroup-del' """ return self.make_command('hostgroup_del', self.cn) def make_retrieve_command(self, all=False, raw=False): """ Make function that retrieves a hostgroup using 'hostgroup-show' """ return self.make_command('hostgroup_show', self.cn, all=all) def make_find_command(self, *args, **kwargs): """ Make function that searches for a hostgroup using 'hostgroup-find' """ return self.make_command('hostgroup_find', *args, **kwargs) def make_update_command(self, updates): """ Make function that updates a hostgroup using 'hostgroup-mod' """ return self.make_command('hostgroup_mod', self.cn, **updates) def make_add_member_command(self, options={}): """ Make function that adds a member to a hostgroup """ return self.make_command('hostgroup_add_member', self.cn, **options) def make_remove_member_command(self, options={}): """ Make function that removes a member from a hostgroup """ return self.make_command('hostgroup_remove_member', self.cn, **options) def track_create(self): """ Updates expected state for hostgroup creation""" self.attrs = dict( dn=self.dn, mepmanagedentry=[DN(('cn', self.cn), ('cn', 'ng'), ('cn', 'alt'), api.env.basedn)], cn=[self.cn], description=[self.description], ipauniqueid=[fuzzy_uuid], objectclass=objectclasses.hostgroup, ) self.exists = True def add_member(self, options): """ Add a member host to hostgroup and perform check """ if u'host' in options: try: self.attrs[u'member_host'] =\ self.attrs[u'member_host'] + [options[u'host']] except KeyError: self.attrs[u'member_host'] = [options[u'host']] # search for hosts in the target hostgroup and # add them as memberindirect hosts elif u'hostgroup' in options: try: self.attrs[u'member_hostgroup'] =\ self.attrs[u'member_hostgroup'] + [options[u'hostgroup']] except KeyError: self.attrs[u'member_hostgroup'] = [options[u'hostgroup']] command = self.make_add_member_command(options) result = command() self.check_add_member(result) def remove_member(self, options): """ Remove a member host from hostgroup and perform check """ if u'host' in options: self.attrs[u'member_host'].remove(options[u'host']) elif u'hostgroup' in options: self.attrs[u'member_hostgroup'].remove(options[u'hostgroup']) try: if not self.attrs[u'member_host']: del self.attrs[u'member_host'] except KeyError: pass try: if not self.attrs[u'member_hostgroup']: del self.attrs[u'member_hostgroup'] except KeyError: pass command = self.make_remove_member_command(options) result = command() self.check_remove_member(result) def update(self, updates, expected_updates=None): """Helper function to update this user and check the result Overriding Tracker method for setting self.attrs correctly; * most attributes stores its value in list * the rest can be overridden by expected_updates * allow deleting parametrs if update value is None """ if expected_updates is None: expected_updates = {} self.ensure_exists() command = self.make_update_command(updates) result = command() for key, value in updates.items(): if value is None: del self.attrs[key] else: self.attrs[key] = [value] for key, value in expected_updates.items(): if value is None: del self.attrs[key] else: self.attrs[key] = value self.check_update( result, extra_keys=set(updates.keys()) | set(expected_updates.keys()) ) def check_create(self, result): """ Checks 'hostgroup_add' command result """ assert_deepequal(dict( value=self.cn, summary=u'Added hostgroup "%s"' % self.cn, result=self.filter_attrs(self.create_keys) ), result) def check_delete(self, result): """ Checks 'hostgroup_del' command result """ assert_deepequal(dict( value=[self.cn], summary=u'Deleted hostgroup "%s"' % self.cn, result=dict(failed=[]), ), result) def check_retrieve(self, result, all=False, raw=False): """ Checks 'hostgroup_show' command result """ if all: expected = self.filter_attrs(self.retrieve_all_keys) else: expected = self.filter_attrs(self.retrieve_keys) assert_deepequal(dict( value=self.cn, summary=None, result=expected ), result) def check_find(self, result, all=False, raw=False): """ Checks 'hostgroup_find' command result """ if all: expected = self.filter_attrs(self.find_all_keys) else: expected = self.filter_attrs(self.find_keys) assert_deepequal(dict( count=1, truncated=False, summary=u'1 hostgroup matched', result=[expected], ), result) def check_update(self, result, extra_keys={}): """ Checks 'hostgroup_mod' command result """ assert_deepequal(dict( value=self.cn, summary=u'Modified hostgroup "%s"' % self.cn, result=self.filter_attrs(self.update_keys | set(extra_keys)) ), result) def check_add_member(self, result): """ Checks 'hostgroup_add_member' command result """ assert_deepequal(dict( completed=1, failed={u'member': {u'host': (), u'hostgroup': ()}}, result=self.filter_attrs(self.add_member_keys) ), result) def check_add_member_negative(self, result, options): """ Checks 'hostgroup_add_member' command result when expected result is failure of the operation""" expected = dict( completed=0, failed={u'member': {u'hostgroup': (), u'user': ()}}, result=self.filter_attrs(self.add_member_keys) ) if u'host' in options: expected[u'failed'][u'member'][u'host'] = [( options[u'host'], u'no such entry')] elif u'hostgroup' in options: expected[u'failed'][u'member'][u'hostgroup'] = [( options[u'hostgroup'], u'no such entry')] assert_deepequal(expected, result) def check_remove_member_negative(self, result, options): """ Checks 'hostgroup_remove_member' command result when expected result is failure of the operation""" expected = dict( completed=0, failed={u'member': {u'hostgroup': (), u'host': ()}}, result=self.filter_attrs(self.add_member_keys) ) if u'user' in options: expected[u'failed'][u'member'][u'host'] = [( options[u'user'], u'This entry is not a member')] elif u'hostgroup' in options: expected[u'failed'][u'member'][u'hostgroup'] = [( options[u'hostgroup'], u'This entry is not a member')] assert_deepequal(expected, result) def check_remove_member(self, result): """ Checks 'hostgroup_remove_member' command result """ self.check_add_member(result)
9,613
Python
.py
217
33.548387
79
0.58711
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,517
__init__.py
freeipa_freeipa/ipatests/test_ipaclient/__init__.py
# # Copyright (C) 2016 FreeIPA Contributors see COPYING for license # """ Sub-package containing unit tests for `ipaclient` package. """
139
Python
.py
6
22
66
0.765152
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,518
test_ldapconf.py
freeipa_freeipa/ipatests/test_ipaclient/test_ldapconf.py
# # Copyright (C) 2019 FreeIPA Contributors see COPYING for license # import os import shutil import tempfile import pytest from ipaplatform.paths import paths import ipatests.util ipatests.util.check_ipaclient_unittests() # noqa: E402 from ipaclient.install.client import configure_openldap_conf # with single URI and space LDAP_CONF_1 = """ # # LDAP Defaults # BASE dc=example,dc=com URI ldap://ldap.example.com # Turning this off breaks GSSAPI used with krb5 when rdns = false SASL_NOCANON on """ # URI with two entries and tabs LDAP_CONF_2 = """ # # LDAP Defaults # BASE\tdc=example,dc=com URI\tldap://ldap.example.com ldap://ldap-master.example.com:666 # Turning this off breaks GSSAPI used with krb5 when rdns = false SASL_NOCANON on """ BASEDN = 'cn=ipa,cn=example' SERVER = 'ldap.ipa.example' class DummyFStore: def backup_file(self, fname): pass def ldap_conf(content): # fixture tmp_path is pytest >= 3.9 tmp_path = tempfile.mkdtemp() cfgfile = os.path.join(tmp_path, 'ldap.conf') if content is not None: with open(cfgfile, 'w') as f: f.write(content) orig_ldap_conf = paths.OPENLDAP_LDAP_CONF try: paths.OPENLDAP_LDAP_CONF = cfgfile configure_openldap_conf(DummyFStore(), BASEDN, [SERVER]) with open(cfgfile) as f: text = f.read() settings = {} for line in text.split('\n'): line = line.strip() if not line or line.startswith('#'): continue k, v = line.split(None, 1) settings.setdefault(k, []).append(v) finally: paths.OPENLDAP_LDAP_CONF = orig_ldap_conf shutil.rmtree(tmp_path) return text, settings def test_openldap_conf_empty(): text, settings = ldap_conf("") assert '# File modified by ipa-client-install' in text assert settings == { 'BASE': [BASEDN], 'URI': ['ldaps://{}'.format(SERVER)], 'SASL_MECH': ['GSSAPI'] } def test_openldap_conf_spaces(): text, settings = ldap_conf(LDAP_CONF_1) assert '# File modified by ipa-client-install' in text assert settings == { 'BASE': ['dc=example,dc=com'], 'URI': ['ldap://ldap.example.com'], 'SASL_NOCANON': ['on'], 'SASL_MECH': ['GSSAPI'] } @pytest.mark.xfail(reason="freeipa ticket 7838", strict=True) def test_openldap_conf_mixed(): text, settings = ldap_conf(LDAP_CONF_2) assert '# File modified by ipa-client-install' in text assert settings == { 'BASE': ['dc=example,dc=com'], 'URI': ['ldap://ldap.example.com ldap://ldap-master.example.com:666'], 'SASL_NOCANON': ['on'], 'SASL_MECH': ['GSSAPI'] }
2,726
Python
.py
87
26.241379
78
0.646654
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,519
test_backend.py
freeipa_freeipa/ipatests/test_ipalib/test_backend.py
# Authors: # Jason Gerard DeRose <jderose@redhat.com> # # Copyright (C) 2008 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ Test the `ipalib.backend` module. """ from __future__ import print_function import threading from ipatests.util import ClassChecker, raises, create_test_api from ipatests.data import unicode_str from ipalib.request import context, Connection from ipalib.frontend import Command from ipalib import backend, plugable, errors from ipapython.version import API_VERSION import pytest pytestmark = pytest.mark.tier0 class test_Backend(ClassChecker): """ Test the `ipalib.backend.Backend` class. """ _cls = backend.Backend def test_class(self): assert self.cls.__bases__ == (plugable.Plugin,) class Disconnect: called = False def __init__(self, id=None): self.id = id def __call__(self): assert self.called is False self.called = True if self.id is not None: delattr(context, self.id) class test_Connectible(ClassChecker): """ Test the `ipalib.backend.Connectible` class. """ _cls = backend.Connectible def test_connect(self): """ Test the `ipalib.backend.Connectible.connect` method. """ # Test that connection is created: api = 'the api instance' class example(self.cls): def create_connection(self, *args, **kw): object.__setattr__(self, 'args', args) object.__setattr__(self, 'kw', kw) return 'The connection.' o = example(api, shared_instance=True) args = ('Arg1', 'Arg2', 'Arg3') kw = dict(key1='Val1', key2='Val2', key3='Val3') assert not hasattr(context, 'example') assert o.connect(*args, **kw) is None conn = context.example assert type(conn) is Connection # pylint: disable=no-member assert o.args == args assert o.kw == kw # pylint: enable=no-member assert conn.conn == 'The connection.' assert conn.disconnect == o.disconnect # Test that Exception is raised if already connected: m = "{0} is already connected ({1} in {2})" e = raises(Exception, o.connect, *args, **kw) assert str(e) == m.format( "example", o.id, threading.current_thread().name ) # Double check that it works after deleting context.example: del context.example assert o.connect(*args, **kw) is None def test_create_connection(self): """ Test the `ipalib.backend.Connectible.create_connection` method. """ api = 'the api instance' class example(self.cls): pass for klass in (self.cls, example): o = klass(api, shared_instance=True) e = raises(NotImplementedError, o.create_connection) assert str(e) == '%s.create_connection()' % klass.__name__ def test_disconnect(self): """ Test the `ipalib.backend.Connectible.disconnect` method. """ api = 'the api instance' class example(self.cls): destroy_connection = Disconnect() o = example(api, shared_instance=True) m = "{0} is not connected ({1} in {2})" e = raises(Exception, o.disconnect) assert str(e) == m.format( "example", o.id, threading.current_thread().name ) context.example = 'The connection.' assert o.disconnect() is None assert example.destroy_connection.called is True def test_destroy_connection(self): """ Test the `ipalib.backend.Connectible.destroy_connection` method. """ api = 'the api instance' class example(self.cls): pass for klass in (self.cls, example): o = klass(api, shared_instance=True) e = raises(NotImplementedError, o.destroy_connection) assert str(e) == '%s.destroy_connection()' % klass.__name__ def test_isconnected(self): """ Test the `ipalib.backend.Connectible.isconnected` method. """ api = 'the api instance' class example(self.cls): pass for klass in (self.cls, example): o = klass(api, shared_instance=True) assert o.isconnected() is False conn = 'whatever' setattr(context, klass.__name__, conn) assert o.isconnected() is True delattr(context, klass.__name__) def test_conn(self): """ Test the `ipalib.backend.Connectible.conn` property. """ api = 'the api instance' msg = '{0} is not connected ({1} in {2})' class example(self.cls): pass for klass in (self.cls, example): o = klass(api, shared_instance=True) e = raises(AttributeError, getattr, o, 'conn') assert str(e) == msg.format( klass.__name__, o.id, threading.current_thread().name ) conn = Connection('The connection.', Disconnect()) setattr(context, klass.__name__, conn) assert o.conn is conn.conn delattr(context, klass.__name__) class test_Executioner(ClassChecker): """ Test the `ipalib.backend.Executioner` class. """ _cls = backend.Executioner def test_execute(self): """ Test the `ipalib.backend.Executioner.execute` method. """ api, _home = create_test_api(in_server=True) class echo(Command): takes_args = ('arg1', 'arg2+') takes_options = ('option1?', 'option2?') def execute(self, *args, **options): assert type(args[1]) is tuple return dict(result=args + (options,)) api.add_plugin(echo) class good(Command): def execute(self, **options): raise errors.ValidationError( name='nurse', error=u'Not naughty!', ) api.add_plugin(good) class bad(Command): def execute(self, **options): raise ValueError('This is private.') api.add_plugin(bad) class with_name(Command): """ Test that a kwarg named 'name' can be used. """ takes_options = 'name' def execute(self, **options): return dict(result=options['name'].upper()) api.add_plugin(with_name) api.finalize() o = self.cls(api) o.finalize() # Test that CommandError is raised: conn = Connection('The connection.', Disconnect('someconn')) context.someconn = conn print(str(list(context.__dict__))) e = raises(errors.CommandError, o.execute, 'nope') assert e.name == 'nope' assert conn.disconnect.called is True # Make sure destroy_context() was called print(str(list(context.__dict__))) assert list(context.__dict__) == [] # Test with echo command: arg1 = unicode_str arg2 = (u'Hello', unicode_str, u'world!') args = (arg1,) + arg2 options = dict(option1=u'How are you?', option2=unicode_str, version=API_VERSION) conn = Connection('The connection.', Disconnect('someconn')) context.someconn = conn print(o.execute('echo', arg1, arg2, **options)) print(dict( result=(arg1, arg2, options) )) assert o.execute('echo', arg1, arg2, **options) == dict( result=(arg1, arg2, options) ) assert conn.disconnect.called is True # Make sure destroy_context() was called assert list(context.__dict__) == [] conn = Connection('The connection.', Disconnect('someconn')) context.someconn = conn assert o.execute('echo', *args, **options) == dict( result=(arg1, arg2, options) ) assert conn.disconnect.called is True # Make sure destroy_context() was called assert list(context.__dict__) == [] # Test with good command: conn = Connection('The connection.', Disconnect('someconn')) context.someconn = conn e = raises(errors.ValidationError, o.execute, 'good') assert e.name == 'nurse' assert e.error == u'Not naughty!' assert conn.disconnect.called is True # Make sure destroy_context() was called assert list(context.__dict__) == [] # Test with bad command: conn = Connection('The connection.', Disconnect('someconn')) context.someconn = conn e = raises(errors.InternalError, o.execute, 'bad') assert conn.disconnect.called is True # Make sure destroy_context() was called assert list(context.__dict__) == [] # Test with option 'name': conn = Connection('The connection.', Disconnect('someconn')) context.someconn = conn expected = dict(result=u'TEST') assert expected == o.execute('with_name', name=u'test', version=API_VERSION)
9,835
Python
.py
247
30.88664
87
0.597549
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,520
test_capabilities.py
freeipa_freeipa/ipatests/test_ipalib/test_capabilities.py
# Authors: # Petr Viktorin <pviktori@redhat.com> # # Copyright (C) 2012 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ Test the `ipalib.errors` module. """ from ipalib.capabilities import capabilities, client_has_capability import pytest pytestmark = pytest.mark.tier0 def test_client_has_capability(): assert capabilities['messages'] == u'2.52' assert client_has_capability(u'2.52', 'messages') assert client_has_capability(u'2.60', 'messages') assert client_has_capability(u'3.0', 'messages') assert not client_has_capability(u'2.11', 'messages') assert not client_has_capability(u'0.1', 'messages')
1,289
Python
.py
31
39.645161
71
0.75818
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,521
test_cli.py
freeipa_freeipa/ipatests/test_ipalib/test_cli.py
# Authors: # Jason Gerard DeRose <jderose@redhat.com> # # Copyright (C) 2008 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ Test the `ipalib.cli` module. """ from ipatests.util import raises, ClassChecker from ipalib import cli, plugable import pytest pytestmark = pytest.mark.tier0 class test_textui(ClassChecker): _cls = cli.textui def test_max_col_width(self): """ Test the `ipalib.cli.textui.max_col_width` method. """ api = 'the api instance' o = self.cls(api) e = raises(TypeError, o.max_col_width, 'hello') assert str(e) == 'rows: need %r or %r; got %r' % (list, tuple, 'hello') rows = [ 'hello', 'empathetic', 'nurse', ] assert o.max_col_width(rows) == len('empathetic') rows = ( ( 'a', 'bbb', 'ccccc'), ('aa', 'bbbb', 'cccccc'), ) assert o.max_col_width(rows, col=0) == 2 assert o.max_col_width(rows, col=1) == 4 assert o.max_col_width(rows, col=2) == 6 def test_to_cli(): """ Test the `ipalib.cli.to_cli` function. """ f = cli.to_cli assert f('initialize') == 'initialize' assert f('user_add') == 'user-add' def test_from_cli(): """ Test the `ipalib.cli.from_cli` function. """ f = cli.from_cli assert f('initialize') == 'initialize' assert f('user-add') == 'user_add' def get_cmd_name(i): return 'cmd_%d' % i class DummyCommand: def __init__(self, name): self.__name = name def __get_name(self): return self.__name name = property(__get_name) class DummyAPI: def __init__(self, cnt): self.__cmd = plugable.APINameSpace(self.__cmd_iter(cnt), DummyCommand) def __get_cmd(self): return self.__cmd Command = property(__get_cmd) def __cmd_iter(self, cnt): for i in range(cnt): yield DummyCommand(get_cmd_name(i)) def finalize(self): pass def register(self, *args, **kw): pass config_cli = """ [global] from_cli_conf = set in cli.conf """ config_default = """ [global] from_default_conf = set in default.conf # Make sure cli.conf is loaded first: from_cli_conf = overridden in default.conf """
2,930
Python
.py
93
26.516129
79
0.63274
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,522
test_aci.py
freeipa_freeipa/ipatests/test_ipalib/test_aci.py
# Authors: # Rob Crittenden <rcritten@redhat.com> # Petr Viktorin <pviktori@redhat.com> # # Copyright (C) 2008 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ Test the `ipalib.aci` module. """ from __future__ import print_function from ipalib.aci import ACI import pytest pytestmark = pytest.mark.tier0 def check_aci_parsing(source, expected): a = ACI(source) print('ACI was: ', a) print('Expected:', expected) assert str(ACI(source)) == expected def test_aci_parsing_1(): check_aci_parsing('(targetattr="title")(targetfilter="(memberOf=cn=bar,cn=groups,cn=accounts ,dc=example,dc=com)")(version 3.0;acl "foobar";allow (write) groupdn="ldap:///cn=foo,cn=groups,cn=accounts,dc=example,dc=com";)', '(targetattr = "title")(targetfilter = "(memberOf=cn=bar,cn=groups,cn=accounts ,dc=example,dc=com)")(version 3.0;acl "foobar";allow (write) groupdn = "ldap:///cn=foo,cn=groups,cn=accounts,dc=example,dc=com";)') def test_aci_parsing_1_with_aci_keyword(): check_aci_parsing('(targetattr="title")(targetfilter="(memberOf=cn=bar,cn=groups,cn=accounts ,dc=example,dc=com)")(version 3.0;aci "foobar";allow (write) groupdn="ldap:///cn=foo,cn=groups,cn=accounts,dc=example,dc=com";)', '(targetattr = "title")(targetfilter = "(memberOf=cn=bar,cn=groups,cn=accounts ,dc=example,dc=com)")(version 3.0;acl "foobar";allow (write) groupdn = "ldap:///cn=foo,cn=groups,cn=accounts,dc=example,dc=com";)') def test_aci_parsing_2(): check_aci_parsing('(target="ldap:///uid=bjensen,dc=example,dc=com")(targetattr=*) (version 3.0;acl "aci1";allow (write) userdn="ldap:///self";)', '(target = "ldap:///uid=bjensen,dc=example,dc=com")(targetattr = "*")(version 3.0;acl "aci1";allow (write) userdn = "ldap:///self";)') def test_aci_parsing_3(): check_aci_parsing(' (targetattr = "givenName || sn || cn || displayName || title || initials || loginShell || gecos || homePhone || mobile || pager || facsimileTelephoneNumber || telephoneNumber || street || roomNumber || l || st || postalCode || manager || secretary || description || carLicense || labeledURI || inetUserHTTPURL || seeAlso || employeeType || businessCategory || ou")(version 3.0;acl "Self service";allow (write) userdn = "ldap:///self";)', '(targetattr = "givenName || sn || cn || displayName || title || initials || loginShell || gecos || homePhone || mobile || pager || facsimileTelephoneNumber || telephoneNumber || street || roomNumber || l || st || postalCode || manager || secretary || description || carLicense || labeledURI || inetUserHTTPURL || seeAlso || employeeType || businessCategory || ou")(version 3.0;acl "Self service";allow (write) userdn = "ldap:///self";)') def test_aci_parsing_4(): check_aci_parsing('(target="ldap:///uid=*,cn=users,cn=accounts,dc=example,dc=com")(version 3.0;acl "add_user";allow (add) groupdn="ldap:///cn=add_user,cn=taskgroups,dc=example,dc=com";)', '(target = "ldap:///uid=*,cn=users,cn=accounts,dc=example,dc=com")(version 3.0;acl "add_user";allow (add) groupdn = "ldap:///cn=add_user,cn=taskgroups,dc=example,dc=com";)') def test_aci_parsing_5(): check_aci_parsing('(targetattr=member)(target="ldap:///cn=ipausers,cn=groups,cn=accounts,dc=example,dc=com")(version 3.0;acl "add_user_to_default_group";allow (write) groupdn="ldap:///cn=add_user_to_default_group,cn=taskgroups,dc=example,dc=com";)', '(target = "ldap:///cn=ipausers,cn=groups,cn=accounts,dc=example,dc=com")(targetattr = "member")(version 3.0;acl "add_user_to_default_group";allow (write) groupdn = "ldap:///cn=add_user_to_default_group,cn=taskgroups,dc=example,dc=com";)') def test_aci_parsing_6(): check_aci_parsing('(targetattr!=member)(targe="ldap:///cn=ipausers,cn=groups,cn=accounts,dc=example,dc=com")(version 3.0;acl "add_user_to_default_group";allow (write) groupdn="ldap:///cn=add_user_to_default_group,cn=taskgroups,dc=example,dc=com";)', '(targe = "ldap:///cn=ipausers,cn=groups,cn=accounts,dc=example,dc=com")(targetattr != "member")(version 3.0;acl "add_user_to_default_group";allow (write) groupdn = "ldap:///cn=add_user_to_default_group,cn=taskgroups,dc=example,dc=com";)') def test_aci_parsing_7(): check_aci_parsing('(targetattr = "userPassword || krbPrincipalKey || sambaLMPassword || sambaNTPassword || passwordHistory")(version 3.0; acl "change_password"; allow (write) groupdn = "ldap:///cn=change_password,cn=taskgroups,dc=example,dc=com";)', '(targetattr = "userPassword || krbPrincipalKey || sambaLMPassword || sambaNTPassword || passwordHistory")(version 3.0;acl "change_password";allow (write) groupdn = "ldap:///cn=change_password,cn=taskgroups,dc=example,dc=com";)') def make_test_aci(): a = ACI() a.name ="foo" a.set_target_attr(['title','givenname'], "!=") a.set_bindrule_keyword("groupdn") a.set_bindrule_operator("=") a.set_bindrule_expression("\"ldap:///cn=foo,cn=groups,cn=accounts,dc=example,dc=com\"") a.permissions = ['read','write','add'] return a def test_aci_equality(): a = make_test_aci() print(a) b = ACI() b.name ="foo" b.set_target_attr(['givenname','title'], "!=") b.set_bindrule_keyword("groupdn") b.set_bindrule_operator("=") b.set_bindrule_expression("\"ldap:///cn=foo,cn=groups,cn=accounts,dc=example,dc=com\"") b.permissions = ['add','read','write'] print(b) assert a.isequal(b) assert a == b assert not a != b # pylint: disable=unneeded-not def check_aci_inequality(b): a = make_test_aci() print(a) print(b) assert not a.isequal(b) assert not a == b assert a != b def test_aci_inequality_targetattr_expression(): b = make_test_aci() b.set_target_attr(['givenname'], "!=") check_aci_inequality(b) def test_aci_inequality_targetattr_op(): b = make_test_aci() b.set_target_attr(['givenname', 'title'], "=") check_aci_inequality(b) def test_aci_inequality_targetfilter(): b = make_test_aci() b.set_target_filter('(objectclass=*)', "=") check_aci_inequality(b) def test_aci_inequality_target(): b = make_test_aci() b.set_target("ldap:///cn=bar,cn=groups,cn=accounts,dc=example,dc=com", "=") check_aci_inequality(b) def test_aci_inequality_bindrule_keyword(): b = make_test_aci() b.set_bindrule_keyword("userdn") check_aci_inequality(b) def test_aci_inequality_bindrule_op(): b = make_test_aci() b.set_bindrule_operator("!=") check_aci_inequality(b) def test_aci_inequality_bindrule_expression(): b = make_test_aci() b.set_bindrule_expression("\"ldap:///cn=bar,cn=groups,cn=accounts,dc=example,dc=com\"") check_aci_inequality(b) def test_aci_inequality_permissions(): b = make_test_aci() b.permissions = ['read', 'search', 'compare'] check_aci_inequality(b) def test_aci_parsing_8(): check_aci_parsing('(targetattr != "userPassword || krbPrincipalKey || sambaLMPassword || sambaNTPassword || passwordHistory || krbMKey")(version 3.0; acl "Enable Anonymous access"; allow (read, search, compare) userdn = "ldap:///anyone";)', '(targetattr != "userPassword || krbPrincipalKey || sambaLMPassword || sambaNTPassword || passwordHistory || krbMKey")(version 3.0;acl "Enable Anonymous access";allow (read,search,compare) userdn = "ldap:///anyone";)') def test_aci_parsing_9(): check_aci_parsing('(targetfilter = "(|(objectClass=person)(objectClass=krbPrincipalAux)(objectClass=posixAccount)(objectClass=groupOfNames)(objectClass=posixGroup))")(targetattr != "aci || userPassword || krbPrincipalKey || sambaLMPassword || sambaNTPassword || passwordHistory")(version 3.0; acl "Account Admins can manage Users and Groups"; allow (add, delete, read, write) groupdn = "ldap:///cn=admins,cn=groups,cn=accounts,dc=greyoak,dc=com";)', '(targetattr != "aci || userPassword || krbPrincipalKey || sambaLMPassword || sambaNTPassword || passwordHistory")(targetfilter = "(|(objectClass=person)(objectClass=krbPrincipalAux)(objectClass=posixAccount)(objectClass=groupOfNames)(objectClass=posixGroup))")(version 3.0;acl "Account Admins can manage Users and Groups";allow (add,delete,read,write) groupdn = "ldap:///cn=admins,cn=groups,cn=accounts,dc=greyoak,dc=com";)') def test_aci_parsing_10(): """test subtypes""" check_aci_parsing('(targetattr="ipaProtectedOperation;read_keys")' '(version 3.0; acl "Allow trust agents to retrieve ' 'keytab keys for cross realm principals"; allow(read) ' 'userattr="ipaAllowedToPerform;read_keys#GROUPDN";)', '(targetattr = "ipaProtectedOperation;read || keys")' '(version 3.0;acl "Allow trust agents to retrieve ' 'keytab keys for cross realm principals";allow (read) ' 'userattr = "ipaAllowedToPerform;read_keys#GROUPDN";)')
9,539
Python
.py
133
66.62406
462
0.689202
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,523
test_messages.py
freeipa_freeipa/ipatests/test_ipalib/test_messages.py
# Authors: # Petr Viktorin <pviktori@redhat.com> # # Copyright (C) 1012 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ Test the `ipalib.messages` module. """ from ipalib import messages from ipalib.capabilities import capabilities from ipatests.test_ipalib import test_errors import pytest pytestmark = pytest.mark.tier0 class HelloMessage(messages.PublicMessage): type = 'info' format = '%(greeting)s, %(object)s!' errno = 1234 class test_PublicMessage(test_errors.test_PublicError): """Test public messages""" # The messages are a lot like public errors; defer testing to that. klass = messages.PublicMessage required_classes = (UserWarning, messages.PublicMessage) class test_PublicMessages(test_errors.BaseMessagesTest): message_list = messages.public_messages errno_range = list(range(10000, 19999)) required_classes = (UserWarning, messages.PublicMessage) texts = messages._texts def extratest(self, cls): if cls is not messages.PublicMessage: assert cls.type in ('debug', 'info', 'warning', 'error') def test_to_dict(): expected = dict( name=u'HelloMessage', type=u'info', message=u'Hello, world!', code=1234, data={'greeting': 'Hello', 'object': 'world'}, ) assert HelloMessage(greeting='Hello', object='world').to_dict() == expected def test_add_message(): result = {} assert capabilities['messages'] == u'2.52' messages.add_message(u'2.52', result, HelloMessage(greeting='Hello', object='world')) messages.add_message(u'2.1', result, HelloMessage(greeting="'Lo", object='version')) messages.add_message(u'2.60', result, HelloMessage(greeting='Hi', object='version')) assert result == {'messages': [ dict( name=u'HelloMessage', type=u'info', message=u'Hello, world!', code=1234, data={'greeting': 'Hello', 'object': 'world'}, ), dict( name=u'HelloMessage', type=u'info', message=u'Hi, version!', code=1234, data={'greeting': 'Hi', 'object': 'version'}, ) ]}
2,918
Python
.py
77
31.792208
79
0.661707
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,524
test_output.py
freeipa_freeipa/ipatests/test_ipalib/test_output.py
# Authors: # Jason Gerard DeRose <jderose@redhat.com> # # Copyright (C) 2009 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ Test the `ipalib.output` module. """ from ipatests.util import raises, ClassChecker from ipalib import output from ipalib.frontend import Command from ipapython.version import API_VERSION import pytest pytestmark = pytest.mark.tier0 class test_Output(ClassChecker): """ Test the `ipalib.output.Output` class. """ _cls = output.Output def test_init(self): """ Test the `ipalib.output.Output.__init__` method. """ o = self.cls('result') assert o.name == 'result' assert o.type is None assert o.doc is None def test_repr(self): """ Test the `ipalib.output.Output.__repr__` method. """ o = self.cls('aye') assert repr(o) == "Output('aye')" o = self.cls('aye', type=int, doc='An A, aye?') assert repr(o) == ( "Output('aye', type=[<type 'int'>], doc='An A, aye?')" ) class Entry(self.cls): pass o = Entry('aye') assert repr(o) == "Entry('aye')" o = Entry('aye', type=int, doc='An A, aye?') assert repr(o) == ( "Entry('aye', type=[<type 'int'>], doc='An A, aye?')" ) class test_ListOfEntries(ClassChecker): """ Test the `ipalib.output.ListOfEntries` class. """ _cls = output.ListOfEntries def test_validate(self): """ Test the `ipalib.output.ListOfEntries.validate` method. """ api = 'the api instance' class example(Command): pass cmd = example(api) inst = self.cls('stuff') okay = dict(foo='bar') nope = ('aye', 'bee') e = raises(TypeError, inst.validate, cmd, [okay, okay, nope], API_VERSION) assert str(e) == output.emsg % ( 'example', 'ListOfEntries', 'stuff', 2, dict, tuple, nope ) e = raises(TypeError, inst.validate, cmd, [nope, okay, nope], API_VERSION) assert str(e) == output.emsg % ( 'example', 'ListOfEntries', 'stuff', 0, dict, tuple, nope )
2,889
Python
.py
84
27.940476
71
0.609896
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,525
test_rpc.py
freeipa_freeipa/ipatests/test_ipalib/test_rpc.py
# Authors: # Jason Gerard DeRose <jderose@redhat.com> # # Copyright (C) 2008 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ Test the `ipalib.rpc` module. """ from __future__ import print_function from xmlrpc.client import Binary, Fault, dumps, loads import urllib import pytest import six from ipatests.util import raises, assert_equal, PluginTester, DummyClass from ipatests.util import Fuzzy from ipatests.data import binary_bytes, utf8_bytes, unicode_str from ipalib.frontend import Command from ipalib.request import context, Connection from ipalib import rpc, errors, api, request as ipa_request from ipapython.version import API_VERSION if six.PY3: unicode = str std_compound = (binary_bytes, utf8_bytes, unicode_str) def dump_n_load(value): param, _method = loads( dumps((value,), allow_none=True) ) return param[0] def round_trip(value): return rpc.xml_unwrap( dump_n_load(rpc.xml_wrap(value, API_VERSION)) ) def test_round_trip(): """ Test `ipalib.rpc.xml_wrap` and `ipalib.rpc.xml_unwrap`. This tests the two functions together with ``xmlrpc.client.dumps()`` and ``xmlrpc.client.loads()`` in a full wrap/dumps/loads/unwrap round trip. """ # We first test that our assumptions about xmlrpc.client module in the Python # standard library are correct: if six.PY2: output_binary_type = bytes else: output_binary_type = Binary if six.PY2: assert_equal(dump_n_load(utf8_bytes), unicode_str) assert_equal(dump_n_load(unicode_str), unicode_str) assert_equal(dump_n_load(Binary(binary_bytes)).data, binary_bytes) assert isinstance(dump_n_load(Binary(binary_bytes)), Binary) assert type(dump_n_load(b'hello')) is output_binary_type assert type(dump_n_load(u'hello')) is str assert_equal(dump_n_load(b''), output_binary_type(b'')) assert_equal(dump_n_load(u''), str()) assert dump_n_load(None) is None # Now we test our wrap and unwrap methods in combination with dumps, loads: # All bytes should come back bytes (because they get wrapped in # xmlrpc.client.Binary(). All unicode should come back unicode because str # explicity get decoded by rpc.xml_unwrap() if they weren't already # decoded by xmlrpc.client.loads(). assert_equal(round_trip(utf8_bytes), utf8_bytes) assert_equal(round_trip(unicode_str), unicode_str) assert_equal(round_trip(binary_bytes), binary_bytes) assert type(round_trip(b'hello')) is bytes assert type(round_trip(u'hello')) is unicode assert_equal(round_trip(b''), b'') assert_equal(round_trip(u''), u'') assert round_trip(None) is None compound = [utf8_bytes, None, binary_bytes, (None, unicode_str), dict(utf8=utf8_bytes, chars=unicode_str, data=binary_bytes) ] assert round_trip(compound) == tuple(compound) def test_xml_wrap(): """ Test the `ipalib.rpc.xml_wrap` function. """ f = rpc.xml_wrap assert f([], API_VERSION) == tuple() assert f({}, API_VERSION) == dict() b = f(b'hello', API_VERSION) assert isinstance(b, Binary) assert b.data == b'hello' u = f(u'hello', API_VERSION) assert type(u) is unicode assert u == u'hello' f([dict(one=False, two=u'hello'), None, b'hello'], API_VERSION) def test_xml_unwrap(): """ Test the `ipalib.rpc.xml_unwrap` function. """ f = rpc.xml_unwrap assert f([]) == tuple() assert f({}) == dict() value = f(Binary(utf8_bytes)) assert type(value) is bytes assert value == utf8_bytes assert f(utf8_bytes) == unicode_str assert f(unicode_str) == unicode_str value = f([True, Binary(b'hello'), dict(one=1, two=utf8_bytes, three=None)]) assert value == (True, b'hello', dict(one=1, two=unicode_str, three=None)) assert type(value[1]) is bytes assert type(value[2]['two']) is unicode def test_xml_dumps(): """ Test the `ipalib.rpc.xml_dumps` function. """ f = rpc.xml_dumps params = (binary_bytes, utf8_bytes, unicode_str, None) # Test serializing an RPC request: data = f(params, API_VERSION, 'the_method') (p, m) = loads(data) assert_equal(m, u'the_method') assert type(p) is tuple assert rpc.xml_unwrap(p) == params # Test serializing an RPC response: data = f((params,), API_VERSION, methodresponse=True) (tup, m) = loads(data) assert m is None assert len(tup) == 1 assert type(tup) is tuple assert rpc.xml_unwrap(tup[0]) == params # Test serializing an RPC response containing a Fault: fault = Fault(69, unicode_str) data = f(fault, API_VERSION, methodresponse=True) e = raises(Fault, loads, data) assert e.faultCode == 69 assert_equal(e.faultString, unicode_str) def test_xml_loads(): """ Test the `ipalib.rpc.xml_loads` function. """ f = rpc.xml_loads params = (binary_bytes, utf8_bytes, unicode_str, None) wrapped = rpc.xml_wrap(params, API_VERSION) # Test un-serializing an RPC request: data = dumps(wrapped, 'the_method', allow_none=True) (p, m) = f(data) assert_equal(m, u'the_method') assert_equal(p, params) # Test un-serializing an RPC response: data = dumps((wrapped,), methodresponse=True, allow_none=True) (tup, m) = f(data) assert m is None assert len(tup) == 1 assert type(tup) is tuple assert_equal(tup[0], params) # Test un-serializing an RPC response containing a Fault: for error in (unicode_str, u'hello'): fault = Fault(69, error) data = dumps(fault, methodresponse=True, allow_none=True, encoding='UTF-8') e = raises(Fault, f, data) assert e.faultCode == 69 assert_equal(e.faultString, error) assert type(e.faultString) is unicode class test_xmlclient(PluginTester): """ Test the `ipalib.rpc.xmlclient` plugin. """ _plugin = rpc.xmlclient def test_forward(self): """ Test the `ipalib.rpc.xmlclient.forward` method. """ class user_add(Command): pass o, _api, _home = self.instance('Backend', user_add, in_server=False) args = (binary_bytes, utf8_bytes, unicode_str) kw = dict(one=binary_bytes, two=utf8_bytes, three=unicode_str) params = [args, kw] result = (unicode_str, binary_bytes, utf8_bytes) conn = DummyClass( ( 'user_add', rpc.xml_wrap(params, API_VERSION), {}, rpc.xml_wrap(result, API_VERSION), ), ( 'user_add', rpc.xml_wrap(params, API_VERSION), {}, Fault(3007, u"'four' is required"), # RequirementError ), ( 'user_add', rpc.xml_wrap(params, API_VERSION), {}, Fault(700, u'no such error'), # There is no error 700 ), ) # Create connection for the current thread setattr(context, o.id, Connection(conn, lambda: None)) context.xmlclient = Connection(conn, lambda: None) # Test with a successful return value: assert o.forward('user_add', *args, **kw) == result # Test with an errno the client knows: e = raises(errors.RequirementError, o.forward, 'user_add', *args, **kw) assert_equal(e.args[0], u"'four' is required") # Test with an errno the client doesn't know e = raises(errors.UnknownError, o.forward, 'user_add', *args, **kw) assert_equal(e.code, 700) assert_equal(e.error, u'no such error') assert context.xmlclient.conn._calledall() is True @pytest.mark.skip_ipaclient_unittest @pytest.mark.needs_ipaapi class test_xml_introspection: @pytest.fixture(autouse=True, scope="class") def xml_introsp_setup(self, request): try: api.Backend.xmlclient.connect() except (errors.NetworkError, IOError): pytest.skip('%r: Server not available: %r' % (__name__, api.env.xmlrpc_uri)) def fin(): ipa_request.destroy_context() request.addfinalizer(fin) def test_list_methods(self): result = api.Backend.xmlclient.conn.system.listMethods() assert len(result) assert 'ping' in result assert 'user_add' in result assert 'system.listMethods' in result assert 'system.methodSignature' in result assert 'system.methodHelp' in result def test_list_methods_many_params(self): try: api.Backend.xmlclient.conn.system.listMethods('foo') except Fault as f: print(f) assert f.faultCode == 3003 assert f.faultString == ( "command 'system.listMethods' takes no arguments") else: raise AssertionError('did not raise') def test_ping_signature(self): result = api.Backend.xmlclient.conn.system.methodSignature('ping') assert result == [['struct', 'array', 'struct']] def test_ping_help(self): result = api.Backend.xmlclient.conn.system.methodHelp('ping') assert result == 'Ping a remote server.' def test_signature_no_params(self): try: api.Backend.xmlclient.conn.system.methodSignature() except Fault as f: print(f) assert f.faultCode == 3007 assert f.faultString == "'method name' is required" else: raise AssertionError('did not raise') def test_signature_many_params(self): try: api.Backend.xmlclient.conn.system.methodSignature('a', 'b') except Fault as f: print(f) assert f.faultCode == 3004 assert f.faultString == ( "command 'system.methodSignature' takes at most 1 argument") else: raise AssertionError('did not raise') def test_help_no_params(self): try: api.Backend.xmlclient.conn.system.methodHelp() except Fault as f: print(f) assert f.faultCode == 3007 assert f.faultString == "'method name' is required" else: raise AssertionError('did not raise') def test_help_many_params(self): try: api.Backend.xmlclient.conn.system.methodHelp('a', 'b') except Fault as f: print(f) assert f.faultCode == 3004 assert f.faultString == ( "command 'system.methodHelp' takes at most 1 argument") else: raise AssertionError('did not raise') @pytest.mark.skip_ipaclient_unittest @pytest.mark.needs_ipaapi class test_rpcclient_context(PluginTester): """ Test the context in `ipalib.rpc.rpcclient` plugin. """ @pytest.fixture(autouse=True) def rpcclient_context_fsetup(self, request): try: api.Backend.rpcclient.connect(ca_certfile='foo') except (errors.NetworkError, IOError): pytest.skip('%r: Server not available: %r' % (__name__, api.env.xmlrpc_uri)) def fin(): if api.Backend.rpcclient.isconnected(): api.Backend.rpcclient.disconnect() request.addfinalizer(fin) def test_context_cafile(self): """ Test that ca_certfile is set in `ipalib.rpc.rpcclient.connect` """ ca_certfile = getattr(context, 'ca_certfile', None) assert_equal(ca_certfile, 'foo') def test_context_principal(self): """ Test that principal is set in `ipalib.rpc.rpcclient.connect` """ principal = getattr(context, 'principal', None) assert_equal(principal, 'admin@%s' % api.env.realm) def test_context_request_url(self): """ Test that request_url is set in `ipalib.rpc.rpcclient.connect` """ request_url = getattr(context, 'request_url', None) assert_equal(request_url, 'https://%s/ipa/session/json' % api.env.host) def test_context_session_cookie(self): """ Test that session_cookie is set in `ipalib.rpc.rpcclient.connect` """ fuzzy_cookie = Fuzzy( r'^ipa_session=MagBearerToken=[A-Za-z0-9+\/]+=*;$') session_cookie = getattr(context, 'session_cookie', None) unquoted = urllib.parse.unquote(session_cookie) assert(unquoted == fuzzy_cookie)
13,147
Python
.py
334
32.038922
83
0.636399
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,526
test_frontend.py
freeipa_freeipa/ipatests/test_ipalib/test_frontend.py
# Authors: # Jason Gerard DeRose <jderose@redhat.com> # # Copyright (C) 2008 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ Test the `ipalib.frontend` module. """ import pytest import six from ipatests.util import raises, read_only from ipatests.util import ClassChecker, create_test_api from ipatests.util import assert_equal from ipalib.constants import TYPE_ERROR from ipalib.base import NameSpace from ipalib import frontend, backend, plugable, errors, parameters, config from ipalib import output, messages from ipalib.parameters import Str from ipapython.version import API_VERSION if six.PY3: unicode = str pytestmark = pytest.mark.tier0 def test_RULE_FLAG(): assert frontend.RULE_FLAG == 'validation_rule' def test_rule(): """ Test the `ipalib.frontend.rule` function. """ flag = frontend.RULE_FLAG rule = frontend.rule def my_func(): pass assert not hasattr(my_func, flag) rule(my_func) assert getattr(my_func, flag) is True @rule def my_func2(): pass assert getattr(my_func2, flag) is True def test_is_rule(): """ Test the `ipalib.frontend.is_rule` function. """ is_rule = frontend.is_rule flag = frontend.RULE_FLAG class no_call: def __init__(self, value): if value is not None: assert value in (True, False) setattr(self, flag, value) class call(no_call): def __call__(self): pass assert is_rule(call(True)) assert not is_rule(no_call(True)) assert not is_rule(call(False)) assert not is_rule(call(None)) class test_HasParam(ClassChecker): """ Test the `ipalib.frontend.Command` class. """ _cls = frontend.HasParam def test_get_param_iterable(self): """ Test the `ipalib.frontend.HasParam._get_param_iterable` method. """ api = 'the api instance' class WithTuple(self.cls): takes_stuff = ('one', 'two') o = WithTuple(api) assert o._get_param_iterable('stuff') is WithTuple.takes_stuff junk = ('three', 'four') class WithCallable(self.cls): def takes_stuff(self): return junk o = WithCallable(api) assert o._get_param_iterable('stuff') is junk class WithParam(self.cls): takes_stuff = parameters.Str('five') o = WithParam(api) assert o._get_param_iterable('stuff') == (WithParam.takes_stuff,) class WithStr(self.cls): takes_stuff = 'six' o = WithStr(api) assert o._get_param_iterable('stuff') == ('six',) class Wrong(self.cls): takes_stuff = ['seven', 'eight'] o = Wrong(api) e = raises(TypeError, o._get_param_iterable, 'stuff') assert str(e) == '%s.%s must be a tuple, callable, or spec; got %r' % ( 'Wrong', 'takes_stuff', Wrong.takes_stuff ) def test_filter_param_by_context(self): """ Test the `ipalib.frontend.HasParam._filter_param_by_context` method. """ api = 'the api instance' class Example(self.cls): def get_stuff(self): return ( 'one', # Make sure create_param() is called for each spec 'two', parameters.Str('three', include='cli'), parameters.Str('four', exclude='server'), parameters.Str('five', exclude=['whatever', 'cli']), ) o = Example(api) # Test when env is None: params = list(o._filter_param_by_context('stuff')) assert list(p.name for p in params) == [ 'one', 'two', 'three', 'four', 'five' ] for p in params: assert type(p) is parameters.Str # Test when env.context == 'cli': cli = config.Env(context='cli') assert cli.context == 'cli' params = list(o._filter_param_by_context('stuff', cli)) assert list(p.name for p in params) == ['one', 'two', 'three', 'four'] for p in params: assert type(p) is parameters.Str # Test when env.context == 'server' server = config.Env(context='server') assert server.context == 'server' params = list(o._filter_param_by_context('stuff', server)) assert list(p.name for p in params) == ['one', 'two', 'five'] for p in params: assert type(p) is parameters.Str # Test with no get_stuff: class Missing(self.cls): pass o = Missing(api) gen = o._filter_param_by_context('stuff') e = raises(NotImplementedError, list, gen) assert str(e) == 'Missing.get_stuff()' # Test when get_stuff is not callable: class NotCallable(self.cls): get_stuff = ('one', 'two') o = NotCallable(api) gen = o._filter_param_by_context('stuff') e = raises(TypeError, list, gen) assert str(e) == '%s.%s must be a callable; got %r' % ( 'NotCallable', 'get_stuff', NotCallable.get_stuff ) class test_Command(ClassChecker): """ Test the `ipalib.frontend.Command` class. """ _cls = frontend.Command def get_subcls(self): """ Return a standard subclass of `ipalib.frontend.Command`. """ class Rule: def __init__(self, name): self.name = name def __call__(self, _, value): if value != self.name: return _('must equal %r') % self.name else: return None default_from = parameters.DefaultFrom( lambda arg: arg, 'default_from' ) def normalizer(value): return value.lower() class example(self.cls): takes_options = ( parameters.Str('option0', Rule('option0'), normalizer=normalizer, default_from=default_from, ), parameters.Str('option1', Rule('option1'), normalizer=normalizer, default_from=default_from, ), ) return example def get_instance(self, args=tuple(), options=tuple()): """ Helper method used to test args and options. """ class api: @staticmethod def is_production_mode(): return False class example(self.cls): takes_args = args takes_options = options o = example(api) o.finalize() return o def test_class(self): """ Test the `ipalib.frontend.Command` class. """ assert self.cls.takes_options == tuple() assert self.cls.takes_args == tuple() def test_get_args(self): """ Test the `ipalib.frontend.Command.get_args` method. """ api = 'the api instance' assert list(self.cls(api).get_args()) == [] args = ('login', 'stuff') o = self.get_instance(args=args) assert tuple(o.get_args()) == args def test_get_options(self): """ Test the `ipalib.frontend.Command.get_options` method. """ api = 'the api instance' options = list(self.cls(api).get_options()) assert len(options) == 1 assert options[0].name == 'version' options = ('verbose', 'debug') o = self.get_instance(options=options) assert len(tuple(o.get_options())) == 3 assert 'verbose' in tuple(o.get_options()) assert 'debug' in tuple(o.get_options()) def test_args(self): """ Test the ``ipalib.frontend.Command.args`` instance attribute. """ class api: @staticmethod def is_production_mode(): return False o = self.cls(api) o.finalize() assert type(o.args) is NameSpace assert len(o.args) == 0 args = ('destination', 'source?') ns = self.get_instance(args=args).args assert type(ns) is NameSpace assert len(ns) == len(args) assert list(ns) == ['destination', 'source'] assert type(ns.destination) is parameters.Str assert type(ns.source) is parameters.Str assert ns.destination.required is True assert ns.destination.multivalue is False assert ns.source.required is False assert ns.source.multivalue is False # Test TypeError: if six.PY2: e = raises(TypeError, self.get_instance, args=(u'whatever',)) assert str(e) == TYPE_ERROR % ( 'spec', (str, parameters.Param), u'whatever', unicode) else: e = raises(TypeError, self.get_instance, args=(b'whatever',)) assert str(e) == TYPE_ERROR % ( 'spec', (str, parameters.Param), b'whatever', bytes) # Test ValueError, required after optional: e = raises(ValueError, self.get_instance, args=('arg1?', 'arg2')) assert str(e) == "arg2: required argument after optional in %s arguments ['arg1?', 'arg2']" % (self.get_instance().name) # Test ValueError, scalar after multivalue: e = raises(ValueError, self.get_instance, args=('arg1+', 'arg2')) assert str(e) == 'arg2: only final argument can be multivalue' def test_max_args(self): """ Test the ``ipalib.frontend.Command.max_args`` instance attribute. """ o = self.get_instance() assert o.max_args == 0 o = self.get_instance(args=('one?',)) assert o.max_args == 1 o = self.get_instance(args=('one', 'two?')) assert o.max_args == 2 o = self.get_instance(args=('one', 'multi+',)) assert o.max_args is None o = self.get_instance(args=('one', 'multi*',)) assert o.max_args is None def test_options(self): """ Test the ``ipalib.frontend.Command.options`` instance attribute. """ class api: @staticmethod def is_production_mode(): return False o = self.cls(api) o.finalize() assert type(o.options) is NameSpace assert len(o.options) == 1 options = ('target', 'files*') ns = self.get_instance(options=options).options assert type(ns) is NameSpace assert len(ns) == len(options) + 1 assert list(ns) == ['target', 'files', 'version'] assert type(ns.target) is parameters.Str assert type(ns.files) is parameters.Str assert ns.target.required is True assert ns.target.multivalue is False assert ns.files.required is False assert ns.files.multivalue is True def test_output(self): """ Test the ``ipalib.frontend.Command.output`` instance attribute. """ class api: @staticmethod def is_production_mode(): return False inst = self.cls(api) inst.finalize() assert type(inst.output) is NameSpace assert list(inst.output) == ['result'] # pylint: disable=no-member assert type(inst.output.result) is output.Output # pylint: enable=no-member def test_iter_output(self): """ Test the ``ipalib.frontend.Command._iter_output`` instance attribute. """ api = 'the api instance' class Example(self.cls): pass inst = Example(api) inst.has_output = tuple() assert list(inst._iter_output()) == [] wrong = ['hello', 'world'] inst.has_output = wrong e = raises(TypeError, list, inst._iter_output()) assert str(e) == 'Example.has_output: need a %r; got a %r: %r' % ( tuple, list, wrong ) wrong = ('hello', 17) inst.has_output = wrong e = raises(TypeError, list, inst._iter_output()) assert str(e) == 'Example.has_output[1]: need a %r; got a %r: %r' % ( (str, output.Output), int, 17 ) okay = ('foo', output.Output('bar'), 'baz') inst.has_output = okay items = list(inst._iter_output()) assert len(items) == 3 assert list(o.name for o in items) == ['foo', 'bar', 'baz'] for o in items: assert type(o) is output.Output def test_convert(self): """ Test the `ipalib.frontend.Command.convert` method. """ class api: @staticmethod def is_production_mode(): return False kw = dict( option0=u'1.5', option1=u'7', ) o = self.subcls(api) o.finalize() for (key, value) in o.convert(**kw).items(): assert_equal(unicode(kw[key]), value) def test_normalize(self): """ Test the `ipalib.frontend.Command.normalize` method. """ class api: @staticmethod def is_production_mode(): return False kw = dict( option0=u'OPTION0', option1=u'OPTION1', ) norm = dict((k, v.lower()) for (k, v) in kw.items()) sub = self.subcls(api) sub.finalize() assert sub.normalize(**kw) == norm def test_get_default(self): """ Test the `ipalib.frontend.Command.get_default` method. """ # FIXME: Add an updated unit tests for get_default() def test_default_from_chaining(self): """ Test chaining of parameters through default_from. """ class my_cmd(self.cls): takes_options = ( Str('option0'), Str('option1', default_from=lambda option0: option0), Str('option2', default_from=lambda option1: option1), ) def run(self, *args, **options): return dict(result=options) kw = dict(option0=u'some value') api, _home = create_test_api() api.finalize() o = my_cmd(api) o.finalize() e = o.get_default(**kw) assert type(e) is dict assert 'option2' in e assert e['option2'] == u'some value' def test_validate(self): """ Test the `ipalib.frontend.Command.validate` method. """ class api: env = config.Env(context='cli') @staticmethod def is_production_mode(): return False sub = self.subcls(api) sub.finalize() # Check with valid values okay = dict( option0=u'option0', option1=u'option1', another_option='some value', version=API_VERSION, ) sub.validate(**okay) # Check with an invalid value fail = dict(okay) fail['option0'] = u'whatever' e = raises(errors.ValidationError, sub.validate, **fail) assert_equal(e.name, u'option0') assert_equal(e.error, u"must equal 'option0'") # Check with a missing required arg fail = dict(okay) fail.pop('option1') e = raises(errors.RequirementError, sub.validate, **fail) assert e.name == 'option1' def test_execute(self): """ Test the `ipalib.frontend.Command.execute` method. """ api = 'the api instance' o = self.cls(api) e = raises(NotImplementedError, o.execute) assert str(e) == 'Command.execute()' def test_args_options_2_params(self): """ Test the `ipalib.frontend.Command.args_options_2_params` method. """ # Test that ZeroArgumentError is raised: o = self.get_instance() e = raises(errors.ZeroArgumentError, o.args_options_2_params, 1) assert e.name == 'example' # Test that MaxArgumentError is raised (count=1) o = self.get_instance(args=('one?',)) e = raises(errors.MaxArgumentError, o.args_options_2_params, 1, 2) assert e.name == 'example' assert e.count == 1 assert str(e) == "command 'example' takes at most 1 argument" # Test that MaxArgumentError is raised (count=2) o = self.get_instance(args=('one', 'two?')) e = raises(errors.MaxArgumentError, o.args_options_2_params, 1, 2, 3) assert e.name == 'example' assert e.count == 2 assert str(e) == "command 'example' takes at most 2 arguments" # Test that OptionError is raised when an extra option is given: o = self.get_instance() e = raises(errors.OptionError, o.args_options_2_params, bad_option=True) assert e.option == 'bad_option' # Test that OverlapError is raised: o = self.get_instance(args=('one', 'two'), options=('three', 'four')) e = raises(errors.OverlapError, o.args_options_2_params, 1, 2, three=3, two=2, four=4, one=1) assert e.names == "['one', 'two']" # Test the permutations: o = self.get_instance(args=('one', 'two*'), options=('three', 'four')) mthd = o.args_options_2_params assert mthd() == dict() assert mthd(1) == dict(one=1) assert mthd(1, 2) == dict(one=1, two=(2,)) assert mthd(1, 21, 22, 23) == dict(one=1, two=(21, 22, 23)) assert mthd(1, (21, 22, 23)) == dict(one=1, two=(21, 22, 23)) assert mthd(three=3, four=4) == dict(three=3, four=4) assert mthd(three=3, four=4, one=1, two=2) == \ dict(one=1, two=2, three=3, four=4) assert mthd(1, 21, 22, 23, three=3, four=4) == \ dict(one=1, two=(21, 22, 23), three=3, four=4) assert mthd(1, (21, 22, 23), three=3, four=4) == \ dict(one=1, two=(21, 22, 23), three=3, four=4) def test_args_options_2_entry(self): """ Test `ipalib.frontend.Command.args_options_2_entry` method. """ class my_cmd(self.cls): takes_args = ( parameters.Str('one', attribute=True), parameters.Str('two', attribute=False), ) takes_options = ( parameters.Str('three', attribute=True, multivalue=True), parameters.Str('four', attribute=True, multivalue=False), ) def run(self, *args, **kw): return self.args_options_2_entry(*args, **kw) args = ('one', 'two') kw = dict(three=('three1', 'three2'), four='four') api, _home = create_test_api() api.finalize() o = my_cmd(api) o.finalize() e = o.run(*args, **kw) assert type(e) is dict assert 'one' in e assert 'two' not in e assert 'three' in e assert 'four' in e assert e['one'] == 'one' assert e['three'] == ['three1', 'three2'] assert e['four'] == 'four' def test_params_2_args_options(self): """ Test the `ipalib.frontend.Command.params_2_args_options` method. """ o = self.get_instance(args='one', options='two') assert o.params_2_args_options() == ((), {}) assert o.params_2_args_options(one=1) == ((1,), {}) assert o.params_2_args_options(two=2) == ((), dict(two=2)) assert o.params_2_args_options(two=2, one=1) == ((1,), dict(two=2)) def test_run(self): """ Test the `ipalib.frontend.Command.run` method. """ class my_cmd(self.cls): def execute(self, *args, **kw): return ('execute', args, kw) def forward(self, *args, **kw): return ('forward', args, kw) args = ('Hello,', 'world,') kw = dict(how_are='you', on_this='fine day?', version=API_VERSION) # Test in server context: api, _home = create_test_api(in_server=True) api.finalize() o = my_cmd(api) if six.PY2: assert o.run.__func__ is self.cls.run.__func__ else: assert o.run.__func__ is self.cls.run out = o.run(*args, **kw) assert ('execute', args, kw) == out # Test in non-server context api, _home = create_test_api(in_server=False) api.finalize() o = my_cmd(api) if six.PY2: assert o.run.__func__ is self.cls.run.__func__ else: assert o.run.__func__ is self.cls.run assert ('forward', args, kw) == o.run(*args, **kw) def test_messages(self): """ Test correct handling of messages """ class TestMessage(messages.PublicMessage): type = 'info' format = 'This is a message.' errno = 1234 class my_cmd(self.cls): def execute(self, *args, **kw): result = {'name': 'execute'} messages.add_message(kw['version'], result, TestMessage()) return result def forward(self, *args, **kw): result = {'name': 'forward'} messages.add_message(kw['version'], result, TestMessage()) return result args = ('Hello,', 'world,') kw = dict(how_are='you', on_this='fine day?', version=API_VERSION) expected = [TestMessage().to_dict()] # Test in server context: api, _home = create_test_api(in_server=True) api.finalize() o = my_cmd(api) if six.PY2: assert o.run.__func__ is self.cls.run.__func__ else: assert o.run.__func__ is self.cls.run assert {'name': 'execute', 'messages': expected} == o.run(*args, **kw) # Test in non-server context api, _home = create_test_api(in_server=False) api.finalize() o = my_cmd(api) if six.PY2: assert o.run.__func__ is self.cls.run.__func__ else: assert o.run.__func__ is self.cls.run assert {'name': 'forward', 'messages': expected} == o.run(*args, **kw) def test_validate_output_basic(self): """ Test the `ipalib.frontend.Command.validate_output` method. """ class api: @staticmethod def is_production_mode(): return False class Example(self.cls): has_output = ('foo', 'bar', 'baz') inst = Example(api) inst.finalize() # Test with wrong type: wrong = ('foo', 'bar', 'baz') e = raises(TypeError, inst.validate_output, wrong) assert str(e) == '%s.validate_output(): need a %r; got a %r: %r' % ( 'Example', dict, tuple, wrong ) # Test with a missing keys: wrong = dict(bar='hello') e = raises(ValueError, inst.validate_output, wrong) assert str(e) == '%s.validate_output(): missing keys %r in %r' % ( 'Example', ['baz', 'foo'], wrong ) # Test with extra keys: wrong = dict(foo=1, bar=2, baz=3, fee=4, azz=5) e = raises(ValueError, inst.validate_output, wrong) assert str(e) == '%s.validate_output(): unexpected keys %r in %r' % ( 'Example', ['azz', 'fee'], wrong ) # Test with different keys: wrong = dict(baz=1, xyzzy=2, quux=3) e = raises(ValueError, inst.validate_output, wrong) assert str(e) == '%s.validate_output(): missing keys %r in %r' % ( 'Example', ['bar', 'foo'], wrong ), str(e) def test_validate_output_per_type(self): """ Test `ipalib.frontend.Command.validate_output` per-type validation. """ class api: @staticmethod def is_production_mode(): return False class Complex(self.cls): has_output = ( output.Output('foo', int), output.Output('bar', list), ) inst = Complex(api) inst.finalize() wrong = dict(foo=17.9, bar=[18]) e = raises(TypeError, inst.validate_output, wrong) assert str(e) == '%s:\n output[%r]: need (%r,); got %r: %r' % ( 'Complex.validate_output()', 'foo', int, float, 17.9 ) wrong = dict(foo=18, bar=17) e = raises(TypeError, inst.validate_output, wrong) assert str(e) == '%s:\n output[%r]: need (%r,); got %r: %r' % ( 'Complex.validate_output()', 'bar', list, int, 17 ) def test_validate_output_nested(self): """ Test `ipalib.frontend.Command.validate_output` nested validation. """ class api: @staticmethod def is_production_mode(): return False class Subclass(output.ListOfEntries): pass # Test nested validation: class nested(self.cls): has_output = ( output.Output('hello', int), Subclass('world'), ) inst = nested(api) inst.finalize() okay = dict(foo='bar') nope = ('aye', 'bee') wrong = dict(hello=18, world=[okay, nope, okay]) e = raises(TypeError, inst.validate_output, wrong) assert str(e) == output.emsg % ( 'nested', 'Subclass', 'world', 1, dict, tuple, nope ) wrong = dict(hello=18, world=[okay, okay, okay, okay, nope]) e = raises(TypeError, inst.validate_output, wrong) assert str(e) == output.emsg % ( 'nested', 'Subclass', 'world', 4, dict, tuple, nope ) def test_get_output_params(self): """ Test the `ipalib.frontend.Command.get_output_params` method. """ class api: @staticmethod def is_production_mode(): return False class example(self.cls): has_output_params = ( 'one', 'two', 'three', ) takes_args = ( 'foo', ) takes_options = ( Str('bar'), 'baz', ) inst = example(api) inst.finalize() assert list(inst.get_output_params()) == [ 'one', 'two', 'three' ] assert list(inst.output_params) == ['one', 'two', 'three'] class test_LocalOrRemote(ClassChecker): """ Test the `ipalib.frontend.LocalOrRemote` class. """ _cls = frontend.LocalOrRemote def test_init(self): """ Test the `ipalib.frontend.LocalOrRemote.__init__` method. """ class api: @staticmethod def is_production_mode(): return False o = self.cls(api) o.finalize() assert list(o.args) == [] assert list(o.options) == ['server', 'version'] op = o.options.server assert op.required is False assert op.default is False def test_run(self): """ Test the `ipalib.frontend.LocalOrRemote.run` method. """ class example(self.cls): takes_args = 'key?' def forward(self, *args, **options): return dict(result=('forward', args, options)) def execute(self, *args, **options): return dict(result=('execute', args, options)) # Test when in_server=False: api, _home = create_test_api(in_server=False) api.add_plugin(example) api.finalize() cmd = api.Command.example assert cmd(version=u'2.47') == dict( result=('execute', (), dict(version=u'2.47')) ) assert cmd(u'var', version=u'2.47') == dict( result=('execute', (u'var',), dict(version=u'2.47')) ) assert cmd(server=True, version=u'2.47') == dict( result=('forward', (), dict(version=u'2.47', server=True)) ) assert cmd(u'var', server=True, version=u'2.47') == dict( result=('forward', (u'var',), dict(version=u'2.47', server=True)) ) # Test when in_server=True (should always call execute): api, _home = create_test_api(in_server=True) api.add_plugin(example) api.finalize() cmd = api.Command.example assert cmd(version=u'2.47') == dict( result=('execute', (), dict(version=u'2.47', server=False)) ) assert cmd(u'var', version=u'2.47') == dict( result=('execute', (u'var',), dict(version=u'2.47', server=False)) ) assert cmd(server=True, version=u'2.47') == dict( result=('execute', (), dict(version=u'2.47', server=True)) ) assert cmd(u'var', server=True, version=u'2.47') == dict( result=('execute', (u'var',), dict(version=u'2.47', server=True)) ) class test_Object(ClassChecker): """ Test the `ipalib.frontend.Object` class. """ _cls = frontend.Object def test_class(self): """ Test the `ipalib.frontend.Object` class. """ assert self.cls.backend is None assert self.cls.methods is None assert self.cls.params is None assert self.cls.params_minus_pk is None assert self.cls.takes_params == tuple() def test_init(self): """ Test the `ipalib.frontend.Object.__init__` method. """ # Setup for test: class DummyAttribute: def __init__(self, obj_name, attr_name, name=None): self.obj_name = obj_name self.attr_name = attr_name if name is None: self.name = '%s_%s' % (obj_name, attr_name) else: self.name = name self.bases = (DummyAttribute,) self.version = '1' self.full_name = '{}/{}'.format(self.name, self.version) self.param = frontend.create_param(attr_name) def __clone__(self, attr_name): return self.__class__( self.obj_name, self.attr_name, getattr(self, attr_name) ) def get_attributes(cnt, format): for name in ['other', 'user', 'another']: for i in range(cnt): yield DummyAttribute(name, format % i) cnt = 10 methods_format = 'method_%d' class FakeAPI: def __init__(self): self._API__plugins = get_attributes(cnt, methods_format) self._API__default_map = {} self.Method = plugable.APINameSpace(self, DummyAttribute) def __contains__(self, key): return hasattr(self, key) def __getitem__(self, key): return getattr(self, key) def is_production_mode(self): return False def _get(self, plugin): return plugin api = FakeAPI() assert len(api.Method) == cnt * 3 class user(self.cls): pass # Actually perform test: o = user(api) assert read_only(o, 'api') is api namespace = o.methods assert isinstance(namespace, NameSpace) assert len(namespace) == cnt f = methods_format for i in range(cnt): attr_name = f % i attr = namespace[attr_name] assert isinstance(attr, DummyAttribute) assert attr is getattr(namespace, attr_name) assert attr.obj_name == 'user' assert attr.attr_name == attr_name assert attr.name == '%s_%s' % ('user', attr_name) # Test params instance attribute o = self.cls(api) ns = o.params assert type(ns) is NameSpace assert len(ns) == 0 class example(self.cls): takes_params = ('banana', 'apple') o = example(api) ns = o.params assert type(ns) is NameSpace assert len(ns) == 2, repr(ns) assert list(ns) == ['banana', 'apple'] for p in ns(): assert type(p) is parameters.Str assert p.required is True assert p.multivalue is False def test_primary_key(self): """ Test the `ipalib.frontend.Object.primary_key` attribute. """ api, _home = create_test_api() api.finalize() # Test with no primary keys: class example1(self.cls): takes_params = ( 'one', 'two', ) o = example1(api) assert o.primary_key is None # Test with 1 primary key: class example2(self.cls): takes_params = ( 'one', 'two', parameters.Str('three', primary_key=True), 'four', ) o = example2(api) pk = o.primary_key assert type(pk) is parameters.Str assert pk.name == 'three' assert pk.primary_key is True assert o.params[2] is o.primary_key assert isinstance(o.params_minus_pk, NameSpace) assert list(o.params_minus_pk) == ['one', 'two', 'four'] # Test with multiple primary_key: class example3(self.cls): takes_params = ( parameters.Str('one', primary_key=True), parameters.Str('two', primary_key=True), 'three', parameters.Str('four', primary_key=True), ) o = example3(api) e = raises(ValueError, o.finalize) assert str(e) == \ 'example3 (Object) has multiple primary keys: one, two, four' def test_backend(self): """ Test the `ipalib.frontend.Object.backend` attribute. """ api, _home = create_test_api() class ldap(backend.Backend): whatever = 'It worked!' api.add_plugin(ldap) class user(frontend.Object): backend_name = 'ldap' api.add_plugin(user) api.finalize() b = api.Object.user.backend assert isinstance(b, ldap) assert b.whatever == 'It worked!' def test_get_dn(self): """ Test the `ipalib.frontend.Object.get_dn` method. """ api = 'the api instance' o = self.cls(api) e = raises(NotImplementedError, o.get_dn, 'primary key') assert str(e) == 'Object.get_dn()' class user(self.cls): pass o = user(api) e = raises(NotImplementedError, o.get_dn, 'primary key') assert str(e) == 'user.get_dn()' def test_params_minus(self): """ Test the `ipalib.frontend.Object.params_minus` method. """ class example(self.cls): takes_params = ('one', 'two', 'three', 'four') api, _home = create_test_api() api.finalize() o = example(api) p = o.params assert tuple(o.params_minus()) == tuple(p()) assert tuple(o.params_minus([])) == tuple(p()) assert tuple(o.params_minus('two', 'three')) == (p.one, p.four) assert tuple(o.params_minus(['two', 'three'])) == (p.one, p.four) assert tuple(o.params_minus(p.two, p.three)) == (p.one, p.four) assert tuple(o.params_minus([p.two, p.three])) == (p.one, p.four) ns = NameSpace([p.two, p.three]) assert tuple(o.params_minus(ns)) == (p.one, p.four) class test_Attribute(ClassChecker): """ Test the `ipalib.frontend.Attribute` class. """ _cls = frontend.Attribute def test_class(self): """ Test the `ipalib.frontend.Attribute` class. """ assert self.cls.__bases__ == (plugable.Plugin,) assert type(self.cls.obj) is property assert type(self.cls.obj_name) is property assert type(self.cls.attr_name) is property def test_init(self): """ Test the `ipalib.frontend.Attribute.__init__` method. """ user_obj = 'The user frontend.Object instance' class api: Object = {("user", "1"): user_obj} @staticmethod def is_production_mode(): return False class user_add(self.cls): pass o = user_add(api) assert read_only(o, 'api') is api assert read_only(o, 'obj') is user_obj assert read_only(o, 'obj_name') == 'user' assert read_only(o, 'attr_name') == 'add' class test_Method(ClassChecker): """ Test the `ipalib.frontend.Method` class. """ _cls = frontend.Method def get_api(self, args=tuple(), options=tuple()): """ Return a finalized `ipalib.plugable.API` instance. """ api, _home = create_test_api() class user(frontend.Object): takes_params = ( 'givenname', 'sn', frontend.Param('uid', primary_key=True), 'initials', ) class user_verb(self.cls): takes_args = args takes_options = options api.add_plugin(user) api.add_plugin(user_verb) api.finalize() return api def test_class(self): """ Test the `ipalib.frontend.Method` class. """ assert self.cls.__bases__ == (frontend.Attribute, frontend.Command) def test_init(self): """ Test the `ipalib.frontend.Method.__init__` method. """ api = 'the api instance' class user_add(self.cls): pass o = user_add(api) assert o.name == 'user_add' assert o.obj_name == 'user' assert o.attr_name == 'add'
38,501
Python
.py
1,031
27.347236
128
0.544181
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,527
test_text.py
freeipa_freeipa/ipatests/test_ipalib/test_text.py
# Authors: # Jason Gerard DeRose <jderose@redhat.com> # # Copyright (C) 2009 Red Hat # see file 'COPYING' for use and warranty contextrmation # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ Test the `ipalib.text` module. """ from __future__ import print_function import os import shutil import tempfile import six import pytest from ipatests.i18n import create_po, po_file_iterate from ipalib.request import context from ipalib import text if six.PY3: unicode = str pytestmark = pytest.mark.tier0 singular = '%(count)d goose makes a %(dish)s' plural = '%(count)d geese make a %(dish)s' def test_create_translation(): f = text.create_translation key = ('foo', None) t = f(key) assert context.__dict__[key] is t class test_TestLang: lang_env_vars = {'LC_ALL', 'LC_MESSAGES', 'LANGUAGE', 'LANG'} def setup_lang(self): """ Set all env variables used by gettext to localize translation files to xh_ZA """ self.lang = 'xh_ZA' self.saved_locale = { k: v for k, v in os.environ.items() if k in self.lang_env_vars} os.environ.update( {env_var: self.lang for env_var in self.lang_env_vars} ) def teardown_lang(self): """ Revert the locale settings to original values. If the original env variable was not set before, it will be popped off os.environ """ for env_var in self.lang_env_vars: if env_var not in self.saved_locale: os.environ.pop(env_var, None) os.environ.update(self.saved_locale) @pytest.fixture(autouse=True) def testlang_setup(self, request): self.tmp_dir = None self.setup_lang() self.domain = 'ipa' self.pot_basename = '%s.pot' % self.domain self.po_basename = '%s.po' % self.lang self.mo_basename = '%s.mo' % self.domain self.tmp_dir = tempfile.mkdtemp() self.locale_dir = os.path.join(self.tmp_dir, 'test_locale') self.msg_dir = os.path.join(self.locale_dir, self.lang, 'LC_MESSAGES') if not os.path.exists(self.msg_dir): os.makedirs(self.msg_dir) self.pot_file = os.path.join( os.path.dirname(__file__), 'data', self.pot_basename) self.mo_file = os.path.join(self.msg_dir, self.mo_basename) self.po_file = os.path.join(self.tmp_dir, self.po_basename) result = create_po(self.pot_file, self.po_file, self.mo_file) if result: pytest.skip( 'Unable to create po file "%s" & mo file "%s" from pot ' 'file "%s"' % (self.po_file, self.mo_file, self.pot_file) ) if not os.path.isfile(self.po_file): pytest.skip( 'Test po file unavailable: {}'.format(self.po_file)) if not os.path.isfile(self.mo_file): pytest.skip( 'Test mo file unavailable: {}'.format(self.mo_file)) self.po_file_iterate = po_file_iterate def fin(): self.teardown_lang() if self.tmp_dir is not None: shutil.rmtree(self.tmp_dir) request.addfinalizer(fin) def test_test_lang(self): print("test_test_lang") # The test installs the test message catalog under the xh_ZA # (e.g. Zambia Xhosa) language by default. It would be nice to # use a dummy language not associated with any real language, # but the setlocale function demands the locale be a valid # known locale, Zambia Xhosa is a reasonable choice :) # Create a gettext translation object specifying our domain as # 'ipa' and the locale_dir as 'test_locale' (i.e. where to # look for the message catalog). Then use that translation # object to obtain the translation functions. def get_msgstr(msg): gt = text.GettextFactory(localedir=self.locale_dir)(msg) return unicode(gt) def get_msgstr_plural(singular, plural, count): ng = text.NGettextFactory(localedir=self.locale_dir)(singular, plural, count) return ng(count) result = self.po_file_iterate(self.po_file, get_msgstr, get_msgstr_plural) assert result == 0 class test_LazyText: klass = text.LazyText def test_init(self): inst = self.klass('foo', 'bar') assert inst.domain == 'foo' assert inst.localedir == 'bar' assert inst.key == ('foo', 'bar') class test_FixMe: klass = text.FixMe def test_init(self): inst = self.klass('user.label') assert inst.msg == 'user.label' assert inst.domain is None assert inst.localedir is None def test_repr(self): inst = self.klass('user.label') assert repr(inst) == "FixMe('user.label')" def test_unicode(self): inst = self.klass('user.label') assert unicode(inst) == u'<user.label>' assert type(unicode(inst)) is unicode class test_Gettext: klass = text.Gettext def test_init(self): inst = self.klass('what up?', 'foo', 'bar') assert inst.domain == 'foo' assert inst.localedir == 'bar' assert inst.msg == 'what up?' assert inst.args == ('what up?', 'foo', 'bar') def test_repr(self): inst = self.klass('foo', 'bar', 'baz') assert repr(inst) == "Gettext('foo', domain='bar', localedir='baz')" def test_unicode(self): inst = self.klass('what up?', 'foo', 'bar') assert unicode(inst) == u'what up?' def test_mod(self): inst = self.klass('hello %(adj)s nurse', 'foo', 'bar') assert inst % dict(adj='tall', stuff='junk') == 'hello tall nurse' def test_format(self): inst = self.klass('{0} {adj} nurse', 'foo', 'bar') posargs = ('hello', 'bye') knownargs = {'adj': 'caring', 'stuff': 'junk'} assert inst.format(*posargs, **knownargs) == 'hello caring nurse' def test_eq(self): inst1 = self.klass('what up?', 'foo', 'bar') inst2 = self.klass('what up?', 'foo', 'bar') inst3 = self.klass('Hello world', 'foo', 'bar') inst4 = self.klass('what up?', 'foo', 'baz') # pylint: disable=comparison-with-itself assert (inst1 == inst1) is True assert (inst1 == inst2) is True assert (inst1 == inst3) is False assert (inst1 == inst4) is False # Test with args flipped assert (inst2 == inst1) is True assert (inst3 == inst1) is False assert (inst4 == inst1) is False def test_ne(self): inst1 = self.klass('what up?', 'foo', 'bar') inst2 = self.klass('what up?', 'foo', 'bar') inst3 = self.klass('Hello world', 'foo', 'bar') inst4 = self.klass('what up?', 'foo', 'baz') assert (inst1 != inst2) is False assert (inst1 != inst2) is False assert (inst1 != inst3) is True assert (inst1 != inst4) is True # Test with args flipped assert (inst2 != inst1) is False assert (inst3 != inst1) is True assert (inst4 != inst1) is True class test_NGettext: klass = text.NGettext def test_init(self): inst = self.klass(singular, plural, 'foo', 'bar') assert inst.singular is singular assert inst.plural is plural assert inst.domain == 'foo' assert inst.localedir == 'bar' assert inst.args == (singular, plural, 'foo', 'bar') def test_repr(self): inst = self.klass('sig', 'plu', 'foo', 'bar') assert repr(inst) == \ "NGettext('sig', 'plu', domain='foo', localedir='bar')" def test_call(self): inst = self.klass(singular, plural, 'foo', 'bar') assert inst(0) == plural assert inst(1) == singular assert inst(2) == plural assert inst(3) == plural def test_mod(self): inst = self.klass(singular, plural, 'foo', 'bar') assert inst % dict(count=0, dish='frown') == '0 geese make a frown' assert inst % dict(count=1, dish='stew') == '1 goose makes a stew' assert inst % dict(count=2, dish='pie') == '2 geese make a pie' def test_format(self): singular = '{count} goose makes a {0} {dish}' plural = '{count} geese make a {0} {dish}' inst = self.klass(singular, plural, 'foo', 'bar') posargs = ('tasty', 'disgusting') knownargs0 = {'count': 0, 'dish': 'frown', 'stuff': 'junk'} knownargs1 = {'count': 1, 'dish': 'stew', 'stuff': 'junk'} knownargs2 = {'count': 2, 'dish': 'pie', 'stuff': 'junk'} expected_str0 = '0 geese make a tasty frown' expected_str1 = '1 goose makes a tasty stew' expected_str2 = '2 geese make a tasty pie' assert inst.format(*posargs, **knownargs0) == expected_str0 assert inst.format(*posargs, **knownargs1) == expected_str1 assert inst.format(*posargs, **knownargs2) == expected_str2 def test_eq(self): inst1 = self.klass(singular, plural, 'foo', 'bar') inst2 = self.klass(singular, plural, 'foo', 'bar') inst3 = self.klass(singular, '%(count)d thingies', 'foo', 'bar') inst4 = self.klass(singular, plural, 'foo', 'baz') # pylint: disable=comparison-with-itself assert (inst1 == inst1) is True assert (inst1 == inst2) is True assert (inst1 == inst3) is False assert (inst1 == inst4) is False # Test with args flipped assert (inst2 == inst1) is True assert (inst3 == inst1) is False assert (inst4 == inst1) is False def test_ne(self): inst1 = self.klass(singular, plural, 'foo', 'bar') inst2 = self.klass(singular, plural, 'foo', 'bar') inst3 = self.klass(singular, '%(count)d thingies', 'foo', 'bar') inst4 = self.klass(singular, plural, 'foo', 'baz') assert (inst1 != inst2) is False assert (inst1 != inst2) is False assert (inst1 != inst3) is True assert (inst1 != inst4) is True # Test with args flipped assert (inst2 != inst1) is False assert (inst3 != inst1) is True assert (inst4 != inst1) is True class test_GettextFactory: klass = text.GettextFactory def test_init(self): # Test with defaults: inst = self.klass() assert inst.domain == 'ipa' assert inst.localedir is None # Test with overrides: inst = self.klass('foo', 'bar') assert inst.domain == 'foo' assert inst.localedir == 'bar' def test_repr(self): # Test with defaults: inst = self.klass() assert repr(inst) == "GettextFactory(domain='ipa', localedir=None)" # Test with overrides: inst = self.klass('foo', 'bar') assert repr(inst) == "GettextFactory(domain='foo', localedir='bar')" def test_call(self): inst = self.klass('foo', 'bar') g = inst('what up?') assert type(g) is text.Gettext assert g.msg == 'what up?' assert g.domain == 'foo' assert g.localedir == 'bar' class test_NGettextFactory: klass = text.NGettextFactory def test_init(self): # Test with defaults: inst = self.klass() assert inst.domain == 'ipa' assert inst.localedir is None # Test with overrides: inst = self.klass('foo', 'bar') assert inst.domain == 'foo' assert inst.localedir == 'bar' def test_repr(self): # Test with defaults: inst = self.klass() assert repr(inst) == "NGettextFactory(domain='ipa', localedir=None)" # Test with overrides: inst = self.klass('foo', 'bar') assert repr(inst) == "NGettextFactory(domain='foo', localedir='bar')" def test_call(self): inst = self.klass('foo', 'bar') ng = inst(singular, plural, 7) assert type(ng) is text.NGettext assert ng.singular is singular assert ng.plural is plural assert ng.domain == 'foo' assert ng.localedir == 'bar' class test_ConcatenatedText: klass = text.ConcatenatedLazyText def test_init(self): lst = ['a', 'b', 'c', 3] inst = self.klass(*lst) assert inst.components == lst assert unicode(inst) == 'abc3' def test_repr(self): lazytext = text.Gettext('foo', 'bar', 'baz') inst = self.klass(lazytext) assert repr(inst) == "ConcatenatedLazyText([%r])" % lazytext def test_unicode(self): inst = self.klass('[', text.Gettext('green', 'foo', 'bar'), 1, ']') assert unicode(inst) == u'[green1]' def test_mod(self): inst = self.klass('[', text.Gettext('%(color)s', 'foo', 'bar'), ']') assert inst % dict(color='red', stuff='junk') == '[red]' def test_format(self): inst = self.klass('{0}', text.Gettext('{color}', 'foo', 'bar'), ']') posargs = ('[', '(') knownargs = {'color': 'red', 'stuff': 'junk'} assert inst.format(*posargs, **knownargs) == '[red]' def test_add(self): inst = (text.Gettext('pale ', 'foo', 'bar') + text.Gettext('blue', 'foo', 'bar')) assert unicode(inst) == 'pale blue' inst = (text.Gettext('bright ', 'foo', 'bar') + text.Gettext('pale ', 'foo', 'bar') + text.Gettext('blue', 'foo', 'bar')) assert unicode(inst) == 'bright pale blue' inst = text.Gettext('yellow', 'foo', 'bar') + '!' assert unicode(inst) == 'yellow!' inst = '!' + text.Gettext('yellow', 'foo', 'bar') assert unicode(inst) == '!yellow' inst = '!' + ('!' + text.Gettext('yellow', 'foo', 'bar')) assert unicode(inst) == '!!yellow' inst = (text.Gettext('yellow', 'foo', 'bar') + '!') + '!' assert unicode(inst) == 'yellow!!'
14,513
Python
.py
340
34.564706
89
0.594016
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,528
test_base.py
freeipa_freeipa/ipatests/test_ipalib/test_base.py
# Authors: # Jason Gerard DeRose <jderose@redhat.com> # # Copyright (C) 2008 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ Test the `ipalib.base` module. """ import six import pytest from ipatests.util import ClassChecker, raises from ipalib.constants import NAME_REGEX, NAME_ERROR from ipalib.constants import TYPE_ERROR, SET_ERROR, DEL_ERROR, OVERRIDE_ERROR from ipalib import base if six.PY3: unicode = str pytestmark = pytest.mark.tier0 class test_ReadOnly(ClassChecker): """ Test the `ipalib.base.ReadOnly` class """ _cls = base.ReadOnly def test_lock(self): """ Test the `ipalib.base.ReadOnly.__lock__` method. """ o = self.cls() assert o._ReadOnly__locked is False o.__lock__() assert o._ReadOnly__locked is True e = raises(AssertionError, o.__lock__) # Can only be locked once assert str(e) == '__lock__() can only be called once' assert o._ReadOnly__locked is True # This should still be True def test_islocked(self): """ Test the `ipalib.base.ReadOnly.__islocked__` method. """ o = self.cls() assert o.__islocked__() is False o.__lock__() assert o.__islocked__() is True def test_setattr(self): """ Test the `ipalib.base.ReadOnly.__setattr__` method. """ o = self.cls() o.attr1 = 'Hello, world!' assert o.attr1 == 'Hello, world!' o.__lock__() for name in ('attr1', 'attr2'): e = raises(AttributeError, setattr, o, name, 'whatever') assert str(e) == SET_ERROR % ('ReadOnly', name, 'whatever') assert o.attr1 == 'Hello, world!' def test_delattr(self): """ Test the `ipalib.base.ReadOnly.__delattr__` method. """ o = self.cls() o.attr1 = 'Hello, world!' o.attr2 = 'How are you?' assert o.attr1 == 'Hello, world!' assert o.attr2 == 'How are you?' del o.attr1 assert not hasattr(o, 'attr1') o.__lock__() e = raises(AttributeError, delattr, o, 'attr2') assert str(e) == DEL_ERROR % ('ReadOnly', 'attr2') assert o.attr2 == 'How are you?' def test_lock(): """ Test the `ipalib.base.lock` function """ f = base.lock # Test with ReadOnly instance: o = base.ReadOnly() assert o.__islocked__() is False assert f(o) is o assert o.__islocked__() is True e = raises(AssertionError, f, o) assert str(e) == 'already locked: %r' % o # Test with another class implemented locking protocol: class Lockable: __locked = False def __lock__(self): self.__locked = True def __islocked__(self): return self.__locked o = Lockable() assert o.__islocked__() is False assert f(o) is o assert o.__islocked__() is True e = raises(AssertionError, f, o) assert str(e) == 'already locked: %r' % o # Test with a class incorrectly implementing the locking protocol: class Broken: def __lock__(self): pass def __islocked__(self): return False o = Broken() e = raises(AssertionError, f, o) assert str(e) == 'failed to lock: %r' % o def test_islocked(): """ Test the `ipalib.base.islocked` function. """ f = base.islocked # Test with ReadOnly instance: o = base.ReadOnly() assert f(o) is False o.__lock__() assert f(o) is True # Test with another class implemented locking protocol: class Lockable: __locked = False def __lock__(self): self.__locked = True def __islocked__(self): return self.__locked o = Lockable() assert f(o) is False o.__lock__() assert f(o) is True # Test with a class incorrectly implementing the locking protocol: class Broken: __lock__ = False def __islocked__(self): return False o = Broken() e = raises(AssertionError, f, o) assert str(e) == 'no __lock__() method: %r' % o def test_check_name(): """ Test the `ipalib.base.check_name` function. """ f = base.check_name okay = [ 'user_add', 'stuff2junk', 'sixty9', ] nope = [ '_user_add', '__user_add', 'user_add_', 'user_add__', '_user_add_', '__user_add__', '60nine', ] for name in okay: assert name is f(name) if six.PY2: bad_type = unicode bad_value = unicode(name) else: bad_type = bytes bad_value = name.encode('ascii') e = raises(TypeError, f, bad_value) assert str(e) == TYPE_ERROR % ('name', str, bad_value, bad_type) for name in nope: e = raises(ValueError, f, name) assert str(e) == NAME_ERROR % (NAME_REGEX, name) for name in okay: e = raises(ValueError, f, name.upper()) assert str(e) == NAME_ERROR % (NAME_REGEX, name.upper()) def membername(i): return 'member%03d' % i class DummyMember: def __init__(self, i): self.i = i self.name = self.__name__ = membername(i) def gen_members(*indexes): return tuple(DummyMember(i) for i in indexes) class test_NameSpace(ClassChecker): """ Test the `ipalib.base.NameSpace` class. """ _cls = base.NameSpace def new(self, count, sort=True): members = tuple(DummyMember(i) for i in range(count, 0, -1)) assert len(members) == count o = self.cls(members, sort=sort) return (o, members) def test_init(self): """ Test the `ipalib.base.NameSpace.__init__` method. """ o = self.cls([]) assert len(o) == 0 assert list(o) == [] assert list(o()) == [] # Test members as attribute and item: for cnt in (3, 42): for sort in (True, False): (o, members) = self.new(cnt, sort=sort) assert len(members) == cnt for m in members: assert getattr(o, m.name) is m assert o[m.name] is m # Test that TypeError is raised if sort is not a bool: e = raises(TypeError, self.cls, [], sort=None) assert str(e) == TYPE_ERROR % ('sort', bool, None, type(None)) # Test that AttributeError is raised with duplicate member name: members = gen_members(0, 1, 2, 1, 3) e = raises(AttributeError, self.cls, members) assert str(e) == OVERRIDE_ERROR % ( 'NameSpace', membername(1), members[1], members[3] ) def test_len(self): """ Test the `ipalib.base.NameSpace.__len__` method. """ for count in (5, 18, 127): o, _members = self.new(count) assert len(o) == count o, _members = self.new(count, sort=False) assert len(o) == count def test_iter(self): """ Test the `ipalib.base.NameSpace.__iter__` method. """ (o, members) = self.new(25) assert list(o) == sorted(m.name for m in members) (o, members) = self.new(25, sort=False) assert list(o) == list(m.name for m in members) def test_call(self): """ Test the `ipalib.base.NameSpace.__call__` method. """ (o, members) = self.new(25) assert list(o()) == sorted(members, key=lambda m: m.name) (o, members) = self.new(25, sort=False) assert tuple(o()) == members def test_contains(self): """ Test the `ipalib.base.NameSpace.__contains__` method. """ yes = (99, 3, 777) no = (9, 333, 77) for sort in (True, False): members = gen_members(*yes) o = self.cls(members, sort=sort) for i in yes: assert membername(i) in o assert membername(i).upper() not in o assert DummyMember(i) in o for i in no: assert membername(i) not in o assert DummyMember(i) not in o def test_getitem(self): """ Test the `ipalib.base.NameSpace.__getitem__` method. """ cnt = 17 for sort in (True, False): (o, members) = self.new(cnt, sort=sort) assert len(members) == cnt if sort is True: members = tuple(sorted(members, key=lambda m: m.name)) # Test str keys: for m in members: assert o[m.name] is m e = raises(KeyError, o.__getitem__, 'nope') # Test int indexes: for i in range(cnt): assert o[i] is members[i] e = raises(IndexError, o.__getitem__, cnt) # Test negative int indexes: for i in range(1, cnt + 1): assert o[-i] is members[-i] e = raises(IndexError, o.__getitem__, -(cnt + 1)) # Test slicing: assert o[3:] == members[3:] assert o[:10] == members[:10] assert o[3:10] == members[3:10] assert o[-9:] == members[-9:] assert o[:-4] == members[:-4] assert o[-9:-4] == members[-9:-4] # Test retrieval by value for member in members: assert o[DummyMember(member.i)] is member # Test that TypeError is raised with wrong type e = raises(TypeError, o.__getitem__, 3.0) assert str(e) == TYPE_ERROR % ( 'key', (str, int, slice, 'object with __name__'), 3.0, float) def test_repr(self): """ Test the `ipalib.base.NameSpace.__repr__` method. """ for cnt in (0, 1, 2): for sort in (True, False): o, _members = self.new(cnt, sort=sort) if cnt == 1: assert repr(o) == \ 'NameSpace(<%d member>, sort=%r)' % (cnt, sort) else: assert repr(o) == \ 'NameSpace(<%d members>, sort=%r)' % (cnt, sort) def test_todict(self): """ Test the `ipalib.base.NameSpace.__todict__` method. """ for cnt in (3, 101): for sort in (True, False): (o, members) = self.new(cnt, sort=sort) d = o.__todict__() assert d == dict((m.name, m) for m in members) # Test that a copy is returned: assert o.__todict__() is not d
11,305
Python
.py
324
26.216049
77
0.545014
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,529
__init__.py
freeipa_freeipa/ipatests/test_ipalib/__init__.py
# Authors: # Jason Gerard DeRose <jderose@redhat.com> # # Copyright (C) 2008 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ Sub-package containing unit tests for `ipalib` package. """
843
Python
.py
21
39.095238
71
0.771011
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,530
test_crud.py
freeipa_freeipa/ipatests/test_ipalib/test_crud.py
# Authors: # Jason Gerard DeRose <jderose@redhat.com> # # Copyright (C) 2008 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ Test the `ipalib.crud` module. """ from ipatests.util import raises, get_api, ClassChecker from ipalib import crud, frontend from ipalib.parameters import Str import pytest pytestmark = pytest.mark.tier0 class CrudChecker(ClassChecker): """ Class for testing base classes in `ipalib.crud`. """ def get_api(self, args=tuple(), options=tuple()): """ Return a finalized `ipalib.plugable.API` instance. """ api, _home = get_api() class user(frontend.Object): takes_params = ( 'givenname', Str('sn', flags='no_update'), Str('uid', primary_key=True), 'initials', Str('uidnumber', flags=['no_create', 'no_search']) ) class user_verb(self.cls): takes_args = args takes_options = options api.add_plugin(user) api.add_plugin(user_verb) api.finalize() return api class test_Create(CrudChecker): """ Test the `ipalib.crud.Create` class. """ _cls = crud.Create def test_get_args(self): """ Test the `ipalib.crud.Create.get_args` method. """ api = self.get_api() assert list(api.Method.user_verb.args) == ['uid'] assert api.Method.user_verb.args.uid.required is True def test_get_options(self): """ Test the `ipalib.crud.Create.get_options` method. """ api = self.get_api() assert list(api.Method.user_verb.options) == \ ['givenname', 'sn', 'initials', 'all', 'raw', 'version'] for param in api.Method.user_verb.options(): if param.name != 'version': assert param.required is True api = self.get_api(options=(Str('extra?'),)) assert list(api.Method.user_verb.options) == \ ['givenname', 'sn', 'initials', 'extra', 'all', 'raw', 'version'] assert api.Method.user_verb.options.extra.required is False class test_Update(CrudChecker): """ Test the `ipalib.crud.Update` class. """ _cls = crud.Update def test_get_args(self): """ Test the `ipalib.crud.Update.get_args` method. """ api = self.get_api() assert list(api.Method.user_verb.args) == ['uid'] assert api.Method.user_verb.args.uid.required is True def test_get_options(self): """ Test the `ipalib.crud.Update.get_options` method. """ api = self.get_api() assert list(api.Method.user_verb.options) == \ ['givenname', 'initials', 'uidnumber', 'all', 'raw', 'version'] for param in api.Method.user_verb.options(): if param.name in ['all', 'raw']: assert param.required is True else: assert param.required is False class test_Retrieve(CrudChecker): """ Test the `ipalib.crud.Retrieve` class. """ _cls = crud.Retrieve def test_get_args(self): """ Test the `ipalib.crud.Retrieve.get_args` method. """ api = self.get_api() assert list(api.Method.user_verb.args) == ['uid'] assert api.Method.user_verb.args.uid.required is True def test_get_options(self): """ Test the `ipalib.crud.Retrieve.get_options` method. """ api = self.get_api() assert list(api.Method.user_verb.options) == ['all', 'raw', 'version'] class test_Delete(CrudChecker): """ Test the `ipalib.crud.Delete` class. """ _cls = crud.Delete def test_get_args(self): """ Test the `ipalib.crud.Delete.get_args` method. """ api = self.get_api() assert list(api.Method.user_verb.args) == ['uid'] assert api.Method.user_verb.args.uid.required is True def test_get_options(self): """ Test the `ipalib.crud.Delete.get_options` method. """ api = self.get_api() assert list(api.Method.user_verb.options) == ['version'] assert len(api.Method.user_verb.options) == 1 class test_Search(CrudChecker): """ Test the `ipalib.crud.Search` class. """ _cls = crud.Search def test_get_args(self): """ Test the `ipalib.crud.Search.get_args` method. """ api = self.get_api() assert list(api.Method.user_verb.args) == ['criteria'] assert api.Method.user_verb.args.criteria.required is False def test_get_options(self): """ Test the `ipalib.crud.Search.get_options` method. """ api = self.get_api() assert list(api.Method.user_verb.options) == \ ['givenname', 'sn', 'uid', 'initials', 'all', 'raw', 'version'] for param in api.Method.user_verb.options(): if param.name in ['all', 'raw']: assert param.required is True else: assert param.required is False class test_CrudBackend(ClassChecker): """ Test the `ipalib.crud.CrudBackend` class. """ _cls = crud.CrudBackend def get_subcls(self): class ldap(self.cls): pass return ldap def check_method(self, name, *args): api = 'the api instance' o = self.cls(api) e = raises(NotImplementedError, getattr(o, name), *args) assert str(e) == 'CrudBackend.%s()' % name sub = self.subcls(api) e = raises(NotImplementedError, getattr(sub, name), *args) assert str(e) == 'ldap.%s()' % name def test_create(self): """ Test the `ipalib.crud.CrudBackend.create` method. """ self.check_method('create') def test_retrieve(self): """ Test the `ipalib.crud.CrudBackend.retrieve` method. """ self.check_method('retrieve', 'primary key', 'attribute') def test_update(self): """ Test the `ipalib.crud.CrudBackend.update` method. """ self.check_method('update', 'primary key') def test_delete(self): """ Test the `ipalib.crud.CrudBackend.delete` method. """ self.check_method('delete', 'primary key') def test_search(self): """ Test the `ipalib.crud.CrudBackend.search` method. """ self.check_method('search')
7,143
Python
.py
203
27.502463
78
0.596898
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,531
test_parameters.py
freeipa_freeipa/ipatests/test_ipalib/test_parameters.py
# -*- coding: utf-8 -*- # Authors: # Jason Gerard DeRose <jderose@redhat.com> # # Copyright (C) 2008 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ Test the `ipalib.parameters` module. """ # FIXME: Pylint errors # pylint: disable=no-member import base64 import datetime import re import sys from decimal import Decimal from inspect import isclass from xmlrpc.client import MAXINT, MININT import pytest import six from cryptography import x509 as crypto_x509 from cryptography.hazmat.backends import default_backend from ipatests.util import raises, ClassChecker, read_only from ipatests.util import dummy_ugettext, assert_equal from ipatests.data import binary_bytes, utf8_bytes, unicode_str from ipalib import parameters, text, errors, config, x509 from ipalib.constants import TYPE_ERROR, CALLABLE_ERROR from ipalib.errors import ValidationError, ConversionError from ipalib import _ from ipapython.dn import DN if six.PY3: unicode = str long = int NULLS = (None, b'', u'', tuple(), []) pytestmark = pytest.mark.tier0 class test_DefaultFrom(ClassChecker): """ Test the `ipalib.parameters.DefaultFrom` class. """ _cls = parameters.DefaultFrom def test_init(self): """ Test the `ipalib.parameters.DefaultFrom.__init__` method. """ def callback(*args): return args keys = ('givenname', 'sn') o = self.cls(callback, *keys) assert read_only(o, 'callback') is callback assert read_only(o, 'keys') == keys o = self.cls(lambda first, last: first[0] + last) assert read_only(o, 'keys') == ('first', 'last') # Test that TypeError is raised when callback isn't callable: e = raises(TypeError, self.cls, 'whatever') assert str(e) == CALLABLE_ERROR % ('callback', 'whatever', str) # Test that TypeError is raised when a key isn't an str: e = raises(TypeError, self.cls, callback, 'givenname', 17) assert str(e) == TYPE_ERROR % ('keys', str, 17, int) # Test that ValueError is raised when inferring keys from a callback # which has *args: e = raises(ValueError, self.cls, lambda foo, *args: None) assert str(e) == "callback: variable-length argument list not allowed" # Test that ValueError is raised when inferring keys from a callback # which has **kwargs: e = raises(ValueError, self.cls, lambda foo, **kwargs: None) assert str(e) == "callback: variable-length argument list not allowed" def test_repr(self): """ Test the `ipalib.parameters.DefaultFrom.__repr__` method. """ def stuff(one, two): pass o = self.cls(stuff) assert repr(o) == "DefaultFrom('one', 'two')" o = self.cls(stuff, 'aye', 'bee', 'see') assert repr(o) == "DefaultFrom('aye', 'bee', 'see')" def cb(first, last): return first[0] + last o = self.cls(cb) assert repr(o) == "DefaultFrom('first', 'last')" o = self.cls(cb, 'aye', 'bee', 'see') assert repr(o) == "DefaultFrom('aye', 'bee', 'see')" def test_call(self): """ Test the `ipalib.parameters.DefaultFrom.__call__` method. """ def callback(givenname, sn): return givenname[0] + sn[0] keys = ('givenname', 'sn') o = self.cls(callback, *keys) kw = dict( givenname='John', sn='Public', hello='world', ) assert o(**kw) == 'JP' assert o() is None for key in ('givenname', 'sn'): kw_copy = dict(kw) del kw_copy[key] assert o(**kw_copy) is None # Test using implied keys: o = self.cls(lambda first, last: first[0] + last) assert o(first='john', last='doe') == 'jdoe' assert o(first='', last='doe') is None assert o(one='john', two='doe') is None # Test that co_varnames slice is used: def callback2(first, last): letter = first[0] return letter + last o = self.cls(callback2) assert o.keys == ('first', 'last') assert o(first='john', last='doe') == 'jdoe' def test_parse_param_spec(): """ Test the `ipalib.parameters.parse_param_spec` function. """ f = parameters.parse_param_spec assert f('name') == ('name', dict(required=True, multivalue=False)) assert f('name?') == ('name', dict(required=False, multivalue=False)) assert f('name*') == ('name', dict(required=False, multivalue=True)) assert f('name+') == ('name', dict(required=True, multivalue=True)) # Make sure other "funny" endings are *not* treated special: assert f('name^') == ('name^', dict(required=True, multivalue=False)) # Test that TypeError is raised if spec isn't an str: if six.PY2: bad_value = u'name?' else: bad_value = b'name?' e = raises(TypeError, f, bad_value) assert str(e) == TYPE_ERROR % ('spec', str, bad_value, type(bad_value)) class DummyRule: def __init__(self, error=None): assert error is None or type(error) is unicode self.error = error self.reset() def __call__(self, *args): self.calls.append(args) return self.error def reset(self): self.calls = [] class test_Param(ClassChecker): """ Test the `ipalib.parameters.Param` class. """ _cls = parameters.Param def test_init(self): """ Test the `ipalib.parameters.Param.__init__` method. """ name = 'my_param' o = self.cls(name) assert o.param_spec is name assert o.name is name assert o.nice == "Param('my_param')" assert o.password is False assert o.__islocked__() is True # Test default rules: assert o.rules == tuple() assert o.class_rules == tuple() assert o.all_rules == tuple() # Test default kwarg values: assert o.cli_name is name assert o.label.msg == 'my_param' assert o.doc.msg == 'my_param' assert o.required is True assert o.multivalue is False assert o.primary_key is False assert o.normalizer is None assert o.default is None assert o.default_from is None assert o.autofill is False assert o.query is False assert o.attribute is False assert o.include is None assert o.exclude is None assert o.flags == frozenset() assert o.sortorder == 2 # Test that doc defaults from label: o = self.cls('my_param', doc=_('Hello world')) assert o.label.msg == 'my_param' assert o.doc.msg == 'Hello world' o = self.cls('my_param', label='My Param') assert o.label == 'My Param' assert o.doc == 'My Param' # Test that ValueError is raised when a kwarg from a subclass # conflicts with an attribute: class Subclass1(self.cls): kwargs = self.cls.kwargs + ( ('convert', callable, None), ) e = raises(ValueError, Subclass1, name) assert str(e) == "kwarg 'convert' conflicts with attribute on Subclass1" # Test type validation of keyword arguments: class Subclass(self.cls): kwargs = self.cls.kwargs + ( ('extra1', bool, True), ('extra2', str, 'Hello'), ('extra3', (int, float), 42), ('extra4', callable, lambda whatever: whatever + 7), ) o = Subclass('my_param') # Test with no **kw: for key, kind, _default in o.kwargs: # Test with a type invalid for all: value = object() kw = {key: value} e = raises(TypeError, Subclass, 'my_param', **kw) if kind is callable: assert str(e) == CALLABLE_ERROR % (key, value, type(value)) else: assert str(e) == TYPE_ERROR % (key, kind, value, type(value)) # Test with None: kw = {key: None} Subclass('my_param', **kw) # Test when using unknown kwargs: e = raises(TypeError, self.cls, 'my_param', flags=['hello', 'world'], whatever=u'Hooray!', ) assert str(e) == \ "Param('my_param'): takes no such kwargs: 'whatever'" e = raises(TypeError, self.cls, 'my_param', great='Yes', ape='he is!') assert str(e) == \ "Param('my_param'): takes no such kwargs: 'ape', 'great'" # Test that ValueError is raised if you provide both include and # exclude: e = raises(ValueError, self.cls, 'my_param', include=['server', 'foo'], exclude=['client', 'bar'], ) assert str(e) == '%s: cannot have both %s=%r and %s=%r' % ( "Param('my_param')", 'include', frozenset(['server', 'foo']), 'exclude', frozenset(['client', 'bar']), ) # Test that default_from gets set: def call(first, last): return first[0] + last o = self.cls('my_param', default_from=call) assert type(o.default_from) is parameters.DefaultFrom assert o.default_from.callback is call def test_repr(self): """ Test the `ipalib.parameters.Param.__repr__` method. """ for name in ['name', 'name?', 'name*', 'name+']: o = self.cls(name) assert repr(o) == 'Param(%r)' % name o = self.cls('name', required=False) assert repr(o) == "Param('name?')" o = self.cls('name', multivalue=True) assert repr(o) == "Param('name+')" def test_use_in_context(self): """ Test the `ipalib.parameters.Param.use_in_context` method. """ set1 = ('one', 'two', 'three') set2 = ('four', 'five', 'six') param1 = self.cls('param1') param2 = self.cls('param2', include=set1) param3 = self.cls('param3', exclude=set2) for context in set1: env = config.Env() env.context = context assert param1.use_in_context(env) is True, context assert param2.use_in_context(env) is True, context assert param3.use_in_context(env) is True, context for context in set2: env = config.Env() env.context = context assert param1.use_in_context(env) is True, context assert param2.use_in_context(env) is False, context assert param3.use_in_context(env) is False, context def test_safe_value(self): """ Test the `ipalib.parameters.Param.safe_value` method. """ values = (unicode_str, binary_bytes, utf8_bytes) o = self.cls('my_param') for value in values: assert o.safe_value(value) is value assert o.safe_value(None) is None p = parameters.Password('my_passwd') for value in values: assert_equal(p.safe_value(value), u'********') assert p.safe_value(None) is None def test_password_whitespaces(self): values = ('Secret123', ' Secret123', 'Secret123 ', ' Secret123 ',) p = parameters.Password('my_passwd') for value in values: assert(p.validate(value)) is None def test_clone(self): """ Test the `ipalib.parameters.Param.clone` method. """ # Test with the defaults orig = self.cls('my_param') clone = orig.clone() assert clone is not orig assert type(clone) is self.cls assert clone.name is orig.name for key, _kind, _default in self.cls.kwargs: assert getattr(clone, key) == getattr(orig, key) # Test with a param spec: orig = self.cls('my_param*') assert orig.param_spec == 'my_param*' clone = orig.clone() assert clone.param_spec == 'my_param*' assert clone is not orig assert type(clone) is self.cls for key, _kind, _default in self.cls.kwargs: assert getattr(clone, key) == getattr(orig, key) # Test with overrides: orig = self.cls('my_param*') assert orig.required is False assert orig.multivalue is True clone = orig.clone(required=True) assert clone is not orig assert type(clone) is self.cls assert clone.required is True assert clone.multivalue is True assert clone.param_spec == 'my_param+' assert clone.name == 'my_param' def test_clone_rename(self): """ Test the `ipalib.parameters.Param.clone` method. """ new_name = 'my_new_param' # Test with the defaults orig = self.cls('my_param') clone = orig.clone_rename(new_name) assert clone is not orig assert type(clone) is self.cls assert clone.name == new_name for key, _kind, _default in self.cls.kwargs: if key in ('cli_name', 'label', 'doc', 'cli_metavar'): continue assert getattr(clone, key) is getattr(orig, key) # Test with overrides: orig = self.cls('my_param*') assert orig.required is False assert orig.multivalue is True clone = orig.clone_rename(new_name, required=True) assert clone is not orig assert type(clone) is self.cls assert clone.required is True assert clone.multivalue is True assert clone.param_spec == "{0}+".format(new_name) assert clone.name == new_name def test_convert(self): """ Test the `ipalib.parameters.Param.convert` method. """ okay = ('Hello', u'Hello', 0, 4.2, True, False, unicode_str) class Subclass(self.cls): def _convert_scalar(self, value, index=None): return value # Test when multivalue=False: o = Subclass('my_param') for value in NULLS: assert o.convert(value) is None assert o.convert(None) is None for value in okay: assert o.convert(value) is value # Test when multivalue=True: o = Subclass('my_param', multivalue=True) for value in NULLS: assert o.convert(value) is None assert o.convert(okay) == okay assert o.convert(NULLS) is None assert o.convert(okay + NULLS) == okay assert o.convert(NULLS + okay) == okay for value in okay: assert o.convert(value) == (value,) assert o.convert([None, value]) == (value,) assert o.convert([value, None]) == (value,) def test_convert_scalar(self): """ Test the `ipalib.parameters.Param._convert_scalar` method. """ dummy = dummy_ugettext() # Test with correct type: o = self.cls('my_param') assert o._convert_scalar(None) is None assert dummy.called() is False # Test with incorrect type raises(errors.ConversionError, o._convert_scalar, 'hello') def test_validate(self): """ Test the `ipalib.parameters.Param.validate` method. """ # Test in default state (with no rules, no kwarg): o = self.cls('my_param') e = raises(errors.RequirementError, o.validate, None) assert e.name == 'my_param' # Test with required=False o = self.cls('my_param', required=False) assert o.required is False assert o.validate(None) is None # Test with query=True: o = self.cls('my_param', query=True) assert o.query is True e = raises(errors.RequirementError, o.validate, None) assert_equal(e.name, u'my_param') # Test with multivalue=True: o = self.cls('my_param', multivalue=True) e = raises(TypeError, o.validate, []) assert str(e) == TYPE_ERROR % ('value', tuple, [], list) e = raises(ValueError, o.validate, tuple()) assert str(e) == 'value: empty tuple must be converted to None' # Test with wrong (scalar) type: e = raises(TypeError, o.validate, (None, None, 42, None)) assert str(e) == TYPE_ERROR % ('my_param', type(None), 42, int) o = self.cls('my_param') e = raises(TypeError, o.validate, 'Hello') assert str(e) == TYPE_ERROR % ('my_param', type(None), 'Hello', str) class Example(self.cls): type = int # Test with some rules and multivalue=False pass1 = DummyRule() pass2 = DummyRule() fail = DummyRule(u'no good') o = Example('example', pass1, pass2) assert o.multivalue is False assert o.validate(11) is None assert pass1.calls == [(text.ugettext, 11)] assert pass2.calls == [(text.ugettext, 11)] pass1.reset() pass2.reset() o = Example('example', pass1, pass2, fail) e = raises(errors.ValidationError, o.validate, 42) assert e.name == 'example' assert e.error == u'no good' assert pass1.calls == [(text.ugettext, 42)] assert pass2.calls == [(text.ugettext, 42)] assert fail.calls == [(text.ugettext, 42)] # Test with some rules and multivalue=True pass1 = DummyRule() pass2 = DummyRule() fail = DummyRule(u'this one is not good') o = Example('example', pass1, pass2, multivalue=True) assert o.multivalue is True assert o.validate((3, 9)) is None assert pass1.calls == [ (text.ugettext, 3), (text.ugettext, 9), ] assert pass2.calls == [ (text.ugettext, 3), (text.ugettext, 9), ] pass1.reset() pass2.reset() o = Example('multi_example', pass1, pass2, fail, multivalue=True) assert o.multivalue is True e = raises(errors.ValidationError, o.validate, (3, 9)) assert e.name == 'multi_example' assert e.error == u'this one is not good' assert pass1.calls == [(text.ugettext, 3)] assert pass2.calls == [(text.ugettext, 3)] assert fail.calls == [(text.ugettext, 3)] def test_validate_scalar(self): """ Test the `ipalib.parameters.Param._validate_scalar` method. """ class MyParam(self.cls): type = bool okay = DummyRule() o = MyParam('my_param', okay) # Test that TypeError is appropriately raised: e = raises(TypeError, o._validate_scalar, 0) assert str(e) == TYPE_ERROR % ('my_param', bool, 0, int) # Test with passing rule: assert o._validate_scalar(True) is None assert o._validate_scalar(False) is None assert okay.calls == [ (text.ugettext, True), (text.ugettext, False), ] # Test with a failing rule: okay = DummyRule() fail = DummyRule(u'this describes the error') o = MyParam('my_param', okay, fail) e = raises(errors.ValidationError, o._validate_scalar, True) assert e.name == 'my_param' assert e.error == u'this describes the error' e = raises(errors.ValidationError, o._validate_scalar, False) assert e.name == 'my_param' assert e.error == u'this describes the error' assert okay.calls == [ (text.ugettext, True), (text.ugettext, False), ] assert fail.calls == [ (text.ugettext, True), (text.ugettext, False), ] def test_get_default(self): """ Test the `ipalib.parameters.Param.get_default` method. """ class PassThrough: value = None def __call__(self, value): assert self.value is None assert value is not None self.value = value return value def reset(self): assert self.value is not None self.value = None class Str(self.cls): type = unicode def __init__(self, name, **kw): # (Pylint complains because the superclass is unknowm) # pylint: disable=super-on-old-class self._convert_scalar = PassThrough() super(Str, self).__init__(name, **kw) # Test with only a static default: o = Str('my_str', normalizer=PassThrough(), default=u'Static Default', ) assert_equal(o.get_default(), u'Static Default') assert o._convert_scalar.value is None assert o.normalizer.value is None # Test with default_from: o = Str('my_str', normalizer=PassThrough(), default=u'Static Default', default_from=lambda first, last: first[0] + last, ) assert_equal(o.get_default(), u'Static Default') assert o._convert_scalar.value is None assert o.normalizer.value is None default = o.get_default(first=u'john', last='doe') assert_equal(default, u'jdoe') assert o._convert_scalar.value is default assert o.normalizer.value is default class test_Flag(ClassChecker): """ Test the `ipalib.parameters.Flag` class. """ _cls = parameters.Flag def test_init(self): """ Test the `ipalib.parameters.Flag.__init__` method. """ # Test with no kwargs: o = self.cls('my_flag') assert o.type is bool assert isinstance(o, parameters.Bool) assert o.autofill is True assert o.default is False # Test that TypeError is raise if default is not a bool: e = raises(TypeError, self.cls, 'my_flag', default=None) assert str(e) == TYPE_ERROR % ('default', bool, None, type(None)) # Test with autofill=False, default=True o = self.cls('my_flag', autofill=False, default=True) assert o.autofill is True assert o.default is True # Test when cloning: orig = self.cls('my_flag') for clone in [orig.clone(), orig.clone(autofill=False)]: assert clone.autofill is True assert clone.default is False assert clone is not orig assert type(clone) is self.cls # Test when cloning with default=True/False orig = self.cls('my_flag') assert orig.clone().default is False assert orig.clone(default=True).default is True orig = self.cls('my_flag', default=True) assert orig.clone().default is True assert orig.clone(default=False).default is False class test_Data(ClassChecker): """ Test the `ipalib.parameters.Data` class. """ _cls = parameters.Data def test_init(self): """ Test the `ipalib.parameters.Data.__init__` method. """ o = self.cls('my_data') assert o.type is type(None) # noqa assert o.password is False assert o.rules == tuple() assert o.class_rules == tuple() assert o.all_rules == tuple() assert o.minlength is None assert o.maxlength is None assert o.length is None # Test mixing length with minlength or maxlength: o = self.cls('my_data', length=5) assert o.length == 5 permutations = [ dict(minlength=3), dict(maxlength=7), dict(minlength=3, maxlength=7), ] for kw in permutations: o = self.cls('my_data', **kw) for (key, value) in kw.items(): assert getattr(o, key) == value e = raises(ValueError, self.cls, 'my_data', length=5, **kw) assert str(e) == \ "Data('my_data'): cannot mix length with minlength or maxlength" # Test when minlength or maxlength are less than 1: e = raises(ValueError, self.cls, 'my_data', minlength=0) assert str(e) == "Data('my_data'): minlength must be >= 1; got 0" e = raises(ValueError, self.cls, 'my_data', maxlength=0) assert str(e) == "Data('my_data'): maxlength must be >= 1; got 0" # Test when minlength > maxlength: e = raises(ValueError, self.cls, 'my_data', minlength=22, maxlength=15) assert str(e) == \ "Data('my_data'): minlength > maxlength (minlength=22, maxlength=15)" # Test when minlength == maxlength e = raises(ValueError, self.cls, 'my_data', minlength=7, maxlength=7) assert str(e) == \ "Data('my_data'): minlength == maxlength; use length=7 instead" class test_Bytes(ClassChecker): """ Test the `ipalib.parameters.Bytes` class. """ _cls = parameters.Bytes def test_init(self): """ Test the `ipalib.parameters.Bytes.__init__` method. """ o = self.cls('my_bytes') assert o.type is bytes assert o.password is False assert o.rules == tuple() assert o.class_rules == tuple() assert o.all_rules == tuple() assert o.minlength is None assert o.maxlength is None assert o.length is None assert o.pattern is None assert o.re is None # Test mixing length with minlength or maxlength: o = self.cls('my_bytes', length=5) assert o.length == 5 assert len(o.class_rules) == 1 assert len(o.rules) == 0 assert len(o.all_rules) == 1 permutations = [ dict(minlength=3), dict(maxlength=7), dict(minlength=3, maxlength=7), ] for kw in permutations: o = self.cls('my_bytes', **kw) assert len(o.class_rules) == len(kw) assert len(o.rules) == 0 assert len(o.all_rules) == len(kw) for (key, value) in kw.items(): assert getattr(o, key) == value e = raises(ValueError, self.cls, 'my_bytes', length=5, **kw) assert str(e) == \ "Bytes('my_bytes'): cannot mix length with minlength or maxlength" # Test when minlength or maxlength are less than 1: e = raises(ValueError, self.cls, 'my_bytes', minlength=0) assert str(e) == "Bytes('my_bytes'): minlength must be >= 1; got 0" e = raises(ValueError, self.cls, 'my_bytes', maxlength=0) assert str(e) == "Bytes('my_bytes'): maxlength must be >= 1; got 0" # Test when minlength > maxlength: e = raises(ValueError, self.cls, 'my_bytes', minlength=22, maxlength=15) assert str(e) == \ "Bytes('my_bytes'): minlength > maxlength (minlength=22, maxlength=15)" # Test when minlength == maxlength e = raises(ValueError, self.cls, 'my_bytes', minlength=7, maxlength=7) assert str(e) == \ "Bytes('my_bytes'): minlength == maxlength; use length=7 instead" def test_rule_minlength(self): """ Test the `ipalib.parameters.Bytes._rule_minlength` method. """ o = self.cls('my_bytes', minlength=3) assert o.minlength == 3 rule = o._rule_minlength translation = u'minlength=%(minlength)r' dummy = dummy_ugettext(translation) assert dummy.translation is translation # Test with passing values: for value in (b'abc', b'four', b'12345'): assert rule(dummy, value) is None assert dummy.called() is False # Test with failing values: for value in (b'', b'a', b'12'): assert_equal( rule(dummy, value), translation % dict(minlength=3) ) assert dummy.message == 'must be at least %(minlength)d bytes' assert dummy.called() is True dummy.reset() def test_rule_maxlength(self): """ Test the `ipalib.parameters.Bytes._rule_maxlength` method. """ o = self.cls('my_bytes', maxlength=4) assert o.maxlength == 4 rule = o._rule_maxlength translation = u'maxlength=%(maxlength)r' dummy = dummy_ugettext(translation) assert dummy.translation is translation # Test with passing values: for value in (b'ab', b'123', b'four'): assert rule(dummy, value) is None assert dummy.called() is False # Test with failing values: for value in (b'12345', b'sixsix'): assert_equal( rule(dummy, value), translation % dict(maxlength=4) ) assert dummy.message == 'can be at most %(maxlength)d bytes' assert dummy.called() is True dummy.reset() def test_rule_length(self): """ Test the `ipalib.parameters.Bytes._rule_length` method. """ o = self.cls('my_bytes', length=4) assert o.length == 4 rule = o._rule_length translation = u'length=%(length)r' dummy = dummy_ugettext(translation) assert dummy.translation is translation # Test with passing values: for value in (b'1234', b'four'): assert rule(dummy, value) is None assert dummy.called() is False # Test with failing values: for value in (b'ab', b'123', b'12345', b'sixsix'): assert_equal( rule(dummy, value), translation % dict(length=4), ) assert dummy.message == 'must be exactly %(length)d bytes' assert dummy.called() is True dummy.reset() def test_rule_pattern(self): """ Test the `ipalib.parameters.Bytes._rule_pattern` method. """ # Test our assumptions about Python re module and Unicode: pat = br'\w+$' r = re.compile(pat) assert r.match(b'Hello_World') is not None assert r.match(utf8_bytes) is None assert r.match(binary_bytes) is None # Create instance: o = self.cls('my_bytes', pattern=pat) assert o.pattern is pat rule = o._rule_pattern translation = u'pattern=%(pattern)r' dummy = dummy_ugettext(translation) # Test with passing values: for value in (b'HELLO', b'hello', b'Hello_World'): assert rule(dummy, value) is None assert dummy.called() is False # Test with failing values: for value in (b'Hello!', b'Hello World', utf8_bytes, binary_bytes): assert_equal( rule(dummy, value), translation % dict(pattern=pat), ) assert_equal(dummy.message, 'must match pattern "%(pattern)s"') assert dummy.called() is True dummy.reset() class test_Str(ClassChecker): """ Test the `ipalib.parameters.Str` class. """ _cls = parameters.Str def test_init(self): """ Test the `ipalib.parameters.Str.__init__` method. """ o = self.cls('my_str') assert o.type is unicode assert o.password is False assert o.minlength is None assert o.maxlength is None assert o.length is None assert o.pattern is None def test_convert_scalar(self): """ Test the `ipalib.parameters.Str._convert_scalar` method. """ o = self.cls('my_str') mthd = o._convert_scalar for value in (u'Hello', 42, 1.2, unicode_str): assert mthd(value) == unicode(value) bad = [True, b'Hello', dict(one=1), utf8_bytes] for value in bad: e = raises(errors.ConversionError, mthd, value) assert e.name == 'my_str' assert_equal(unicode(e.error), u'must be Unicode text') bad = [(u'Hello',), [42.3]] for value in bad: e = raises(errors.ConversionError, mthd, value) assert e.name == 'my_str' assert_equal(unicode(e.error), u'Only one value is allowed') assert o.convert(None) is None def test_rule_minlength(self): """ Test the `ipalib.parameters.Str._rule_minlength` method. """ o = self.cls('my_str', minlength=3) assert o.minlength == 3 rule = o._rule_minlength translation = u'minlength=%(minlength)r' dummy = dummy_ugettext(translation) assert dummy.translation is translation # Test with passing values: for value in (u'abc', u'four', u'12345'): assert rule(dummy, value) is None assert dummy.called() is False # Test with failing values: for value in (u'', u'a', u'12'): assert_equal( rule(dummy, value), translation % dict(minlength=3) ) assert dummy.message == 'must be at least %(minlength)d characters' assert dummy.called() is True dummy.reset() def test_rule_maxlength(self): """ Test the `ipalib.parameters.Str._rule_maxlength` method. """ o = self.cls('my_str', maxlength=4) assert o.maxlength == 4 rule = o._rule_maxlength translation = u'maxlength=%(maxlength)r' dummy = dummy_ugettext(translation) assert dummy.translation is translation # Test with passing values: for value in (u'ab', u'123', u'four'): assert rule(dummy, value) is None assert dummy.called() is False # Test with failing values: for value in (u'12345', u'sixsix'): assert_equal( rule(dummy, value), translation % dict(maxlength=4) ) assert dummy.message == 'can be at most %(maxlength)d characters' assert dummy.called() is True dummy.reset() def test_rule_length(self): """ Test the `ipalib.parameters.Str._rule_length` method. """ o = self.cls('my_str', length=4) assert o.length == 4 rule = o._rule_length translation = u'length=%(length)r' dummy = dummy_ugettext(translation) assert dummy.translation is translation # Test with passing values: for value in (u'1234', u'four'): assert rule(dummy, value) is None assert dummy.called() is False # Test with failing values: for value in (u'ab', u'123', u'12345', u'sixsix'): assert_equal( rule(dummy, value), translation % dict(length=4), ) assert dummy.message == 'must be exactly %(length)d characters' assert dummy.called() is True dummy.reset() def test_rule_pattern(self): """ Test the `ipalib.parameters.Str._rule_pattern` method. """ # Test our assumptions about Python re module and Unicode: pat = r'\w{5}$' r1 = re.compile(pat) r2 = re.compile(pat, re.UNICODE) if six.PY2: assert r1.match(unicode_str) is None else: assert r1.match(unicode_str) is not None assert r2.match(unicode_str) is not None # Create instance: o = self.cls('my_str', pattern=pat) assert o.pattern is pat rule = o._rule_pattern translation = u'pattern=%(pattern)r' dummy = dummy_ugettext(translation) # Test with passing values: for value in (u'HELLO', u'hello', unicode_str): assert rule(dummy, value) is None assert dummy.called() is False # Test with failing values: for value in (u'H LLO', u'***lo', unicode_str + unicode_str): assert_equal( rule(dummy, value), translation % dict(pattern=pat), ) assert_equal(dummy.message, 'must match pattern "%(pattern)s"') assert dummy.called() is True dummy.reset() class test_Password(ClassChecker): """ Test the `ipalib.parameters.Password` class. """ _cls = parameters.Password def test_init(self): """ Test the `ipalib.parameters.Password.__init__` method. """ o = self.cls('my_password') assert o.type is unicode assert o.minlength is None assert o.maxlength is None assert o.length is None assert o.pattern is None assert o.password is True def test_convert_scalar(self): """ Test the `ipalib.parameters.Password._convert_scalar` method. """ o = self.cls('my_password') e = raises(errors.PasswordMismatch, o._convert_scalar, [u'one', u'two']) assert e.name == 'my_password' assert o._convert_scalar([u'one', u'one']) == u'one' assert o._convert_scalar(u'one') == u'one' class EnumChecker(ClassChecker): """ Test *Enum classes. """ _cls = parameters.StrEnum def test_init(self): """Test the `__init__` method""" values = self._test_values o = self.cls(self._name, values=values) assert o.type is self._datatype assert o.values is values assert o.class_rules == (o._rule_values,) assert o.rules == tuple() assert o.all_rules == (o._rule_values,) def test_bad_types(self): """Test failure with incorrect types""" badvalues = self._bad_type_values e = raises(TypeError, self.cls, 'my_enum', values=badvalues) assert str(e) == TYPE_ERROR % ( "%s('my_enum') values[1]" % self._cls.__name__, self._datatype, badvalues[1], self._bad_type) def test_empty(self): """Test that ValueError is raised when list of values is empty""" badvalues = tuple() e = raises(ValueError, self.cls, 'empty_enum', values=badvalues) assert_equal(str(e), "%s('empty_enum'): list of values must not " "be empty" % self._cls.__name__) def test_rules_values(self): """Test the `_rule_values` method""" def test_rules_with_passing_rules(self): """Test with passing values""" o = self.cls('my_enum', values=self._test_values) rule = o._rule_values dummy = dummy_ugettext(self._translation) for v in self._test_values: assert rule(dummy, v) is None assert dummy.called() is False def test_rules_with_failing_rules(self): """Test with failing values""" o = self.cls('my_enum', values=self._test_values) rule = o._rule_values dummy = dummy_ugettext(self._translation) for val in self._bad_values: assert_equal( rule(dummy, val), self._translation % dict(values=self._test_values), ) assert_equal(dummy.message, "must be one of %(values)s") dummy.reset() def test_one_value(self): """test a special case when we have just one allowed value""" values = (self._test_values[0], ) o = self.cls('my_enum', values=values) rule = o._rule_values dummy = dummy_ugettext(self._single_value_translation) for val in self._bad_values: assert_equal( rule(dummy, val), self._single_value_translation % dict(values=values), ) assert_equal(dummy.message, "must be '%(value)s'") dummy.reset() class test_StrEnum(EnumChecker): """ Test the `ipalib.parameters.StrEnum` class. """ _cls = parameters.StrEnum _name = 'my_strenum' _datatype = unicode _test_values = u'Hello', u'tall', u'nurse!' _bad_type_values = u'Hello', 1, u'nurse!' _bad_type = int _translation = u"values='Hello', 'tall', 'nurse!'" _bad_values = u'Howdy', u'quiet', u'library!' _single_value_translation = u"value='Hello'" def check_int_scalar_conversions(o): """ Assure radix prefixes work, str objects fail, floats (native & string) are truncated, large magnitude values are promoted to long, empty strings & invalid numerical representations fail """ # Assure invalid inputs raise error for bad in ['hello', u'hello', True, None, u'', u'.', 8j, ()]: e = raises(errors.ConversionError, o._convert_scalar, bad) assert e.name == 'my_number' # Assure large magnitude values are handled correctly assert type(o._convert_scalar(sys.maxsize * 2)) == long assert o._convert_scalar(sys.maxsize * 2) == sys.maxsize * 2 assert o._convert_scalar(unicode(sys.maxsize * 2)) == sys.maxsize * 2 assert o._convert_scalar(long(16)) == 16 # Assure normal conversions produce expected result assert o._convert_scalar(u'16.99') == 16 assert o._convert_scalar(16.99) == 16 assert o._convert_scalar(u'16') == 16 assert o._convert_scalar(u'0x10') == 16 assert o._convert_scalar(u'020') == 16 assert o._convert_scalar(u'0o20') == 16 class test_IntEnum(EnumChecker): """ Test the `ipalib.parameters.IntEnum` class. """ _cls = parameters.IntEnum _name = 'my_intenum' _datatype = int _test_values = 1, 2, -3 _bad_type_values = 1, 2.0, -3 _bad_type = float _translation = u"values=1, 2, 3" _bad_values = 4, 5, -6 _single_value_translation = u"value=1" def test_convert_scalar(self): """ Test the `ipalib.parameters.IntEnum._convert_scalar` method. """ param = self.cls('my_number', values=(1, 2, 3, 4, 5)) check_int_scalar_conversions(param) class test_Number(ClassChecker): """ Test the `ipalib.parameters.Number` class. """ _cls = parameters.Number def test_init(self): """ Test the `ipalib.parameters.Number.__init__` method. """ o = self.cls('my_number') assert o.type is type(None) # noqa assert o.password is False assert o.rules == tuple() assert o.class_rules == tuple() assert o.all_rules == tuple() class test_Int(ClassChecker): """ Test the `ipalib.parameters.Int` class. """ _cls = parameters.Int def test_init(self): """ Test the `ipalib.parameters.Int.__init__` method. """ # Test with no kwargs: o = self.cls('my_number') assert o.type == int assert o.allowed_types == (int,) assert isinstance(o, parameters.Int) assert o.minvalue == int(MININT) assert o.maxvalue == int(MAXINT) # Test when min > max: e = raises(ValueError, self.cls, 'my_number', minvalue=22, maxvalue=15) assert str(e) == \ "Int('my_number'): minvalue > maxvalue (minvalue=22, maxvalue=15)" def test_rule_minvalue(self): """ Test the `ipalib.parameters.Int._rule_minvalue` method. """ o = self.cls('my_number', minvalue=3) assert o.minvalue == 3 rule = o._rule_minvalue translation = u'minvalue=%(minvalue)r' dummy = dummy_ugettext(translation) assert dummy.translation is translation # Test with passing values: for value in (4, 99, 1001): assert rule(dummy, value) is None assert dummy.called() is False # Test with failing values: for value in (-1, 0, 2): assert_equal( rule(dummy, value), translation % dict(minvalue=3) ) assert dummy.message == 'must be at least %(minvalue)d' assert dummy.called() is True dummy.reset() def test_rule_maxvalue(self): """ Test the `ipalib.parameters.Int._rule_maxvalue` method. """ o = self.cls('my_number', maxvalue=4) assert o.maxvalue == 4 rule = o._rule_maxvalue translation = u'maxvalue=%(maxvalue)r' dummy = dummy_ugettext(translation) assert dummy.translation is translation # Test with passing values: for value in (-1, 0, 4): assert rule(dummy, value) is None assert dummy.called() is False # Test with failing values: for value in (5, 99, 1009): assert_equal( rule(dummy, value), translation % dict(maxvalue=4) ) assert dummy.message == 'can be at most %(maxvalue)d' assert dummy.called() is True dummy.reset() def test_convert_scalar(self): """ Test the `ipalib.parameters.Int._convert_scalar` method. """ param = self.cls('my_number') check_int_scalar_conversions(param) def test_safe_json(self): param = self.cls( "large", minvalue=self.cls.MIN_SAFE_INTEGER, maxvalue=self.cls.MAX_SAFE_INTEGER ) for value in (-((2 ** 53) - 1), 0, (2 ** 53) - 1): param.validate(value) for value in (-2 ** 53, 2 ** 53): with pytest.raises(errors.ValidationError): param.validate(value) with pytest.raises(ValueError): self.cls("toolarge", maxvalue=2**53) with pytest.raises(ValueError): self.cls("toosmall", minvalue=-2**53) class test_Decimal(ClassChecker): """ Test the `ipalib.parameters.Decimal` class. """ _cls = parameters.Decimal def test_init(self): """ Test the `ipalib.parameters.Decimal.__init__` method. """ # Test with no kwargs: o = self.cls('my_number') assert o.type is Decimal assert isinstance(o, parameters.Decimal) assert o.minvalue is None assert o.maxvalue is None # Test when min > max: e = raises(ValueError, self.cls, 'my_number', minvalue=Decimal('22.5'), maxvalue=Decimal('15.1')) assert str(e) == \ "Decimal('my_number'): minvalue > maxvalue (minvalue=22.5, maxvalue=15.1)" def test_rule_minvalue(self): """ Test the `ipalib.parameters.Decimal._rule_minvalue` method. """ o = self.cls('my_number', minvalue='3.1') assert o.minvalue == Decimal('3.1') rule = o._rule_minvalue translation = u'minvalue=%(minvalue)s' dummy = dummy_ugettext(translation) assert dummy.translation is translation # Test with passing values: for value in (Decimal('3.2'), Decimal('99.0')): assert rule(dummy, value) is None assert dummy.called() is False # Test with failing values: for value in (Decimal('-1.2'), Decimal('0.0'), Decimal('3.0')): assert_equal( rule(dummy, value), translation % dict(minvalue=Decimal('3.1')) ) assert dummy.message == 'must be at least %(minvalue)s' assert dummy.called() is True dummy.reset() def test_rule_maxvalue(self): """ Test the `ipalib.parameters.Decimal._rule_maxvalue` method. """ o = self.cls('my_number', maxvalue='4.7') assert o.maxvalue == Decimal('4.7') rule = o._rule_maxvalue translation = u'maxvalue=%(maxvalue)r' dummy = dummy_ugettext(translation) assert dummy.translation is translation # Test with passing values: for value in (Decimal('-1.0'), Decimal('0.1'), Decimal('4.2')): assert rule(dummy, value) is None assert dummy.called() is False # Test with failing values: for value in (Decimal('5.3'), Decimal('99.9')): assert_equal( rule(dummy, value), translation % dict(maxvalue=Decimal('4.7')) ) assert dummy.message == 'can be at most %(maxvalue)s' assert dummy.called() is True dummy.reset() def test_precision(self): """ Test the `ipalib.parameters.Decimal` precision attribute """ # precission is None param = self.cls('my_number') for value in (Decimal('0'), Decimal('4.4'), Decimal('4.67')): assert_equal( param(value), value) # precision is 0 param = self.cls('my_number', precision=0) for original,expected in ((Decimal('0'), '0'), (Decimal('1.1'), '1'), (Decimal('4.67'), '5')): assert_equal( str(param(original)), expected) # precision is 1 param = self.cls('my_number', precision=1) for original,expected in ((Decimal('0'), '0.0'), (Decimal('1.1'), '1.1'), (Decimal('4.67'), '4.7')): assert_equal( str(param(original)), expected) # value has too many digits param = self.cls('my_number', precision=1) e = raises(ConversionError, param, '123456789012345678901234567890') assert str(e).startswith("invalid 'my_number': ") def test_exponential(self): """ Test the `ipalib.parameters.Decimal` exponential attribute """ param = self.cls('my_number', exponential=True) for original,expected in ((Decimal('0'), '0'), (Decimal('1E3'), '1E+3'), (Decimal('3.4E2'), '3.4E+2')): assert_equal( str(param(original)), expected) param = self.cls('my_number', exponential=False) for original,expected in ((Decimal('0'), '0'), (Decimal('1E3'), '1000'), (Decimal('3.4E2'), '340')): assert_equal( str(param(original)), expected) def test_numberclass(self): """ Test the `ipalib.parameters.Decimal` numberclass attribute """ # test default value: '-Normal', '+Zero', '+Normal' param = self.cls('my_number') for value,raises_verror in ((Decimal('0'), False), (Decimal('-0'), True), (Decimal('1E8'), False), (Decimal('-1.1'), False), (Decimal('-Infinity'), True), (Decimal('+Infinity'), True), (Decimal('NaN'), True)): if raises_verror: raises(ValidationError, param, value) else: param(value) param = self.cls('my_number', exponential=True, numberclass=('-Normal', '+Zero', '+Infinity')) for value,raises_verror in ((Decimal('0'), False), (Decimal('-0'), True), (Decimal('1E8'), True), (Decimal('-1.1'), False), (Decimal('-Infinity'), True), (Decimal('+Infinity'), False), (Decimal('NaN'), True)): if raises_verror: raises(ValidationError, param, value) else: param(value) class test_AccessTime(ClassChecker): """ Test the `ipalib.parameters.AccessTime` class. """ _cls = parameters.AccessTime def test_init(self): """ Test the `ipalib.parameters.AccessTime.__init__` method. """ # Test with no kwargs: o = self.cls('my_time') assert o.type is unicode assert isinstance(o, parameters.AccessTime) assert o.multivalue is False translation = u'length=%(length)r' dummy = dummy_ugettext(translation) assert dummy.translation is translation rule = o._rule_required # Check some good rules for value in (u'absolute 201012161032 ~ 201012161033', u'periodic monthly week 2 day Sat,Sun 0900-1300', u'periodic yearly month 4 day 1-31 0800-1400', u'periodic weekly day 7 0800-1400', u'periodic daily 0800-1400', ): assert rule(dummy, value) is None assert dummy.called() is False # And some bad ones for value in (u'absolute 201012161032 - 201012161033', u'absolute 201012161032 ~', u'periodic monthly day Sat,Sun 0900-1300', u'periodical yearly month 4 day 1-31 0800-1400', u'periodic weekly day 8 0800-1400', ): raises(ValidationError, o._rule_required, None, value) def test_create_param(): """ Test the `ipalib.parameters.create_param` function. """ f = parameters.create_param # Test that Param instances are returned unchanged: params = ( parameters.Param('one?'), parameters.Int('two+'), parameters.Str('three*'), parameters.Bytes('four'), ) for p in params: assert f(p) is p # Test that the spec creates an Str instance: for spec in ('one?', 'two+', 'three*', 'four'): (name, kw) = parameters.parse_param_spec(spec) p = f(spec) assert p.param_spec == spec assert p.name == name assert p.required is kw['required'] assert p.multivalue is kw['multivalue'] # Test that TypeError is raised when spec is neither a Param nor a str: if six.PY2: bad_value = u'one' else: bad_value = b'one' for spec in (bad_value, 42, parameters.Param, parameters.Str): e = raises(TypeError, f, spec) assert str(e) == \ TYPE_ERROR % ('spec', (str, parameters.Param), spec, type(spec)) def test_messages(): """ Test module level message in `ipalib.parameters`. """ for name in dir(parameters): if name.startswith('_'): continue attr = getattr(parameters, name) if not (isclass(attr) and issubclass(attr, parameters.Param)): continue assert type(attr.type_error) is str assert attr.type_error in parameters.__messages class test_IA5Str(ClassChecker): """ Test the `ipalib.parameters.IA5Str` class. """ _cls = parameters.IA5Str def test_convert_scalar(self): """ Test the `ipalib.parameters.IA5Str._convert_scalar` method. """ o = self.cls('my_str') mthd = o._convert_scalar for value in (u'Hello', 42, 1.2): assert mthd(value) == unicode(value) bad = ['Helloá'] for value in bad: e = raises(errors.ConversionError, mthd, value) assert e.name == 'my_str' if six.PY2: assert_equal(e.error, u"The character '\\xc3' is not allowed.") else: assert_equal(e.error, u"The character 'á' is not allowed.") class test_DateTime(ClassChecker): """ Test the `ipalib.parameters.DateTime` class. """ _cls = parameters.DateTime def test_init(self): """ Test the `ipalib.parameters.DateTime.__init__` method. """ # Test with no kwargs: o = self.cls('my_datetime') assert o.type is datetime.datetime assert isinstance(o, parameters.DateTime) assert o.multivalue is False # Check full time formats date = datetime.datetime(1991, 12, 7, 6, 30, 5) assert date == o.convert(u'19911207063005Z') assert date == o.convert(u'1991-12-07T06:30:05Z') assert date == o.convert(u'1991-12-07 06:30:05Z') # Check time formats without seconds date = datetime.datetime(1991, 12, 7, 6, 30) assert date == o.convert(u'1991-12-07T06:30Z') assert date == o.convert(u'1991-12-07 06:30Z') # Check date formats date = datetime.datetime(1991, 12, 7) assert date == o.convert(u'1991-12-07Z') # Check some wrong formats for value in (u'19911207063005', u'1991-12-07T06:30:05', u'1991-12-07 06:30:05', u'1991-12-07T06:30', u'1991-12-07 06:30', u'1991-12-07', u'1991-31-12Z', u'1991-12-07T25:30:05Z', ): raises(ConversionError, o.convert, value) class test_CertificateSigningRequest(ClassChecker): """ Test the `ipalib.parameters.CertificateSigningRequest` class """ _cls = parameters.CertificateSigningRequest sample_csr = ( b'-----BEGIN CERTIFICATE REQUEST-----\n' b'MIIBjjCB+AIBADBPMQswCQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEQ\n' b'MA4GA1UEChMHRXhhbXBsZTEZMBcGA1UEAxMQdGVzdC5leGFtcGxlLmNvbTCBnzAN\n' b'BgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAyxsN5dmvyKiw+5nyrcO3a61sivZRg+ja\n' b'kyNIyUo+tIUiYwTdpPESAHTWRlk0XhydauAkWfOIN7pR3a5Z+kQw8W7F+DuZze2M\n' b'6wRNmN+NTrTlqnKOiMHBXhIM0Qxrx68GDctYqtnKTVT94FvvLl9XYVdUEi2ePTc2\n' b'Nyfr1z66+W0CAwEAAaAAMA0GCSqGSIb3DQEBBQUAA4GBAIf3r+Y6WHrFnttUqDow\n' b'9/UCHtCeQlQoJqjjxi5wcjbkGwTgHbx/BPOd/8OVaHElboMXLGaZx+L/eFO6E9Yg\n' b'mDOYv3OsibDFGaEhJrU8EnfuFZKnbrGeSC9Hkqrq+3OjqacaPla5N7MHKbfLY377\n' b'ddbOHKzR0sURZ+ro4z3fATW2\n' b'-----END CERTIFICATE REQUEST-----\n' ) # certmonger <= 0.79.5 (most probably in higher versions, too) will be # sending us just base64-encoded DER certs without the information it's # base64-encoded bytes (__base64__: in the JSON request), we need to # support that too, unfortunately sample_base64 = ( "MIICETCCAXoCAQAwTzELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWEx" "EDAOBgNVBAoTB0V4YW1wbGUxGTAXBgNVBAMTEHRlc3QuZXhhbXBsZS5jb20wgZ8w" "DQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAOXfP8LeiU7g6wLCclgkT1lVskK+Lxm1" "6ijE4LmEQBk5nn2P46im+E/UOgTddbDo5cdJlkoCnqXkO4RkqJckXYDxfI34KL3C" "CRFPvOa5Sg02m1x5Rg3boZfS6NciP62lRp0SI+0TCt3F16wYZxMahVIOXjbJ6Lu5" "mGjNn7XaWJhFAgMBAAGggYEwfwYJKoZIhvcNAQkOMXIwcDAeBgNVHREEFzAVghN0" "ZXN0bG93LmV4YW1wbGUuY29tME4GA1UdHwRHMEUwQ6BBoD+GHGh0dHA6Ly9jYS5l" "eGFtcGxlLmNvbS9teS5jcmyGH2h0dHA6Ly9vdGhlci5leGFtcGxlLmNvbS9teS5j" "cmwwDQYJKoZIhvcNAQEFBQADgYEAkv8pppcgGhX7erJmvg9r2UHrRriuKaOYgKZQ" "lf/eBt2N0L2mV4QvCY82H7HWuE+7T3mra9ikfvz0nYkPJQe2gntjZzECE0Jt5LWR" "UZOFwX8N6wrX11U2xu0NlvsbjU6siWd6OZjZ1p5/V330lzut/q3CNzaAcW1Fx3wL" "sV5SXSw=" ) sample_der_csr = ( b'0\x82\x02\x110\x82\x01z\x02\x01\x000O1\x0b0\t\x06\x03U\x04\x06\x13' b'\x02US1\x130\x11\x06\x03U\x04\x08\x13\nCalifornia1\x100\x0e\x06\x03U' b'\x04\n\x13\x07Example1\x190\x17\x06\x03U\x04\x03\x13\x10test.example' b'.com0\x81\x9f0\r\x06\t*\x86H\x86\xf7\r\x01\x01\x01\x05\x00\x03\x81' b'\x8d\x000\x81\x89\x02\x81\x81\x00\xe5\xdf?\xc2\xde\x89N\xe0\xeb\x02' b'\xc2rX$OYU\xb2B\xbe/\x19\xb5\xea(\xc4\xe0\xb9\x84@\x199\x9e}\x8f\xe3' b'\xa8\xa6\xf8O\xd4:\x04\xddu\xb0\xe8\xe5\xc7I\x96J\x02\x9e\xa5\xe4;' b'\x84d\xa8\x97$]\x80\xf1|\x8d\xf8(\xbd\xc2\t\x11O\xbc\xe6\xb9J\r6\x9b' b'\\yF\r\xdb\xa1\x97\xd2\xe8\xd7"?\xad\xa5F\x9d\x12#\xed\x13\n\xdd\xc5' b'\xd7\xac\x18g\x13\x1a\x85R\x0e^6\xc9\xe8\xbb\xb9\x98h\xcd\x9f\xb5' b'\xdaX\x98E\x02\x03\x01\x00\x01\xa0\x81\x810\x7f\x06\t*\x86H\x86\xf7' b'\r\x01\t\x0e1r0p0\x1e\x06\x03U\x1d\x11\x04\x170\x15\x82\x13' b'testlow.example.com0N\x06\x03U\x1d\x1f\x04G0E0C\xa0A\xa0?\x86' b'\x1chttp://ca.example.com/my.crl\x86\x1fhttp://other.example.com/' b'my.crl0\r\x06\t*\x86H\x86\xf7\r\x01\x01\x05\x05\x00\x03\x81\x81\x00' b'\x92\xff)\xa6\x97 \x1a\x15\xfbz\xb2f\xbe\x0fk\xd9A\xebF\xb8\xae)\xa3' b'\x98\x80\xa6P\x95\xff\xde\x06\xdd\x8d\xd0\xbd\xa6W\x84/\t\x8f6\x1f' b'\xb1\xd6\xb8O\xbbOy\xabk\xd8\xa4~\xfc\xf4\x9d\x89\x0f%\x07\xb6\x82' b'{cg1\x02\x13Bm\xe4\xb5\x91Q\x93\x85\xc1\x7f\r\xeb\n\xd7\xd7U6\xc6' b'\xed\r\x96\xfb\x1b\x8dN\xac\x89gz9\x98\xd9\xd6\x9e\x7fW}\xf4\x97;' b'\xad\xfe\xad\xc276\x80qmE\xc7|\x0b\xb1^R],' ) malformed_csr = ( b'-----BEGIN CERTIFICATE REQUEST-----\n' b'VGhpcyBpcyBhbiBpbnZhbGlkIENTUg==\n' b'-----END CERTIFICATE REQUEST-----\n' ) def test_init(self): # create the parameter o = self.cls('csr') assert o.type is crypto_x509.CertificateSigningRequest assert isinstance(o, parameters.CertificateSigningRequest) assert o.multivalue is False def test_convert(self): o = self.cls('csr') # test that we're able to handle PEM CSR input equally as bytes, string # and cryptography x509._CertificateSigningRequest object for prep_input in ( lambda x: x, lambda x: x.decode('utf-8'), lambda x: crypto_x509.load_pem_x509_csr(x, default_backend()) ): # test that input is correctly converted to python-crytography # object representation csr_object = o.convert(prep_input(self.sample_csr)) assert isinstance(csr_object, crypto_x509.CertificateSigningRequest) assert (csr_object.public_bytes(x509.Encoding.PEM) == self.sample_csr) # test that we fail the same with malformed CSR as bytes or str for prep_input in ( lambda x: x, lambda x: x.decode('utf-8'), ): # test that malformed CSRs won't be accepted raises(errors.CertificateOperationError, o.convert, prep_input(self.malformed_csr)) # test DER as an input to the convert method csr_object = o.convert(self.sample_der_csr) assert isinstance(csr_object, crypto_x509.CertificateSigningRequest) assert (csr_object.public_bytes(x509.Encoding.DER) == self.sample_der_csr) # test base64-encoded DER as an input to the convert method csr_object = o.convert(self.sample_base64) assert isinstance(csr_object, crypto_x509.CertificateSigningRequest) assert (csr_object.public_bytes(x509.Encoding.DER) == base64.b64decode(self.sample_base64)) # test that wrong type will not be accepted bad_value = datetime.date.today() raises(ConversionError, o.convert, bad_value) class test_DNParam(ClassChecker): """ Test the `ipalib.parameters.DN` class. """ _cls = parameters.DNParam def test_init(self): """ Test the `ipalib.parameters.DN.__init__` method. """ o = self.cls('my_dn') assert o.type is DN assert o.password is False def test_convert_scalar(self): """ Test the `ipalib.parameters.DNParam._convert_scalar` method. """ o = self.cls('my_dn') mthd = o._convert_scalar # param can be built from a string or from a DN good = [ 'cn=dn,cn=suffix', DN('cn=dn,cn=suffix') ] for value in good: assert mthd(value) == DN(value) # param cannot be built from a tuple or list if single-valued bad = [ ['cn=dn,cn=suffix'], ['cn=dn', 'cn=suffix'], ('cn=dn', 'cn=suffix'), (('cn', 'dn'), ('cn', 'suffix')) ] for value in bad: e = raises(errors.ConversionError, mthd, value) assert e.name == 'my_dn' assert_equal(unicode(e.error), u'Only one value is allowed') assert o.convert(None) is None def test_convert_singlevalued(self): """ Test the `DNParam.convert` method with a single-valued param. """ o = self.cls('my_dn?') mthd = o.convert # param can be built from a string or from a DN good = [ 'cn=dn,cn=suffix', DN('cn=dn,cn=suffix') ] for value in good: assert mthd(value) == DN(value) # param cannot be built from a tuple or list if single-valued bad = [ ['cn=dn,cn=suffix'], ['cn=dn', 'cn=suffix'], ('cn=dn', 'cn=suffix'), (('cn', 'dn'), ('cn', 'suffix')) ] for value in bad: e = raises(errors.ConversionError, mthd, value) assert e.name == 'my_dn' assert_equal(unicode(e.error), u'Only one value is allowed') assert o.convert(None) is None def test_convert_multivalued(self): """ Test the `DNParam.convert` method with a multivalued param. """ o = self.cls('my_dn*') mthd = o.convert # param can be built from a tuple/list good = [ ('cn=dn1,cn=suffix',), ('cn=dn1,cn=suffix', 'cn=dn2,cn=suffix'), ['cn=dn1,cn=suffix'], ['cn=dn1,cn=suffix', 'cn=dn2,cn=suffix'], ] for value in good: assert mthd(value) == tuple(DN(oneval) for oneval in value) assert o.convert(None) is None class test_SerialNumber(ClassChecker): """ Test the `ipalib.parameters.SerialNumber` class. """ _cls = parameters.SerialNumber def test_init(self): """ Test the `ipalib.parameters.SerialNumber.__init__` method. """ o = self.cls('my_serial') assert o.type is str assert o.length is None def test_validate_scalar(self): """ Test the `ipalib.parameters.SerialNumber._convert_scalar` method. """ o = self.cls('my_serial') mthd = o._validate_scalar for value in ('1234', '0xabcd', '0xABCD'): assert mthd(value) is None bad = ['Hello', '123A'] for value in bad: e = raises(errors.ValidationError, mthd, value) assert e.name == 'my_serial' assert_equal(e.error, 'must be an integer') bad = ['-1234', '-0xAFF'] for value in bad: e = raises(errors.ValidationError, mthd, value) assert e.name == 'my_serial' assert_equal(e.error, 'must be at least 0') bad = ['0xGAH', '0x',] for value in bad: e = raises(errors.ValidationError, mthd, value) assert e.name == 'my_serial' assert_equal( e.error, 'invalid valid hex' )
67,463
Python
.py
1,668
30.630096
105
0.57694
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,532
test_util.py
freeipa_freeipa/ipatests/test_ipalib/test_util.py
# # Copyright (C) 2018 FreeIPA Contributors see COPYING for license # """Tests for ipalib.util module """ import os import ssl from unittest import mock import pytest from ipalib.util import ( get_pager, create_https_connection, get_proper_tls_version_span ) from ipaplatform.constants import constants @pytest.mark.parametrize('pager,expected_result', [ # Valid values ('cat', '/bin/cat'), ('/bin/cat', '/bin/cat'), # Invalid values (wrong command, package is not installed, etc) ('cat_', None), ('', None) ]) def test_get_pager(pager, expected_result): with mock.patch.dict(os.environ, {'PAGER': pager}): pager = get_pager() assert(pager == expected_result or pager.endswith(expected_result)) BASE_CTX = ssl.SSLContext(ssl.PROTOCOL_TLS) if constants.TLS_HIGH_CIPHERS is not None: BASE_CTX.set_ciphers(constants.TLS_HIGH_CIPHERS) else: BASE_CTX.set_ciphers("PROFILE=SYSTEM") # options: IPA still supports Python 3.6 without min/max version setters BASE_OPT = BASE_CTX.options BASE_OPT |= ( ssl.OP_ALL | ssl.OP_NO_COMPRESSION | ssl.OP_SINGLE_DH_USE | ssl.OP_SINGLE_ECDH_USE ) TLS_OPT = ( ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3 | ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1 ) OP_NO_TLSv1_3 = getattr(ssl, "OP_NO_TLSv1_3", 0) # make pylint happy @pytest.mark.skip_if_platform( "debian", reason="Crypto policy is not supported on Debian" ) @pytest.mark.parametrize('minver,maxver,opt,expected', [ (None, None, BASE_OPT, None), (None, "tls1.3", BASE_OPT | TLS_OPT, ["tls1.2", "tls1.3"]), ("tls1.2", "tls1.3", BASE_OPT | TLS_OPT, ["tls1.2", "tls1.3"]), ("tls1.2", None, BASE_OPT | TLS_OPT, ["tls1.2", "tls1.3"]), ("tls1.2", "tls1.2", BASE_OPT | TLS_OPT | OP_NO_TLSv1_3, ["tls1.2"]), (None, "tls1.2", BASE_OPT | TLS_OPT | OP_NO_TLSv1_3, ["tls1.2"]), ("tls1.3", "tls1.3", BASE_OPT | TLS_OPT | ssl.OP_NO_TLSv1_2, ["tls1.3"]), ("tls1.3", None, BASE_OPT | TLS_OPT | ssl.OP_NO_TLSv1_2, ["tls1.3"]), ]) def test_tls_version_span(minver, maxver, opt, expected): assert get_proper_tls_version_span(minver, maxver) == expected # file must exist and contain certs cafile = ssl.get_default_verify_paths().cafile conn = create_https_connection( "invalid.test", cafile=cafile, tls_version_min=minver, tls_version_max=maxver ) ctx = getattr(conn, "_context") assert ctx.options == BASE_OPT | opt assert ctx.get_ciphers() == BASE_CTX.get_ciphers()
2,498
Python
.py
67
33.567164
77
0.664601
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,533
test_errors.py
freeipa_freeipa/ipatests/test_ipalib/test_errors.py
# Authors: # Jason Gerard DeRose <jderose@redhat.com> # # Copyright (C) 2008 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ Test the `ipalib.errors` module. """ # FIXME: Pylint errors # pylint: disable=no-member import re import inspect import pytest import six from ipatests.util import assert_equal, raises from ipalib import errors from ipalib.constants import TYPE_ERROR if six.PY3: unicode = str pytestmark = pytest.mark.tier0 class PrivateExceptionTester: _klass = None __klass = None def __get_klass(self): if self.__klass is None: self.__klass = self._klass assert issubclass(self.__klass, Exception) assert issubclass(self.__klass, errors.PrivateError) assert not issubclass(self.__klass, errors.PublicError) return self.__klass klass = property(__get_klass) def new(self, **kw): for (key, value) in kw.items(): assert not hasattr(self.klass, key), key inst = self.klass(**kw) # pylint: disable=not-callable assert isinstance(inst, Exception) assert isinstance(inst, errors.PrivateError) # pylint: disable=isinstance-second-argument-not-valid-type assert isinstance(inst, self.klass) # pylint: enable=isinstance-second-argument-not-valid-type assert not isinstance(inst, errors.PublicError) for (key, value) in kw.items(): assert getattr(inst, key) is value assert str(inst) == self.klass.format % kw return inst class test_PrivateError(PrivateExceptionTester): """ Test the `ipalib.errors.PrivateError` exception. """ _klass = errors.PrivateError def test_init(self): """ Test the `ipalib.errors.PrivateError.__init__` method. """ inst = self.klass(key1='Value 1', key2='Value 2') assert inst.key1 == 'Value 1' assert inst.key2 == 'Value 2' assert str(inst) == '' # Test subclass and use of format: class subclass(self.klass): format = '%(true)r %(text)r %(number)r' kw = dict(true=True, text='Hello!', number=18) inst = subclass(**kw) assert inst.true is True assert inst.text is kw['text'] assert inst.number is kw['number'] assert str(inst) == subclass.format % kw # Test via PrivateExceptionTester.new() inst = self.new(**kw) assert isinstance(inst, self.klass) assert inst.true is True assert inst.text is kw['text'] assert inst.number is kw['number'] class test_SubprocessError(PrivateExceptionTester): """ Test the `ipalib.errors.SubprocessError` exception. """ _klass = errors.SubprocessError def test_init(self): """ Test the `ipalib.errors.SubprocessError.__init__` method. """ bin_false = '/bin/false' inst = self.new(returncode=1, argv=(bin_false,)) assert inst.returncode == 1 assert inst.argv == (bin_false,) assert str(inst) == "return code 1 from ('{}',)".format(bin_false) class test_PluginSubclassError(PrivateExceptionTester): """ Test the `ipalib.errors.PluginSubclassError` exception. """ _klass = errors.PluginSubclassError def test_init(self): """ Test the `ipalib.errors.PluginSubclassError.__init__` method. """ inst = self.new(plugin='bad', bases=('base1', 'base2')) assert inst.plugin == 'bad' assert inst.bases == ('base1', 'base2') assert str(inst) == \ "'bad' not subclass of any base in ('base1', 'base2')" class test_PluginDuplicateError(PrivateExceptionTester): """ Test the `ipalib.errors.PluginDuplicateError` exception. """ _klass = errors.PluginDuplicateError def test_init(self): """ Test the `ipalib.errors.PluginDuplicateError.__init__` method. """ inst = self.new(plugin='my_plugin') assert inst.plugin == 'my_plugin' assert str(inst) == "'my_plugin' was already registered" class test_PluginOverrideError(PrivateExceptionTester): """ Test the `ipalib.errors.PluginOverrideError` exception. """ _klass = errors.PluginOverrideError def test_init(self): """ Test the `ipalib.errors.PluginOverrideError.__init__` method. """ inst = self.new(base='Base', name='cmd', plugin='my_cmd') assert inst.base == 'Base' assert inst.name == 'cmd' assert inst.plugin == 'my_cmd' assert str(inst) == "unexpected override of Base.cmd with 'my_cmd'" class test_PluginMissingOverrideError(PrivateExceptionTester): """ Test the `ipalib.errors.PluginMissingOverrideError` exception. """ _klass = errors.PluginMissingOverrideError def test_init(self): """ Test the `ipalib.errors.PluginMissingOverrideError.__init__` method. """ inst = self.new(base='Base', name='cmd', plugin='my_cmd') assert inst.base == 'Base' assert inst.name == 'cmd' assert inst.plugin == 'my_cmd' assert str(inst) == "Base.cmd not registered, cannot override with 'my_cmd'" ############################################################################## # Unit tests for public errors: class PublicExceptionTester: _klass = None __klass = None def __get_klass(self): if self.__klass is None: self.__klass = self._klass assert issubclass(self.__klass, Exception) assert issubclass(self.__klass, errors.PublicError) assert not issubclass(self.__klass, errors.PrivateError) assert type(self.__klass.errno) is int assert 900 <= self.__klass.errno <= 5999 return self.__klass klass = property(__get_klass) def new(self, format=None, message=None, **kw): # Test that TypeError is raised if message isn't unicode: e = raises(TypeError, self.klass, message=b'The message') assert str(e) == TYPE_ERROR % ('message', unicode, b'The message', bytes) # Test the instance: for (key, value) in kw.items(): assert not hasattr(self.klass, key), key # pylint: disable=not-callable inst = self.klass(format=format, message=message, **kw) # pylint: enable=not-callable for required_class in self.required_classes: assert isinstance(inst, required_class) # pylint: disable=isinstance-second-argument-not-valid-type assert isinstance(inst, self.klass) # pylint: enable=isinstance-second-argument-not-valid-type assert not isinstance(inst, errors.PrivateError) for (key, value) in kw.items(): assert getattr(inst, key) is value return inst class test_PublicError(PublicExceptionTester): """ Test the `ipalib.errors.PublicError` exception. """ _klass = errors.PublicError required_classes = Exception, errors.PublicError def test_init(self): message = u'The translated, interpolated message' format = 'key=%(key1)r and key2=%(key2)r' val1 = u'Value 1' val2 = u'Value 2' kw = dict(key1=val1, key2=val2) # Test with format=str, message=None inst = self.klass(format, **kw) assert inst.format is format assert_equal(str(inst), format % kw) assert inst.forwarded is False assert inst.key1 is val1 assert inst.key2 is val2 # Test with format=None, message=unicode inst = self.klass(message=message, **kw) assert inst.format is None assert str(inst) == message assert inst.strerror is message assert inst.forwarded is True assert inst.key1 is val1 assert inst.key2 is val2 # Test with format=None, message=bytes e = raises(TypeError, self.klass, message=b'the message', **kw) assert str(e) == TYPE_ERROR % ('message', unicode, b'the message', bytes) # Test with format=None, message=None e = raises(ValueError, self.klass, **kw) assert (str(e) == '%s.format is None yet format=None, message=None' % self.klass.__name__) ###################################### # Test via PublicExceptionTester.new() # Test with format=str, message=None inst = self.new(format, **kw) assert isinstance(inst, self.klass) assert inst.format is format assert_equal(str(inst), format % kw) assert inst.forwarded is False assert inst.key1 is val1 assert inst.key2 is val2 # Test with format=None, message=unicode inst = self.new(message=message, **kw) assert isinstance(inst, self.klass) assert inst.format is None assert str(inst) == message assert inst.strerror is message assert inst.forwarded is True assert inst.key1 is val1 assert inst.key2 is val2 ################## # Test a subclass: class subclass(self.klass): format = '%(true)r %(text)r %(number)r' kw = dict(true=True, text=u'Hello!', number=18) # Test with format=str, message=None e = raises(ValueError, subclass, format, **kw) assert str(e) == 'non-generic %r needs format=None; got format=%r' % ( 'subclass', format) # Test with format=None, message=None: inst = subclass(**kw) assert inst.format is subclass.format assert_equal(str(inst), subclass.format % kw) assert inst.forwarded is False assert inst.true is True assert inst.text is kw['text'] assert inst.number is kw['number'] # Test with format=None, message=unicode: inst = subclass(message=message, **kw) assert inst.format is subclass.format assert str(inst) == message assert inst.strerror is message assert inst.forwarded is True assert inst.true is True assert inst.text is kw['text'] assert inst.number is kw['number'] # Test with instructions: # first build up "instructions", then get error and search for # lines of instructions appended to the end of the strerror # despite the parameter 'instructions' not existing in the format instructions = u"The quick brown fox jumps over the lazy dog".split() # this expression checks if each word of instructions # exists in a string as a separate line, with right order regexp = re.compile('(?ims).*' + ''.join('(%s).*' % (x) for x in instructions) + '$') inst = subclass(instructions=instructions, **kw) assert inst.format is subclass.format assert_equal(inst.instructions, unicode(instructions)) inst_match = regexp.match(inst.strerror).groups() assert_equal(list(inst_match),list(instructions)) class BaseMessagesTest: """Generic test for all of a module's errors or messages """ def test_public_messages(self): i = 0 for klass in self.message_list: for required_class in self.required_classes: assert issubclass(klass, required_class) assert type(klass.errno) is int assert klass.errno in self.errno_range doc = inspect.getdoc(klass) assert doc is not None, 'need class docstring for %s' % klass.__name__ m = re.match(r'^\*{2}(\d+)\*{2} ', doc) assert m is not None, "need '**ERRNO**' in %s docstring" % klass.__name__ errno = int(m.group(1)) assert errno == klass.errno, ( 'docstring=%r but errno=%r in %s' % (errno, klass.errno, klass.__name__) ) self.extratest(klass) # Test format if klass.format is not None: assert klass.format is self.texts[i] i += 1 def extratest(self, cls): pass class test_PublicErrors: message_list = errors.public_errors errno_range = list(range(900, 5999)) required_classes = (Exception, errors.PublicError) texts = errors._texts def extratest(self, cls): assert not issubclass(cls, errors.PrivateError)
12,993
Python
.py
314
33.471338
88
0.628628
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,534
test_plugable.py
freeipa_freeipa/ipatests/test_ipalib/test_plugable.py
# Authors: # Jason Gerard DeRose <jderose@redhat.com> # # Copyright (C) 2008 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ Test the `ipalib.plugable` module. """ # FIXME: Pylint errors # pylint: disable=no-member import os import sys import textwrap from ipalib import plugable, errors, create_api from ipatests.util import raises, read_only from ipatests.util import ClassChecker, create_test_api, TempHome import pytest pytestmark = pytest.mark.tier0 class test_Plugin(ClassChecker): """ Test the `ipalib.plugable.Plugin` class. """ _cls = plugable.Plugin def test_class(self): """ Test the `ipalib.plugable.Plugin` class. """ assert self.cls.__bases__ == (plugable.ReadOnly,) assert type(self.cls.api) is property def test_init(self): """ Test the `ipalib.plugable.Plugin.__init__` method. """ api = 'the api instance' o = self.cls(api) assert o.name == 'Plugin' assert isinstance(o.doc, str) class some_subclass(self.cls): """ Do sub-classy things. Although it doesn't know how to comport itself and is not for mixed company, this class *is* useful as we all need a little sub-class now and then. One more paragraph. """ o = some_subclass(api) assert o.name == 'some_subclass' assert o.summary == 'Do sub-classy things.' assert isinstance(o.doc, str) class another_subclass(self.cls): pass o = another_subclass(api) assert o.summary == u'<%s.%s>' % (another_subclass.__module__, another_subclass.__name__) def test_finalize(self): """ Test the `ipalib.plugable.Plugin.finalize` method. """ class api: @staticmethod def is_production_mode(): return False o = self.cls(api) assert not o.__islocked__() o.finalize() assert o.__islocked__() def test_Registry(): """ Test the `ipalib.plugable.Registry` class """ class Base1: pass class Base2: pass class plugin1(Base1): pass class plugin2(Base2): pass # Test creation of Registry: r = plugable.Registry() # Check that TypeError is raised trying to register something that isn't # a class: p = plugin1() e = raises(TypeError, r(), p) assert str(e) == 'plugin must be callable; got %r' % p # Check that registration works r()(plugin1) # Check that DuplicateError is raised trying to register exact class # again: e = raises(errors.PluginDuplicateError, r(), plugin1) assert e.plugin is plugin1 # Check that overriding works class base1_extended(Base1): pass class plugin1(base1_extended): # pylint: disable=function-redefined pass r(override=True)(plugin1) # Test that another plugin can be registered: r()(plugin2) # Setup to test more registration: class plugin1a(Base1): pass r()(plugin1a) class plugin1b(Base1): pass r()(plugin1b) class plugin2a(Base2): pass r()(plugin2a) class plugin2b(Base2): pass r()(plugin2b) class test_API(ClassChecker): """ Test the `ipalib.plugable.API` class. """ _cls = plugable.API def test_API(self): """ Test the `ipalib.plugable.API` class. """ assert issubclass(plugable.API, plugable.ReadOnly) # Setup the test bases, create the API: class base0(plugable.Plugin): def method(self, n): return n class base1(plugable.Plugin): def method(self, n): return n + 1 class API(plugable.API): bases = (base0, base1) modules = () api = API() api.env.mode = 'unit_test' api.env.in_tree = True r = api.add_plugin class base0_plugin0(base0): pass r(base0_plugin0) class base0_plugin1(base0): pass r(base0_plugin1) class base0_plugin2(base0): pass r(base0_plugin2) class base1_plugin0(base1): pass r(base1_plugin0) class base1_plugin1(base1): pass r(base1_plugin1) class base1_plugin2(base1): pass r(base1_plugin2) # Test API instance: assert api.isdone('bootstrap') is False assert api.isdone('finalize') is False api.finalize() assert api.isdone('bootstrap') is True assert api.isdone('finalize') is True def get_base_name(b): return 'base%d' % b def get_plugin_name(b, p): return 'base%d_plugin%d' % (b, p) for b in range(2): base_name = get_base_name(b) base = locals()[base_name] ns = getattr(api, base_name) assert isinstance(ns, plugable.APINameSpace) assert read_only(api, base_name) is ns assert len(ns) == 3 for p in range(3): plugin_name = get_plugin_name(b, p) plugin = locals()[plugin_name] inst = ns[plugin_name] assert isinstance(inst, base) assert isinstance(inst, plugin) assert inst.name == plugin_name assert inst.method(7) == 7 + b # Test that calling finilize again raises AssertionError: e = raises(Exception, api.finalize) assert str(e) == 'API.finalize() already called', str(e) def test_bootstrap(self): """ Test the `ipalib.plugable.API.bootstrap` method. """ o, _home = create_test_api() assert o.env._isdone('_bootstrap') is False assert o.env._isdone('_finalize_core') is False assert o.isdone('bootstrap') is False o.bootstrap(my_test_override='Hello, world!') assert o.isdone('bootstrap') is True assert o.env._isdone('_bootstrap') is True assert o.env._isdone('_finalize_core') is True assert o.env.my_test_override == 'Hello, world!' e = raises(Exception, o.bootstrap) assert str(e) == 'API.bootstrap() already called' def test_load_plugins(self): """ Test the `ipalib.plugable.API.load_plugins` method. """ o, _home = create_test_api() assert o.isdone('bootstrap') is False assert o.isdone('load_plugins') is False o.load_plugins() assert o.isdone('bootstrap') is True assert o.isdone('load_plugins') is True e = raises(Exception, o.load_plugins) assert str(e) == 'API.load_plugins() already called' def test_ipaconf_env(self): ipa_confdir = os.environ.get('IPA_CONFDIR', None) try: with TempHome() as home: defaultconf = home.join('default.conf') with open(defaultconf, 'w') as f: f.write(textwrap.dedent(""" [global] basedn = dc=ipa,dc=test realm = IPA.TEST domain = ipa.test """) ) os.environ['IPA_CONFDIR'] = home.path api = create_api(mode='unit_test') api.bootstrap() api.finalize() assert api.env.confdir == home.path assert api.env.conf_default == defaultconf assert api.env.realm == 'IPA.TEST' assert api.env.domain == 'ipa.test' os.environ['IPA_CONFDIR'] = home.join('invalid') api = create_api(mode='unit_test') with pytest.raises(errors.EnvironmentError): api.bootstrap() finally: if ipa_confdir: os.environ['IPA_CONFDIR'] = ipa_confdir else: os.environ.pop('IPA_CONFDIR') class test_cli(ClassChecker): """ Test the `ipalib.plugable` global bootstrap. """ def test_no_args(self): sys.argv = ['/usr/bin/ipa'] api = create_api(mode='unit_test') (_options, argv) = api.bootstrap_with_global_options( context='unit_test') assert len(argv) == 0 assert _options.env is None assert _options.conf is None assert _options.debug is None assert _options.delegate is None assert _options.verbose is None def test_one_arg(self): sys.argv = ['/usr/bin/ipa', 'user-show'] api = create_api(mode='unit_test') (_options, argv) = api.bootstrap_with_global_options( context='unit_test') assert argv == ['user-show'] assert _options.verbose is None def test_args_valid_option(self): sys.argv = ['/usr/bin/ipa', '-v', 'user-show'] api = create_api(mode='unit_test') (_options, argv) = api.bootstrap_with_global_options( context='unit_test') assert argv == ['user-show'] assert _options.verbose == 1 def test_args_invalid_option(self): sys.argv = ['/usr/bin/ipa', '-verbose', 'user-show'] api = create_api(mode='unit_test') try: api.bootstrap_with_global_options(context='unit_test') except errors.OptionError as e: assert e.msg == 'Unable to parse option rbose'
10,268
Python
.py
288
26.489583
79
0.581477
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,535
test_config.py
freeipa_freeipa/ipatests/test_ipalib/test_config.py
# Authors: # Martin Nagy <mnagy@redhat.com> # Jason Gerard DeRose <jderose@redhat.com> # # Copyright (C) 2008 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ Test the `ipalib.config` module. """ from os import path import site import sys from ipatests.util import raises, delitem, ClassChecker from ipatests.util import getitem from ipatests.util import TempDir, TempHome from ipalib.constants import OVERRIDE_ERROR, SET_ERROR, DEL_ERROR from ipalib.constants import NAME_REGEX, NAME_ERROR from ipalib import config, constants, base import pytest pytestmark = pytest.mark.tier0 # Valid environment variables in (key, raw, value) tuples: # key: the name of the environment variable # raw: the value being set (possibly a string repr) # value: the expected value after the lightweight conversion good_vars = ( ('a_string', u'Hello world!', u'Hello world!'), ('trailing_whitespace', u' value ', u'value'), ('an_int', 42, 42), ('int_repr', ' 42 ', 42), ('not_a_float', '3.14', u'3.14'), ('true', True, True), ('true_repr', ' True ', True), ('false', False, False), ('false_repr', ' False ', False), ('none', None, None), ('none_repr', ' None ', None), ('empty', '', None), # These verify that the implied conversion is case-sensitive: ('not_true', u' true ', u'true'), ('not_false', u' false ', u'false'), ('not_none', u' none ', u'none'), ) bad_names = ( ('CamelCase', u'value'), ('_leading_underscore', u'value'), ('trailing_underscore_', u'value'), ) # Random base64-encoded data to simulate a misbehaving config file. config_bad = """ /9j/4AAQSkZJRgABAQEAlgCWAAD//gAIT2xpdmVy/9sAQwAQCwwODAoQDg0OEhEQExgoGhgWFhgx IyUdKDozPTw5Mzg3QEhcTkBEV0U3OFBtUVdfYmdoZz5NcXlwZHhcZWdj/8AACwgAlgB0AQERAP/E ABsAAAEFAQEAAAAAAAAAAAAAAAQAAQIDBQYH/8QAMhAAAgICAAUDBAIABAcAAAAAAQIAAwQRBRIh MUEGE1EiMmFxFIEVI0LBFjNSYnKRof/aAAgBAQAAPwDCtzmNRr1o/MEP1D6f7kdkRakgBsAtoQhk xls/y3Z113I11mhiUc1ewCf1Oq4anJgINdhLhQoextfedmYrenfcvdzaFQnYAE08XhONTWEK8+js Fpo1oqAKoAA8CWjoJJTHM8kJ5jsiOiszAKD1+IV/hmW76rosbfnlh1Pp3Mah2srCnXQE9YXiel/c p5r7uVj2CwxPTuFjjmdLbteNwmrLwsYe3TjsD8cmjKV43ycy+3o76D4llFuXmuCoZEPczXVOSsLv f5lgGpNZLxJL2jnvMar0/wAOp6jHDH/uO4RViY9f/KpRdfC6k3R9fRyj+pRZVkWKqF10e+hCKaFq XlH/ALlmhK7Met/uUGZ5ow8XL57lU8/Yt4lx4jUOJphLobTe/wDaHeZLxHXtJEya9o5lFzCqpmPY CUYoPtDfc9TLj0G5jZvHaMFirAs++oEHq9U4rbNiMp8a6wO/1Zbzn2alC+Nx8P1JfdeBboA+AILx rin8pfbA1ynvKuFUXZOXXkLbzOp2R56andL2G45MmO0RPWWLEe8GzaffoKb/ADI44Pt9ZXxAuuFa axtgp0BOSPCcviNX8n3Aw8KTNHB4FiY9StkobLWHVSeghq8M4bkAhKKyV6Hl8RV8MwMZG1Uuz3Jn IcUQJlMFGlJ6D4hfpymy7iChHKqvVtefxO7Ai1txLBIn7pcojN3jGVhQO0ZgCNfM5ZHycTLycSkr yhtqD4Bmrfw5cuqsm6xHXyp1seRLcHCp4dQy1bOzslj1MzeJ5dVFnuMVdgOiHxOWzrmyMg2Nrbde k3vR2OTddcd6A5R8GdZqOo67k4wXrLAQPMRKnzImMZEzm+P1nFz6cxQeVujagWR6jsYiqivlH/Ux 1M+7jWY30i7QHx1gF11tjGyxiSfmVc+503pPidVROHYNNY21b/adVZZySo3uOo1qIZQYd9RCzfYm TUk/qW71LjGkTA+IYiZmM1T9N9j8Gee5+McXJem0/Wp8GUK6KOi7b5MgzFjsxpJHZGDKSCOxE3cD OvsxbbLc9lsT7Vc73KX4ln3q1ZyVrPx2J/uAjLyan37z7B+Zp4vqPJqKi0K4EvzvUt1qBMdfb+T5 gycfzkXXuc35InfE6nO8Y9SjFc1Yqh2Hdj2mH/xFxR26XgD/AMRJf45mWMqW5bBD3KqAZlZtb++7 kEqTsHe//sG1CcTBvy7OWpD+Sewhz8CyKCTYAQPiGV0LVWPdxqQNADQ6zL4nWq2gopU6+ofmA8x3 1MlvfeIGbnBeCHitRt94IFbRGus2U9H08v13sT+BNHjeX/D4bY4OmP0rPPbHLMWJ2Yy2EDQjVsos BdeYDx8wo5L5KpSdLWPAE1+G8NrFtBKgOAXPTf6mzViql5ZBoE87eJZkKbOQ8m+Yjf5EBzcO621y GCqD0H41Obzq7U6vzM577HTXgzPPeOIvM1eB59nD8xXVj7bHTr8iej1MtlauvUMNgzi/V2ctliYy HYTq37nMExpZXRZYpZVJUdzNjg+FXYwZgdhv6nVVUJU/uH7iNf1CARrtF0IB113M7jTNVjFl2xJA 5ROey88OrVOugOy67TDs+89NRKdSYILdRC8ZQVJ+PHyJs4fqe3EoFPLzBexPxOdusa2xndiWY7JM qMUNrzOTAfHC9XO9/E3vT9blVJB0o2Zu3MAoYrsL13Ii0Muw3XvJG9KkDOeqjf6gWcw5A33XN9nX tOeyMRFWy3Jch+bX7mXmCsW/5RBXUoHaOIRi2asAJ0IRbjqzll3o/EAaRiltDojgv2E1aePmhEWq rsNHZ7wir1K/8Y1vUCSCAd+IXiZ9b1gLYvN07trXTUD4rxN2TkUgEts8p2NDtD0t5MVGchr2Xe99 hMPNvD1LX5J2TuZhGyYwBijjfiHU5bJXrnYfqBRtRtSbIBWG3+xI6HiLUWz8xA9RuaVNrMAPfB5x r6v9MLr4S1il7LaxyjY69Jl5eG+Kyhiv1jYIMGYMO8etGscKoJJ8Cbp4bVg4ivaq22t3G/tmRYo5 zyjQ+JRFFET01GB0Yid9YiYh1l9KgEHqT8Tco/hewA/NzgdQdwTNGNTY3uU2crL9HN00ZlovNzfV oCanBrBRk1rpCHPUkQjjYoW4GtwAw30MDpuxvbAvpJceR5mXFFEY0W4o4mpg0XNXutQxPUHxLb8q 7mRDyszLr6esz8u++9wL2LcvQb8RXCkhBV3A6mR5rEVSrdFPT8SBLMdsdmWe6P8AUAx+TB4oooxi i1Jmt0+5dfuOLbANB2H6MjzNzc2zv5ji1g2+5/MYnbb+Yh+T0kubUY940UUbUWtRpJN8w1CfebkK WfUu+/mDOAGOjsRo0UkIo+pPl6Rckl7ehuR1INGAj9u0kW2nXvK45YlQp1odukaICSAjgSQWf//Z """ # A config file that tries to override some standard vars: config_override = """ [global] key0 = var0 home = /home/sweet/home key1 = var1 site_packages = planet key2 = var2 key3 = var3 """ # A config file that tests the automatic type conversion config_good = """ [global] string = Hello world! null = None yes = True no = False number = 42 floating = 3.14 """ # A default config file to make sure it does not overwrite the explicit one config_default = """ [global] yes = Hello not_in_other = foo_bar """ class test_Env(ClassChecker): """ Test the `ipalib.config.Env` class. """ _cls = config.Env def test_init(self): """ Test the `ipalib.config.Env.__init__` method. """ o = self.cls() assert list(o) == [] assert len(o) == 0 assert o.__islocked__() is False def test_lock(self): """ Test the `ipalib.config.Env.__lock__` method. """ o = self.cls() assert o.__islocked__() is False o.__lock__() assert o.__islocked__() is True e = raises(Exception, o.__lock__) assert str(e) == 'Env.__lock__() already called' # Also test with base.lock() function: o = self.cls() assert o.__islocked__() is False assert base.lock(o) is o assert o.__islocked__() is True e = raises(AssertionError, base.lock, o) assert str(e) == 'already locked: %r' % o def test_islocked(self): """ Test the `ipalib.config.Env.__islocked__` method. """ o = self.cls() assert o.__islocked__() is False assert base.islocked(o) is False o.__lock__() assert o.__islocked__() is True assert base.islocked(o) is True def test_setattr(self): """ Test the `ipalib.config.Env.__setattr__` method. """ o = self.cls() for (name, raw, value) in good_vars: # Test setting the value: setattr(o, name, raw) result = getattr(o, name) assert type(result) is type(value) assert result == value assert result is o[name] # Test that value cannot be overridden once set: e = raises(AttributeError, setattr, o, name, raw) assert str(e) == OVERRIDE_ERROR % ('Env', name, value, raw) # Test that values cannot be set once locked: o = self.cls() o.__lock__() for (name, raw, value) in good_vars: e = raises(AttributeError, setattr, o, name, raw) assert str(e) == SET_ERROR % ('Env', name, raw) # Test that name is tested with check_name(): o = self.cls() for (name, value) in bad_names: e = raises(ValueError, setattr, o, name, value) assert str(e) == NAME_ERROR % (NAME_REGEX, name) def test_setitem(self): """ Test the `ipalib.config.Env.__setitem__` method. """ o = self.cls() for (key, raw, value) in good_vars: # Test setting the value: o[key] = raw result = o[key] assert type(result) is type(value) assert result == value assert result is getattr(o, key) # Test that value cannot be overridden once set: e = raises(AttributeError, o.__setitem__, key, raw) assert str(e) == OVERRIDE_ERROR % ('Env', key, value, raw) # Test that values cannot be set once locked: o = self.cls() o.__lock__() for (key, raw, value) in good_vars: e = raises(AttributeError, o.__setitem__, key, raw) assert str(e) == SET_ERROR % ('Env', key, raw) # Test that name is tested with check_name(): o = self.cls() for (key, value) in bad_names: e = raises(ValueError, o.__setitem__, key, value) assert str(e) == NAME_ERROR % (NAME_REGEX, key) def test_getitem(self): """ Test the `ipalib.config.Env.__getitem__` method. """ o = self.cls() value = u'some value' o.key = value assert o.key is value assert o['key'] is value for name in ('one', 'two'): e = raises(KeyError, getitem, o, name) assert str(e) == repr(name) def test_delattr(self): """ Test the `ipalib.config.Env.__delattr__` method. This also tests that ``__delitem__`` is not implemented. """ o = self.cls() o.one = 1 assert o.one == 1 for key in ('one', 'two'): e = raises(AttributeError, delattr, o, key) assert str(e) == DEL_ERROR % ('Env', key) e = raises(AttributeError, delitem, o, key) assert str(e) == '__delitem__' def test_contains(self): """ Test the `ipalib.config.Env.__contains__` method. """ o = self.cls() items = [ ('one', 1), ('two', 2), ('three', 3), ('four', 4), ] for (key, value) in items: assert key not in o o[key] = value assert key in o def test_len(self): """ Test the `ipalib.config.Env.__len__` method. """ o = self.cls() assert len(o) == 0 for i in range(1, 11): key = 'key%d' % i value = u'value %d' % i o[key] = value assert o[key] is value assert len(o) == i def test_iter(self): """ Test the `ipalib.config.Env.__iter__` method. """ o = self.cls() default_keys = tuple(o) keys = ('one', 'two', 'three', 'four', 'five') for key in keys: o[key] = 'the value' assert list(o) == sorted(keys + default_keys) def test_merge(self): """ Test the `ipalib.config.Env._merge` method. """ group1 = ( ('key1', u'value 1'), ('key2', u'value 2'), ('key3', u'value 3'), ('key4', u'value 4'), ) group2 = ( ('key0', u'Value 0'), ('key2', u'Value 2'), ('key4', u'Value 4'), ('key5', u'Value 5'), ) o = self.cls() assert o._merge(**dict(group1)) == (4, 4) assert len(o) == 4 assert list(o) == list(key for (key, value) in group1) for (key, value) in group1: assert getattr(o, key) is value assert o[key] is value assert o._merge(**dict(group2)) == (2, 4) assert len(o) == 6 expected = dict(group2) expected.update(dict(group1)) assert list(o) == sorted(expected) assert expected['key2'] == 'value 2' # And not 'Value 2' for (key, value) in expected.items(): assert getattr(o, key) is value assert o[key] is value assert o._merge(**expected) == (0, 6) assert len(o) == 6 assert list(o) == sorted(expected) def test_merge_from_file(self): """ Test the `ipalib.config.Env._merge_from_file` method. """ tmp = TempDir() assert callable(tmp.join) # Test a config file that doesn't exist no_exist = tmp.join('no_exist.conf') assert not path.exists(no_exist) o = self.cls() o._bootstrap() keys = tuple(o) orig = dict((k, o[k]) for k in o) assert o._merge_from_file(no_exist) is None assert tuple(o) == keys # Test an empty config file empty = tmp.touch('empty.conf') assert path.isfile(empty) assert o._merge_from_file(empty) == (0, 0) assert tuple(o) == keys # Test a mal-formed config file: bad = tmp.join('bad.conf') open(bad, 'w').write(config_bad) assert path.isfile(bad) assert o._merge_from_file(bad) is None assert tuple(o) == keys # Test a valid config file that tries to override override = tmp.join('override.conf') open(override, 'w').write(config_override) assert path.isfile(override) assert o._merge_from_file(override) == (4, 6) for (k, v) in orig.items(): assert o[k] is v assert list(o) == sorted(keys + ('key0', 'key1', 'key2', 'key3', 'config_loaded')) for i in range(4): assert o['key%d' % i] == ('var%d' % i) keys = tuple(o) # Test a valid config file with type conversion good = tmp.join('good.conf') open(good, 'w').write(config_good) assert path.isfile(good) assert o._merge_from_file(good) == (6, 6) added = ('string', 'null', 'yes', 'no', 'number', 'floating') assert list(o) == sorted(keys + added) # pylint: disable=no-member assert o.string == 'Hello world!' assert o.null is None assert o.yes is True assert o.no is False assert o.number == 42 assert o.floating == '3.14' # pylint: enable=no-member def new(self, in_tree=False): """ Set os.environ['HOME'] to a tempdir. Returns tuple with new Env instance and the TempHome instance. This helper method is used in testing the bootstrap related methods below. """ home = TempHome() o = self.cls() if in_tree: o.in_tree = True return (o, home) def bootstrap(self, **overrides): """ Helper method used in testing bootstrap related methods below. """ (o, home) = self.new() assert o._isdone('_bootstrap') is False o._bootstrap(**overrides) assert o._isdone('_bootstrap') is True e = raises(Exception, o._bootstrap) assert str(e) == 'Env._bootstrap() already called' return (o, home) def test_bootstrap(self): """ Test the `ipalib.config.Env._bootstrap` method. """ # Test defaults created by _bootstrap(): (o, home) = self.new() o._bootstrap() ipalib = path.dirname(path.abspath(config.__file__)) assert o.ipalib == ipalib assert o.site_packages == path.dirname(ipalib) assert o.script == path.abspath(sys.argv[0]) assert o.bin == path.dirname(path.abspath(sys.argv[0])) assert o.home == home.path assert o.dot_ipa == home.join('.ipa') assert o.context == 'default' if ( # venv site module doesn't have getsitepackages() not hasattr(site, "getsitepackages") or o.site_packages in site.getsitepackages() ): assert o.in_tree is False assert o.confdir == '/etc/ipa' assert o.conf == '/etc/ipa/default.conf' assert o.conf_default == o.conf else: assert o.in_tree is True assert o.confdir == o.dot_ipa assert o.conf == home.join('.ipa/default.conf') assert o.conf_default == o.conf # Test overriding values created by _bootstrap() (o, home) = self.bootstrap(in_tree='True', context='server') assert o.in_tree is True assert o.context == 'server' assert o.conf == home.join('.ipa', 'server.conf') o, home = self.bootstrap( conf='/my/wacky/whatever.conf', in_tree=False ) assert o.in_tree is False assert o.context == 'default' assert o.conf == '/my/wacky/whatever.conf' assert o.conf_default == '/etc/ipa/default.conf' o, home = self.bootstrap( conf_default='/my/wacky/default.conf', in_tree=False ) assert o.in_tree is False assert o.context == 'default' assert o.conf == '/etc/ipa/default.conf' assert o.conf_default == '/my/wacky/default.conf' # Test various overrides and types conversion kw = dict( yes=True, no=False, num=42, msg='Hello, world!', ) override = dict( (k, u' %s ' % v) for (k, v) in kw.items() ) (o, home) = self.new() for key in kw: assert key not in o o._bootstrap(**override) for (key, value) in kw.items(): assert getattr(o, key) == value assert o[key] == value def finalize_core(self, ctx, **defaults): """ Helper method used in testing `Env._finalize_core`. """ # We must force in_tree=True so we don't load possible config files in # /etc/ipa/, whose contents could break this test: (o, home) = self.new(in_tree=True) if ctx: o.context = ctx # Check that calls cascade down the chain: set_here = ('in_server', 'logdir', 'log') assert o._isdone('_bootstrap') is False assert o._isdone('_finalize_core') is False assert o._isdone('_finalize') is False for key in set_here: assert key not in o o._finalize_core(**defaults) assert o._isdone('_bootstrap') is True assert o._isdone('_finalize_core') is True assert o._isdone('_finalize') is False # Should not cascade for key in set_here: assert key in o # Check that it can't be called twice: e = raises(Exception, o._finalize_core) assert str(e) == 'Env._finalize_core() already called' return (o, home) def test_finalize_core(self): """ Test the `ipalib.config.Env._finalize_core` method. """ # Test that correct defaults are generated: (o, home) = self.finalize_core(None) assert o.in_server is False assert o.logdir == home.join('.ipa', 'log') assert o.log == home.join('.ipa', 'log', 'default.log') # Test with context='server' (o, home) = self.finalize_core('server') assert o.in_server is True assert o.logdir == home.join('.ipa', 'log') assert o.log == home.join('.ipa', 'log', 'server.log') # Test that **defaults can't set in_server, logdir, nor log: (o, home) = self.finalize_core(None, in_server='IN_SERVER', logdir='LOGDIR', log='LOG', ) assert o.in_server is False assert o.logdir == home.join('.ipa', 'log') assert o.log == home.join('.ipa', 'log', 'default.log') # Test loading config file, plus test some in-tree stuff (o, home) = self.bootstrap(in_tree=True, context='server') for key in ('yes', 'no', 'number'): assert key not in o home.write(config_good, '.ipa', 'server.conf') home.write(config_default, '.ipa', 'default.conf') o._finalize_core() assert o.in_tree is True assert o.context == 'server' assert o.in_server is True assert o.logdir == home.join('.ipa', 'log') assert o.log == home.join('.ipa', 'log', 'server.log') # pylint: disable=no-member assert o.yes is True assert o.no is False assert o.number == 42 assert o.not_in_other == 'foo_bar' # pylint: enable=no-member # Test using DEFAULT_CONFIG: defaults = dict(constants.DEFAULT_CONFIG) (o, home) = self.finalize_core(None, **defaults) list_o = [key for key in o if key != 'fips_mode'] assert list_o == sorted(defaults) for (key, value) in defaults.items(): if value is object: continue if key == 'mode': continue assert o[key] == value, '%r is %r; should be %r' % (key, o[key], value) def test_finalize(self): """ Test the `ipalib.config.Env._finalize` method. """ # Check that calls cascade up the chain: o, _home = self.new(in_tree=True) assert o._isdone('_bootstrap') is False assert o._isdone('_finalize_core') is False assert o._isdone('_finalize') is False o._finalize() assert o._isdone('_bootstrap') is True assert o._isdone('_finalize_core') is True assert o._isdone('_finalize') is True # Check that it can't be called twice: e = raises(Exception, o._finalize) assert str(e) == 'Env._finalize() already called' # Check that _finalize() calls __lock__() o, _home = self.new(in_tree=True) assert o.__islocked__() is False o._finalize() assert o.__islocked__() is True e = raises(Exception, o.__lock__) assert str(e) == 'Env.__lock__() already called' # Check that **lastchance works o, _home = self.finalize_core(None) key = 'just_one_more_key' value = u'with one more value' lastchance = {key: value} assert key not in o assert o._isdone('_finalize') is False o._finalize(**lastchance) assert key in o assert o[key] is value
22,101
Python
.py
563
31.253996
90
0.609884
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,536
test_x509.py
freeipa_freeipa/ipatests/test_ipalib/test_x509.py
# Authors: # Rob Crittenden <rcritten@redhat.com> # # Copyright (C) 2010 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ Test the `ipalib.x509` module. """ import base64 from binascii import hexlify from configparser import RawConfigParser import datetime from io import StringIO import os import pickle import pytest from cryptography import x509 as crypto_x509 from cryptography.x509.general_name import DNSName from ipalib import x509 from ipapython.dn import DN pytestmark = pytest.mark.tier0 # certutil - # certificate for CN=ipa.example.com,O=IPA goodcert = ( b'MIICAjCCAWugAwIBAgICBEUwDQYJKoZIhvcNAQEFBQAwKTEnMCUGA1UEAxMeSVBB' b'IFRlc3QgQ2VydGlmaWNhdGUgQXV0aG9yaXR5MB4XDTEwMDYyNTEzMDA0MloXDTE1' b'MDYyNTEzMDA0MlowKDEMMAoGA1UEChMDSVBBMRgwFgYDVQQDEw9pcGEuZXhhbXBs' b'ZS5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAJcZ+H6+cQaN/BlzR8OY' b'kVeJgaU5tCaV9FF1m7Ws/ftPtTJUaSL1ncp6603rjA4tH1aa/B8i8xdC46+ZbY2a' b'u8b9ryGcOsx2uaRpNLEQ2Fy//q1kQC8oM+iD8Nd6osF0a2wnugsgnJHPuJzhViaW' b'xYgzk5DRdP81debokF3f3FX/AgMBAAGjOjA4MBEGCWCGSAGG+EIBAQQEAwIGQDAT' b'BgNVHSUEDDAKBggrBgEFBQcDATAOBgNVHQ8BAf8EBAMCBPAwDQYJKoZIhvcNAQEF' b'BQADgYEALD6X9V9w381AzzQPcHsjIjiX3B/AF9RCGocKZUDXkdDhsD9NZ3PLPEf1' b'AMjkraKG963HPB8scyiBbbSuSh6m7TCp0eDgRpo77zNuvd3U4Qpm0Qk+KEjtHQDj' b'NNG6N4ZnCQPmjFPScElvc/GgW7XMbywJy2euF+3/Uip8cnPgSH4=' ) goodcert_headers = ( b'-----BEGIN CERTIFICATE-----\n' + goodcert + b'\n-----END CERTIFICATE-----' ) # The base64-encoded string 'bad cert' badcert = ( b'-----BEGIN CERTIFICATE-----\n' b'YmFkIGNlcnQ=\r\n' b'-----END CERTIFICATE-----' ) good_pkcs7 = ( b'-----BEGIN PKCS7-----\n' b'MIIDvAYJKoZIhvcNAQcCoIIDrTCCA6kCAQExADALBgkqhkiG9w0BBwGgggOPMIID\n' b'izCCAnOgAwIBAgIBATANBgkqhkiG9w0BAQsFADA2MRQwEgYDVQQKDAtFWEFNUExF\n' b'LkNPTTEeMBwGA1UEAwwVQ2VydGlmaWNhdGUgQXV0aG9yaXR5MB4XDTE3MDkyMDIw\n' b'NDI1N1oXDTM3MDkyMDIwNDI1N1owNjEUMBIGA1UECgwLRVhBTVBMRS5DT00xHjAc\n' b'BgNVBAMMFUNlcnRpZmljYXRlIEF1dGhvcml0eTCCASIwDQYJKoZIhvcNAQEBBQAD\n' b'ggEPADCCAQoCggEBAMNojX57UCCPTtEn9tQJBS4By5NixwodKm1UqOGsiecDrB0i\n' b'Pw7D6uGP6g4b6srYtbh+YsRJnfekB2L08q1dX3LVEItq2TS0WKqgZuRZkw7DvnGl\n' b'eANMwjHmE8k6/E0yI3GGxJLAfDZYw6CDspLkyN9anjQwVCz5N5z5bpeqi5BeVwin\n' b'O8WVF6FNn3iyL66uwOsTGEzCo3Y5HiwqYgaND73TtdsBHcIqOdRql3CC3IdoXXcW\n' b'044w4Lm2E95MuY729pPBHREtyzVkYtyuoKJ8KApghIY5oCklBkRDjyFK4tE7iF/h\n' b's+valeT9vcz2bHMIpvbjqAu/kqE8MjcNEFPjLhcCAwEAAaOBozCBoDAfBgNVHSME\n' b'GDAWgBTUB04/d1eLhbMtBi4AB65tsAt+2TAPBgNVHRMBAf8EBTADAQH/MA4GA1Ud\n' b'DwEB/wQEAwIBxjAdBgNVHQ4EFgQU1AdOP3dXi4WzLQYuAAeubbALftkwPQYIKwYB\n' b'BQUHAQEEMTAvMC0GCCsGAQUFBzABhiFodHRwOi8vaXBhLWNhLmdyZXlvYWsuY29t\n' b'L2NhL29jc3AwDQYJKoZIhvcNAQELBQADggEBADQFwX1uh8tqLq8SqWZWtH95j33o\n' b'5Ze2dW7sVppb/wVnNauG0wDQW7uIx+Ynr7GgufXLNBMn1aP/mA2CdHk7NZz2IB1s\n' b'ZvbIfE8dVxzkA+Hh9d6cdgk4eU5rGf6Fw8ScEJ/48Mmncea3uGkHcOmt+BGLA8a1\n' b'wtruy+iQylOkbv36CbxKV7IsZDP106Zc+cVeOUQZnCLKmvQkotn6UJd8N1X0R2J3\n' b'4/qv0rUtcCnyEBNSgpTGCRlYM4kd98Dqc5W7wUpMcsQMFxQMSYY7pFQkdLPfJEx2\n' b'Mg63SPawxfAgUeukrdsF3wTIKkIBu1TVse+kvRvgmRRrfF2a4ZOv5qORe2uhADEA\n' b'-----END PKCS7-----' ) long_oid_cert = b''' -----BEGIN CERTIFICATE----- MIIFiTCCBHGgAwIBAgITSAAAAAd1bEC5lsOdnQAAAAAABzANBgkqhkiG9w0BAQsF ADBLMRUwEwYKCZImiZPyLGQBGRYFbG9jYWwxEjAQBgoJkiaJk/IsZAEZFgJhZDEe MBwGA1UEAxMVYWQtV0lOLVBQSzAxNUY5TURRLUNBMB4XDTE3MDUyNTIzNDg0NVoX DTE5MDUyNTIzNTg0NVowNDESMBAGA1UEChMJSVBBLkxPQ0FMMR4wHAYDVQQDExVD ZXJ0aWZpY2F0ZSBBdXRob3JpdHkwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK AoIBAQDyyuty6irlL89hdaSW0UyAGLsOOMgAuJwBAeuRUorR159rsSnUXLcTHIsm EszKhwxp3NkkawRWx/s0UN1m2+RUwMl6gvlw+G80Mz0S77C77M+2lO8HRmZGm+Wu zBNcc9SANHuDQ1NISfZgLiscMS0+l0T3g6/Iqtg1kPWrq/tMevfh6tJEIedSBGo4 3xKEMSDkrvaeTuSVrgn/QT0m+WNccZa0c7X35L/hgR22/l5sr057Ef8F9vL8zUH5 TttFBIuiWJo8A8XX9I1zYIFhWjW3OVDZPBUnhGHH6yNyXGxXMRfcrrc74eTw8ivC 080AQuRtgwvDErB/JPDJ5w5t/ielAgMBAAGjggJ7MIICdzA9BgkrBgEEAYI3FQcE MDAuBiYrBgEEAYI3FQiEoqJGhYq1PoGllQqGi+F4nacAgRODs5gfgozzAAIBZAIB BTAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBhjAdBgNVHQ4EFgQUnSrC yW3CR0e3ilJdN6kL06P3KHMwHwYDVR0jBBgwFoAUj69xtyUNwp8on+NWO+HlxKyg X7AwgdgGA1UdHwSB0DCBzTCByqCBx6CBxIaBwWxkYXA6Ly8vQ049YWQtV0lOLVBQ SzAxNUY5TURRLUNBLENOPVdJTi1QUEswMTVGOU1EUSxDTj1DRFAsQ049UHVibGlj JTIwS2V5JTIwU2VydmljZXMsQ049U2VydmljZXMsQ049Q29uZmlndXJhdGlvbixE Qz1hZCxEQz1sb2NhbD9jZXJ0aWZpY2F0ZVJldm9jYXRpb25MaXN0P2Jhc2U/b2Jq ZWN0Q2xhc3M9Y1JMRGlzdHJpYnV0aW9uUG9pbnQwgcQGCCsGAQUFBwEBBIG3MIG0 MIGxBggrBgEFBQcwAoaBpGxkYXA6Ly8vQ049YWQtV0lOLVBQSzAxNUY5TURRLUNB LENOPUFJQSxDTj1QdWJsaWMlMjBLZXklMjBTZXJ2aWNlcyxDTj1TZXJ2aWNlcyxD Tj1Db25maWd1cmF0aW9uLERDPWFkLERDPWxvY2FsP2NBQ2VydGlmaWNhdGU/YmFz ZT9vYmplY3RDbGFzcz1jZXJ0aWZpY2F0aW9uQXV0aG9yaXR5MDMGA1UdIAQsMCow KAYmKwYBBAGCNxUIhKKiRoWKtT6BpZUKhovheJ2nAIEThrXzUYabpA4wDQYJKoZI hvcNAQELBQADggEBAIsFS+Qc/ufTrkuHbMmzksOpxq+OIi9rot8zy9/1Vmj6d+iP kB+vQ1u4/IhdQArJFNhsBzWSY9Pi8ZclovpepFeEZfXPUenyeRCU43HdMXcHXnlP YZfyLQWOugdo1WxK6S9qQSOSlC7BSGZWvKkiAPAwr4zNbbS+ROA2w0xaYMv0rr5W A4UAyzZAdqaGRJBRvCZ/uFHM5wMw0LzNCL4CqKW9jfZX0Fc2tdGx8zbTYxIdgr2D PL25as32r3S/m4uWqoQaK0lxK5Y97eusK2rrmidy32Jctzwl29UWq8kpjRAuD8iR CSc7sKqOf+fn3+fKITR2/DcSVvb0SGCr5fVVnjQ= -----END CERTIFICATE----- ''' ipa_demo_crt = b'''\ -----BEGIN CERTIFICATE----- MIIGFTCCBP2gAwIBAgISA61CoqWtpZoTEyfLCXliPLYFMA0GCSqGSIb3DQEBCwUA MEoxCzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1MZXQncyBFbmNyeXB0MSMwIQYDVQQD ExpMZXQncyBFbmNyeXB0IEF1dGhvcml0eSBYMzAeFw0xODA3MjUwNTM2NTlaFw0x ODEwMjMwNTM2NTlaMCAxHjAcBgNVBAMTFWlwYS5kZW1vMS5mcmVlaXBhLm9yZzCC ASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKisvYUdarWE0CS9i+RcNf9Q 41Euw36R4Myf/PUCDVUvGsVXQWSCanbtyxa8Ows4cAHrfqhiKAnSg0IhLqCMJVQ8 8F699FHrP9EfPmZkG3RMLYPxKNrSmOVyNpIEQY9qfkDXZPLung6dk/c225Znoltq bVWLObXA7eP9C/djupg3gUD7vOAMHFmfZ3OKnx1uktL5p707o2/qlkSiEO4Z5ebD M8X0dTkN8V3LCCOjzCp88itGUWJM8Tjb86WkmYkJxmeZx6REd37rDXjqgYhwgXOB bSqDkYKRaihwvd5Up/vE1wApBS1k7b1oEW80teDUbzbaaqp7oBWbZD2Ac1yJF7UC AwEAAaOCAx0wggMZMA4GA1UdDwEB/wQEAwIFoDAdBgNVHSUEFjAUBggrBgEFBQcD AQYIKwYBBQUHAwIwDAYDVR0TAQH/BAIwADAdBgNVHQ4EFgQUUmTMI1CB6qFMXc0+ AGmqpfBAwhIwHwYDVR0jBBgwFoAUqEpqYwR93brm0Tm3pkVl7/Oo7KEwbwYIKwYB BQUHAQEEYzBhMC4GCCsGAQUFBzABhiJodHRwOi8vb2NzcC5pbnQteDMubGV0c2Vu Y3J5cHQub3JnMC8GCCsGAQUFBzAChiNodHRwOi8vY2VydC5pbnQteDMubGV0c2Vu Y3J5cHQub3JnLzAgBgNVHREEGTAXghVpcGEuZGVtbzEuZnJlZWlwYS5vcmcwgf4G A1UdIASB9jCB8zAIBgZngQwBAgEwgeYGCysGAQQBgt8TAQEBMIHWMCYGCCsGAQUF BwIBFhpodHRwOi8vY3BzLmxldHNlbmNyeXB0Lm9yZzCBqwYIKwYBBQUHAgIwgZ4M gZtUaGlzIENlcnRpZmljYXRlIG1heSBvbmx5IGJlIHJlbGllZCB1cG9uIGJ5IFJl bHlpbmcgUGFydGllcyBhbmQgb25seSBpbiBhY2NvcmRhbmNlIHdpdGggdGhlIENl cnRpZmljYXRlIFBvbGljeSBmb3VuZCBhdCBodHRwczovL2xldHNlbmNyeXB0Lm9y Zy9yZXBvc2l0b3J5LzCCAQQGCisGAQQB1nkCBAIEgfUEgfIA8AB2AMEWSuCnctLU OS3ICsEHcNTwxJvemRpIQMH6B1Fk9jNgAAABZNAnsSAAAAQDAEcwRQIgHkd/UkTZ w8iV1Ox8MPHLrpY33cX6i5FV6w9+7YH3H2kCIQCVcrhsr4fokDyE2ueUqSFxkBVH WND84/w5rFNAPjyO1QB2ACk8UZZUyDlluqpQ/FgH1Ldvv1h6KXLcpMMM9OVFR/R4 AAABZNAnsyUAAAQDAEcwRQIhALDWY2k55abu7IPwnFvMr4Zqd1DYQXEKWZEQLXUP s4XGAiAabjpUwrLKVXpbp4WNLkTNlFjrSJafOzLG68H9AnoD4zANBgkqhkiG9w0B AQsFAAOCAQEAfBNuQn/A2olJHxoBGLfMcQCkkNOfvBpfQeKgni2VVM+r1ZY8YVXx OtVnV6XQ5M+l+6xlRpP1IwDdmJd/yaQgwbmYf4zl94W/s/qq4nlTd9G4ahmJOhlc mWeIQMoEtAmQlIOqWto+Knfakz6Xyo+HVCQEyeoBmYFGZcakeAm6tp/6qtpkej+4 wBjShMPAdSYDPRaAqnZ3BAK2UmmlpAA5tkNvqOaHBCi760zYoxT6j1an7FotG0v9 2+W0aL34eMWKz/g4qhwk+Jiz45LLQWhHGIgXIUoNSzHgLIVuVOQI8DPsguvT6GHW QUs1Hx1wL7mL4U8fKCFDKA+ds2B2xWgoZg== -----END CERTIFICATE----- ''' v1_cert = b'''\ -----BEGIN CERTIFICATE----- MIICwTCCAakCFG3lgHmtal7cilKoevNM/kD4gIToMA0GCSqGSIb3DQEBCwUAMB8x HTAbBgNVBAMMFEV4YW1wbGUtVGVzdC1DQS0xMTg4MB4XDTIxMDYxMTE5NTgwNVoX DTIxMDYxMjE5NTgwNVowGzEZMBcGA1UEAwwQaXBhLmV4YW1wbGUudGVzdDCCASIw DQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALsi+qZj7MB/okR4QFUYBHgLyFXr TVd4ENDYERPhHddMkShWsAD6jG7bo/fvrWdaVKdoawghQZymI0o7VVwwuu5+EVA+ gp/vKQM+QiF2fnbprLKVdZHexqdCyo0lMSGDeSobg3iH8iHiq4StYkGyXuUzcbgf 6avajlASGC7b4W7RahTION+GJFrP/eW392Oceu6idY6rl3Joyo9SY+zX+pAR0tDC +ixaYWkk9UxVuh4ObRToNLlHsnBWs3D6eZUiwBoX5QALWxwtdmsofwEOg3D+a2/h RihBnZzghQUOf9pjcu/jdgUzd0fsH9FpZVad3HjQmGq2Vgy/rT6STG9ojecCAwEA ATANBgkqhkiG9w0BAQsFAAOCAQEAMdB8pCPqEsJY5bnJNdr6EXdEIHk/l2P8tWJs wlpdAcOm5NfeZkOkGVYC4HTPNkMQ+K7K7VqHNT7hDjdNS0Gp/LVoHxBrQPAgsM7I RTZteGkCqIEBUxXvX2hKnMtuuAe9ljYlVF1P+WsV7qXP/M7RsWb2d+9ubA28mYD/ lhW/TB0/2EzP6QuiMh7bURIoQWw/733cfMIoP7XRVGn5Ux2z+o2hl5oOjHl7KBDa /6PWd4wOMU/cY2fOPPJQ7eSGJh4VCe64au3S6zAtoTE8XXweo/cDD70NZnmwdeGQ bswNlxWfohaW0FzTRfTMbIrwoUCWil/Uw2kBYnld15gwzuLDNQ== -----END CERTIFICATE----- ''' class test_x509: """ Test `ipalib.x509` I created the contents of this certificate with a self-signed CA with: % certutil -R -s "CN=ipa.example.com,O=IPA" -d . -a -o example.csr % ./ipa host-add ipa.example.com % ./ipa cert-request --add --principal=test/ipa.example.com example.csr """ def test_1_load_base64_cert(self): """ Test loading a base64-encoded certificate. """ # Load a good cert x509.load_pem_x509_certificate(goodcert_headers) # Load a good cert with headers and leading text newcert = ( b'leading text\n' + goodcert_headers) x509.load_pem_x509_certificate(newcert) # Load a good cert with bad headers newcert = b'-----BEGIN CERTIFICATE-----' + goodcert_headers with pytest.raises((TypeError, ValueError)): x509.load_pem_x509_certificate(newcert) # Load a bad cert with pytest.raises(ValueError): x509.load_pem_x509_certificate(badcert) def test_1_load_der_cert(self): """ Test loading a DER certificate. """ der = base64.b64decode(goodcert) # Load a good cert x509.load_der_x509_certificate(der) def test_3_cert_contents(self): """ Test the contents of a certificate """ # Verify certificate contents. This exercises python-cryptography # more than anything but confirms our usage of it. not_before = datetime.datetime(2010, 6, 25, 13, 0, 42, 0, datetime.timezone.utc) not_after = datetime.datetime(2015, 6, 25, 13, 0, 42, 0, datetime.timezone.utc) cert = x509.load_pem_x509_certificate(goodcert_headers) assert DN(cert.subject) == DN(('CN', 'ipa.example.com'), ('O', 'IPA')) assert DN(cert.issuer) == DN(('CN', 'IPA Test Certificate Authority')) assert cert.serial_number == 1093 assert cert.not_valid_before == not_before assert cert.not_valid_after == not_after assert cert.not_valid_before_utc == not_before assert cert.not_valid_after_utc == not_after assert cert.san_general_names == [] assert cert.san_a_label_dns_names == [] assert cert.extended_key_usage == {'1.3.6.1.5.5.7.3.1'} assert cert.extended_key_usage_bytes == ( b'0\x16\x06\x03U\x1d%\x01\x01\xff\x04\x0c0\n\x06\x08' b'+\x06\x01\x05\x05\x07\x03\x01' ) def test_cert_with_timezone(self): """ Test the not_before and not_after values in a diffent timezone Test for https://pagure.io/freeipa/issue/9462 """ # Store initial timezone, then set to New York tz = os.environ.get('TZ', None) os.environ['TZ'] = 'America/New_York' # Load the cert, extract not before and not after cert = x509.load_pem_x509_certificate(goodcert_headers) not_before = datetime.datetime(2010, 6, 25, 13, 0, 42, 0, datetime.timezone.utc) not_after = datetime.datetime(2015, 6, 25, 13, 0, 42, 0, datetime.timezone.utc) # Reset timezone to previous value if tz: os.environ['TZ'] = tz else: os.environ.pop('TZ', None) # ensure the timezone doesn't mess with not_before and not_after assert cert.not_valid_before == not_before assert cert.not_valid_after == not_after assert cert.not_valid_before_utc == not_before assert cert.not_valid_after_utc == not_after def test_load_pkcs7_pem(self): certlist = x509.pkcs7_to_certs(good_pkcs7, datatype=x509.PEM) assert len(certlist) == 1 cert = certlist[0] assert DN(cert.subject) == DN('CN=Certificate Authority,O=EXAMPLE.COM') assert cert.serial_number == 1 def test_long_oid(self): """ Test cerificate with very long OID. In this case we are using a certificate from an opened case where one of X509v3 Certificate`s Policies OID is longer then 80 chars. """ cert = x509.load_pem_x509_certificate(long_oid_cert) ext = cert.extensions.get_extension_for_class(crypto_x509. CertificatePolicies) assert len(ext.value) == 1 assert ext.value[0].policy_identifier.dotted_string == ( u'1.3.6.1.4.1.311.21.8.8950086.10656446.2706058.12775672.480128.' '147.13466065.13029902') def test_ipa_demo_letsencrypt(self): cert = x509.load_pem_x509_certificate(ipa_demo_crt) assert DN(cert.subject) == DN('CN=ipa.demo1.freeipa.org') assert DN(cert.issuer) == DN( "CN=Let's Encrypt Authority X3,O=Let's Encrypt,C=US") assert cert.serial_number == 0x03ad42a2a5ada59a131327cb0979623cb605 not_before = datetime.datetime(2018, 7, 25, 5, 36, 59, 0, datetime.timezone.utc) not_after = datetime.datetime(2018, 10, 23, 5, 36, 59, 0, datetime.timezone.utc) assert cert.not_valid_before == not_before assert cert.not_valid_after == not_after assert cert.not_valid_before_utc == not_before assert cert.not_valid_after_utc == not_after assert cert.san_general_names == [DNSName('ipa.demo1.freeipa.org')] assert cert.san_a_label_dns_names == ['ipa.demo1.freeipa.org'] assert cert.extended_key_usage == { '1.3.6.1.5.5.7.3.1', '1.3.6.1.5.5.7.3.2' } assert cert.extended_key_usage_bytes == ( b'0 \x06\x03U\x1d%\x01\x01\xff\x04\x160\x14\x06\x08+\x06\x01' b'\x05\x05\x07\x03\x01\x06\x08+\x06\x01\x05\x05\x07\x03\x02' ) def test_x509_v1_cert(self): with pytest.raises(ValueError): x509.load_pem_x509_certificate(v1_cert) class test_ExternalCAProfile: def test_MSCSTemplateV1_good(self): o = x509.MSCSTemplateV1("MySubCA") assert hexlify(o.get_ext_data()) == b'1e0e004d007900530075006200430041' def test_MSCSTemplateV1_bad(self): with pytest.raises(ValueError): x509.MSCSTemplateV1("MySubCA:1") def test_MSCSTemplateV1_pickle_roundtrip(self): o = x509.MSCSTemplateV1("MySubCA") s = pickle.dumps(o) assert o.get_ext_data() == pickle.loads(s).get_ext_data() def test_MSCSTemplateV2_too_few_parts(self): with pytest.raises(ValueError): x509.MSCSTemplateV2("1.2.3.4") def test_MSCSTemplateV2_too_many_parts(self): with pytest.raises(ValueError): x509.MSCSTemplateV2("1.2.3.4:100:200:300") def test_MSCSTemplateV2_bad_oid(self): with pytest.raises(ValueError): x509.MSCSTemplateV2("not_an_oid:1") def test_MSCSTemplateV2_non_numeric_major_version(self): with pytest.raises(ValueError): x509.MSCSTemplateV2("1.2.3.4:major:200") def test_MSCSTemplateV2_non_numeric_minor_version(self): with pytest.raises(ValueError): x509.MSCSTemplateV2("1.2.3.4:100:minor") def test_MSCSTemplateV2_major_version_lt_zero(self): with pytest.raises(ValueError): x509.MSCSTemplateV2("1.2.3.4:-1:200") def test_MSCSTemplateV2_minor_version_lt_zero(self): with pytest.raises(ValueError): x509.MSCSTemplateV2("1.2.3.4:100:-1") def test_MSCSTemplateV2_major_version_gt_max(self): with pytest.raises(ValueError): x509.MSCSTemplateV2("1.2.3.4:4294967296:200") def test_MSCSTemplateV2_minor_version_gt_max(self): with pytest.raises(ValueError): x509.MSCSTemplateV2("1.2.3.4:100:4294967296") def test_MSCSTemplateV2_good_major(self): o = x509.MSCSTemplateV2("1.2.3.4:4294967295") assert hexlify(o.get_ext_data()) == b'300c06032a0304020500ffffffff' def test_MSCSTemplateV2_good_major_minor(self): o = x509.MSCSTemplateV2("1.2.3.4:4294967295:0") assert hexlify(o.get_ext_data()) \ == b'300f06032a0304020500ffffffff020100' def test_MSCSTemplateV2_pickle_roundtrip(self): o = x509.MSCSTemplateV2("1.2.3.4:4294967295:0") s = pickle.dumps(o) assert o.get_ext_data() == pickle.loads(s).get_ext_data() def test_ExternalCAProfile_dispatch(self): """ Test that constructing ExternalCAProfile actually returns an instance of the appropriate subclass. """ assert isinstance( x509.ExternalCAProfile("MySubCA"), x509.MSCSTemplateV1) assert isinstance( x509.ExternalCAProfile("1.2.3.4:100"), x509.MSCSTemplateV2) def test_write_pkispawn_config_file_MSCSTemplateV1(self): template = x509.MSCSTemplateV1(u"SubCA") expected = ( '[CA]\n' 'pki_req_ext_oid = 1.3.6.1.4.1.311.20.2\n' 'pki_req_ext_data = 1e0a00530075006200430041\n\n' ) self._test_write_pkispawn_config_file(template, expected) def test_write_pkispawn_config_file_MSCSTemplateV2(self): template = x509.MSCSTemplateV2(u"1.2.3.4:4294967295") expected = ( '[CA]\n' 'pki_req_ext_oid = 1.3.6.1.4.1.311.21.7\n' 'pki_req_ext_data = 300c06032a0304020500ffffffff\n\n' ) self._test_write_pkispawn_config_file(template, expected) def _test_write_pkispawn_config_file(self, template, expected): """ Test that the values we read from an ExternalCAProfile object can be used to produce a reasonable-looking pkispawn configuration. """ config = RawConfigParser() config.optionxform = str config.add_section("CA") config.set("CA", "pki_req_ext_oid", template.ext_oid) config.set("CA", "pki_req_ext_data", hexlify(template.get_ext_data()).decode('ascii')) out = StringIO() config.write(out) assert out.getvalue() == expected
19,250
Python
.py
391
42.659847
79
0.752845
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,537
test_upgrade.py
freeipa_freeipa/ipatests/test_integration/test_upgrade.py
# # Copyright (C) 2018 FreeIPA Contributors see COPYING for license # """ Module provides tests to verify that the upgrade script works. """ import base64 import configparser import os import io import textwrap from subprocess import CalledProcessError from cryptography.hazmat.primitives import serialization import pytest from ipaplatform.paths import paths from ipapython.dn import DN from ipapython.ipautil import template_str from ipaserver.install import bindinstance from ipaserver.install.sysupgrade import STATEFILE_FILE from ipalib.constants import DEFAULT_CONFIG from ipatests.test_integration.base import IntegrationTest from ipatests.pytest_ipa.integration import tasks # old template without comments for testing # and "dnssec-validation no" OLD_NAMED_TEMPLATE = """ options { listen-on-v6 {any;}; directory "$NAMED_VAR_DIR"; // the default dump-file "${NAMED_DATA_DIR}cache_dump.db"; statistics-file "${NAMED_DATA_DIR}named_stats.txt"; memstatistics-file "${NAMED_DATA_DIR}named_mem_stats.txt"; tkey-gssapi-keytab "$NAMED_KEYTAB"; pid-file "$NAMED_PID"; dnssec-enable yes; dnssec-validation no; bindkeys-file "$BINDKEYS_FILE"; managed-keys-directory "$MANAGED_KEYS_DIR"; $INCLUDE_CRYPTO_POLICY }; logging { channel default_debug { file "${NAMED_DATA_DIR}named.run"; severity dynamic; print-time yes; }; }; include "$RFC1912_ZONES"; include "$ROOT_KEY"; /* WARNING: This part of the config file is IPA-managed. * Modifications may break IPA setup or upgrades. */ dyndb "ipa" "$BIND_LDAP_SO" { uri "ldapi://%2fvar%2frun%2fslapd-$SERVER_ID.socket"; base "cn=dns,$SUFFIX"; server_id "$FQDN"; auth_method "sasl"; sasl_mech "GSSAPI"; sasl_user "DNS/$FQDN"; }; /* End of IPA-managed part. */ """ def named_test_template(host): # create bind instance to get a substitution dict bind = bindinstance.BindInstance() bind.setup_templating( fqdn=host.hostname, realm_name=host.domain.realm, domain_name=host.domain.name, ) sub_dict = bind.sub_dict.copy() sub_dict.update(BINDKEYS_FILE="/etc/named.iscdlv.key") return template_str(OLD_NAMED_TEMPLATE, sub_dict) def clear_sysupgrade(host, *sections): # get state file statefile = os.path.join(paths.STATEFILE_DIR, STATEFILE_FILE) state = host.get_file_contents(statefile, encoding="utf-8") # parse it parser = configparser.ConfigParser() parser.optionxform = str parser.read_string(state) # remove sections for section in sections: parser.remove_section(section) # dump the modified config out = io.StringIO() parser.write(out) # upload it host.put_file_contents(statefile, out.getvalue()) def get_main_krb_rec_dn(domain): return DN( ('idnsname', '_kerberos'), ('idnsname', domain.name + '.'), dict(DEFAULT_CONFIG)['container_dns'], domain.basedn, ) def get_location_krb_rec_dn(domain, location): return DN( ('idnsname', '_kerberos.' + location + '._locations'), ('idnsname', domain.name + '.'), dict(DEFAULT_CONFIG)['container_dns'], domain.basedn, ) class TestUpgrade(IntegrationTest): """ Test ipa-server-upgrade. Note that ipa-server-upgrade on a CA-less installation is tested in ``test_caless.TestIPACommands.test_invoke_upgrader``. """ @classmethod def install(cls, mh): tasks.install_master(cls.master) tasks.install_dns(cls.master) @pytest.fixture def setup_locations(self): realm = self.master.domain.realm _locations = [] def _setup_locations(locations): _locations = locations ldap = self.master.ldap_connect() for location in locations: self.master.run_command(['ipa', 'location-add', location]) self.master.run_command([ 'ipa', 'server-mod', '--location=' + locations[0], self.master.hostname, ]) main_krb_rec = ldap.get_entry( get_main_krb_rec_dn(self.master.domain), ) main_krb_rec['objectClass'].remove('idnsTemplateObject') del main_krb_rec['idnsTemplateAttribute;cnamerecord'] ldap.update_entry(main_krb_rec) for location in locations: location_krb_rec = ldap.get_entry( get_location_krb_rec_dn(self.master.domain, location), ) del location_krb_rec['tXTRecord'] ldap.update_entry(location_krb_rec) yield _setup_locations ldap = self.master.ldap_connect() modified = False main_krb_rec = ldap.get_entry(get_main_krb_rec_dn(self.master.domain)) if 'idnsTemplateObject' not in main_krb_rec['objectClass']: main_krb_rec['objectClass'].append('idnsTemplateObject') modified = True if 'idnsTemplateAttribute;cnamerecord' not in main_krb_rec: main_krb_rec['idnsTemplateAttribute;cnamerecord'] = \ '_kerberos.\\{substitutionvariable_ipalocation\\}._locations' modified = True if modified: ldap.update_entry(main_krb_rec) for location in _locations: location_krb_rec = ldap.get_entry( get_location_krb_rec_dn(self.master.domain, location), ) if 'tXTRecord' not in location_krb_rec: location_krb_rec['tXTRecord'] = f'"{realm}"' ldap.update_entry(location_krb_rec) self.master.run_command([ 'ipa', 'server-mod', '--location=', self.master.hostname, ]) for location in _locations: self.master.run_command(['ipa', 'location-del', location]) def test_invoke_upgrader(self): cmd = self.master.run_command(['ipa-server-upgrade'], raiseonerr=False) assert ("DN: cn=Schema Compatibility,cn=plugins,cn=config does not \ exists or haven't been updated" not in cmd.stdout_text) assert cmd.returncode == 0 def test_double_encoded_cacert(self): """Test for BZ 1644874 In old IPA version, the entry cn=CAcert,cn=ipa,cn=etc,$basedn could contain a double-encoded cert, which leads to ipa-server-upgrade failure. Force a double-encoded value then call upgrade to check the fix. """ # Read the current entry from LDAP ldap = self.master.ldap_connect() basedn = self.master.domain.basedn dn = DN(('cn', 'CAcert'), ('cn', 'ipa'), ('cn', 'etc'), basedn) entry = ldap.get_entry(dn) # Extract the certificate as DER then double-encode cacert = entry['cacertificate;binary'][0] cacert_der = cacert.public_bytes(serialization.Encoding.DER) cacert_b64 = base64.b64encode(cacert_der) # overwrite the value with double-encoded cert entry.single_value['cACertificate;binary'] = cacert_b64 ldap.update_entry(entry) # try the upgrade self.master.run_command(['ipa-server-upgrade']) # reconnect to the master (upgrade stops 389-ds) ldap = self.master.ldap_connect() # read the value after upgrade, should be fixed entry = ldap.get_entry(dn) try: _cacert = entry['cacertificate;binary'] except ValueError: raise AssertionError('%s contains a double-encoded cert' % entry.dn) def get_named_confs(self): named_conf = self.master.get_file_contents( paths.NAMED_CONF, encoding="utf-8" ) print(named_conf) custom_conf = self.master.get_file_contents( paths.NAMED_CUSTOM_CONF, encoding="utf-8" ) print(custom_conf) opt_conf = self.master.get_file_contents( paths.NAMED_CUSTOM_OPTIONS_CONF, encoding="utf-8" ) print(opt_conf) log_conf = self.master.get_file_contents( paths.NAMED_LOGGING_OPTIONS_CONF, encoding="utf-8" ) print(log_conf) return named_conf, custom_conf, opt_conf, log_conf @pytest.mark.skip_if_platform( "debian", reason="Debian does not use crypto policy" ) def test_named_conf_crypto_policy(self): named_conf = self.master.get_file_contents( paths.NAMED_CONF, encoding="utf-8" ) assert paths.NAMED_CRYPTO_POLICY_FILE in named_conf def test_current_named_conf(self): named_conf, custom_conf, opt_conf, log_conf = self.get_named_confs() # verify that all includes are present exactly one time inc_opt_conf = f'include "{paths.NAMED_CUSTOM_OPTIONS_CONF}";' assert named_conf.count(inc_opt_conf) == 1 inc_custom_conf = f'include "{paths.NAMED_CUSTOM_CONF}";' assert named_conf.count(inc_custom_conf) == 1 inc_log_conf = f'include "{paths.NAMED_LOGGING_OPTIONS_CONF}";' assert named_conf.count(inc_log_conf) == 1 assert "dnssec-validation yes;" in opt_conf assert "dnssec-validation" not in named_conf assert custom_conf assert log_conf def test_update_named_conf_simple(self): # remove files to force a migration self.master.run_command( [ "rm", "-f", paths.NAMED_CUSTOM_CONF, paths.NAMED_CUSTOM_OPTIONS_CONF, paths.NAMED_LOGGING_OPTIONS_CONF, ] ) self.master.run_command(['ipa-server-upgrade']) named_conf, custom_conf, opt_conf, log_conf = self.get_named_confs() # not empty assert custom_conf.strip() assert log_conf.strip() # has dnssec-validation enabled in option config assert "dnssec-validation yes;" in opt_conf assert "dnssec-validation" not in named_conf # verify that both includes are present exactly one time inc_opt_conf = f'include "{paths.NAMED_CUSTOM_OPTIONS_CONF}";' assert named_conf.count(inc_opt_conf) == 1 inc_custom_conf = f'include "{paths.NAMED_CUSTOM_CONF}";' assert named_conf.count(inc_custom_conf) == 1 inc_log_conf = f'include "{paths.NAMED_LOGGING_OPTIONS_CONF}";' assert named_conf.count(inc_log_conf) == 1 def test_update_named_conf_old(self): # remove files to force a migration self.master.run_command( [ "rm", "-f", paths.NAMED_CUSTOM_CONF, paths.NAMED_CUSTOM_OPTIONS_CONF, paths.NAMED_LOGGING_OPTIONS_CONF, ] ) # dump an old named conf to verify migration old_contents = named_test_template(self.master) self.master.put_file_contents(paths.NAMED_CONF, old_contents) clear_sysupgrade(self.master, "dns", "named.conf") # check and skip dnssec-enable-related issues in 9.18+ # where dnssec-enable option was removed completely try: self.master.run_command( ["named-checkconf", paths.NAMED_CONF] ) except CalledProcessError as e: if not('dnssec-enable' in e.output): raise e # upgrade self.master.run_command(['ipa-server-upgrade']) named_conf, custom_conf, opt_conf, log_conf = self.get_named_confs() # not empty assert custom_conf.strip() assert log_conf.strip() # dnssec-validation is migrated as "disabled" from named.conf assert "dnssec-validation no;" in opt_conf assert "dnssec-validation" not in named_conf # verify that both includes are present exactly one time inc_opt_conf = f'include "{paths.NAMED_CUSTOM_OPTIONS_CONF}";' assert named_conf.count(inc_opt_conf) == 1 inc_custom_conf = f'include "{paths.NAMED_CUSTOM_CONF}";' assert named_conf.count(inc_custom_conf) == 1 inc_log_conf = f'include "{paths.NAMED_LOGGING_OPTIONS_CONF}";' assert named_conf.count(inc_log_conf) == 1 def test_admin_root_alias_upgrade_CVE_2020_10747(self): # Test upgrade for CVE-2020-10747 fix # https://bugzilla.redhat.com/show_bug.cgi?id=1810160 rootprinc = "root@{}".format(self.master.domain.realm) self.master.run_command( ["ipa", "user-remove-principal", "admin", rootprinc] ) result = self.master.run_command(["ipa", "user-show", "admin"]) assert rootprinc not in result.stdout_text self.master.run_command(['ipa-server-upgrade']) result = self.master.run_command(["ipa", "user-show", "admin"]) assert rootprinc in result.stdout_text def test_pwpolicy_upgrade(self): """Test that ipapwdpolicy objectclass is added to all policies""" entry_ldif = textwrap.dedent(""" dn: cn=global_policy,cn={realm},cn=kerberos,{base_dn} changetype: modify delete: passwordGraceLimit - delete: objectclass objectclass: ipapwdpolicy """).format( base_dn=str(self.master.domain.basedn), realm=self.master.domain.realm) tasks.ldapmodify_dm(self.master, entry_ldif) tasks.kinit_admin(self.master) self.master.run_command(['ipa-server-upgrade']) result = self.master.run_command(["ipa", "pwpolicy-find"]) # if it is still missing the oc it won't be displayed assert 'global_policy' in result.stdout_text def test_kra_detection(self): """Test that ipa-server-upgrade correctly detects KRA presence Test for https://pagure.io/freeipa/issue/8596 When the directory /var/lib/pki/pki-tomcat/kra/ exists, the upgrade wrongly assumes that KRA component is installed and crashes. The test creates an empty dir and calls kra.is_installed() to make sure that KRA detection is not based on the directory presence. Note: because of issue https://github.com/dogtagpki/pki/issues/3397 ipa-server-upgrade fails even with the kra detection fix. That's why the test does not exercise the whole ipa-server-upgrade command but only the KRA detection part. """ kra_path = os.path.join(paths.VAR_LIB_PKI_TOMCAT_DIR, "kra") try: self.master.run_command(["mkdir", "-p", kra_path]) script = ( "from ipalib import api; " "from ipaserver.install import krainstance; " "api.bootstrap(); " "api.finalize(); " "kra = krainstance.KRAInstance(api.env.realm); " "print(kra.is_installed())" ) result = self.master.run_command(['python3', '-c', script]) assert "False" in result.stdout_text finally: self.master.run_command(["rmdir", kra_path]) def test_krb_uri_txt_to_cname(self, setup_locations): """Test that ipa-server-upgrade correctly updates Kerberos DNS records Test for https://pagure.io/freeipa/issue/9257 Kerberos URI and TXT DNS records should be location-aware in case the server is part of a location, in order for DNS discovery to prioritize servers from the same location. This means that for such servers the _kerberos record should be a CNAME one pointing to the appropriate set of location-aware records. """ realm = self.master.domain.realm locations = ['a', 'b'] setup_locations(locations) self.master.run_command(['ipa-server-upgrade']) ldap = self.master.ldap_connect() main_krb_rec = ldap.get_entry( get_main_krb_rec_dn(self.master.domain), ) assert 'idnsTemplateObject' in main_krb_rec['objectClass'] assert len(main_krb_rec['idnsTemplateAttribute;cnamerecord']) == 1 assert main_krb_rec['idnsTemplateAttribute;cnamerecord'][0] \ == '_kerberos.\\{substitutionvariable_ipalocation\\}._locations' for location in locations: location_krb_rec = ldap.get_entry( get_location_krb_rec_dn(self.master.domain, location), ) assert 'tXTRecord' in location_krb_rec assert len(location_krb_rec['tXTRecord']) == 1 assert location_krb_rec['tXTRecord'][0] == f'"{realm}"' def test_pki_dropin_file(self): """Test that upgrade adds the drop-in file if missing Test for ticket 9381 Simulate an update from a version that didn't provide /etc/systemd/system/pki-tomcatd@pki-tomcat.service.d/ipa.conf, remove one of the certificate profiles from LDAP and check that upgrade completes successfully and adds the missing file. When the drop-in file is missing, the upgrade tries to login to PKI in order to migrate the profile and fails because PKI failed to start. """ self.master.run_command(["rm", "-f", paths.SYSTEMD_PKI_TOMCAT_IPA_CONF]) ldif = textwrap.dedent(""" dn: cn=caECServerCertWithSCT,ou=certificateProfiles,ou=ca,o=ipaca changetype: delete """) tasks.ldapmodify_dm(self.master, ldif) self.master.run_command(['ipa-server-upgrade']) assert self.master.transport.file_exists( paths.SYSTEMD_PKI_TOMCAT_IPA_CONF) def test_ssh_config(self): """Test that pkg upgrade does not create /etc/ssh/ssh_config.orig Test for ticket 9610 The upgrade of ipa-client package should not create a backup file /etc/ssh/ssh_config.orig if no change is applied. """ # Ensure there is no backup file before the test self.master.run_command(["rm", "-f", paths.SSH_CONFIG + ".orig"]) # Force client package reinstallation to trigger %post scriptlet tasks.reinstall_packages(self.master, ['*ipa-client']) assert not self.master.transport.file_exists( paths.SSH_CONFIG + ".orig") def test_mspac_attribute_set(self): """ This testcase deletes the already existing attribute 'ipaKrbAuthzData: MS-PAC'. The test then runs ipa-server-upgrade and checks that the attribute 'ipaKrbAuthzData: MS-PAC' is added again. """ base_dn = str(self.master.domain.basedn) dn = DN( ("cn", "ipaConfig"), ("cn", "etc"), base_dn ) ldif = textwrap.dedent(""" dn: cn=ipaConfig,cn=etc,{} changetype: modify delete: ipaKrbAuthzData """).format(base_dn) tasks.ldapmodify_dm(self.master, ldif) tasks.kinit_admin(self.master) self.master.run_command(['ipa-server-upgrade']) result = tasks.ldapsearch_dm(self.master, str(dn), ["ipaKrbAuthzData"]) assert 'ipaKrbAuthzData: MS-PAC' in result.stdout_text
19,401
Python
.py
450
33.653333
80
0.623067
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,538
test_trust.py
freeipa_freeipa/ipatests/test_integration/test_trust.py
# Copyright (C) 2019 FreeIPA Contributors see COPYING for license from __future__ import absolute_import import re import textwrap import time import functools import pytest from ipaplatform.constants import constants as platformconstants from ipaplatform.paths import paths from ipatests.test_integration.base import IntegrationTest from ipatests.pytest_ipa.integration import tasks from ipatests.pytest_ipa.integration import fips from ipatests.util import xfail_context from ipapython.dn import DN from collections import namedtuple from contextlib import contextmanager TestDataRule = namedtuple('TestDataRule', ['name', 'ruletype', 'user', 'subject']) def skip_in_fips_mode_due_to_issue_8715(test_method): @functools.wraps(test_method) def wrapper(instance): if fips.is_fips_enabled(instance.master): pytest.skip('Skipping in FIPS mode due to ' 'https://pagure.io/freeipa/issue/8715') else: test_method(instance) return wrapper class BaseTestTrust(IntegrationTest): num_clients = 1 topology = 'line' num_ad_domains = 1 num_ad_subdomains = 1 num_ad_treedomains = 1 upn_suffix = 'UPNsuffix.com' upn_username = 'upnuser' upn_name = 'UPN User' upn_principal = '{}@{}'.format(upn_username, upn_suffix) upn_password = 'Secret123456' shared_secret = 'qwertyuiopQq!1' default_shell = platformconstants.DEFAULT_SHELL @classmethod def install(cls, mh): if not cls.master.transport.file_exists('/usr/bin/rpcclient'): raise pytest.skip("Package samba-client not available " "on {}".format(cls.master.hostname)) super(BaseTestTrust, cls).install(mh) cls.ad = cls.ads[0] cls.ad_domain = cls.ad.domain.name tasks.install_adtrust(cls.master) cls.check_sid_generation() tasks.sync_time(cls.master, cls.ad) if cls.num_ad_subdomains > 0: cls.child_ad = cls.ad_subdomains[0] cls.ad_subdomain = cls.child_ad.domain.name if cls.num_ad_treedomains > 0: cls.tree_ad = cls.ad_treedomains[0] cls.ad_treedomain = cls.tree_ad.domain.name # values used in workaround for # https://bugzilla.redhat.com/show_bug.cgi?id=1711958 cls.srv_gc_record_name = \ '_ldap._tcp.Default-First-Site-Name._sites.gc._msdcs' cls.srv_gc_record_value = '0 100 389 {}.'.format(cls.master.hostname) @classmethod def check_sid_generation(cls): command = ['ipa', 'user-show', 'admin', '--all', '--raw'] # TODO: remove duplicate definition and import from common module _sid_identifier_authority = '(0x[0-9a-f]{1,12}|[0-9]{1,10})' sid_regex = 'S-1-5-21-%(idauth)s-%(idauth)s-%(idauth)s'\ % dict(idauth=_sid_identifier_authority) stdout_re = re.escape(' ipaNTSecurityIdentifier: ') + sid_regex tasks.run_repeatedly(cls.master, command, test=lambda x: re.search(stdout_re, x)) def check_trustdomains(self, realm, expected_ad_domains): """Check that ipa trustdomain-find lists all expected domains""" result = self.master.run_command(['ipa', 'trustdomain-find', realm]) for domain in expected_ad_domains: expected_text = 'Domain name: %s\n' % domain assert expected_text in result.stdout_text expected_text = ("Number of entries returned %s\n" % len(expected_ad_domains)) assert expected_text in result.stdout_text def check_range_properties(self, realm, expected_type, expected_size): """Check the properties of the created range""" range_name = realm.upper() + '_id_range' result = self.master.run_command(['ipa', 'idrange-show', range_name, '--all', '--raw']) expected_text = 'ipaidrangesize: %s\n' % expected_size assert expected_text in result.stdout_text expected_text = 'iparangetype: %s\n' % expected_type assert expected_text in result.stdout_text def mod_idrange_auto_private_group( self, option='false' ): """ Set the auto-private-group option of the default trusted AD domain range. """ tasks.kinit_admin(self.master) rangename = self.ad_domain.upper() + '_id_range' error_msg = "ipa: ERROR: no modifications to be performed" cmd = ["ipa", "idrange-mod", rangename, "--auto-private-groups", option] result = self.master.run_command(cmd, raiseonerr=False) if result.returncode != 0: tasks.assert_error(result, error_msg) tasks.clear_sssd_cache(self.master) tasks.clear_sssd_cache(self.clients[0]) test = self.master.run_command(["ipa", "idrange-show", rangename]) assert "Auto private groups: {0}".format(option) in test.stdout_text def get_user_id(self, host, username): """ User uid gid is parsed from the output of id user command. """ tasks.clear_sssd_cache(self.master) tasks.clear_sssd_cache(self.clients[0]) self.master.run_command(["id", username]) test_id = host.run_command(["id", username]) regex = r"^uid=(?P<uid>\d+).*gid=(?P<gid>\d+).*groups=(?P<groups>\d+)" match = re.match(regex, test_id.stdout_text) uid = match.group('uid') gid = match.group('gid') return uid, gid @contextmanager def set_idoverrideuser(self, user, uid, gid): """ Fixture to add/remove idoverrideuser for default idview, also creates idm group with the provided gid because gid overrides requires an existing group. """ tasks.clear_sssd_cache(self.master) tasks.clear_sssd_cache(self.clients[0]) tasks.kinit_admin(self.master) try: args = ["ipa", "idoverrideuser-add", "Default Trust View", "--gid", gid, "--uid", uid, user] self.master.run_command(args) tasks.group_add(self.master, "idgroup", extra_args=["--gid", gid]) yield finally: self.master.run_command([ "ipa", "idoverrideuser-del", "Default Trust View", user] ) self.master.run_command(["ipa", "group-del", "idgroup"]) def remove_trust(self, ad): tasks.remove_trust_with_ad(self.master, ad.domain.name, ad.hostname) tasks.clear_sssd_cache(self.master) class TestTrust(BaseTestTrust): # Tests for non-posix AD trust def test_establish_nonposix_trust(self): tasks.configure_dns_for_trust(self.master, self.ad) tasks.establish_trust_with_ad( self.master, self.ad_domain, extra_args=['--range-type', 'ipa-ad-trust']) def test_trustdomains_found_in_nonposix_trust(self): self.check_trustdomains( self.ad_domain, [self.ad_domain, self.ad_subdomain]) def test_range_properties_in_nonposix_trust(self): self.check_range_properties(self.ad_domain, 'ipa-ad-trust', 200000) def test_user_gid_uid_resolution_in_nonposix_trust(self): """Check that user has SID-generated UID""" # Using domain name since it is lowercased realm name for AD domains testuser = 'testuser@%s' % self.ad_domain result = self.master.run_command(['getent', 'passwd', testuser]) # This regex checks that Test User does not have UID 10042 nor belongs # to the group with GID 10047 testuser_regex = r"^testuser@%s:\*:(?!10042)(\d+):(?!10047)(\d+):"\ r"Test User:/home/%s/testuser:%s$"\ % (re.escape(self.ad_domain), re.escape(self.ad_domain), self.default_shell, ) assert re.search( testuser_regex, result.stdout_text), result.stdout_text def test_ipa_commands_run_as_aduser(self): """Test if proper error thrown when AD user tries to run IPA commands Before fix the error used to implies that the ipa setup is broken. Fix is to throw the proper error. This test is to check that the error with 'Invalid credentials' thrown when AD user tries to run IPA commands. related: https://pagure.io/freeipa/issue/8163 """ tasks.kdestroy_all(self.master) ad_admin = 'Administrator@%s' % self.ad_domain tasks.kinit_as_user(self.master, ad_admin, self.master.config.ad_admin_password) err_string1 = 'ipa: ERROR: Insufficient access: ' err_string2 = 'Invalid credentials' result = self.master.run_command(['ipa', 'ping'], raiseonerr=False) assert err_string1 in result.stderr_text assert err_string2 in result.stderr_text tasks.kdestroy_all(self.master) tasks.kinit_admin(self.master) def test_ipa_management_run_as_aduser(self): """Test if adding AD user to a role makes it an administrator""" ipauser = u'tuser' ad_admin = 'Administrator@%s' % self.ad_domain tasks.kdestroy_all(self.master) tasks.kinit_admin(self.master) self.master.run_command(['ipa', 'idoverrideuser-add', 'Default Trust View', ad_admin]) self.master.run_command(['ipa', 'role-add-member', 'User Administrator', '--idoverrideusers', ad_admin]) tasks.kdestroy_all(self.master) tasks.kinit_as_user(self.master, ad_admin, self.master.config.ad_admin_password) # Create a user in IPA as Active Directory administrator self.test_ipauser_authentication_with_nonposix_trust() tasks.kdestroy_all(self.master) tasks.kinit_as_user(self.master, ad_admin, self.master.config.ad_admin_password) self.master.run_command(['ipa', 'user-del', ipauser], raiseonerr=False) tasks.kdestroy_all(self.master) tasks.kinit_admin(self.master) def test_password_login_as_aduser(self): """Test if AD user can login with password to Web UI""" ad_admin = 'Administrator@%s' % self.ad_domain tasks.kdestroy_all(self.master) user_and_password = ('user=%s&password=%s' % (ad_admin, self.master.config.ad_admin_password)) host = self.master.hostname cmd_args = [ paths.BIN_CURL, '-v', '-H', 'referer:https://{}/ipa'.format(host), '-H', 'Content-Type:application/x-www-form-urlencoded', '-H', 'Accept:text/plain', '--cacert', paths.IPA_CA_CRT, '--data', user_and_password, 'https://{}/ipa/session/login_password'.format(host)] result = self.master.run_command(cmd_args) assert "Set-Cookie: ipa_session=MagBearerToken" in result.stderr_text tasks.kinit_admin(self.master) def test_ipauser_authentication_with_nonposix_trust(self): ipauser = u'tuser' original_passwd = 'Secret123' new_passwd = 'userPasswd123' # create an ipauser for this test self.master.run_command(['ipa', 'user-add', ipauser, '--first=Test', '--last=User', '--password'], stdin_text=original_passwd) # change password for the user to be able to kinit tasks.ldappasswd_user_change(ipauser, original_passwd, new_passwd, self.master) # try to kinit as ipauser self.master.run_command([ 'kinit', '-E', '{0}@{1}'.format(ipauser, self.master.domain.name)], stdin_text=new_passwd) # Tests for UPN suffixes def test_upn_in_nonposix_trust(self): """Check that UPN is listed as trust attribute""" result = self.master.run_command(['ipa', 'trust-show', self.ad_domain, '--all', '--raw']) assert ("ipantadditionalsuffixes: {}".format(self.upn_suffix) in result.stdout_text) def test_upn_user_resolution_in_nonposix_trust(self): """Check that user with UPN can be resolved""" result = self.master.run_command(['getent', 'passwd', self.upn_principal]) # result will contain AD domain, not UPN upnuser_regex = ( r"^{}@{}:\*:(\d+):(\d+):{}:/home/{}/{}:{}$".format( self.upn_username, self.ad_domain, self.upn_name, self.ad_domain, self.upn_username, self.default_shell, ) ) assert re.search(upnuser_regex, result.stdout_text), result.stdout_text def test_upn_user_authentication_in_nonposix_trust(self): """ Check that AD user with UPN can authenticate in IPA """ self.master.run_command(['kinit', '-C', '-E', self.upn_principal], stdin_text=self.upn_password) @contextmanager def check_sudorules_for(self, object_type, object_name, testuser, expected): """Verify trusted domain objects can be added to sudorules""" # Create a SUDO rule that allows test user # to run any command on any host as root without password # and check that it is indeed possible to do so with sudo -l hbacrule = 'hbacsudoers-' + object_type sudorule = 'testrule-' + object_type commands = [['ipa', 'hbacrule-add', hbacrule, '--usercat=all', '--hostcat=all'], ['ipa', 'hbacrule-add-service', hbacrule, '--hbacsvcs=sudo'], ['ipa', 'sudocmd-add', 'ALL'], ['ipa', 'sudorule-add', sudorule, '--hostcat=all'], ['ipa', 'sudorule-add-user', sudorule, '--users', object_name], ['ipa', 'sudorule-add-option', sudorule, '--sudooption', '!authenticate'], ['ipa', 'sudorule-add-allow-command', sudorule, '--sudocmds', 'ALL']] for c in commands: self.master.run_command(c) # allow additional configuration yield TestDataRule(sudorule, 'sudo', object_name, testuser) # Modify refresh_expired_interval to reduce time for refreshing # expired entries in SSSD cache in order to avoid waiting at least # 30 seconds before SSSD updates SUDO rules and undertermined time # that takes to refresh the rules. sssd_conf_backup = tasks.FileBackup(self.master, paths.SSSD_CONF) try: with tasks.remote_sssd_config(self.master) as sssd_conf: sssd_conf.edit_domain( self.master.domain, 'refresh_expired_interval', 1) sssd_conf.edit_domain( self.master.domain, 'entry_cache_timeout', 1) tasks.clear_sssd_cache(self.master) # Sleep some time so that SSSD settles down # cache updates time.sleep(10) result = self.master.run_command( ['su', '-', testuser, '-c', 'sudo -l']) if isinstance(expected, (tuple, list)): assert any(x for x in expected if x in result.stdout_text) else: assert expected in result.stdout_text finally: sssd_conf_backup.restore() tasks.clear_sssd_cache(self.master) commands = [['ipa', 'sudorule-del', sudorule], ['ipa', 'sudocmd-del', 'ALL'], ['ipa', 'hbacrule-del', hbacrule]] for c in commands: self.master.run_command(c) def test_sudorules_ad_users(self): """Verify trusted domain users can be added to sudorules""" tasks.kdestroy_all(self.master) tasks.kinit_admin(self.master) testuser = '%s@%s' % (self.master.config.ad_admin_name, self.ad_domain) expected = "(root) NOPASSWD: ALL" with self.check_sudorules_for("user", testuser, testuser, expected): # no additional configuration pass def test_sudorules_ad_groups(self): """Verify trusted domain groups can be added to sudorules""" tasks.kdestroy_all(self.master) tasks.kinit_admin(self.master) testuser = '%s@%s' % (self.master.config.ad_admin_name, self.ad_domain) testgroup = 'Enterprise Admins@%s' % self.ad_domain expected = "(root) NOPASSWD: ALL" with self.check_sudorules_for("group", testuser, testuser, expected) as sudorule: # Remove the user and instead add a group self.master.run_command(['ipa', 'sudorule-remove-user', sudorule.name, '--users', sudorule.user]) self.master.run_command(['ipa', 'sudorule-add-user', sudorule.name, '--groups', testgroup]) def test_sudorules_ad_runasuser(self): """Verify trusted domain users can be added to runAsUser""" tasks.kdestroy_all(self.master) tasks.kinit_admin(self.master) testuser = '%s@%s' % (self.master.config.ad_admin_name, self.ad_domain) expected = "(%s) NOPASSWD: ALL" % (testuser.lower()) with self.check_sudorules_for("user", testuser, testuser, expected) as sudorule: # Add runAsUser with the same user self.master.run_command(['ipa', 'sudorule-add-runasuser', sudorule.name, '--users', sudorule.subject]) def test_sudorules_ad_runasuser_group(self): """Verify trusted domain groups can be added to runAsUser""" tasks.kdestroy_all(self.master) tasks.kinit_admin(self.master) testuser = '%s@%s' % (self.master.config.ad_admin_name, self.ad_domain) testgroup = 'Enterprise Admins@%s' % self.ad_domain expected1 = '("%%%s") NOPASSWD: ALL' % testgroup.lower() expected2 = '("%%%%%s") NOPASSWD: ALL' % testgroup.lower() with self.check_sudorules_for("group", testuser, testuser, [expected1, expected2]) as sudorule: # Add runAsUser with the same user self.master.run_command(['ipa', 'sudorule-add-runasuser', sudorule.name, '--groups', testgroup]) def test_sudorules_ad_runasgroup(self): """Verify trusted domain groups can be added to runAsGroup""" tasks.kdestroy_all(self.master) tasks.kinit_admin(self.master) testuser = '%s@%s' % (self.master.config.ad_admin_name, self.ad_domain) testgroup = 'Enterprise Admins@%s' % self.ad_domain expected = '(%s : "%%%s") NOPASSWD: ALL' % (testuser.lower(), testgroup.lower()) with self.check_sudorules_for("group", testuser, testuser, expected) as sudorule: # Add runAsGroup with the same user self.master.run_command(['ipa', 'sudorule-add-runasgroup', sudorule.name, '--groups', testgroup]) # Test with AD trust defining subordinate suffixes def test_subordinate_suffix(self): """Test subordinate UPN suffixes routing. Given an AD domain ad.test with additional UPN suffix suffix.ad.test check that requests from IPA for suffix.ad.test are properly routed to ad.test. This is a regression test for https://pagure.io/freeipa/issue/8554 """ # Create subordinate UPN suffix subordinate_suffix = 'test_subdomain.' + self.ad_domain self.ad.run_command([ 'powershell', '-c', 'Set-ADForest -Identity {} -UPNSuffixes @{{add="{}"}}'.format( self.ad_domain, subordinate_suffix)]) try: # Verify UPN suffix is created cmd = ('Get-ADForest -Identity {} ' '| Select-Object -Property UPNSuffixes' .format(self.ad_domain)) res = self.ad.run_command(['powershell', '-c', cmd]) assert subordinate_suffix in res.stdout_text # Verify IPA does not receive subordinate suffix from AD self.master.run_command( ['ipa', 'trust-fetch-domains', self.ad_domain], ok_returncode=1) res = self.master.run_command( ['ipa', 'trust-show', self.ad_domain]) assert subordinate_suffix not in res.stdout_text # Set UPN for the AD user upn = 'testuser@' + subordinate_suffix cmd = 'Set-Aduser -UserPrincipalName {} -Identity testuser'.format( upn) self.ad.run_command(['powershell', '-c', cmd]) # Check user resolution res = self.master.run_command(['getent', 'passwd', upn]) expected_regex = ( r'^testuser@{domain}:\*:(\d+):(\d+):' r'Test User:/home/{domain}/testuser:{shell}$' .format(domain=re.escape(self.ad_domain), shell=self.default_shell)) assert re.search(expected_regex, res.stdout_text) # Check user authentication self.master.run_command( ['kinit', '-E', upn], stdin_text='Secret123') finally: # cleanup tasks.kdestroy_all(self.master) cmd = ('Set-ADForest -Identity {} -UPNSuffixes @{{Remove="{}"}}' .format(self.ad_domain, subordinate_suffix)) self.ad.run_command(['powershell', '-c', cmd]) def test_ssh_aduser(self): """Test ssh with GSSAPI is working with aduser When kerberos ticket is obtained for child domain user and ssh with this ticket should be successful with no password prompt. Related : https://pagure.io/freeipa/issue/9316 """ testuser = 'testuser@{0}'.format(self.ad_domain) testusersub = 'subdomaintestuser@{0}'.format(self.ad_subdomain) def sshuser(host, user): tasks.kdestroy_all(host) try: tasks.kinit_as_user(host, user, host.config.ad_admin_password ) ssh_cmd = "ssh -q -K -l {user} {host} hostname" valid_ssh = host.run_command( ssh_cmd.format(user=user, host=host.hostname) ) assert host.hostname in valid_ssh.stdout_text finally: tasks.kdestroy_all(host) sshuser(self.master, testuser) sshuser(self.master, testusersub) def test_remove_nonposix_trust(self): self.remove_trust(self.ad) tasks.unconfigure_dns_for_trust(self.master, self.ad) # Tests for posix AD trust def test_establish_posix_trust(self): tasks.configure_dns_for_trust(self.master, self.ad) tasks.establish_trust_with_ad( self.master, self.ad_domain, extra_args=['--range-type', 'ipa-ad-trust-posix']) def test_trustdomains_found_in_posix_trust(self): """Tests that all trustdomains can be found.""" self.check_trustdomains( self.ad_domain, [self.ad_domain, self.ad_subdomain]) def test_range_properties_in_posix_trust(self): """Check the properties of the created range""" self.check_range_properties(self.ad_domain, 'ipa-ad-trust-posix', 200000) def test_user_uid_gid_resolution_in_posix_trust(self): """Check that user has AD-defined UID""" # Using domain name since it is lowercased realm name for AD domains testuser = 'testuser@%s' % self.ad_domain result = self.master.run_command(['getent', 'passwd', testuser]) testuser_stdout = "testuser@%s:*:10042:10047:"\ "Test User:/home/%s/testuser:%s"\ % (self.ad_domain, self.ad_domain, self.default_shell, ) assert testuser_stdout in result.stdout_text def test_user_without_posix_attributes_not_visible(self): """Check that user has AD-defined UID""" # Using domain name since it is lowercased realm name for AD domains nonposixuser = 'nonposixuser@%s' % self.ad_domain result = self.master.run_command(['getent', 'passwd', nonposixuser], raiseonerr=False) # Getent exits with 2 for non-existent user assert result.returncode == 2 def test_override_homedir(self): """POSIX attributes should not be overwritten or missing. Regression test for bug https://pagure.io/SSSD/sssd/issue/2474 When there is IPA-AD trust with POSIX attributes, including the home directory set in the AD LDAP and in sssd.conf subdomain_homedir = %o is added after initgroup call home directory should be correct and do not report in logs like, 'get_subdomain_homedir_of_user failed: * [Home directory is NULL]' """ tasks.backup_file(self.master, paths.SSSD_CONF) log_file = '{0}/sssd_{1}.log' .format(paths.VAR_LOG_SSSD_DIR, self.master.domain.name) logsize = len(self.master.get_file_contents(log_file)) try: testuser = 'testuser@%s' % self.ad_domain with tasks.remote_sssd_config(self.master) as sssd_conf: sssd_conf.edit_domain(self.master.domain, 'subdomain_homedir', '%o') tasks.clear_sssd_cache(self.master) # The initgroups operation now uses the LDAP connection because # the LDAP AD DS server contains the POSIX attributes self.master.run_command(['getent', 'initgroups', '-s', 'sss', testuser]) result = self.master.run_command(['getent', 'passwd', testuser]) assert '/home/testuser' in result.stdout_text sssd_log2 = self.master.get_file_contents(log_file)[logsize:] assert b'get_subdomain_homedir_of_user failed' not in sssd_log2 finally: tasks.restore_files(self.master) tasks.clear_sssd_cache(self.master) def test_extdom_plugin(self): """Extdom plugin should not return error (32)/'No such object' Regression test for https://pagure.io/freeipa/issue/8044 If there is a timeout during a request to SSSD the extdom plugin should not return error 'No such object' and the existing user should not be added to negative cache on the client. """ extdom_dn = DN( ('cn', 'ipa_extdom_extop'), ('cn', 'plugins'), ('cn', 'config') ) client = self.clients[0] tasks.backup_file(self.master, paths.SSSD_CONF) res = self.master.run_command(['pidof', 'sssd_be']) pid = res.stdout_text.strip() test_id = 'id testuser@%s' % self.ad_domain client.run_command(test_id) conn = self.master.ldap_connect() entry = conn.get_entry(extdom_dn) orig_extdom_timeout = entry.single_value.get('ipaextdommaxnsstimeout') # set the extdom plugin timeout to 1s (1000) entry.single_value['ipaextdommaxnsstimeout'] = 1000 conn.update_entry(entry) self.master.run_command(['ipactl', 'restart']) with tasks.remote_sssd_config(self.master) as sssd_conf: sssd_conf.edit_domain(self.master.domain, 'timeout', '999999') remove_cache = 'sss_cache -E' self.master.run_command(remove_cache) client.run_command(remove_cache) log_file = '{0}/sssd_{1}.log'.format(paths.VAR_LOG_SSSD_DIR, client.domain.name) logsize = len(client.get_file_contents(log_file)) try: # stop sssd_be, needed to simulate a timeout in the extdom plugin. self.master.run_command('kill -STOP %s' % pid) try: client.run_command(test_id) error = 'ldap_extended_operation result: No such object(32)' sssd_log2 = client.get_file_contents(log_file)[logsize:] assert error.encode() not in sssd_log2 finally: self.master.run_command('kill -CONT %s' % pid) finally: # reconnect and set back to default extdom plugin conn = self.master.ldap_connect() entry = conn.get_entry(extdom_dn) entry.single_value['ipaextdommaxnsstimeout'] = orig_extdom_timeout conn.update_entry(entry) tasks.restore_files(self.master) self.master.run_command(['ipactl', 'restart']) def test_remove_posix_trust(self): self.remove_trust(self.ad) tasks.unconfigure_dns_for_trust(self.master, self.ad) # Tests for handling invalid trust types def test_invalid_range_types(self): invalid_range_types = ['ipa-local', 'ipa-ad-winsync', 'ipa-ipa-trust', 'random-invalid', 're@ll%ybad12!'] tasks.configure_dns_for_trust(self.master, self.ad) try: for range_type in invalid_range_types: tasks.kinit_admin(self.master) result = self.master.run_command( ['ipa', 'trust-add', '--type', 'ad', self.ad_domain, '--admin', 'Administrator@' + self.ad_domain, '--range-type', range_type, '--password'], raiseonerr=False, stdin_text=self.master.config.ad_admin_password) # The trust-add command is supposed to fail assert result.returncode == 1 assert "ERROR: invalid 'range_type'" in result.stderr_text finally: tasks.unconfigure_dns_for_trust(self.master, self.ad) # Tests for external trust with AD subdomain def test_establish_external_subdomain_trust(self): tasks.configure_dns_for_trust(self.master, self.ad) tasks.establish_trust_with_ad( self.master, self.ad_subdomain, extra_args=['--range-type', 'ipa-ad-trust', '--external=True']) def test_trustdomains_found_in_external_subdomain_trust(self): self.check_trustdomains( self.ad_subdomain, [self.ad_subdomain]) def test_user_gid_uid_resolution_in_external_subdomain_trust(self): """Check that user has SID-generated UID""" testuser = 'subdomaintestuser@{0}'.format(self.ad_subdomain) result = self.master.run_command(['getent', 'passwd', testuser]) testuser_regex = (r"^subdomaintestuser@{0}:\*:(?!10142)(\d+):" r"(?!10147)(\d+):Subdomaintest User:" r"/home/{1}/subdomaintestuser:{2}$".format( re.escape(self.ad_subdomain), re.escape(self.ad_subdomain), self.default_shell, )) assert re.search(testuser_regex, result.stdout_text) def test_remove_external_subdomain_trust(self): self.remove_trust(self.child_ad) tasks.unconfigure_dns_for_trust(self.master, self.ad) # Tests for non-external trust with AD subdomain def test_establish_nonexternal_subdomain_trust(self): tasks.configure_dns_for_trust(self.master, self.ad) try: tasks.kinit_admin(self.master) result = self.master.run_command([ 'ipa', 'trust-add', '--type', 'ad', self.ad_subdomain, '--admin', 'Administrator@' + self.ad_subdomain, '--password', '--range-type', 'ipa-ad-trust' ], stdin_text=self.master.config.ad_admin_password, raiseonerr=False) assert result != 0 assert ("Domain '{0}' is not a root domain".format( self.ad_subdomain) in result.stderr_text) finally: tasks.unconfigure_dns_for_trust(self.master, self.ad) # Tests for external trust with tree domain def test_establish_external_treedomain_trust(self): tasks.configure_dns_for_trust(self.master, self.ad, self.tree_ad) tasks.establish_trust_with_ad( self.master, self.ad_treedomain, extra_args=['--range-type', 'ipa-ad-trust', '--external=True']) def test_trustdomains_found_in_external_treedomain_trust(self): self.check_trustdomains( self.ad_treedomain, [self.ad_treedomain]) def test_user_gid_uid_resolution_in_external_treedomain_trust(self): """Check that user has SID-generated UID""" testuser = 'treetestuser@{0}'.format(self.ad_treedomain) result = self.master.run_command(['getent', 'passwd', testuser]) testuser_regex = (r"^treetestuser@{0}:\*:(?!10242)(\d+):" r"(?!10247)(\d+):TreeTest User:" r"/home/{1}/treetestuser:{2}$".format( re.escape(self.ad_treedomain), re.escape(self.ad_treedomain), self.default_shell, )) assert re.search( testuser_regex, result.stdout_text), result.stdout_text def test_ssh_adtreeuser(self): testuser = 'treetestuser@{0}'.format(self.ad_treedomain) self.master.run_command(["id", testuser]) tasks.clear_sssd_cache(self.master) tasks.kdestroy_all(self.master) try: tasks.kinit_as_user(self.master, testuser, password="Secret123456" ) ssh_cmd = "ssh -q -K -l {user} {host} hostname" valid_ssh = self.master.run_command( ssh_cmd.format(user=testuser, host=self.master.hostname) ) assert self.master.hostname in valid_ssh.stdout_text finally: tasks.kdestroy_all(self.master) def test_remove_external_treedomain_trust(self): self.remove_trust(self.tree_ad) tasks.unconfigure_dns_for_trust(self.master, self.ad, self.tree_ad) # Test for non-external trust with tree domain def test_establish_nonexternal_treedomain_trust(self): tasks.configure_dns_for_trust(self.master, self.ad, self.tree_ad) try: tasks.kinit_admin(self.master) result = self.master.run_command([ 'ipa', 'trust-add', '--type', 'ad', self.ad_treedomain, '--admin', 'Administrator@' + self.ad_treedomain, '--password', '--range-type', 'ipa-ad-trust' ], stdin_text=self.master.config.ad_admin_password, raiseonerr=False) assert result != 0 assert ("Domain '{0}' is not a root domain".format( self.ad_treedomain) in result.stderr_text) finally: tasks.unconfigure_dns_for_trust(self.master, self.ad, self.tree_ad) # Tests for external trust with root domain def test_establish_external_rootdomain_trust(self): tasks.configure_dns_for_trust(self.master, self.ad) tasks.establish_trust_with_ad( self.master, self.ad_domain, extra_args=['--range-type', 'ipa-ad-trust', '--external=True']) def test_trustdomains_found_in_external_rootdomain_trust(self): self.check_trustdomains(self.ad_domain, [self.ad_domain]) def test_remove_external_rootdomain_trust(self): self.remove_trust(self.ad) tasks.unconfigure_dns_for_trust(self.master, self.ad) # Test for one-way forest trust with shared secret @skip_in_fips_mode_due_to_issue_8715 def test_establish_forest_trust_with_shared_secret(self): tasks.configure_dns_for_trust(self.master, self.ad) tasks.configure_windows_dns_for_trust(self.ad, self.master) # this is a workaround for # https://bugzilla.redhat.com/show_bug.cgi?id=1711958 self.master.run_command( ['ipa', 'dnsrecord-add', self.master.domain.name, self.srv_gc_record_name, '--srv-rec', self.srv_gc_record_value]) # create windows side of trust using powershell bindings # to .Net functions ps_cmd = ( '[System.DirectoryServices.ActiveDirectory.Forest]' '::getCurrentForest()' '.CreateLocalSideOfTrustRelationship("{}", 1, "{}")'.format( self.master.domain.name, self.shared_secret)) self.ad.run_command(['powershell', '-c', ps_cmd]) # create ipa side of trust tasks.establish_trust_with_ad( self.master, self.ad_domain, shared_secret=self.shared_secret) @skip_in_fips_mode_due_to_issue_8715 def test_trustdomains_found_in_forest_trust_with_shared_secret(self): result = self.master.run_command( ['ipa', 'trust-fetch-domains', self.ad.domain.name], raiseonerr=False) assert result.returncode == 1 self.check_trustdomains( self.ad_domain, [self.ad_domain, self.ad_subdomain]) @skip_in_fips_mode_due_to_issue_8715 def test_user_gid_uid_resolution_in_forest_trust_with_shared_secret(self): """Check that user has SID-generated UID""" # Using domain name since it is lowercased realm name for AD domains testuser = 'testuser@%s' % self.ad_domain result = self.master.run_command(['getent', 'passwd', testuser]) # This regex checks that Test User does not have UID 10042 nor belongs # to the group with GID 10047 testuser_regex = r"^testuser@%s:\*:(?!10042)(\d+):(?!10047)(\d+):"\ r"Test User:/home/%s/testuser:%s$"\ % (re.escape(self.ad_domain), re.escape(self.ad_domain), self.default_shell, ) assert re.search( testuser_regex, result.stdout_text), result.stdout_text @skip_in_fips_mode_due_to_issue_8715 def test_remove_forest_trust_with_shared_secret(self): ps_cmd = ( '[System.DirectoryServices.ActiveDirectory.Forest]' '::getCurrentForest()' '.DeleteLocalSideOfTrustRelationship("{}")'.format( self.master.domain.name)) self.ad.run_command(['powershell', '-c', ps_cmd]) self.remove_trust(self.ad) # this is cleanup for workaround for # https://bugzilla.redhat.com/show_bug.cgi?id=1711958 self.master.run_command( ['ipa', 'dnsrecord-del', self.master.domain.name, self.srv_gc_record_name, '--srv-rec', self.srv_gc_record_value]) tasks.unconfigure_windows_dns_for_trust(self.ad, self.master) tasks.unconfigure_dns_for_trust(self.master, self.ad) # Test for one-way external trust with shared secret @skip_in_fips_mode_due_to_issue_8715 def test_establish_external_trust_with_shared_secret(self): tasks.configure_dns_for_trust(self.master, self.ad) tasks.configure_windows_dns_for_trust(self.ad, self.master) # create windows side of trust using netdom.exe utility self.ad.run_command( ['netdom.exe', 'trust', self.master.domain.name, '/d:' + self.ad.domain.name, '/passwordt:' + self.shared_secret, '/add', '/oneside:TRUSTED']) # create ipa side of trust tasks.establish_trust_with_ad( self.master, self.ad_domain, shared_secret=self.shared_secret, extra_args=['--range-type', 'ipa-ad-trust', '--external=True']) @skip_in_fips_mode_due_to_issue_8715 def test_trustdomains_found_in_external_trust_with_shared_secret(self): result = self.master.run_command( ['ipa', 'trust-fetch-domains', self.ad.domain.name], raiseonerr=False) assert result.returncode == 1 self.check_trustdomains( self.ad_domain, [self.ad_domain]) @skip_in_fips_mode_due_to_issue_8715 def test_user_uid_resolution_in_external_trust_with_shared_secret(self): """Check that user has SID-generated UID""" # Using domain name since it is lowercased realm name for AD domains testuser = 'testuser@%s' % self.ad_domain result = self.master.run_command(['getent', 'passwd', testuser]) # This regex checks that Test User does not have UID 10042 nor belongs # to the group with GID 10047 testuser_regex = r"^testuser@%s:\*:(?!10042)(\d+):(?!10047)(\d+):"\ r"Test User:/home/%s/testuser:%s$"\ % (re.escape(self.ad_domain), re.escape(self.ad_domain), self.default_shell, ) assert re.search( testuser_regex, result.stdout_text), result.stdout_text @skip_in_fips_mode_due_to_issue_8715 def test_remove_external_trust_with_shared_secret(self): self.ad.run_command( ['netdom.exe', 'trust', self.master.domain.name, '/d:' + self.ad.domain.name, '/remove', '/oneside:TRUSTED'] ) self.remove_trust(self.ad) tasks.unconfigure_windows_dns_for_trust(self.ad, self.master) tasks.unconfigure_dns_for_trust(self.master, self.ad) def test_server_option_with_unreachable_ad(self): """ Check trust can be established with partially unreachable AD topology The SRV records for AD services can point to hosts unreachable for ipa master. In this case we must be able to establish trust and fetch domains list by using "--server" option. This is the regression test for https://pagure.io/freeipa/issue/7895. """ # To simulate Windows Server advertising unreachable hosts in SRV # records we create specially crafted zone file for BIND DNS server tasks.backup_file(self.master, paths.NAMED_CONF) ad_zone = textwrap.dedent(''' $ORIGIN {ad_dom}. $TTL 86400 @ IN A {ad_ip} IN NS {ad_host}. IN SOA {ad_host}. hostmaster.{ad_dom}. 39 900 600 86400 3600 _msdcs IN NS {ad_host}. _gc._tcp.Default-First-Site-Name._sites IN SRV 0 100 3268 unreachable.{ad_dom}. _kerberos._tcp.Default-First-Site-Name._sites IN SRV 0 100 88 unreachable.{ad_dom}. _ldap._tcp.Default-First-Site-Name._sites IN SRV 0 100 389 unreachable.{ad_dom}. _gc._tcp IN SRV 0 100 3268 unreachable.{ad_dom}. _kerberos._tcp IN SRV 0 100 88 unreachable.{ad_dom}. _kpasswd._tcp IN SRV 0 100 464 unreachable.{ad_dom}. _ldap._tcp IN SRV 0 100 389 unreachable.{ad_dom}. _kerberos._udp IN SRV 0 100 88 unreachable.{ad_dom}. _kpasswd._udp IN SRV 0 100 464 unreachable.{ad_dom}. {ad_short} IN A {ad_ip} unreachable IN A {unreachable} DomainDnsZones IN A {ad_ip} _ldap._tcp.Default-First-Site-Name._sites.DomainDnsZones IN SRV 0 100 389 unreachable.{ad_dom}. _ldap._tcp.DomainDnsZones IN SRV 0 100 389 unreachable.{ad_dom}. ForestDnsZones IN A {ad_ip} _ldap._tcp.Default-First-Site-Name._sites.ForestDnsZones IN SRV 0 100 389 unreachable.{ad_dom}. _ldap._tcp.ForestDnsZones IN SRV 0 100 389 unreachable.{ad_dom}. '''.format( # noqa: E501 ad_ip=self.ad.ip, unreachable='192.168.254.254', ad_host=self.ad.hostname, ad_dom=self.ad.domain.name, ad_short=self.ad.shortname)) ad_zone_file = tasks.create_temp_file(self.master, directory='/etc') self.master.put_file_contents(ad_zone_file, ad_zone) self.master.run_command( ['chmod', '--reference', paths.NAMED_CONF, ad_zone_file]) self.master.run_command( ['chown', '--reference', paths.NAMED_CONF, ad_zone_file]) named_conf = self.master.get_file_contents(paths.NAMED_CONF, encoding='utf-8') named_conf += textwrap.dedent(f''' zone "{self.ad.domain.name}" {{ type master; file "{ad_zone_file}"; }}; ''') self.master.put_file_contents(paths.NAMED_CONF, named_conf) tasks.restart_named(self.master) try: # Check that trust can not be established without --server option # This checks that our setup is correct result = self.master.run_command( ['ipa', 'trust-add', self.ad_domain, '--admin', 'Administrator@' + self.ad_domain, '--password'], raiseonerr=False, stdin_text=self.master.config.ad_admin_password) assert result.returncode == 1 assert 'Unable to read domain information' in result.stderr_text httpd_error_log = self.master.get_file_contents( paths.VAR_LOG_HTTPD_ERROR, encoding='utf-8' ) assert 'CIFS server communication error: code "3221225653", ' \ 'message "{Device Timeout}' in httpd_error_log # Check that trust is successfully established with --server option tasks.establish_trust_with_ad( self.master, self.ad_domain, extra_args=['--server', self.ad.hostname]) # Check domains can not be fetched without --server option # This checks that our setup is correct result = self.master.run_command( ['ipa', 'trust-fetch-domains', self.ad.domain.name], raiseonerr=False) assert result.returncode == 1 assert ('Fetching domains from trusted forest failed' in result.stderr_text) # Check that domains can be fetched with --server option result = self.master.run_command( ['ipa', 'trust-fetch-domains', self.ad.domain.name, '--server', self.ad.hostname], raiseonerr=False) assert result.returncode == 1 assert ('List of trust domains successfully refreshed' in result.stdout_text) finally: tasks.restore_files(self.master) tasks.restart_named(self.master) tasks.clear_sssd_cache(self.master) self.master.run_command(['rm', '-f', ad_zone_file]) tasks.configure_dns_for_trust(self.master, self.ad) self.remove_trust(self.ad) class TestNonPosixAutoPrivateGroup(BaseTestTrust): """ Tests for auto-private-groups option with non posix AD trust Related : https://pagure.io/freeipa/issue/8807 """ topology = 'line' num_ad_domains = 1 num_clients = 1 num_ad_subdomains = 0 num_ad_treedomains = 0 uid_override = "99999999" gid_override = "78878787" def test_add_nonposix_trust(self): tasks.configure_dns_for_trust(self.master, self.ad) tasks.establish_trust_with_ad( self.master, self.ad_domain, extra_args=['--range-type', 'ipa-ad-trust']) @pytest.mark.parametrize('type', ['hybrid', 'true', "false"]) def test_auto_private_groups_default_trusted_range(self, type): """ Modify existing range for default trusted AD domain range with auto-private-groups set as true/hybrid/false and test user with no posix attributes. """ self.mod_idrange_auto_private_group(type) nonposixuser = "nonposixuser@%s" % self.ad_domain (uid, gid) = self.get_user_id(self.clients[0], nonposixuser) if type == "true": assert uid == gid else: test_group = self.clients[0].run_command(["id", nonposixuser]) gid_str = "gid={0}(domain users@{1})".format(gid, self.ad_domain) grp_str = "groups={0}(domain users@{1})".format(gid, self.ad_domain) assert gid_str in test_group.stdout_text assert grp_str in test_group.stdout_text assert uid != gid @pytest.mark.parametrize('type', ['hybrid', 'true', "false"]) def test_idoverride_with_auto_private_group(self, type): """ Override ad trusted user in default trust view and set auto-private-groups=[hybrid,true,false] and ensure that overridden values takes effect. """ nonposixuser = "nonposixuser@%s" % self.ad_domain with self.set_idoverrideuser(nonposixuser, self.uid_override, self.gid_override ): self.mod_idrange_auto_private_group(type) sssd_version = tasks.get_sssd_version(self.clients[0]) bad_version = (tasks.parse_version("2.8.2") <= sssd_version < tasks.parse_version("2.9.4")) cond = (type == 'hybrid') and bad_version with xfail_context(condition=cond, reason="https://pagure.io/freeipa/issue/9295"): (uid, gid) = self.get_user_id(self.clients[0], nonposixuser) assert (uid == self.uid_override and gid == self.gid_override) test_group = self.clients[0].run_command( ["id", nonposixuser]).stdout_text cond2 = ((type == 'false' and sssd_version >= tasks.parse_version("2.9.4")) or type == 'hybrid') with xfail_context(cond2, 'https://github.com/SSSD/sssd/issues/5989 ' 'and 7169'): assert "domain users@{0}".format(self.ad_domain) in test_group @pytest.mark.parametrize('type', ['hybrid', 'true', "false"]) def test_nonposixuser_nondefault_primary_group(self, type): """ Test for non default primary group. For hybrid/false gid corresponds to the group testgroup1. """ nonposixuser1 = "nonposixuser1@%s" % self.ad_domain self.mod_idrange_auto_private_group(type) (uid, gid) = self.get_user_id(self.clients[0], nonposixuser1) if type == "true": assert uid == gid else: test_group = self.clients[0].run_command(["id", nonposixuser1]) gid_str = "gid={0}(testgroup1@{1})".format(gid, self.ad_domain) group = "groups={0}(testgroup1@{1})".format(gid, self.ad_domain) assert (gid_str in test_group.stdout_text and group in test_group.stdout_text) class TestPosixAutoPrivateGroup(BaseTestTrust): """ Tests for auto-private-groups option with posix AD trust Related : https://pagure.io/freeipa/issue/8807 """ topology = 'line' num_ad_domains = 1 num_clients = 1 num_ad_subdomains = 0 num_ad_treedomains = 0 uid_override = "99999999" gid_override = "78878787" def test_add_posix_trust(self): tasks.configure_dns_for_trust(self.master, self.ad) tasks.establish_trust_with_ad( self.master, self.ad_domain, extra_args=['--range-type', 'ipa-ad-trust-posix']) @pytest.mark.parametrize('type', ['hybrid', 'true', "false"]) def test_gidnumber_not_corresponding_existing_group(self, type): """ Test checks that sssd can resolve AD users which contain posix attributes (uidNumber and gidNumber) but there is no group with the corresponding gidNumber. """ posixuser = "testuser2@%s" % self.ad_domain self.mod_idrange_auto_private_group(type) if type != "true": result = self.clients[0].run_command(['id', posixuser], raiseonerr=False) tasks.assert_error(result, "no such user") else: # sssd_version = tasks.get_sssd_version(self.clients[0]) with xfail_context(True, 'https://github.com/SSSD/sssd/issues/5988'): (uid, gid) = self.get_user_id(self.clients[0], posixuser) assert uid == gid assert uid == '10060' @pytest.mark.parametrize('type', ['hybrid', 'true', "false"]) def test_only_uid_number_auto_private_group_default(self, type): """ Test checks that posix user with only uidNumber defined and gidNumber not set, auto-private-group is set to false/true/hybrid """ posixuser = "testuser1@%s" % self.ad_domain self.mod_idrange_auto_private_group(type) if type == "true": sssd_version = tasks.get_sssd_version(self.clients[0]) bad_version = (tasks.parse_version("2.8.2") <= sssd_version < tasks.parse_version("2.9.4")) with xfail_context(bad_version, "https://pagure.io/freeipa/issue/9295"): (uid, gid) = self.get_user_id(self.clients[0], posixuser) assert uid == gid else: for host in [self.master, self.clients[0]]: result = host.run_command(['id', posixuser], raiseonerr=False) tasks.assert_error(result, "no such user") @pytest.mark.parametrize('type', ['hybrid', 'true', "false"]) def test_auto_private_group_primary_group(self, type): """ Test checks that AD users which contain posix attributes (uidNumber and gidNumber) and there is primary group with gid number defined. """ posixuser = "testuser@%s" % self.ad_domain self.mod_idrange_auto_private_group(type) (uid, gid) = self.get_user_id(self.clients[0], posixuser) test_grp = self.clients[0].run_command(["id", posixuser]) assert uid == '10042' if type == "true": assert uid == gid groups = "groups=10042(testuser@{0}),10047(testgroup@{1})".format( self.ad_domain, self.ad_domain) assert groups in test_grp.stdout_text else: assert gid == '10047' groups = "10047(testgroup@{0})".format(self.ad_domain) assert groups in test_grp.stdout_text @pytest.mark.parametrize('type', ['hybrid', 'true', "false"]) def test_idoverride_with_auto_private_group(self, type): """ Override ad trusted user in default trust view and set auto-private-groups=[hybrid,true,false] and ensure that overridden values takes effect. """ posixuser = "testuser@%s" % self.ad_domain with self.set_idoverrideuser(posixuser, self.uid_override, self.gid_override): self.mod_idrange_auto_private_group(type) (uid, gid) = self.get_user_id(self.clients[0], posixuser) assert(uid == self.uid_override and gid == self.gid_override) result = self.clients[0].run_command(['id', posixuser]) sssd_version = tasks.get_sssd_version(self.clients[0]) bad_version = sssd_version >= tasks.parse_version("2.9.4") with xfail_context(bad_version and type in ('false', 'hybrid'), "https://github.com/SSSD/sssd/issues/7169"): assert "10047(testgroup@{0})".format( self.ad_domain) in result.stdout_text
56,712
Python
.py
1,110
38.454955
107
0.586468
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,539
test_authselect.py
freeipa_freeipa/ipatests/test_integration/test_authselect.py
# # Copyright (C) 2018 FreeIPA Contributors see COPYING for license # """ Module provides tests to verify that the authselect code works. """ from __future__ import absolute_import import os import pytest from ipaplatform.paths import paths from ipatests.test_integration.base import IntegrationTest from ipatests.pytest_ipa.integration import tasks default_profile = 'sssd' preconfigured_profile = 'winbind' preconfigured_options = ('with-fingerprint',) def check_authselect_profile(host, expected_profile, expected_options=()): """ Checks that the current authselect profile on the host matches expected one """ cmd = host.run_command( ['cat', '/etc/authselect/authselect.conf']) lines = cmd.stdout_text.splitlines() assert lines[0] == expected_profile options = lines[1::] for option in expected_options: assert option in options def apply_authselect_profile(host, profile, options=()): """ Apply the specified authselect profile and options with --force """ cmd = ['authselect', 'select', profile] cmd.extend(options) cmd.append('--force') host.run_command(cmd) @pytest.mark.skipif( paths.AUTHSELECT is None, reason="Authselect is only available in fedora-like distributions") class TestClientInstallation(IntegrationTest): """ Tests the client installation with authselect profile. When the system is a fresh installation, authselect tool is available and the default profile 'sssd' without any option is set by default. But when the system has been upgraded from older version, even though authselect tool is available, no profile is set (authselect current would return 'No existing configuration detected'). This test ensures that both scenarios are properly handled by the client installer. """ num_clients = 1 msg_warn_install = ( "WARNING: The configuration pre-client installation " "is not managed by authselect and cannot be backed up. " "Uninstallation may not be able to revert to the original state.") msg_warn_uninstall = ( "WARNING: Unable to revert to the pre-installation " "state ('authconfig' tool has been deprecated in favor of " "'authselect'). The default sssd profile will be used instead.") @classmethod def install(cls, mh): tasks.install_master(cls.master, setup_dns=False) cls.client = cls.clients[0] def _install_client(self, extraargs=[]): cmd = ['ipa-client-install', '-U', '--domain', self.client.domain.name, '--realm', self.client.domain.realm, '-p', self.client.config.admin_name, '-w', self.client.config.admin_password, '--server', self.master.hostname] cmd.extend(extraargs) return self.client.run_command(cmd, raiseonerr=False) def _uninstall_client(self): return self.client.run_command( ['ipa-client-install', '--uninstall', '-U'], raiseonerr=False) def test_install_client_no_preconfigured_profile(self): """ Test client installation on an upgraded system. """ # On a machine upgraded from authconfig, there is no profile # To simulate this use case, remove /etc/authselect/authselect.conf # before launching client installation self.client.run_command( ['rm', '-f', '/etc/authselect/authselect.conf']) result = self._install_client() assert result.returncode == 0 # With the fix for 8189, there is no warning any more # because install is performing a pre-install backup assert self.msg_warn_install not in result.stderr_text # Client installation must configure the 'sssd' profile # with sudo check_authselect_profile(self.client, default_profile, ('with-sudo',)) def test_uninstall_client_no_preconfigured_profile(self): """ Test client un-installation when there was no authselect profile """ # The client did not have any authselect profile before install, # but uninstall must be able to restore the backup # Check that no profile is configured after uninstall result = self._uninstall_client() assert result.returncode == 0 assert not self.client.transport.file_exists( '/etc/authselect/authselect.conf') def test_install_client_preconfigured_profile(self): """ Test client installation when a different profile was present before client configuration """ # Configure a profile winbind with feature with-fingerprint apply_authselect_profile( self.client, preconfigured_profile, preconfigured_options) # Make sure that oddjobd is disabled and stopped self.client.run_command(["systemctl", "disable", "oddjobd", "--now"]) # Call the installer, must succeed and store the winbind profile # in the statestore, but install sssd profile with-mkhomedir result = self._install_client(extraargs=['-f', '--mkhomedir']) assert result.returncode == 0 assert self.msg_warn_install not in result.stderr_text # Client installation must configure the 'sssd' profile # with mkhomedir (because of extraargs) and with sudo check_authselect_profile( self.client, default_profile, ('with-mkhomedir', 'with-sudo')) # Test for ticket 7604: # ipa-client-install --mkhomedir doesn't enable oddjobd # Check that oddjobd has been enabled and started # because --mkhomedir was used status = self.client.run_command(["systemctl", "status", "oddjobd"]) assert "active (running)" in status.stdout_text def test_uninstall_client_preconfigured_profile(self): """ Test client un-installation when a different profile was present before client configuration """ # Uninstall must revert to the preconfigured profile with options result = self._uninstall_client() assert result.returncode == 0 assert self.msg_warn_uninstall not in result.stderr_text check_authselect_profile( self.client, preconfigured_profile, preconfigured_options) def test_install_client_no_sudo(self): """ Test client installation with --no-sudo option """ result = self._install_client(extraargs=['-f', '--no-sudo']) assert result.returncode == 0 assert self.msg_warn_install not in result.stderr_text # Client installation must configure the 'sssd' profile # but not with sudo (because of extraargs) check_authselect_profile(self.client, default_profile, ()) def test_uninstall_wrong_sysrestore(self): """ Test client uninstallation when sysrestore.state is incomplete Test for issue 7657 """ # Remove the keys 'profile' and 'features_list' from sysrestore.state def keep(line): if line.startswith('profile') or line.startswith('features_list'): return False return True sysrestore_state_file = os.path.join(paths.IPA_CLIENT_SYSRESTORE, "sysrestore.state") content = self.client.get_file_contents(sysrestore_state_file, encoding='utf-8') lines = [line.rstrip() for line in content.split('\n') if keep(line)] new_content = '\n'.join(lines) self.client.put_file_contents(sysrestore_state_file, new_content) result = self._uninstall_client() assert result.returncode == 0 def test_install_client_subid(self): """ Test client installation with --subid option """ result = self._install_client(extraargs=['-f', '--subid']) assert result.returncode == 0 # Client installation must configure the 'sssd' profile # with subid feature check_authselect_profile( self.client, default_profile, ('with-sudo', 'with-subid')) @classmethod def uninstall(cls, mh): super(TestClientInstallation, cls).uninstall(mh) # Clean-up the authselect profile and re-use the default 'sssd' apply_authselect_profile(cls.client, default_profile) @pytest.mark.skipif( paths.AUTHSELECT is None, reason="Authselect is only available in fedora-like distributions") class TestServerInstallation(IntegrationTest): """ Tests the server installation with authselect profile. When the system is a fresh installation, authselect tool is available and the default profile 'sssd' without any option is set by default. But when the system has been upgraded from older version, even though authselect tool is available, no profile is set (authselect current would return 'No existing configuration detected'). This test ensures that both scenarios are properly handled by the server installer. """ @classmethod def install(cls, mh): pass def test_install(self): """ Test server installation when a different profile was present before server configuration """ # Configure a profile winbind with feature with-fingerprint apply_authselect_profile( self.master, preconfigured_profile, preconfigured_options) tasks.install_master(self.master, setup_dns=False) check_authselect_profile(self.master, default_profile, ('with-sudo',)) def test_uninstall(self): """ Test server uninstallation when a different profile was present before server installation """ # uninstall must revert to the preconfigured profile tasks.uninstall_master(self.master) check_authselect_profile( self.master, preconfigured_profile, preconfigured_options) def test_install_with_subid(self): """ Test server installation when --subid option is specified """ tasks.install_master(self.master, extra_args=["--subid"]) check_authselect_profile( self.master, default_profile, ('with-sudo', 'with-subid')) def test_uninstall_with_subid(self): """ Test server uninstallation when --subid option was configured """ # uninstall must revert to the preconfigured profile tasks.uninstall_master(self.master) check_authselect_profile( self.master, preconfigured_profile, preconfigured_options) @classmethod def uninstall(cls, mh): # Clean-up the authselect profile and re-use the default 'sssd' apply_authselect_profile(cls.master, default_profile)
10,844
Python
.py
238
37.453782
78
0.672942
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,540
test_forced_client_reenrollment.py
freeipa_freeipa/ipatests/test_integration/test_forced_client_reenrollment.py
# Authors: # Ana Krivokapic <akrivoka@redhat.com> # # Copyright (C) 2013 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from __future__ import absolute_import import logging import os import subprocess from ipaplatform.paths import paths import pytest from ipatests.test_integration.base import IntegrationTest from ipatests.pytest_ipa.integration import tasks logger = logging.getLogger(__name__) CLIENT_KEYTAB = paths.KRB5_KEYTAB class TestForcedClientReenrollment(IntegrationTest): """ Forced client re-enrollment http://www.freeipa.org/page/V3/Forced_client_re-enrollment#Test_Plan """ num_replicas = 1 num_clients = 1 @classmethod def install(cls, mh): super(TestForcedClientReenrollment, cls).install(mh) tasks.install_master(cls.master) cls.client_dom = cls.clients[0].hostname.split('.', 1)[1] if cls.client_dom != cls.master.domain.name: # In cases where client is managed by upstream DNS server we # overlap its zone so we can save DNS records (e.g. SSHFP) for # comparison. servers = [cls.master] + cls.replicas tasks.add_dns_zone(cls.master, cls.client_dom, skip_overlap_check=True, dynamic_update=True, add_a_record_hosts=servers ) tasks.install_replica(cls.master, cls.replicas[0], setup_ca=False) cls.clients[0].resolver.backup() cls.clients[0].resolver.setup_resolver(cls.master.ip) cls.BACKUP_KEYTAB = os.path.join( cls.master.config.test_dir, 'krb5.keytab' ) def test_reenroll_with_force_join(self, client): """ Client re-enrollment using admin credentials (--force-join) """ sshfp_record_pre = self.get_sshfp_record() self.restore_client() self.check_client_host_entry() self.reenroll_client(force_join=True) sshfp_record_post = self.get_sshfp_record() assert sshfp_record_pre == sshfp_record_post def test_reenroll_with_keytab(self, client): """ Client re-enrollment using keytab """ self.backup_keytab() sshfp_record_pre = self.get_sshfp_record() self.restore_client() self.check_client_host_entry() self.restore_keytab() self.reenroll_client(keytab=self.BACKUP_KEYTAB) sshfp_record_post = self.get_sshfp_record() assert sshfp_record_pre == sshfp_record_post def test_reenroll_with_both_force_join_and_keytab(self, client): """ Client re-enrollment using both --force-join and --keytab options """ self.backup_keytab() sshfp_record_pre = self.get_sshfp_record() self.restore_client() self.check_client_host_entry() self.restore_keytab() self.reenroll_client(force_join=True, keytab=self.BACKUP_KEYTAB) sshfp_record_post = self.get_sshfp_record() assert sshfp_record_pre == sshfp_record_post def test_reenroll_to_replica(self, client): """ Client re-enrollment using keytab, to a replica """ self.backup_keytab() sshfp_record_pre = self.get_sshfp_record() self.restore_client() self.check_client_host_entry() self.restore_keytab() self.reenroll_client(keytab=self.BACKUP_KEYTAB, to_replica=True) sshfp_record_post = self.get_sshfp_record() assert sshfp_record_pre == sshfp_record_post def test_try_to_reenroll_with_disabled_host(self, client): """ Client re-enrollment using keytab, with disabled host """ self.backup_keytab() self.disable_client_host_entry() self.restore_client() self.check_client_host_entry(enabled=False) self.restore_keytab() self.reenroll_client(keytab=self.BACKUP_KEYTAB, expect_fail=True) def test_try_to_reenroll_with_uninstalled_host(self, client): """ Client re-enrollment using keytab, with uninstalled host """ self.backup_keytab() self.uninstall_client() self.restore_client() self.check_client_host_entry(enabled=False) self.restore_keytab() self.reenroll_client(keytab=self.BACKUP_KEYTAB, expect_fail=True) def test_try_to_reenroll_with_deleted_host(self, client): """ Client re-enrollment using keytab, with deleted host """ self.backup_keytab() self.delete_client_host_entry() self.restore_client() self.check_client_host_entry(not_found=True) self.restore_keytab() self.reenroll_client(keytab=self.BACKUP_KEYTAB, expect_fail=True) def test_try_to_reenroll_with_incorrect_keytab(self, client): """ Client re-enrollment using keytab, with incorrect keytab file """ EMPTY_KEYTAB = os.path.join( self.clients[0].config.test_dir, 'empty.keytab' ) self.restore_client() self.check_client_host_entry() self.clients[0].run_command(['touch', EMPTY_KEYTAB]) self.reenroll_client(keytab=EMPTY_KEYTAB, expect_fail=True) def test_try_to_reenroll_with_empty_keytab(self, client): """ Client re-enrollment with invalid (empty) client keytab file """ self.restore_client() self.check_client_host_entry() try: os.remove(CLIENT_KEYTAB) except OSError: pass self.clients[0].run_command(['touch', CLIENT_KEYTAB]) self.reenroll_client(force_join=True) def uninstall_client(self, unshare=False): """Uninstall client Set unshare to unshare the network namespace. This means that the uninstall command will not have network access. """ args = [] if unshare: args = ['unshare', '--net'] args.extend(['ipa-client-install', '--uninstall', '-U']) self.clients[0].run_command( args, set_env=False, raiseonerr=False ) def restore_client(self): # As machine-level backup and restore is difficult to automate for # testing purposes, restoring the client from backup can be simulated # by performing the following step: # unshare -n ip ipa-client-install --uninstall -U # Or the following steps: # iptables -A INPUT -j REJECT -p all --source $MASTER_IP # ipa-client-install --uninstall -U # iptables -F # The steps described above will sever communication between server # and client, and then uninstall the client. As a consequence, the # client's host entry will remain on the server, ensuring that the # forced re-enrollment feature works. self.uninstall_client(unshare=True) def reenroll_client(self, keytab=None, to_replica=False, force_join=False, expect_fail=False): server = self.replicas[0] if to_replica else self.master client = self.clients[0] args = [ 'ipa-client-install', '-U', '--server', server.hostname, '--domain', server.domain.name ] if force_join: args.append('--force-join') if keytab: args.extend(['--keytab', keytab]) else: args.extend([ '-p', client.config.admin_name, '-w', client.config.admin_password ]) result = client.run_command( args, set_env=False, raiseonerr=not expect_fail ) assert 'IPA Server: %s' % server.hostname in result.stderr_text if expect_fail: err_msg = "Kerberos authentication failed: " assert result.returncode == 1 assert err_msg in result.stderr_text elif force_join and keytab: warn_msg = ("Option 'force-join' has no additional effect " "when used with together with option 'keytab'.") assert warn_msg in result.stderr_text def check_client_host_entry(self, enabled=True, not_found=False): result = self.master.run_command( ['ipa', 'host-show', self.clients[0].hostname], raiseonerr=not not_found ) if not_found: assert result.returncode == 2 assert 'host not found' in result.stderr_text elif enabled: assert 'Certificate:' not in result.stdout_text assert 'Keytab: True' in result.stdout_text else: assert 'Certificate:' not in result.stdout_text assert 'Keytab: False' in result.stdout_text def disable_client_host_entry(self): self.master.run_command( ['ipa', 'host-disable', self.clients[0].hostname] ) @classmethod def delete_client_host_entry(cls): try: cls.master.run_command( ['ipa', 'host-del', cls.clients[0].hostname] ) except subprocess.CalledProcessError as e: if e.returncode != 2: raise def get_sshfp_record(self): sshfp_record = '' client_host = self.clients[0].hostname.split('.')[0] result = self.master.run_command( ['ipa', 'dnsrecord-show', self.client_dom, client_host] ) lines = result.stdout_text.splitlines() for line in lines: if 'SSHFP record:' in line: sshfp_record = line.replace('SSHFP record:', '').strip() assert sshfp_record, 'SSHFP record not found' sshfp_record = set(sshfp_record.split(', ')) logger.debug("SSHFP record for host %s: %s", client_host, str(sshfp_record)) return sshfp_record def backup_keytab(self): contents = self.clients[0].get_file_contents(CLIENT_KEYTAB) self.master.put_file_contents(self.BACKUP_KEYTAB, contents) def restore_keytab(self): contents = self.master.get_file_contents(self.BACKUP_KEYTAB) self.clients[0].put_file_contents(self.BACKUP_KEYTAB, contents) @pytest.fixture() def client(request): tasks.install_client(request.cls.master, request.cls.clients[0]) def teardown_client(): tasks.uninstall_client(request.cls.clients[0]) request.cls.delete_client_host_entry() request.addfinalizer(teardown_client)
11,215
Python
.py
272
32.136029
78
0.628233
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,541
test_winsyncmigrate.py
freeipa_freeipa/ipatests/test_integration/test_winsyncmigrate.py
# # Copyright (C) 2019 FreeIPA Contributors see COPYING for license # """ Module provides tests for the ipa-winsync-migrate command. """ import os import base64 import re import pytest from ipaplatform.constants import constants as platformconstants from ipatests.pytest_ipa.integration import tasks from ipatests.test_integration.base import IntegrationTest def get_windows_certificate(ad_host): certs_path = '/cygdrive/c/Windows/System32/CertSrv/CertEnroll/' cert_filename = '%s_%s-%s-CA.crt' % ( ad_host.hostname, ad_host.domain.name.split('.')[0], ad_host.shortname.upper()) return ad_host.get_file_contents(os.path.join(certs_path, cert_filename)) def convert_crt_to_cer(data): header = b'-----BEGIN CERTIFICATE-----\n' trailer = b'-----END CERTIFICATE-----\n' return header + base64.encodebytes(data) + trailer def establish_winsync_agreement(master, ad): win_cert = get_windows_certificate(ad) cert_path = master.run_command(['mktemp']).stdout_text.strip() master.put_file_contents(cert_path, convert_crt_to_cer(win_cert)) master.run_command(['kdestroy', '-A']) master.run_command([ 'ipa-replica-manage', 'connect', '--winsync', '--binddn', 'cn=%s,cn=users,%s' % (ad.config.ad_admin_name, ad.domain.basedn), '--bindpw', ad.config.ad_admin_password, '--password', master.config.dirman_password, '--cacert', cert_path, '--passsync', 'dummy', ad.hostname, '-v' ]) master.run_command(['rm', cert_path]) def ipa_output_fields(s): return [line.strip() for line in s.splitlines()] class TestWinsyncMigrate(IntegrationTest): topology = 'star' num_ad_domains = 1 ipa_group = 'ipa_group' ad_user = 'testuser' default_shell = platformconstants.DEFAULT_SHELL selinuxuser = platformconstants.SELINUX_USERMAP_ORDER.split( "$", maxsplit=1 )[0] test_role = 'test_role' test_hbac_rule = 'test_hbac_rule' test_selinux_map = 'test_selinux_map' test_role_with_nonposix_chars = '$the test,role!' test_role_with_nonposix_chars_normalized = 'the_testrole' collision_role1 = 'collision role' collision_role2 = 'collision, role' collision_role3 = 'collision_role' collision_role_normalized = 'collision_role' @classmethod def install(cls, mh): super(TestWinsyncMigrate, cls).install(mh) cls.ad = cls.ads[0] cls.trust_test_user = '%s@%s' % (cls.ad_user, cls.ad.domain.name) tasks.configure_dns_for_trust(cls.master, cls.ad) tasks.install_adtrust(cls.master) cls.create_test_objects() establish_winsync_agreement(cls.master, cls.ad) tasks.kinit_admin(cls.master) cls.setup_user_memberships(cls.ad_user) # store user uid and gid result = cls.master.run_command(['getent', 'passwd', cls.ad_user]) testuser_regex = ( r"^{0}:\*:(\d+):(\d+):{0}:/home/{0}:{1}$".format( cls.ad_user, cls.default_shell, ) ) m = re.match(testuser_regex, result.stdout_text) cls.test_user_uid, cls.test_user_gid = m.groups() @classmethod def create_test_objects(cls): tasks.group_add(cls.master, cls.ipa_group) for role in [cls.test_role, cls.collision_role1, cls.collision_role2, cls.collision_role3, cls.test_role_with_nonposix_chars]: cls.master.run_command(['ipa', 'role-add', role]) cls.master.run_command(['ipa', 'hbacrule-add', cls.test_hbac_rule]) cls.master.run_command([ 'ipa', 'selinuxusermap-add', cls.test_selinux_map, '--selinuxuser', cls.selinuxuser]) @classmethod def setup_user_memberships(cls, user): cls.master.run_command(['ipa', 'group-add-member', cls.ipa_group, '--users', user]) for role in [cls.test_role, cls.collision_role1, cls.collision_role2, cls.collision_role3, cls.test_role_with_nonposix_chars]: cls.master.run_command(['ipa', 'role-add-member', role, '--users', user]) cls.master.run_command(['ipa', 'hbacrule-add-user', cls.test_hbac_rule, '--users', user]) cls.master.run_command(['ipa', 'selinuxusermap-add-user', cls.test_selinux_map, '--users', user]) def check_replication_agreement_exists(self, server_name, should_exist): result = self.master.run_command( ['ipa-replica-manage', 'list', server_name]) if should_exist: expected_message = '%s: winsync' % self.ad.hostname else: expected_message = ('Cannot find %s in public server list' % server_name) assert result.stdout_text.strip() == expected_message def test_preconditions(self): self.check_replication_agreement_exists(self.ad.hostname, True) # check user exists at ipa server result = self.master.run_command(['ipa', 'user-show', self.ad_user], raiseonerr=False) assert result.returncode == 0 def test_migration(self): tasks.establish_trust_with_ad(self.master, self.ad.domain.name) result = self.master.run_command([ 'ipa-winsync-migrate', '-U', '--realm', self.ad.domain.name, '--server', self.ad.hostname]) assert ('The ipa-winsync-migrate command was successful' in result.stderr_text) tasks.clear_sssd_cache(self.master) def test_replication_agreement_deleted(self): self.check_replication_agreement_exists(self.ad.hostname, False) def test_user_deleted_from_ipa_server(self): result = self.master.run_command(['ipa', 'user-show', self.ad_user], raiseonerr=False) assert result.returncode == 2 def test_user_attributes_preserved(self): result = self.master.run_command(['getent', 'passwd', self.trust_test_user]) passwd_template = ( '{trust_user}:*:{uid}:{gid}:{user}:/home/{domain}/{user}:{shell}') expected_result = passwd_template.format( user=self.ad_user, uid=self.test_user_uid, gid=self.test_user_gid, domain=self.ad.domain.name, trust_user=self.trust_test_user, shell=self.default_shell, ) assert result.stdout_text.strip() == expected_result def test_idoverride(self): result = self.master.run_command([ 'ipa', 'idoverrideuser-show', '--raw', 'Default Trust View', self.trust_test_user]) idoverride_fields = [line for line in ipa_output_fields(result.stdout_text) if 'ipaanchoruuid:' not in line] expected_fields = [ 'uid: %s' % self.ad_user, 'uidnumber: %s' % self.test_user_uid, 'gidnumber: %s' % self.test_user_gid, 'gecos: %s' % self.ad_user, 'loginshell: %s' % self.default_shell, ] assert sorted(idoverride_fields) == sorted(expected_fields) def test_groups_membership_preserved(self): result = self.master.run_command([ 'ipa', 'group-show', 'group_%s_winsync_external' % self.ipa_group]) output_fields = ipa_output_fields(result.stdout_text) assert 'External member: %s' % self.trust_test_user in output_fields assert 'Member of groups: %s' % self.ipa_group in output_fields def test_role_membership_preserved(self): result = self.master.run_command([ 'ipa', 'group-show', 'role_%s_winsync_external' % self.test_role]) output_fields = ipa_output_fields(result.stdout_text) assert 'External member: %s' % self.trust_test_user in output_fields assert 'Roles: %s' % self.test_role def test_selinuxusermap_membership_preserved(self): wrapper_group = 'selinux_%s_winsync_external' % self.test_selinux_map result = self.master.run_command(['ipa', 'selinuxusermap-show', self.test_selinux_map]) assert ('User Groups: %s' % wrapper_group in ipa_output_fields(result.stdout_text)) result = self.master.run_command(['ipa', 'group-show', wrapper_group]) assert ('External member: %s' % self.trust_test_user in ipa_output_fields(result.stdout_text)) def test_hbacrule_membership_preserved(self): result = self.master.run_command([ 'ipa', 'group-show', 'hbacrule_%s_winsync_external' % self.test_hbac_rule]) output_fields = ipa_output_fields(result.stdout_text) assert 'External member: %s' % self.trust_test_user in output_fields assert 'Member of HBAC rule: %s' % self.test_hbac_rule in output_fields def test_non_posix_chars_in_group_names_replaced(self): result = self.master.run_command([ 'ipa', 'role-show', self.test_role_with_nonposix_chars]) expected_group_name = ('role_%s_winsync_external' % self.test_role_with_nonposix_chars_normalized) assert ('Member groups: %s' % expected_group_name in ipa_output_fields(result.stdout_text)) @pytest.mark.xfail(reason='BZ1698118', strict=True) def test_collisions_resolved(self): group = 'role_%s_winsync_external' % self.collision_role_normalized result = self.master.run_command(['ipa', 'group-show', group]) output_fields = ipa_output_fields(result.stdout_text) assert 'Roles: %s' % self.collision_role1 in output_fields assert 'External member: %s' % self.trust_test_user in output_fields group = 'role_%s_winsync_external1' % self.collision_role_normalized result = self.master.run_command(['ipa', 'group-show', group]) output_fields = ipa_output_fields(result.stdout_text) assert 'Roles: %s' % self.collision_role2 in output_fields assert 'External member: %s' % self.trust_test_user in output_fields group = 'role_%s_winsync_external2' % self.collision_role_normalized result = self.master.run_command(['ipa', 'group-show', group]) output_fields = ipa_output_fields(result.stdout_text) assert 'Roles: %s' % self.collision_role3 in output_fields assert 'External member: %s' % self.trust_test_user in output_fields
10,622
Python
.py
208
40.985577
79
0.621471
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,542
test_service_permissions.py
freeipa_freeipa/ipatests/test_integration/test_service_permissions.py
# Authors: # Petr Viktorin <pviktori@redhat.com> # # Copyright (C) 2014 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import os from ipatests.test_integration.base import IntegrationTest from ipatests.pytest_ipa.integration import tasks from ipaplatform.osinfo import osinfo import pytest skip_rbcd_tests = any([ (osinfo.id == 'fedora' and osinfo.version_number < (38,)), (osinfo.id == 'rhel' and osinfo.version_number < (9,2))]) class TestServicePermissions(IntegrationTest): topology = 'star' def test_service_as_user_admin(self): """Test that a service in User Administrator role can manage users""" service_name1 = 'testservice1/%s@%s' % (self.master.hostname, self.master.domain.realm) keytab_file1 = os.path.join(self.master.config.test_dir, 'testservice_keytab1') # Prepare a service self.master.run_command(['ipa', 'service-add', service_name1]) self.master.run_command(['ipa-getkeytab', '-p', service_name1, '-k', keytab_file1, '-s', self.master.hostname]) # Check that the service cannot add a user self.master.run_command(['kdestroy']) self.master.run_command(['kinit', '-k', service_name1, '-t', keytab_file1]) result = self.master.run_command(['ipa', 'role-add-member', 'User Administrator', '--service', service_name1], raiseonerr=False) assert result.returncode > 0 # Add service to User Administrator role self.master.run_command(['kdestroy']) tasks.kinit_admin(self.master) self.master.run_command(['ipa', 'role-add-member', 'User Administrator', '--service', service_name1]) # Check that the service now can add a user self.master.run_command(['kdestroy']) self.master.run_command(['kinit', '-k', service_name1, '-t', keytab_file1]) self.master.run_command(['ipa', 'user-add', 'tuser', '--first', 'a', '--last', 'b', '--random']) # Clean up self.master.run_command(['kdestroy']) tasks.kinit_admin(self.master) self.master.run_command(['ipa', 'service-del', service_name1]) self.master.run_command(['ipa', 'user-del', 'tuser']) def test_service_access(self): """ Test that user is granted access when authenticated using credentials that are sufficient for a service, and denied access when using insufficient credentials""" service_name2 = 'testservice2/%s@%s' % (self.master.hostname, self.master.domain.realm) keytab_file2 = os.path.join(self.master.config.test_dir, 'testservice_keytab2') # Prepare a service without authentication indicator self.master.run_command(['ipa', 'service-add', service_name2]) self.master.run_command(['ipa-getkeytab', '-p', service_name2, '-k', keytab_file2]) # Set authentication-type for admin user self.master.run_command(['ipa', 'user-mod', 'admin', '--user-auth-type=password', '--user-auth-type=otp']) # Authenticate self.master.run_command(['kinit', '-k', service_name2, '-t', keytab_file2]) # Verify access to service is granted result = self.master.run_command(['kvno', service_name2], raiseonerr=False) assert result.returncode == 0 # Obtain admin ticket to be able to update service tasks.kinit_admin(self.master) # Modify service to have authentication indicator self.master.run_command(['ipa', 'service-mod', service_name2, '--auth-ind=otp']) self.master.run_command(['ipa-getkeytab', '-p', service_name2, '-k', keytab_file2]) # Authenticate self.master.run_command(['kinit', '-k', service_name2, '-t', keytab_file2]) # Verify access to service is rejected result = self.master.run_command(['kvno', service_name2], raiseonerr=False) assert result.returncode > 0 def test_service_del(self): """ Test that host can add and remove its own services. Related to : https://pagure.io/freeipa/issue/7486""" self.master.run_command(['kinit', '-kt', '/etc/krb5.keytab']) # Add service service_name3 = "testservice3" + '/' + self.master.hostname self.master.run_command(['ipa', 'service-add', service_name3]) self.master.run_command(['ipa', 'service-del', service_name3]) @pytest.mark.xfail( skip_rbcd_tests, reason='krb5 before 1.20', strict=True) def test_service_delegation(self): """ Test that host can handle resource-based constrained delegation of own services. """ keytab_file = '/etc/krb5.keytab' keytab_file4 = '/tmp/krb5-testservice4.keytab' hostservice_name4 = "host" + "/" + self.master.hostname service_name4 = "testservice4" + '/' + self.master.hostname self.master.run_command(['kinit', '-kt', keytab_file]) # Add service and configure delegation self.master.run_command(['ipa', 'service-add', service_name4]) self.master.run_command(['kdestroy']) tasks.kinit_admin(self.master) self.master.run_command(['ipa', 'service-add-delegation', service_name4, hostservice_name4]) self.master.run_command(['kinit', '-kt', keytab_file]) self.master.run_command(['ipa-getkeytab', '-p', service_name4, '-k', keytab_file4]) # Verify access to service is granted result = self.master.run_command(['kvno', '-U', 'admin', '-k', keytab_file, '-P', hostservice_name4, service_name4], raiseonerr=False) assert result.returncode == 0 tasks.kinit_admin(self.master) self.master.run_command(['ipa', 'service-remove-delegation', service_name4, hostservice_name4]) # Verify access to service is not granted self.master.run_command(['kinit', '-kt', keytab_file]) result = self.master.run_command(['kvno', '-U', 'admin', '-k', keytab_file, '-P', hostservice_name4, service_name4], raiseonerr=False) assert result.returncode > 0 self.master.run_command(['ipa', 'service-del', service_name4])
8,119
Python
.py
153
38.137255
78
0.553565
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,543
test_epn.py
freeipa_freeipa/ipatests/test_integration/test_epn.py
# # Copyright (C) 2020 FreeIPA Contributors see COPYING for license # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. ###### # This test suite will _expectedly_ fail if run at the end of the UTC day # because users would be created during day N and then EPN output checked # during day N+1. This is expected and should be ignored as it does not # reflect a product bug. -- fcami ###### from __future__ import print_function, absolute_import import base64 import datetime import email import json import logging import os import pytest import textwrap from subprocess import CalledProcessError from ipaplatform.paths import paths from ipatests.test_integration.base import IntegrationTest from ipatests.pytest_ipa.integration.firewall import Firewall from ipatests.pytest_ipa.integration import tasks logger = logging.getLogger(__name__) EPN_PKG = ["*ipa-client-epn"] SMTP_CLIENT_CERT = os.path.join(paths.OPENSSL_CERTS_DIR, "smtp_client.pem") SMTP_CLIENT_KEY = os.path.join(paths.OPENSSL_PRIVATE_DIR, "smtp_client.key") SMTP_CLIENT_KEY_PASS = "Secret123" SMTPD_KEY = os.path.join(paths.OPENSSL_PRIVATE_DIR, "postfix.key") SMTPD_CERT = os.path.join(paths.OPENSSL_CERTS_DIR, "postfix.pem") DEFAULT_EPN_CONF = textwrap.dedent( """\ [global] """ ) USER_EPN_CONF = DEFAULT_EPN_CONF + textwrap.dedent( """\ smtp_user={user} smtp_password={password} """ ) STARTTLS_EPN_CONF = USER_EPN_CONF + textwrap.dedent( """\ smtp_server={server} smtp_security=starttls """ ) SSL_EPN_CONF = USER_EPN_CONF + textwrap.dedent( """\ smtp_server={server} smtp_port=465 smtp_security=ssl """ ) CLIENT_CERT_EPN_CONF = textwrap.dedent( """\ smtp_client_cert={client_cert} smtp_client_key={client_key} smtp_client_key_pass={client_key_pass} """ ) def datetime_to_generalized_time(dt): """Convert datetime to LDAP_GENERALIZED_TIME_FORMAT Note: Move into ipalib. """ dt = dt.timetuple() generalized_time_str = str(dt.tm_year) + "".join( "0" * (2 - len(str(item))) + str(item) for item in (dt.tm_mon, dt.tm_mday, dt.tm_hour, dt.tm_min, dt.tm_sec,) ) return generalized_time_str + "Z" def postconf(host, option): host.run_command(r"postconf -e '%s'" % option) def configure_postfix(host, realm): """Configure postfix for: * SASL auth * to be the destination of the IPA domain. """ # Setup the keytab we need for SASL auth host.run_command(r"ipa service-add smtp/%s --force" % host.hostname) host.run_command(r"ipa-getkeytab -p smtp/%s -k /etc/postfix/smtp.keytab" % host.hostname) host.run_command(r"chown root:mail /etc/postfix/smtp.keytab") host.run_command(r"chmod 640 /etc/postfix/smtp.keytab") # Configure the SASL smtp service to use GSSAPI host.run_command( r"sed -i 's/plain login/GSSAPI plain login/' /etc/sasl2/smtpd.conf") host.run_command( r"sed -i 's/MECH=pam/MECH=kerberos5/' /etc/sysconfig/saslauthd") postconf(host, 'import_environment = MAIL_CONFIG MAIL_DEBUG MAIL_LOGTAG TZ ' 'XAUTHORITY DISPLAY LANG=C KRB5_KTNAME=/etc/postfix/smtp.keytab') postconf(host, 'smtpd_client_restrictions = permit_sasl_authenticated, reject') postconf(host, 'smtpd_recipient_restrictions = permit_sasl_authenticated, reject') postconf(host, 'smtpd_sender_restrictions = permit_sasl_authenticated, reject') postconf(host, 'smtpd_sasl_auth_enable = yes') postconf(host, 'smtpd_sasl_security_options = noanonymous') postconf(host, 'smtpd_sasl_tls_security_options = $smtpd_sasl_security_options') postconf(host, 'broken_sasl_auth_clients = yes') postconf(host, 'smtpd_sasl_authenticated_header = yes') postconf(host, 'smtpd_sasl_local_domain = %s' % realm) # TLS will not be used postconf(host, 'smtpd_tls_security_level = none') # disable procmail if exists, make use of default local(8) delivery agent postconf(host, "mailbox_command=") # listen on all active interfaces postconf(host, "inet_interfaces = all") host.run_command(["systemctl", "restart", "saslauthd"]) result = host.run_command(["postconf", "mydestination"]) mydestination = result.stdout_text.strip() + ", " + host.domain.name postconf(host, mydestination) host.run_command(["systemctl", "restart", "postfix"]) def configure_starttls(host): """Obtain a TLS cert for the host and configure postfix for starttls Depends on configure_postfix() being executed first. """ host.run_command(["rm", "-f", SMTPD_KEY, SMTPD_CERT]) host.run_command(["ipa-getcert", "request", "-f", SMTPD_CERT, "-k", SMTPD_KEY, "-K", "smtp/%s" % host.hostname, "-D", host.hostname, "-O", "postfix", "-o", "postfix", "-M", "0640", "-m", "0640", "-w", ]) postconf(host, 'smtpd_tls_loglevel = 1') postconf(host, 'smtpd_tls_auth_only = yes') postconf(host, "smtpd_tls_key_file = {}".format(SMTPD_KEY)) postconf(host, "smtpd_tls_cert_file = {}".format(SMTPD_CERT)) postconf(host, 'smtpd_tls_received_header = yes') postconf(host, 'smtpd_tls_session_cache_timeout = 3600s') # announce STARTTLS support to remote SMTP clients, not require postconf(host, 'smtpd_tls_security_level = may') host.run_command(["systemctl", "restart", "postfix"]) def configure_ssl_client_cert(host): """Obtain a TLS cert for the SMTP client and configure postfix for client certificate verification. Depends on configure_starttls(). """ host.run_command(["rm", "-f", SMTP_CLIENT_KEY, SMTP_CLIENT_CERT]) host.run_command(["ipa-getcert", "request", "-f", SMTP_CLIENT_CERT, "-k", SMTP_CLIENT_KEY, "-K", "smtp_client/%s" % host.hostname, "-D", host.hostname, "-P", "Secret123", "-w", ]) # mandatory TLS encryption postconf(host, "smtpd_tls_security_level = encrypt") # require a trusted remote SMTP client certificate postconf(host, "smtpd_tls_req_ccert = yes") # CA certificates of root CAs trusted to sign remote SMTP client cert postconf(host, f"smtpd_tls_CAfile = {paths.IPA_CA_CRT}") if host.is_fips_mode: postconf(host, 'smtpd_tls_fingerprint_digest = sha256') host.run_command(["systemctl", "restart", "postfix"]) def configure_ssl(host): """Enable the ssl listener on port 465. """ conf = host.get_file_contents('/etc/postfix/master.cf', encoding='utf-8') conf += 'smtps inet n - n - - smtpd\n' conf += ' -o syslog_name=postfix/smtps\n' conf += ' -o smtpd_tls_wrappermode=yes\n' conf += ' -o smtpd_sasl_auth_enable=yes\n' host.put_file_contents('/etc/postfix/master.cf', conf) host.run_command(["systemctl", "restart", "postfix"]) def decode_header(header): """Decode the header if needed and return the value""" # Only support one value for now (value, encoding) = email.header.decode_header(header)[0] if encoding: return value.decode(encoding) else: return value def validate_mail(host, id, content): """Retrieve a remote e-mail and determine if it matches the current user""" mail = host.get_file_contents('/var/mail/user%d' % id) msg = email.message_from_bytes(mail) assert decode_header(msg['To']) == 'user%d@%s' % (id, host.domain.name) assert decode_header(msg['From']) == 'IPA-EPN <noreply@%s>' % \ host.domain.name assert decode_header(msg['subject']) == 'Your password will expire soon.' for part in msg.walk(): if part.get_content_maintype() == 'multipart': continue body = part.get_payload() decoded = base64.b64decode(body).decode('utf-8') assert content in decoded class TestEPN(IntegrationTest): """Test Suite for EPN: https://pagure.io/freeipa/issue/3687 """ num_clients = 1 notify_ttls = (28, 14, 7, 3, 1) def _check_epn_output( self, host, dry_run=False, mailtest=False, from_nbdays=None, to_nbdays=None, raiseonerr=True, validatejson=True ): result = tasks.ipa_epn( host, from_nbdays=from_nbdays, to_nbdays=to_nbdays, mailtest=mailtest, dry_run=dry_run, raiseonerr=raiseonerr ) if validatejson: json.dumps(json.loads(result.stdout_text), ensure_ascii=False) return (result.stdout_text, result.stderr_text, result.returncode) @classmethod def install(cls, mh): # External DNS is only available before install so cache a copy # of the *ipa-epn-client package so we can experimentally remove # it later. # # Notes: # - A package can't be downloaded that is already installed so we # have to remove it first. # - dnf cleans up previously downloaded locations so make a copy it # doesn't know about. # - Adds a class variable, pkg, containing the package name of # the downloaded *ipa-client-epn rpm. hosts = [cls.master, cls.clients[0]] tasks.uninstall_packages(cls.clients[0],EPN_PKG) pkgdir = tasks.download_packages(cls.clients[0], EPN_PKG) pkg = cls.clients[0].run_command(r'ls -1 {}'.format(pkgdir)) cls.pkg = pkg.stdout_text.strip() cls.clients[0].run_command(['cp', os.path.join(pkgdir, cls.pkg), '/tmp']) cls.clients[0].run_command(r'rm -rf {}'.format(pkgdir)) for host in hosts: tasks.install_packages(host, EPN_PKG + ["postfix"]) try: tasks.install_packages(host, ["cyrus-sasl"]) except Exception: # the package is likely already installed pass tasks.install_master(cls.master, setup_dns=True) tasks.install_client(cls.master, cls.clients[0]) for host in hosts: configure_postfix(host, cls.master.domain.realm) Firewall(host).enable_services(["smtp", "smtps"]) @classmethod def uninstall(cls, mh): super(TestEPN, cls).uninstall(mh) tasks.uninstall_packages(cls.master,EPN_PKG) tasks.uninstall_packages(cls.master, ["postfix"]) tasks.uninstall_packages(cls.clients[0], EPN_PKG) tasks.uninstall_packages(cls.clients[0], ["postfix"]) cls.master.run_command(r'rm -f /etc/postfix/smtp.keytab') for cert in [SMTPD_CERT, SMTP_CLIENT_CERT]: cls.master.run_command(["getcert", "stop-tracking", "-f", cert]) cls.master.run_command( [ "rm", "-f", SMTPD_CERT, SMTPD_KEY, SMTP_CLIENT_CERT, SMTP_CLIENT_KEY, ] ) @pytest.mark.skip_if_platform( "debian", reason="Cannot check installed packages using RPM" ) def test_EPN_config_file(self): """Check that the EPN configuration file is installed. https://pagure.io/freeipa/issue/8374 """ epn_conf = "/etc/ipa/epn.conf" epn_template = "/etc/ipa/epn/expire_msg.template" if tasks.get_platform(self.master) != "fedora": cmd1 = self.master.run_command(["rpm", "-qc", "ipa-client-epn"]) else: cmd1 = self.master.run_command(["rpm", "-qc", "freeipa-client-epn"]) assert epn_conf in cmd1.stdout_text assert epn_template in cmd1.stdout_text cmd2 = self.master.run_command(["sha256sum", epn_conf]) ck = "06a73f15562686516c984dd9fe61689c5268ff1c5a13e69f8b347afef41b3277" assert cmd2.stdout_text.find(ck) == 0 def test_EPN_connection_refused(self): """Test EPN behavior when the configured SMTP is down """ self.master.run_command(["systemctl", "stop", "postfix"]) (unused, stderr_text, rc) = self._check_epn_output( self.master, mailtest=True, raiseonerr=False, validatejson=False ) self.master.run_command(["systemctl", "start", "postfix"]) assert "IPA-EPN: Could not connect to the configured SMTP server" in \ stderr_text assert rc > 0 def test_EPN_no_security_downgrade_starttls(self): """Configure postfix without starttls and test no auth happens """ epn_conf = STARTTLS_EPN_CONF.format( server=self.master.hostname, user=self.master.config.admin_name, password=self.master.config.admin_password, ) self.master.put_file_contents('/etc/ipa/epn.conf', epn_conf) (unused, stderr_text, rc) = self._check_epn_output( self.master, mailtest=True, raiseonerr=False, validatejson=False ) expected_msg = "IPA-EPN: Unable to create an encrypted session to" assert expected_msg in stderr_text assert rc > 0 def test_EPN_no_security_downgrade_tls(self): """Configure postfix without tls and test no auth happens """ epn_conf = SSL_EPN_CONF.format( server=self.master.hostname, user=self.master.config.admin_name, password=self.master.config.admin_password, ) self.master.put_file_contents('/etc/ipa/epn.conf', epn_conf) (unused, stderr_text, rc) = self._check_epn_output( self.master, mailtest=True, raiseonerr=False, validatejson=False ) expected_msg = ( "IPA-EPN: Could not connect to the configured SMTP " "server" ) assert expected_msg in stderr_text assert rc > 0 def test_EPN_smoketest_1(self): """No users except admin. Check --dry-run output. With the default configuration, the result should be an empty list. Also check behavior on master and client alike. """ self.master.put_file_contents('/etc/ipa/epn.conf', DEFAULT_EPN_CONF) # check EPN on client (LDAP+GSSAPI) (stdout_text, unused, _unused) = self._check_epn_output( self.clients[0], dry_run=True ) assert len(json.loads(stdout_text)) == 0 # check EPN on master (LDAPI) (stdout_text, unused, _unused) = self._check_epn_output( self.master, dry_run=True ) assert len(json.loads(stdout_text)) == 0 @pytest.fixture def cleanupusers(self): """Fixture to remove any users added as part of the tests. It isn't necessary to remove all users created. Ignore all errors. """ yield for user in ["testuser0", "testuser1"]: try: self.master.run_command(['ipa', 'user-del', user]) except Exception: pass @pytest.fixture def cleanupmail(self): """Cleanup any existing mail that has been sent.""" cmd = ["rm", "-f"] for i in range(30): cmd.append("/var/mail/user%d" % i) self.master.run_command(cmd) def test_EPN_smoketest_2(self, cleanupusers): """Add a user without password. Add a user whose password expires within the default time range. Check --dry-run output. """ tasks.user_add(self.master, "testuser0") tasks.user_add( self.master, "testuser1", password="Secret123", extra_args=[ "--password-expiration", datetime_to_generalized_time( datetime.datetime.now( tz=datetime.timezone.utc) + datetime.timedelta( days=7) ), ], ) (stdout_text_client, unused, _unused) = self._check_epn_output( self.clients[0], dry_run=True ) (stdout_text_master, unused, _unused) = self._check_epn_output( self.master, dry_run=True ) assert stdout_text_master == stdout_text_client assert "testuser0" not in stdout_text_client assert "testuser1" in stdout_text_client def test_EPN_smoketest_3(self): """Add a bunch of users with incrementally expiring passwords (one per day). Check --dry-run output. """ users = {} userbase_str = "user" for i in range(30): uid = userbase_str + str(i) users[i] = dict( uid=uid, days=i, krbpasswordexpiration=datetime_to_generalized_time( datetime.datetime.now( tz=datetime.timezone.utc) + datetime.timedelta( days=i) ), ) for user_info in users.values(): tasks.user_add( self.master, user_info["uid"], extra_args=[ "--password-expiration", user_info["krbpasswordexpiration"], ], password=None, ) (stdout_text_client, unused, _unused) = self._check_epn_output( self.clients[0], dry_run=True ) (stdout_text_master, unused, _unused) = self._check_epn_output( self.master, dry_run=True ) assert stdout_text_master == stdout_text_client user_lst = [] for user in json.loads(stdout_text_master): user_lst.append(user["uid"]) expected_users = ["user1", "user3", "user7", "user14", "user28"] assert sorted(user_lst) == sorted(expected_users) def test_EPN_nbdays_0(self, cleanupmail): """Test the to/from nbdays options (implies --dry-run) We have a set of users installed with varying expiration dates. Confirm that to/from nbdays finds them. Make sure --dry-run does not accidentally send emails. """ # Use the notify_ttls values with a 1-day sliding window for i in self.notify_ttls: user_list = [] (stdout_text_client, unused, _unused) = self._check_epn_output( self.clients[0], from_nbdays=i, to_nbdays=i + 1, dry_run=True ) for user in json.loads(stdout_text_client): user_list.append(user["uid"]) assert len(user_list) == 1 userid = "user{id}".format(id=i) assert user_list[0] == userid # Check that the user list is expected for any given notify_ttls. (stdout_text_client, unused, _unused) = self._check_epn_output( self.clients[0], to_nbdays=i ) user_list = [user["uid"] for user in json.loads(stdout_text_client)] assert len(user_list) == 1 assert user_list[0] == "user{id}".format(id=i - 1) # make sure no emails were sent result = self.clients[0].run_command(['ls', '-lha', '/var/mail/']) assert userid not in result.stdout_text def test_EPN_nbdays_1(self, cleanupmail): """Test that for a given range, we find the users in that range""" # Use hardcoded date ranges for now for date_range in [(0, 5), (7, 15), (1, 20)]: expected_user_list = ["user{i}".format(i=i) for i in range(date_range[0], date_range[1])] (stdout_text_client, unused, _unused) = self._check_epn_output( self.clients[0], from_nbdays=date_range[0], to_nbdays=date_range[1] ) user_list = [user["uid"] for user in json.loads(stdout_text_client)] for user in expected_user_list: assert user in user_list for user in user_list: assert user in expected_user_list # Test the to/from nbdays options behavior with illegal input def test_EPN_nbdays_input_0(self): """Make sure that --to-nbdays implies --dry-run ; therefore check that the output is valid JSON and contains the expected user. """ (stdout_text_client, unused, _unused) = self._check_epn_output( self.clients[0], to_nbdays=5, dry_run=False ) assert len(json.loads(stdout_text_client)) == 1 assert json.loads(stdout_text_client)[0]["uid"] == "user4" def test_EPN_nbdays_input_1(self): """Make sure that --from-nbdays cannot be used without --to-nbdays""" (unused, stderr_text_client, rc) = \ self._check_epn_output( self.clients[0], from_nbdays=3, raiseonerr=False, validatejson=False ) assert "You cannot specify --from-nbdays without --to-nbdays" \ in stderr_text_client assert rc > 0 def test_EPN_nbdays_input_2(self): """alpha input""" (unused, stderr, rc) = self._check_epn_output( self.clients[0], to_nbdays="abc", raiseonerr=False, validatejson=False ) assert "error: --to-nbdays must be a positive integer." in stderr assert rc > 0 def test_EPN_nbdays_input_3(self): """from_nbdays > to_nbdays""" (unused, stderr, rc) = self._check_epn_output( self.clients[0], from_nbdays=9, to_nbdays=7, raiseonerr=False, validatejson=False ) assert "error: --from-nbdays must be smaller than --to-nbdays." in \ stderr assert rc > 0 def test_EPN_nbdays_input_4(self): """decimal input""" (unused, stderr, rc) = self._check_epn_output( self.clients[0], to_nbdays=7.3, raiseonerr=False, validatejson=False ) logger.info(stderr) assert rc > 0 assert "error: --to-nbdays must be a positive integer." in stderr # From here the tests build on one another: # 1) add auth # 2) tweak the template # 3) add starttls def test_EPN_authenticated(self, cleanupmail): """Enable authentication and test that mail is delivered """ epn_conf = USER_EPN_CONF.format( user=self.master.config.admin_name, password=self.master.config.admin_password, ) self.master.put_file_contents('/etc/ipa/epn.conf', epn_conf) tasks.ipa_epn(self.master) for i in self.notify_ttls: validate_mail(self.master, i, "Hi test user,\n\nYour password will expire") def test_EPN_template(self, cleanupmail): """Modify the template to ensure changes are applied. """ exp_msg = textwrap.dedent(''' Hi {{ first }} {{last}}, Your login entry {{uid}} is going to expire on {{ expiration }}. Please change it soon. Your friendly neighborhood admins. ''') self.master.put_file_contents('/etc/ipa/epn/expire_msg.template', exp_msg) tasks.ipa_epn(self.master) for i in self.notify_ttls: validate_mail(self.master, i, "Hi test user,\nYour login entry user%d is going" % i) def test_mailtest(self, cleanupmail): """Execute mailtest to validate mail is working Set of of our pre-created users as the smtp_admin to receive the mail, run ipa-epn --mailtest, then validate the result. Using a non-expired user here, user2, to receive the result. """ epn_conf = ( USER_EPN_CONF + textwrap.dedent( """\ smtp_admin=user2@{domain} """ ) ).format( user=self.master.config.admin_name, password=self.master.config.admin_password, domain=self.master.domain.name, ) self.master.put_file_contents('/etc/ipa/epn.conf', epn_conf) tasks.ipa_epn(self.master, mailtest=True) validate_mail(self.master, 2, "Hi SAMPLE USER,\nYour login entry SAUSER is going") def test_mailtest_dry_run(self): try: tasks.ipa_epn(self.master, mailtest=True, dry_run=True) except CalledProcessError as e: assert 'You cannot specify' in e.stderr else: raise AssertionError('--mail-test and --dry-run aren\'t supposed ' 'to succeed') def test_EPN_starttls(self, cleanupmail): """Configure with starttls and test delivery """ epn_conf = STARTTLS_EPN_CONF.format( server=self.master.hostname, user=self.master.config.admin_name, password=self.master.config.admin_password, ) self.master.put_file_contents('/etc/ipa/epn.conf', epn_conf) configure_starttls(self.master) tasks.ipa_epn(self.master) for i in self.notify_ttls: validate_mail(self.master, i, "Hi test user,\nYour login entry user%d is going" % i) def test_EPN_ssl(self, cleanupmail): """Configure with ssl and test delivery """ epn_conf = SSL_EPN_CONF.format( server=self.master.hostname, user=self.master.config.admin_name, password=self.master.config.admin_password, ) self.master.put_file_contents('/etc/ipa/epn.conf', epn_conf) configure_ssl(self.master) tasks.ipa_epn(self.master) for i in self.notify_ttls: validate_mail(self.master, i, "Hi test user,\nYour login entry user%d is going" % i) def test_EPN_ssl_client_cert(self, cleanupmail): """Configure with ssl + client certificate and test delivery """ epn_conf = (SSL_EPN_CONF + CLIENT_CERT_EPN_CONF).format( server=self.master.hostname, user=self.master.config.admin_name, password=self.master.config.admin_password, client_cert=SMTP_CLIENT_CERT, client_key=SMTP_CLIENT_KEY, client_key_pass=SMTP_CLIENT_KEY_PASS, ) self.master.put_file_contents('/etc/ipa/epn.conf', epn_conf) configure_ssl_client_cert(self.master) tasks.ipa_epn(self.master) for i in self.notify_ttls: validate_mail( self.master, i, "Hi test user,\nYour login entry user%d is going" % i ) def test_EPN_starttls_client_cert(self, cleanupmail): """Configure with starttls + client certificate and test delivery """ epn_conf = (STARTTLS_EPN_CONF + CLIENT_CERT_EPN_CONF).format( server=self.master.hostname, user=self.master.config.admin_name, password=self.master.config.admin_password, client_cert=SMTP_CLIENT_CERT, client_key=SMTP_CLIENT_KEY, client_key_pass=SMTP_CLIENT_KEY_PASS, ) self.master.put_file_contents('/etc/ipa/epn.conf', epn_conf) tasks.ipa_epn(self.master) for i in self.notify_ttls: validate_mail( self.master, i, "Hi test user,\nYour login entry user%d is going" % i ) def test_EPN_delay_config(self, cleanupmail): """Test the smtp_delay configuration option """ epn_conf = DEFAULT_EPN_CONF + textwrap.dedent( """\ smtp_delay=A """ ) self.master.put_file_contents('/etc/ipa/epn.conf', epn_conf) result = tasks.ipa_epn(self.master, raiseonerr=False) assert "could not convert string to float: 'A'" in result.stderr_text epn_conf = DEFAULT_EPN_CONF + textwrap.dedent( """\ smtp_delay=-1 """ ) self.master.put_file_contents('/etc/ipa/epn.conf', epn_conf) result = tasks.ipa_epn(self.master, raiseonerr=False) assert "smtp_delay cannot be less than zero" in result.stderr_text def test_EPN_admin(self): """The admin user is special and has no givenName by default It also doesn't by default have an e-mail address Check --dry-run output. """ self.master.put_file_contents('/etc/ipa/epn.conf', DEFAULT_EPN_CONF) self.master.run_command( ['ipa', 'user-mod', 'admin', '--password-expiration', datetime_to_generalized_time( datetime.datetime.now( tz=datetime.timezone.utc) + datetime.timedelta( days=7) )] ) (unused, stderr_text, _unused) = self._check_epn_output( self.master, dry_run=True ) assert "uid=admin" in stderr_text @pytest.mark.skip_if_platform( "debian", reason="Don't know how to download-only pkgs in Debian" ) def test_EPN_reinstall(self): """Test that EPN can be installed, uninstalled and reinstalled. Since post-install we no longer have access to the repos the package is downloaded and stored prior to server installation. """ tasks.uninstall_packages(self.clients[0], EPN_PKG) tasks.install_packages(self.clients[0], [os.path.join('/tmp', self.pkg)]) self.clients[0].run_command(r'rm -f /tmp/{}'.format(self.pkg)) # re-installing will create a new epn.conf so any execution # of ipa-epn will verify the reinstall was ok. Since the previous # test would have failed this one should be ok with new config. # Re-run the admin user expected failure (unused, stderr_text, _unused) = self._check_epn_output( self.master, dry_run=True ) assert "uid=admin" in stderr_text
31,037
Python
.py
732
32.452186
80
0.596488
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,544
test_sssd.py
freeipa_freeipa/ipatests/test_integration/test_sssd.py
# # Copyright (C) 2019 FreeIPA Contributors see COPYING for license # """This module provides tests for SSSD as used in IPA""" from __future__ import absolute_import import time from contextlib import contextmanager import re import os import pytest import subprocess import textwrap from ipatests.test_integration.base import IntegrationTest from ipatests.pytest_ipa.integration import tasks from ipatests.pytest_ipa.integration.tasks import clear_sssd_cache from ipatests.util import xfail_context from ipaplatform.tasks import tasks as platform_tasks from ipaplatform.osinfo import osinfo from ipaplatform.paths import paths from ipapython.dn import DN class TestSSSDWithAdTrust(IntegrationTest): topology = 'star' num_ad_domains = 1 num_ad_subdomains = 1 num_clients = 1 users = { 'ipa': { 'name': 'user1', 'password': 'SecretUser1', 'group': 'user1', }, 'ad': { 'name_tmpl': 'testuser@{domain}', 'password': 'Secret123', 'group_tmpl': 'testgroup@{domain}', }, 'child_ad': { 'name_tmpl': 'subdomaintestuser@{domain}', 'password': 'Secret123', }, 'fakeuser': { 'name': 'some_user@some.domain' }, } ipa_user = 'user1' ipa_user_password = 'SecretUser1' intermed_user = 'user2' ad_user_tmpl = 'testuser@{domain}' ad_user_password = 'Secret123' @classmethod def install(cls, mh): super(TestSSSDWithAdTrust, cls).install(mh) cls.ad = cls.ads[0] cls.child_ad = cls.ad_subdomains[0] tasks.install_adtrust(cls.master) tasks.configure_dns_for_trust(cls.master, cls.ad) tasks.establish_trust_with_ad(cls.master, cls.ad.domain.name) cls.users['ad']['name'] = cls.users['ad']['name_tmpl'].format( domain=cls.ad.domain.name) cls.users['ad']['group'] = cls.users['ad']['group_tmpl'].format( domain=cls.ad.domain.name) cls.users['child_ad']['name'] = ( cls.users['child_ad']['name_tmpl'].format( domain=cls.child_ad.domain.name)) tasks.user_add(cls.master, cls.intermed_user) tasks.create_active_user(cls.master, cls.ipa_user, cls.ipa_user_password) @contextmanager def config_sssd_cache_auth(self, cached_auth_timeout): sssd_conf_backup = tasks.FileBackup(self.master, paths.SSSD_CONF) with tasks.remote_sssd_config(self.master) as sssd_conf: sssd_conf.edit_domain(self.master.domain, 'cached_auth_timeout', cached_auth_timeout) sssd_conf.edit_service('pam', 'pam_verbosity', '2') try: tasks.clear_sssd_cache(self.master) yield finally: sssd_conf_backup.restore() tasks.clear_sssd_cache(self.master) def is_auth_cached(self, user): cmd = ['su', '-l', user['name'], '-c', 'true'] res = tasks.run_command_as_user(self.master, self.intermed_user, cmd, stdin_text=user['password'] + '\n') return 'Authenticated with cached credentials.' in res.stdout_text @pytest.mark.parametrize('user', ['ipa', 'ad']) def test_auth_cache_disabled_by_default(self, user): """Check credentials not cached with default sssd config. Regression test for cached_auth_timeout option https://bugzilla.redhat.com/show_bug.cgi?id=1685581 """ with self.config_sssd_cache_auth(cached_auth_timeout=None): assert not self.is_auth_cached(self.users[user]) assert not self.is_auth_cached(self.users[user]) @pytest.mark.parametrize('user', ['ipa', 'ad']) def test_auth_cache_disabled_with_value_0(self, user): """Check credentials not cached with cached_auth_timeout=0 in sssd.conf Regression test for cached_auth_timeout option https://bugzilla.redhat.com/show_bug.cgi?id=1685581 """ with self.config_sssd_cache_auth(cached_auth_timeout=0): assert not self.is_auth_cached(self.users[user]) assert not self.is_auth_cached(self.users[user]) @pytest.mark.parametrize('user', ['ipa', 'ad']) def test_auth_cache_enabled_when_configured(self, user): """Check credentials are cached with cached_auth_timeout=30 Regression test for cached_auth_timeout option https://bugzilla.redhat.com/show_bug.cgi?id=1685581 """ timeout = 30 with self.config_sssd_cache_auth(cached_auth_timeout=timeout): start = time.time() # check auth is cached after first login assert not self.is_auth_cached(self.users[user]) assert self.is_auth_cached(self.users[user]) # check cache expires after configured timeout elapsed = time.time() - start time.sleep(timeout - 5 - elapsed) assert self.is_auth_cached(self.users[user]) time.sleep(10) assert not self.is_auth_cached(self.users[user]) @contextmanager def filter_user_setup(self, user): sssd_conf_backup = tasks.FileBackup(self.master, paths.SSSD_CONF) try: with tasks.remote_sssd_config(self.master) as sssd_conf: sssd_conf.edit_service("nss", 'filter_users', self.users[user]['name']) tasks.clear_sssd_cache(self.master) yield finally: sssd_conf_backup.restore() tasks.clear_sssd_cache(self.master) @pytest.mark.xfail( osinfo.id == 'fedora' and osinfo.version_number <= (29,), reason='https://pagure.io/SSSD/sssd/issue/3978') @pytest.mark.parametrize('user', ['ad', 'fakeuser']) def test_is_user_filtered(self, user): """No lookup in data provider from 'filter_users' config option. Test for https://bugzilla.redhat.com/show_bug.cgi?id=1685472 https://bugzilla.redhat.com/show_bug.cgi?id=1724088 When there are users in filter_users in domain section then no look up should be in data provider. """ with self.filter_user_setup(user=user): log_file = '{0}/sssd_nss.log'.format(paths.VAR_LOG_SSSD_DIR) logsize = tasks.get_logsize(self.master, log_file) self.master.run_command( ['getent', 'passwd', self.users[user]['name']], ok_returncode=2) sssd_log = self.master.get_file_contents(log_file)[logsize:] dp_req = ("Looking up [{0}] in data provider".format( self.users[user]['name'])) assert not dp_req.encode() in sssd_log def test_extdom_group(self): """ipa-extdom-extop plugin should allow @ in group name. Test for : https://bugzilla.redhat.com/show_bug.cgi?id=1746951 If group contains @ in group name from AD, eg. abc@pqr@AD.DOMAIN then it should fetch successfully on ipa-client. """ client = self.clients[0] hosts = [self.master, client] ad_group = 'group@group@{0}'.format(self.ad.domain.name) expression = '((?P<name>.+)@(?P<domain>[^@]+$))' master_conf_backup = tasks.FileBackup(self.master, paths.SSSD_CONF) client_conf_backup = tasks.FileBackup(client, paths.SSSD_CONF) for host in hosts: with tasks.remote_sssd_config(host) as sssd_conf: sssd_conf.edit_service('sssd', 're_expression', expression) tasks.clear_sssd_cache(host) try: cmd = ['getent', 'group', ad_group] result = self.master.run_command(cmd) assert ad_group in result.stdout_text result2 = client.run_command(cmd) assert ad_group in result2.stdout_text finally: master_conf_backup.restore() client_conf_backup.restore() tasks.clear_sssd_cache(self.master) tasks.clear_sssd_cache(client) def test_external_group_paging(self): """SSSD should fetch external groups without any limit. Regression test for https://pagure.io/SSSD/sssd/issue/4058 1: Add external groups more than limit. 2: Run the command id aduser@ADDOMAIN.COM 3: sssd should retrieve all the external groups. """ new_limit = 50 master = self.master conn = master.ldap_connect() dn = DN(('cn', 'config')) entry = conn.get_entry(dn) orig_limit = entry.single_value.get('nsslapd-sizelimit') ldap_query = textwrap.dedent(""" dn: cn=config changetype: modify replace: nsslapd-sizelimit nsslapd-sizelimit: {limit} """) tasks.ldapmodify_dm(master, ldap_query.format(limit=new_limit)) sssd_conf_backup = tasks.FileBackup(self.master, paths.SSSD_CONF) ldap_page_size = new_limit - 1 group_count = new_limit + 2 # default ldap_page_size is '1000', adding workaround as # ldap_page_size < nsslapd-sizelimit in sssd.conf # Related issue : https://pagure.io/389-ds-base/issue/50888 with tasks.remote_sssd_config(self.master) as sssd_conf: sssd_conf.edit_domain( self.master.domain, 'ldap_page_size', ldap_page_size) tasks.clear_sssd_cache(master) tasks.kinit_admin(master) for i in range(group_count): master.run_command(['ipa', 'group-add', '--external', 'ext-ipatest{0}'.format(i)]) try: log_file = '{0}/sssd_{1}.log'.format( paths.VAR_LOG_SSSD_DIR, master.domain.name) group_entry = b'[%d] external groups found' % group_count logsize = tasks.get_logsize(master, log_file) master.run_command(['id', self.users['ad']['name']]) sssd_logs = master.get_file_contents(log_file)[logsize:] assert group_entry in sssd_logs finally: for i in range(group_count): master.run_command(['ipa', 'group-del', 'ext-ipatest{0}'.format(i)]) # reset to original limit tasks.ldapmodify_dm(master, ldap_query.format(limit=orig_limit)) sssd_conf_backup.restore() @pytest.mark.parametrize('user_origin', ['ipa', 'ad']) def test_sssd_cache_refresh(self, user_origin): """Check SSSD updates expired cache items for domain and its subdomains Regression test for https://pagure.io/SSSD/sssd/issue/4012 """ def get_cache_update_time(obj_kind, obj_name): res = self.master.run_command( ['sssctl', '{}-show'.format(obj_kind), obj_name]) m = re.search(r'Cache entry last update time:\s+([^\n]+)', res.stdout_text) update_time = m.group(1).strip() assert update_time return update_time # by design, sssd does first update of expired records in 30 seconds # since start refresh_time = 30 user = self.users[user_origin]['name'] group = self.users[user_origin]['group'] sssd_conf_backup = tasks.FileBackup(self.master, paths.SSSD_CONF) try: with tasks.remote_sssd_config(self.master) as sssd_conf: sssd_conf.edit_domain( self.master.domain, 'refresh_expired_interval', 1) sssd_conf.edit_domain( self.master.domain, 'entry_cache_timeout', 1) tasks.clear_sssd_cache(self.master) start = time.time() self.master.run_command(['id', user]) user_update_time = get_cache_update_time('user', user) group_update_time = get_cache_update_time('group', group) time.sleep(start + refresh_time - time.time() + 5) assert get_cache_update_time('user', user) != user_update_time assert (get_cache_update_time('group', group) != group_update_time) finally: sssd_conf_backup.restore() tasks.clear_sssd_cache(self.master) def test_ext_grp_with_ldap(self): """User and group with same name should not break reading AD user data. Regression test for https://pagure.io/SSSD/sssd/issue/4073 When aduser is added in extrnal group and this group is added in group with same name of nonprivate ipa user and possix id, then lookup of aduser and group should be successful when cache is empty. """ cmd = self.master.run_command(['sssd', '--version']) sssd_version = platform_tasks.parse_ipa_version( cmd.stdout_text.strip()) if sssd_version <= platform_tasks.parse_ipa_version('2.2.2'): pytest.skip("Fix for https://pagure.io/SSSD/sssd/issue/4073 " "unavailable with sssd-2.2.2") client = self.clients[0] user = 'ipatest' userid = '100996' ext_group = 'ext-ipatest' tasks.kinit_admin(self.master) # add user with same uid and gidnumber tasks.user_add(self.master, user, extra_args=[ '--noprivate', '--uid', userid, '--gidnumber', userid]) # add group with same as user_name and user_id. tasks.group_add(self.master, user, extra_args=['--gid', userid]) tasks.group_add(self.master, ext_group, extra_args=['--external']) self.master.run_command( ['ipa', 'group-add-member', '--group', ext_group, user]) self.master.run_command([ 'ipa', '-n', 'group-add-member', '--external', self.users['ad']['name'], ext_group]) tasks.clear_sssd_cache(self.master) tasks.clear_sssd_cache(client) try: result = client.run_command(['id', self.users['ad']['name']]) assert '{uid}({name})'.format(uid=userid, name=user) in result.stdout_text finally: self.master.run_command(['ipa', 'user-del', user]) self.master.run_command(['ipa', 'group-del', user, ext_group]) @pytest.mark.parametrize('user_origin', ['ipa', 'ad']) def test_external_group_member_mismatch(self, user_origin): """Prevent adding IPA objects as external group external members External groups must only allow adding non-IPA objects as external members in 'ipa group-add-member foo --external bar'. """ master = self.master tasks.clear_sssd_cache(master) tasks.kinit_admin(master) master.run_command(['ipa', 'group-add', '--external', 'ext-ipatest']) try: master.run_command(['ipa', '-n', 'group-add-member', 'ext-ipatest', '--external', self.users[user_origin]['name']]) except subprocess.CalledProcessError: # Only 'ipa' origin should throw a validation error assert user_origin == 'ipa' finally: master.run_command(['ipa', 'group-del', 'ext-ipatest']) @contextmanager def disabled_trustdomain(self): ad_domain_name = self.ad.domain.name ad_subdomain_name = self.child_ad.domain.name self.master.run_command(['ipa', 'trustdomain-disable', ad_domain_name, ad_subdomain_name]) tasks.clear_sssd_cache(self.master) try: yield finally: self.master.run_command(['ipa', 'trustdomain-enable', ad_domain_name, ad_subdomain_name]) tasks.clear_sssd_cache(self.master) @pytest.mark.parametrize('user_origin', ['ipa', 'ad']) def test_trustdomain_disable_does_not_disable_root_domain(self, user_origin): """Test that disabling trustdomain does not affect other domains.""" user = self.users[user_origin]['name'] with self.disabled_trustdomain(): self.master.run_command(['id', user]) def test_aduser_with_idview(self): """Test that trusted AD users should not lose their AD domains. This is a regression test for sssd bug: https://pagure.io/SSSD/sssd/issue/4173 1. Override AD user's UID, GID by adding it in ID view on IPA server. 2. Stop the SSSD, and clear SSSD cache and restart SSSD on a IPA client 3. getent with UID from ID view should return AD domain after default memcache_timeout. """ client = self.clients[0] user = self.users['ad']['name'] idview = 'testview' def verify_retrieved_users_domain(): # Wait for the record to expire in SSSD's cache # (memcache_timeout default value is 300s). test_user = ['su', user, '-c', 'sleep 360; getent passwd 10001'] result = client.run_command(test_user) assert user in result.stdout_text # verify the user can be retrieved initially tasks.clear_sssd_cache(self.master) self.master.run_command(['id', user]) self.master.run_command(['ipa', 'idview-add', idview]) self.master.run_command(['ipa', 'idoverrideuser-add', idview, user]) self.master.run_command(['ipa', 'idview-apply', idview, '--hosts={0}'.format(client.hostname)]) self.master.run_command(['ipa', 'idoverrideuser-mod', idview, user, '--uid=10001', '--gid=10000']) try: clear_sssd_cache(client) sssd_version = tasks.get_sssd_version(client) with xfail_context(sssd_version < tasks.parse_version('2.3.0'), 'https://pagure.io/SSSD/sssd/issue/4173'): verify_retrieved_users_domain() finally: self.master.run_command(['ipa', 'idview-del', idview]) def test_trustdomain_disable_disables_subdomain(self): """Test that users from disabled trustdomains can not use ipa resources This is a regression test for sssd bug: https://pagure.io/SSSD/sssd/issue/4078 """ user = self.users['child_ad']['name'] # verify the user can be retrieved initially self.master.run_command(['id', user]) with self.disabled_trustdomain(): res = self.master.run_command(['id', user], raiseonerr=False) sssd_version = tasks.get_sssd_version(self.master) with xfail_context(sssd_version < tasks.parse_version('2.2.3'), 'https://pagure.io/SSSD/sssd/issue/4078'): assert res.returncode == 1 assert 'no such user' in res.stderr_text # verify the user can be retrieved after re-enabling trustdomain self.master.run_command(['id', user]) @pytest.mark.xfail( osinfo.id == 'fedora' and osinfo.version_number <= (31,), reason='https://pagure.io/SSSD/sssd/issue/3721', ) def test_subdomain_lookup_with_certmaprule_containing_dn(self): """DN names on certmaprules should not break AD Trust lookups. Regression test for https://pagure.io/SSSD/sssd/issue/3721 """ tasks.kinit_admin(self.master) # verify the user can be retrieved initially first_res = self.master.run_command(['id', self.users['ad']['name']]) cert_cn = 'CN=adca' cert_dcs = 'DC=' + ',DC='.join(self.ad.domain.name.split('.')) cert_subject = cert_cn + ',' + cert_dcs self.master.run_command([ 'ipa', 'certmaprule-add', "'{}'".format(cert_subject), "--maprule='(userCertificate;binary={cert!bin})'", "--matchrule='<ISSUER>{}'".format(cert_subject), "--domain={}".format(self.master.domain.name) ]) try: tasks.clear_sssd_cache(self.master) # verify the user can be retrieved after the certmaprule is added second_res = self.master.run_command( ['id', self.users['ad']['name']]) assert first_res.stdout_text == second_res.stdout_text verify_in_stdout = ['gid', 'uid', 'groups', self.users['ad']['name']] for text in verify_in_stdout: assert text in second_res.stdout_text finally: self.master.run_command( ['ipa', 'certmaprule-del', "'{}'".format(cert_subject)]) @contextmanager def override_gid_setup(self, gid): sssd_conf_backup = tasks.FileBackup(self.master, paths.SSSD_CONF) try: with tasks.remote_sssd_config(self.master) as sssd_conf: sssd_conf.edit_domain(self.master.domain, 'override_gid', gid) tasks.clear_sssd_cache(self.master) yield finally: sssd_conf_backup.restore() tasks.clear_sssd_cache(self.master) def test_override_gid_subdomain(self): """Test that override_gid is working for subdomain This is a regression test for sssd bug: https://pagure.io/SSSD/sssd/issue/4061 """ tasks.clear_sssd_cache(self.master) user = self.users['child_ad']['name'] gid = 10264 # verify the user can be retrieved initially self.master.run_command(['id', user]) with self.override_gid_setup(gid): test_gid = self.master.run_command(['id', user]) sssd_version = tasks.get_sssd_version(self.master) with xfail_context(sssd_version < tasks.parse_version('2.3.0'), 'https://pagure.io/SSSD/sssd/issue/4061'): assert 'gid={id}'.format(id=gid) in test_gid.stdout_text def test_aduser_mgmt(self): """Test for aduser-group management with posix AD trust Verify that query to the AD specific attributes for a user or a group directly is successful. Related : https://pagure.io/freeipa/issue/9127 """ tasks.remove_trust_with_ad(self.master, self.ad.domain.name, self.ad.hostname) tasks.configure_windows_dns_for_trust(self.ad, self.master) tasks.establish_trust_with_ad( self.master, self.ad.domain.name, extra_args=['--range-type', 'ipa-ad-trust-posix', '--two-way=true']) aduser = 'mytestuser@%s' % self.ad.domain.name tasks.clear_sssd_cache(self.master) self.master.run_command( ['getent', 'group', aduser], ok_returncode=2) sssd_conf_backup = tasks.FileBackup(self.master, paths.SSSD_CONF) content = self.master.get_file_contents(paths.SSSD_CONF, encoding='utf-8') conf = content + "\n[domain/{0}/{1}]\nldap_group_name = info".format( self.master.domain.name, self.ad.domain.name ) self.master.put_file_contents(paths.SSSD_CONF, conf) tasks.clear_sssd_cache(self.master) tasks.clear_sssd_cache(self.clients[0]) regex = r"^uid=(?P<uid>\d+).*gid=(?P<gid>\d+).*groups=(?P<groups>\d+)" try: for host in [self.master, self.clients[0]]: test_id = host.run_command(["id", aduser]) match = re.match(regex, test_id.stdout_text) uid = match.group('uid') gid = match.group('gid') assert uid == gid host.run_command(["getent", "passwd", aduser]) host.run_command(["getent", "group", aduser]) finally: sssd_conf_backup.restore() tasks.clear_sssd_cache(self.master) class TestNestedMembers(IntegrationTest): num_clients = 1 username = "testuser001" userpasswd = 'Secret123' @classmethod def install(cls, mh): tasks.install_master(cls.master) tasks.install_client(cls.master, cls.clients[0]) @pytest.fixture def nested_group_setup(self, tmpdir): """Setup and Clean up groups and user created""" master = self.master client = self.clients[0] # add a user and set password tasks.create_active_user(master, self.username, self.userpasswd) tasks.kinit_admin(master) privkey, pubkey = tasks.generate_ssh_keypair() with open(os.path.join( tmpdir, 'ssh_priv_key'), 'w') as fp: fp.write(privkey) master.run_command([ 'ipa', 'user-mod', self.username, '--ssh', "{}".format(pubkey) ]) master.put_file_contents('/tmp/user_ssh_priv_key', privkey) master.run_command(['chmod', '600', '/tmp/user_ssh_priv_key']) # add group groupa cmd_output = master.run_command(['ipa', 'group-add', 'groupa']) assert 'Added group "groupa"' in cmd_output.stdout_text # add group groupb cmd_output = master.run_command(['ipa', 'group-add', 'groupb']) assert 'Added group "groupb"' in cmd_output.stdout_text # add group groupc cmd_output = master.run_command(['ipa', 'group-add', 'groupc']) assert 'Added group "groupc"' in cmd_output.stdout_text client.put_file_contents('/tmp/user_ssh_priv_key', privkey) client.run_command(['chmod', '600', '/tmp/user_ssh_priv_key']) yield # test cleanup for group in ['groupa', 'groupb', 'groupc']: self.master.run_command(['ipa', 'group-del', group, '--continue']) self.master.run_command(['ipa', 'user-del', self.username, '--no-preserve', '--continue']) tasks.kdestroy_all(self.master) tasks.kdestroy_all(self.clients[0]) def test_nested_group_members(self, tmpdir, nested_group_setup): """Nested group memberships should be honoured "groupc" should be a child of "groupb" so that parent child relationship is as follows: "groupa"->"groupb"->"groupc" testuser001 is direct member of "groupa" and as a result member of "groupb" and "groupc"". Now if one adds a direct membership to "groupb" nothing will change. Now if one removes the direct membership to "groupb" nothing should change, the memberships should be honored Linked Issue: https://pagure.io/SSSD/sssd/issue/3636 """ master = self.master client = self.clients[0] # add group members cmd_output = master.run_command(['ipa', 'group-add-member', 'groupb', '--groups', 'groupa']) assert 'Group name: groupb' in cmd_output.stdout_text assert 'Member groups: groupa' in cmd_output.stdout_text assert 'Number of members added 1' in cmd_output.stdout_text cmd_output = master.run_command(['ipa', 'group-add-member', 'groupc', '--groups', 'groupb']) assert 'Group name: groupc' in cmd_output.stdout_text assert 'Member groups: groupb' in cmd_output.stdout_text assert 'Indirect Member groups: groupa' in cmd_output.stdout_text # add user to group 'groupa' cmd_output = master.run_command(['ipa', 'group-add-member', 'groupa', '--users', self.username]) assert 'Group name: groupa' in cmd_output.stdout_text assert_str = 'Member users: {}'.format(self.username) assert assert_str in cmd_output.stdout_text assert 'Member of groups: groupb' in cmd_output.stdout_text assert 'Indirect Member of group: groupc' in cmd_output.stdout_text # clear sssd_cache clear_sssd_cache(master) # user lookup # at this point, testuser001 has the following group memberships # Member of groups: groupa, ipausers # Indirect Member of group: groupb, groupc cmd_output = master.run_command(['ipa', 'user-show', self.username]) assert 'groupa' in cmd_output.stdout_text assert 'ipausers' in cmd_output.stdout_text assert 'groupb' in cmd_output.stdout_text assert 'groupc' in cmd_output.stdout_text clear_sssd_cache(client) # Workaround for https://pagure.io/freeipa/issue/9615 # Make sure that / on the client has expected permissions client.run_command(['chmod', '755', '/']) cmd = ['ssh', '-i', '/tmp/user_ssh_priv_key', '-q', '{}@{}'.format(self.username, client.hostname), 'groups'] cmd_output = master.run_command(cmd) assert self.username in cmd_output.stdout_text assert 'groupa' in cmd_output.stdout_text assert 'groupb' in cmd_output.stdout_text assert 'groupc' in cmd_output.stdout_text # add member cmd_output = master.run_command(['ipa', 'group-add-member', 'groupb', '--users', self.username]) assert 'Group name: groupb' in cmd_output.stdout_text assert_str = 'Member users: {}'.format(self.username) assert assert_str in cmd_output.stdout_text assert 'Member groups: groupa' in cmd_output.stdout_text assert 'Member of groups: groupc' in cmd_output.stdout_text assert 'Number of members added 1' in cmd_output.stdout_text # now check ssh on the client clear_sssd_cache(client) # after adding testuser001 to b group # testuser001 will have the following memberships # Member of groups: groupa, ipausers, groupb # Indirect Member of group: groupc cmd = ['ssh', '-i', '/tmp/user_ssh_priv_key', '-q', '{}@{}'.format(self.username, client.hostname), 'groups'] cmd_output = client.run_command(cmd) assert self.username in cmd_output.stdout_text assert 'groupa' in cmd_output.stdout_text assert 'groupb' in cmd_output.stdout_text assert 'groupc' in cmd_output.stdout_text # now back to server to remove member cmd_output = master.run_command(['ipa', 'group-remove-member', 'groupb', '--users', self.username]) assert_str = 'Indirect Member users: {}'.format(self.username) assert 'Group name: groupb' in cmd_output.stdout_text assert 'Member groups: groupa' in cmd_output.stdout_text assert 'Member of groups: groupc' in cmd_output.stdout_text assert assert_str in cmd_output.stdout_text assert 'Number of members removed 1' in cmd_output.stdout_text clear_sssd_cache(master) # now check ssh on the client again # after removing testuser001 from b group # testuser001 will have the following memberships # Member of groups: groupa, ipausers # Indirect Member of group: groupb, groupc clear_sssd_cache(client) cmd = ['ssh', '-i', '/tmp/user_ssh_priv_key', '-q', '{}@{}'.format(self.username, client.hostname), 'groups'] cmd_output = client.run_command(cmd) assert self.username in cmd_output.stdout_text assert 'groupa' in cmd_output.stdout_text assert 'groupb' in cmd_output.stdout_text assert 'groupc' in cmd_output.stdout_text
31,751
Python
.py
650
37.552308
80
0.596705
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,545
test_adtrust_install.py
freeipa_freeipa/ipatests/test_integration/test_adtrust_install.py
# # Copyright (C) 2020 FreeIPA Contributors see COPYING for license # """This module provides tests for ipa-adtrust-install utility""" import re import os import textwrap import subprocess from ipaplatform.paths import paths from ipapython.dn import DN from ipatests.pytest_ipa.integration import tasks from ipatests.test_integration.base import IntegrationTest from pkg_resources import parse_version import pytest class TestIpaAdTrustInstall(IntegrationTest): topology = 'line' num_replicas = 1 def unconfigure_replica_as_agent(self, host): """ Remove a replica from the list of agents. cn=adtrust agents,cn=sysaccounts,cn=etc,$BASEDN contains a list of members representing the agents. Remove the replica principal from this list. This is a hack allowing to run multiple times ipa-adtrust-install --add-agents (otherwise if the replica is in the list of agents, it won't be seen as a possible agent to be added). """ remove_agent_ldif = textwrap.dedent(""" dn: cn=adtrust agents,cn=sysaccounts,cn=etc,{base_dn} changetype: modify delete: member member: fqdn={hostname},cn=computers,cn=accounts,{base_dn} """.format(base_dn=host.domain.basedn, hostname=host.hostname)) # ok_returncode =16 if the attribute is not present tasks.ldapmodify_dm(self.master, remove_agent_ldif, ok_returncode=[0, 16]) def test_samba_config_file(self): """Check that ipa-adtrust-install generates sane smb.conf This is regression test for issue https://pagure.io/freeipa/issue/6951 """ self.master.run_command( ['ipa-adtrust-install', '-a', self.master.config.admin_password, '--add-sids', '-U']) res = self.master.run_command(['testparm', '-s']) assert 'ERROR' not in (res.stdout_text + res.stderr_text) def test_add_agent_not_allowed(self): """Check that add-agents can be run only by Admins.""" user = "nonadmin" passwd = "Secret123" host = self.replicas[0].hostname data_fmt = '{{"method":"trust_enable_agent","params":[["{}"],{{}}]}}' try: # Create a nonadmin user that will be used by curl. # First, display SSSD kdcinfo: # https://bugzilla.redhat.com/show_bug.cgi?id=1850445#c1 self.master.run_command([ "cat", "/var/lib/sss/pubconf/kdcinfo.%s" % self.master.domain.realm ], raiseonerr=False) # Set krb5_trace to True: https://pagure.io/freeipa/issue/8353 tasks.create_active_user( self.master, user, passwd, first=user, last=user, krb5_trace=True ) tasks.kinit_as_user(self.master, user, passwd, krb5_trace=True) # curl --negotiate -u : is using GSS-API i.e. nonadmin user cmd_args = [ paths.BIN_CURL, '-H', 'referer:https://{}/ipa'.format(host), '-H', 'Content-Type:application/json', '-H', 'Accept:applicaton/json', '--negotiate', '-u', ':', '--cacert', paths.IPA_CA_CRT, '-d', data_fmt.format(host), '-X', 'POST', 'https://{}/ipa/json'.format(host)] res = self.master.run_command(cmd_args) expected = 'Insufficient access: not allowed to remotely add agent' assert expected in res.stdout_text finally: tasks.kinit_admin(self.master) self.master.run_command(['ipa', 'user-del', user]) def test_add_agent_on_stopped_replica(self): """ Check ipa-adtrust-install --add-agents when the replica is stopped. Scenario: stop a replica Call ipa-adtrust-install --add-agents and configure the stopped replica as a new agent. The tool must detect that the replica is stopped and warn that a part of the configuration failed. Test for https://pagure.io/freeipa/issue/8148 """ self.unconfigure_replica_as_agent(self.replicas[0]) self.replicas[0].run_command(['ipactl', 'stop']) try: cmd = ['ipa-adtrust-install', '--add-agents'] with self.master.spawn_expect(cmd) as e: e.expect('admin password:') e.sendline(self.master.config.admin_password) # WARNING: The smb.conf already exists. # Running ipa-adtrust-install # will break your existing samba configuration. # Do you wish to continue? [no]: e.expect([ 'smb\\.conf detected.+Overwrite smb\\.conf\\?', 'smb\\.conf already exists.+Do you wish to continue\\?']) e.sendline('yes') e.expect_exact('Enable trusted domains support in slapi-nis?') e.sendline('no') # WARNING: 1 IPA masters are not yet able to serve information # about users from trusted forests. # Installer can add them to the list of IPA masters allowed to # access information about trusts. # If you choose to do so, you also need to restart LDAP # service on # those masters. # Refer to ipa-adtrust-install(1) man page for details. # IPA master[replica1.testrelm.test]?[no]: e.expect('Installer can add them to the list of IPA masters ' 'allowed to access information about trusts.+' 'IPA master \\[{}\\]' .format(re.escape(self.replicas[0].hostname)), timeout=120) e.sendline('yes') e.expect('"ipactl restart".+"systemctl restart sssd".+' + re.escape(self.replicas[0].hostname), timeout=60) e.expect_exit(ignore_remaining_output=True) finally: self.replicas[0].run_command(['ipactl', 'start']) def test_add_agent_on_running_replica_without_compat(self): """ Check ipa-adtrust-install --add-agents when the replica is running Scenario: replica up and running Call ipa-adtrust-install --add-agents and configure the replica as a new agent. The Schema Compat plugin must be automatically configured on the replica. """ self.unconfigure_replica_as_agent(self.replicas[0]) cmd = ['ipa-adtrust-install', '--add-agents'] with self.master.spawn_expect(cmd) as e: e.expect_exact('admin password:') e.sendline(self.master.config.admin_password) # WARNING: The smb.conf already exists. # Running ipa-adtrust-install # will break your existing samba configuration. # Do you wish to continue? [no]: e.expect([ 'smb\\.conf detected.+Overwrite smb\\.conf\\?', 'smb\\.conf already exists.+Do you wish to continue\\?']) e.sendline('yes') e.expect_exact('Enable trusted domains support in slapi-nis?') e.sendline('no') # WARNING: 1 IPA masters are not yet able to serve information # about users from trusted forests. # Installer can add them to the list of IPA masters allowed to # access information about trusts. # If you choose to do so, you also need to restart LDAP service on # those masters. # Refer to ipa-adtrust-install(1) man page for details. # IPA master[replica1.testrelm.test]?[no]: e.expect('Installer can add them to the list of IPA masters ' 'allowed to access information about trusts.+' 'IPA master \\[{}\\]' .format(re.escape(self.replicas[0].hostname)), timeout=120) e.sendline('yes') e.expect_exit(ignore_remaining_output=True, timeout=60) output = e.get_last_output() assert 'Setup complete' in output # The replica must have been restarted automatically, no msg required assert 'ipactl restart' not in output def test_add_agent_on_running_replica_with_compat(self): """ Check ipa-addtrust-install --add-agents when the replica is running Scenario: replica up and running Call ipa-adtrust-install --add-agents --enable-compat and configure the replica as a new agent. The Schema Compat plugin must be automatically configured on the replica. """ self.unconfigure_replica_as_agent(self.replicas[0]) cmd = ['ipa-adtrust-install', '--add-agents', '--enable-compat'] with self.master.spawn_expect(cmd) as e: e.expect_exact('admin password:') e.sendline(self.master.config.admin_password) # WARNING: The smb.conf already exists. # Running ipa-adtrust-install # will break your existing samba configuration. # Do you wish to continue? [no]: e.expect([ 'smb\\.conf detected.+Overwrite smb\\.conf\\?', 'smb\\.conf already exists.+Do you wish to continue\\?']) e.sendline('yes') # WARNING: 1 IPA masters are not yet able to serve information # about users from trusted forests. # Installer can add them to the list of IPA masters allowed to # access information about trusts. # If you choose to do so, you also need to restart LDAP service on # those masters. # Refer to ipa-adtrust-install(1) man page for details. # IPA master[replica1.testrelm.test]?[no]: e.expect('Installer can add them to the list of IPA masters ' 'allowed to access information about trusts.+' 'IPA master \\[{}\\]' .format(re.escape(self.replicas[0].hostname)), timeout=120) e.sendline('yes') e.expect_exit(ignore_remaining_output=True, timeout=60) output = e.get_last_output() assert 'Setup complete' in output # The replica must have been restarted automatically, no msg required assert 'ipactl restart' not in output # Ensure that the schema compat plugin is configured: conn = self.replicas[0].ldap_connect() entry = conn.get_entry(DN( "cn=users,cn=Schema Compatibility,cn=plugins,cn=config")) assert entry.single_value['schema-compat-lookup-nsswitch'] == "user" entry = conn.get_entry(DN( "cn=groups,cn=Schema Compatibility,cn=plugins,cn=config")) assert entry.single_value['schema-compat-lookup-nsswitch'] == "group" def test_schema_compat_attribute(self): """Test if schema-compat-entry-attribute is set This is to ensure if said entry is set after installation with AD. related: https://pagure.io/freeipa/issue/8193 """ conn = self.replicas[0].ldap_connect() entry = conn.get_entry(DN( "cn=groups,cn=Schema Compatibility,cn=plugins,cn=config")) entry_list = list(entry['schema-compat-entry-attribute']) value = (r'ipaexternalmember=%deref_r(' '"member","ipaexternalmember")') assert value in entry_list def test_ipa_user_pac(self): """Test that a user can request a service ticket with PAC""" user = 'testpacuser' user_princ = '@'.join([user, self.master.domain.realm]) passwd = 'Secret123' # Create a user with a password tasks.create_active_user( self.master, user, passwd, extra_args=["--homedir", "/home/{}".format(user)], krb5_trace=True ) try: # Defaults: host/... principal for service # keytab in /etc/krb5.keytab self.master.run_command(["kinit", '-k']) # Don't use enterprise principal here because it doesn't work # bug in krb5: src/lib/gssapi/krb5/acquire_cred.c:scan_cache() # where enterprise principals aren't taken into account result = self.master.run_command( [os.path.join(paths.LIBEXEC_IPA_DIR, "ipa-print-pac"), "ticket", user_princ], stdin_text=(passwd + '\n'), raiseonerr=False ) assert "PAC_DATA" in result.stdout_text finally: tasks.kinit_admin(self.master) self.master.run_command(['ipa', 'user-del', user]) def test_ipa_user_s4u2self_pac(self): """Test that a service can request S4U2Self ticket with PAC""" user = 'tests4u2selfuser' user_princ = '@'.join([user, self.master.domain.realm]) passwd = 'Secret123' # Create a user with a password tasks.create_active_user( self.master, user, passwd, extra_args=["--homedir", "/home/{}".format(user)], krb5_trace=True ) try: # Defaults: host/... principal for service # keytab in /etc/krb5.keytab self.master.run_command(["kinit", '-k']) result = self.master.run_command( [os.path.join(paths.LIBEXEC_IPA_DIR, "ipa-print-pac"), "-E", "impersonate", user_princ], raiseonerr=False ) assert "PAC_DATA" in result.stdout_text finally: tasks.kinit_admin(self.master) self.master.run_command(['ipa', 'user-del', user]) @pytest.mark.parametrize('netbios_name', ['testrelm', '.TESTRELM', 'Te!5@relm', 'TEST.REALM']) def test_adtrust_install_with_incorrect_netbios_name(self, netbios_name): """ Test that ipa-adtrust-install returns an error when an incorrect netbios name is provided """ msg = ( "ipaserver.install.adtrust: ERROR \n" "Illegal NetBIOS name [{}].\n\n" "ipaserver.install.adtrust: ERROR " "Up to 15 characters and only uppercase " "ASCII letters, digits and dashes are allowed." " Empty string is not allowed.\n" "Aborting installation.\n" ).format(netbios_name) result = self.master.run_command( [ "ipa-adtrust-install", "-a", self.master.config.admin_password, "--netbios-name", netbios_name, "-U", ], raiseonerr=False, ) assert result.returncode != 0 assert msg in result.stderr_text def test_adtrust_install_with_numerical_netbios_name(self): """ Test that ipa-adtrust-install works with numerical netbios name """ netbios_name = '1234567' msg = ( 'NetBIOS domain name will be changed to 1234567' ) result = self.master.run_command( [ "ipa-adtrust-install", "-a", self.master.config.admin_password, "--netbios-name", netbios_name, "-U", ], raiseonerr=False, ) assert msg in result.stdout_text assert result.returncode == 0 def test_adtrust_install_with_non_ipa_user(self): """ Test that ipa-adtrust-install command returns an error when kinit is done as alias i.e root which is not an ipa user. """ msg = ( 'Unrecognized error during check of admin rights: ' 'root: user not found' ) user = 'root' self.master.run_command( ["kinit", "-E", user], stdin_text=self.master.config.admin_password ) result = self.master.run_command( ["ipa-adtrust-install", "-A", user, "-a", self.master.config.admin_password, "-U"], raiseonerr=False ) assert result.returncode != 0 assert msg in result.stderr_text def test_adtrust_install_as_regular_ipa_user(self): """ This testcase checks that when regular ipa user does kinit and runs the ipa-adtrust-install command, the command is not run and message is displayed on the console. """ user = "ipauser1" passwd = "Secret123" try: tasks.create_active_user( self.master, user, password=passwd, first=user, last=user, ) tasks.kinit_as_user(self.master, user, passwd) self.master.run_command(["klist", "-l"]) result = self.master.run_command( ["ipa-adtrust-install", "-A", user, "-a", passwd, "-U"], raiseonerr=False ) msg = "Must have administrative privileges to " \ "setup AD trusts on server\n" assert msg in result.stderr_text assert result.returncode != 0 finally: self.master.run_command(["kdestroy", "-A"]) tasks.kinit_admin(self.master) def test_adtrust_install_as_non_root_user(self): """ This testcase checks that when regular ipa user logins and then runs ipa-adtrust-install command, the command fails to run """ user = "ipauser2" pwd = "Secret123" cmd = ["ipa-adtrust-install"] msg = ( "Must be root to setup AD trusts on server" ) try: tasks.create_active_user(self.master, user, pwd) tasks.run_command_as_user( self.master, user, cmd ) except subprocess.CalledProcessError as e: assert msg in e.stderr assert e.returncode != 0 else: pytest.fail( "Run ipa-adtrust-install as non " "root user did not return error" ) def test_adtrust_install_as_admins_group_user(self): """ Test to check that ipa-adtrust-install is successfull when a regular ipa user is part of the admins group """ user = "testuser1" pwd = "Secret123" tasks.create_active_user(self.master, user, pwd) tasks.kinit_admin(self.master) self.master.run_command( ["ipa", "group-add-member", "admins", "--users={}".format(user)] ) self.master.run_command(["kdestroy", "-A"]) self.master.run_command( ["ipa-adtrust-install", "-A", user, "-a", pwd, "-U"] ) def test_adtrust_install_with_incorrect_admin_password(self): """ Test to check ipa-adtrust-install with incorrect admin password """ password = "wrong_pwd" expected_substring = ( "Must have Kerberos credentials to setup AD trusts on server:" ) self.master.run_command(["kdestroy", "-A"]) result = self.master.run_command( ["ipa-adtrust-install", "-A", "admin", "-a", password, "-U"], raiseonerr=False ) assert expected_substring in result.stderr_text assert result.returncode != 0 def test_adtrust_install_with_invalid_rid_base_value(self): """ Test to check adtrust install with invalid rid-base value """ rid_base_value = "103.2" msg = ( "ipa-adtrust-install: error: option " "--rid-base: " "invalid integer value: '{}'" ).format(rid_base_value) result = self.master.run_command( [ "ipa-adtrust-install", "-A", "admin", "-a", self.master.config.admin_password, "--rid-base", rid_base_value, "-U", ], raiseonerr=False, ) assert msg in result.stderr_text assert result.returncode != 0 def test_adtrust_install_with_invalid_secondary_rid_base(self): """ Test to check adtrust install with invalid secondary rid-base value """ sec_rid_base_value = "103.2" msg = ( "ipa-adtrust-install: error: option " "--secondary-rid-base: invalid integer value: '{}'" ).format(sec_rid_base_value) result = self.master.run_command( [ "ipa-adtrust-install", "-A", "admin", "-a", self.master.config.admin_password, "--secondary-rid-base", sec_rid_base_value, "-U", ], raiseonerr=False, ) assert msg in result.stderr_text assert result.returncode != 0 def test_adtrust_reinstall_updates_ipaNTFlatName_attribute(self): """ Test checks that reinstalling ipa-adtrust-install with new netbios name reflects changes in ipaNTFlatName attribute and ipa trustconfig-show also reflects the same. """ netbios_name = "TEST8REALM" cmd = self.master.run_command( [ "ipa-adtrust-install", "-a", self.master.config.admin_password, "--netbios-name", netbios_name, "-U", ] ) trust_dn = "cn={},cn=ad,cn=etc,{}".format( self.master.domain.name, self.master.domain.basedn ) cmd_args = ["ldapsearch", "-Y", "GSSAPI", "(ipaNTFlatName=*)", "-s", "base", "-b", trust_dn] cmd = self.master.run_command(cmd_args) cmd1 = self.master.run_command(["ipa", "trustconfig-show"]) assert "ipaNTFlatName: {}".format(netbios_name) in cmd.stdout_text assert "NetBIOS name: {}".format(netbios_name) in cmd1.stdout_text def test_smb_not_starting_post_adtrust_install(self): """ Test checks that winbindd crash doesn't occur and smb service is running post ipa-adtrust-install. https://bugzilla.redhat.com/show_bug.cgi?id=991251 """ samba_msg = ( 'Unit smb.service entered failed state' ) core_dump_msg = ( 'dumping core in /var/log/samba/cores/winbindd' ) smb_cmd = self.master.run_command( ['systemctl', 'status', 'smb'] ) assert smb_cmd.returncode == 0 assert samba_msg not in smb_cmd.stdout_text winbind_cmd = self.master.run_command( ['systemctl', 'status', 'winbind'] ) assert winbind_cmd.returncode == 0 assert core_dump_msg not in winbind_cmd.stdout_text def test_samba_credential_cache_is_removed_post_uninstall(self): """ Test checks that samba credential cache is removed after ipa-server is uninstalled. https://pagure.io/freeipa/issue/3479 """ self.master.run_command( ["ipa-adtrust-install", "-a", self.master.config.admin_password, "-U"] ) assert self.master.transport.file_exists(paths.KRB5CC_SAMBA) tasks.uninstall_replica(self.master, self.replicas[0]) tasks.uninstall_master(self.master) assert not self.master.transport.file_exists(paths.KRB5CC_SAMBA) def test_adtrust_install_without_ipa_installed(self): """ Tests checks that ipa-adrust-install warns when ipa is not installed on the system """ msg = ( "IPA is not configured on this system." ) result = self.master.run_command( ["ipa-adtrust-install", "-a", self.master.config.admin_password, "-U"], raiseonerr=False) assert msg in result.stderr_text assert result.returncode != 0 def test_adtrust_install_without_integrated_dns(self): """ Test checks ipa-adtrust-install displays the necessary service records to be added on a IPA server without integrated dns setup. """ realm = self.master.domain.realm.lower() hostname = self.master.hostname msg = ( "Done configuring CIFS.\n" "DNS management was not enabled at install time.\n" "Add the following service records to your DNS server " "for DNS zone {0}: \n" "_ldap._tcp.Default-First-Site-Name._sites.dc._msdcs.{0}. " "3600 IN SRV 0 100 389 {1}.\n" "_ldap._tcp.dc._msdcs.{0}. 3600 IN SRV 0 100 389 {1}.\n" "_kerberos._tcp.Default-First-Site-Name._sites.dc._msdcs.{0}. " "3600 IN SRV 0 100 88 {1}.\n" "_kerberos._udp.Default-First-Site-Name._sites.dc._msdcs.{0}. " "3600 IN SRV 0 100 88 {1}.\n" "_kerberos._tcp.dc._msdcs.{0}. 3600 IN SRV 0 100 88 {1}.\n" "_kerberos._udp.dc._msdcs.{0}. 3600 IN SRV 0 100 88 {1}.\n\n" "================================================================" "=============\n" "Setup complete\n\n" ).format(realm, hostname) result = tasks.install_master(self.master, setup_dns=False) assert result.returncode == 0 cmd = self.master.run_command( ["ipa-adtrust-install", "-a", self.master.config.admin_password, "-U"] ) assert msg in cmd.stdout_text def test_adtrust_install_with_debug_option(self): """ Test checks that ipa-adtrust-install runs with debug option without any error. """ self.master.run_command( ["ipa-adtrust-install", "-a", self.master.config.admin_password, "-U", "-d"] ) def test_adtrust_install_cli_without_smbpasswd_file(self): """ Test checks that ipa-adtrust-install works fine even without smbpasswd file https://pagure.io/freeipa/issue/3181 """ error_msg = ( "< type 'file' > was not found on this system " "Please install the 'samba' packages and start " "the installation again Aborting installation" ) self.master.run_command( ["mv", "/usr/bin/smbpasswd", "/usr/bin/smbpasswd.old"] ) cmd = ["ipa-adtrust-install"] with self.master.spawn_expect(cmd) as e: e.expect_exact("admin password:") e.sendline(self.master.config.admin_password) # WARNING: The smb.conf already exists. # Running ipa-adtrust-install # will break your existing samba configuration. # Do you wish to continue? [no]: e.expect( [ "smb\\.conf detected.+Overwrite smb\\.conf\\?", "smb\\.conf already exists.+Do you wish to continue\\?", ] ) e.sendline("yes") e.expect(["Enable trusted domains support in slapi-nis\\?"]) e.sendline("no") e.expect_exit(ignore_remaining_output=True, timeout=60) output = e.get_last_output() assert "Setup complete" in output assert error_msg not in output # Rename the smbpasswd file to original self.master.run_command( ["mv", "/usr/bin/smbpasswd.old", "/usr/bin/smbpasswd"] ) def test_adtrust_install_enable_compat(self): """ Test adtrust_install with enable compat option """ self.master.run_command( ["ipa-adtrust-install", "-a", self.master.config.admin_password, "--enable-compat", "-U"] ) conn = self.master.ldap_connect() entry = conn.get_entry( DN("cn=users,cn=Schema Compatibility,cn=plugins,cn=config") ) assert entry.single_value["schema-compat-lookup-nsswitch"] == "user" def test_adtrust_install_invalid_ipaddress_option(self): """ Test ipa-adtrust-install with invalid --ip-address option """ msg = ( 'ipa-adtrust-install: error: no such option: --ip-address' ) result = self.master.run_command( ["ipa-adtrust-install", "-a", self.master.config.admin_password, "--ip-address", "-U"], raiseonerr=False ) assert msg in result.stderr_text assert result.returncode != 0 def test_syntax_error_in_ipachangeconf(self): """ Test checks that ipa-adtrust-install doesn't fail with 'Syntax Error' when dns_lookup_kdc is set to False in /etc/krb5.conf https://pagure.io/freeipa/issue/3132 """ error_msg = ( 'The ipa-adtrust-install command failed, exception: ' 'SyntaxError: Syntax Error: Unknown line format' ) tasks.FileBackup(self.master, paths.KRB5_CONF) krb5_cfg = self.master.get_file_contents(paths.KRB5_CONF, encoding='utf-8') new_krb5_cfg = krb5_cfg.replace( 'dns_lookup_kdc = true', 'dns_lookup_kdc = false' ) self.master.put_file_contents(paths.KRB5_CONF, new_krb5_cfg) result = self.master.run_command( ["ipa-adtrust-install", "-a", self.master.config.admin_password, "-U"], raiseonerr=False ) assert error_msg not in result.stderr_text def test_unattended_adtrust_install_uses_default_netbios_name(self): """ ipa-adtrust-install unattended install should use default netbios name rather than prompting for it. https://fedorahosted.org/freeipa/ticket/3497 """ msg = ( 'Enter the NetBIOS name for the IPA domain' 'Only up to 15 uppercase ASCII letters and ' 'digits are allowed.' ) result = self.master.run_command( ["ipa-adtrust-install", "-a", self.master.config.admin_password, "-U"] ) assert result.returncode == 0 assert msg not in result.stdout_text def test_adtrust_install_with_def_rid_base_values(self): """ Test that ipa-adtrust-install install is successful with default rid and secondary values """ rid_base = '1000' sec_rid_base = '100000000' self.master.run_command( ["ipa-adtrust-install", "-a", self.master.config.admin_password, "--rid-base", rid_base, "--secondary-rid-base", sec_rid_base, "-U"] ) def test_ipa_adtrust_install_with_add_agents_option(self): """ This testcase checks that ipa-adtrust-install with --add-agents works without any error on IPA server """ result = self.master.run_command( ["ipa-adtrust-install", "-a", self.master.config.admin_password, "--add-agents", "-U"] ) assert result.returncode == 0 def test_ipa_adtrust_install_with_add_sids_option(self): """ This testcase checks that ipa-adtrust-install with --add-sids option works without any error """ msg = ( 'adding SIDs to existing users and groups\n' 'This step may take considerable amount of time, please wait..' ) result = self.master.run_command( ["ipa-adtrust-install", "-a", self.master.config.admin_password, "--add-sids", "-U"] ) assert msg in result.stdout_text def test_cldap_responder_doesnot_hang_for_domain_discovery(self): """ This testcase checks that cldap responder doesnot hang for domain discovery. https://pagure.io/freeipa/issue/3639 """ version = tasks.get_openldap_client_version(self.master) if parse_version(version) >= parse_version('2.6'): pytest.skip('bz2167328') base_dn = "" srch_filter = "(&(DnsDomain={})(NtVer=\\06\\00\\00\\00)" \ "(AAC=\\00\\00\\00\\00))".format(self.master.domain.name) self.master.run_command( ["ipa-adtrust-install", "-a", self.master.config.admin_password, "-U"] ) result = self.master.run_command( ["ldapsearch", "-LL", "-H", "cldap://{}".format(self.master.hostname), "-b", base_dn, "-s", "base", srch_filter] ) assert result.returncode == 0 assert 'dn:\nnetlogon::' in result.stdout_text def test_user_connects_smb_share_if_locked_specific_group(self): """ Test scenario: Create a share in the samba server Access the share as admin, should work set valid users = admins to limit the share access to members of the "admins" group Access the share as admin, should work https://pagure.io/freeipa/issue/4234 """ msg = "tree connect failed: NT_STATUS_ACCESS_DENIED" self.master.run_command( ["ipa-adtrust-install", "-a", self.master.config.admin_password, "-U"] ) # Wait for SSSD to become online before doing any other check tasks.wait_for_sssd_domain_status_online(self.master) self.master.run_command(["mkdir", "/freeipa4234"]) self.master.run_command( ["chcon", "-t", "samba_share_t", "/freeipa4234"]) self.master.run_command( ["setfacl", "-m", "g:admins:rwx", "/freeipa4234"]) self.master.run_command( ["net", "conf", "setparm", "share", "comment", "Test Share"]) self.master.run_command( ["net", "conf", "setparm", "share", "read only", "no"]) self.master.run_command( ["net", "conf", "setparm", "share", "path", "/freeipa4234"]) self.master.run_command(["touch", "before"]) self.master.run_command(["touch", "after"]) # Find cache for the admin user cache_args = [] cache = tasks.get_credential_cache(self.master) if cache: cache_args = ["--use-krb5-ccache", cache] cmd_args = ["smbclient", "--use-kerberos=desired"] cmd_args.extend(cache_args) cmd_args.extend([ "-c=put before", "//{}/share".format(self.master.hostname) ]) self.master.run_command(cmd_args) self.master.run_command( ["net", "conf", "setparm", "share", "valid users", "@admins"]) cmd_args = ["smbclient", "--use-kerberos=desired"] cmd_args.extend(cache_args) cmd_args.extend([ "-c=put after", "//{}/share".format(self.master.hostname) ]) result = self.master.run_command(cmd_args) assert msg not in result.stdout_text
35,554
Python
.py
844
30.748815
79
0.564388
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,546
test_cli_ipa_not_configured.py
freeipa_freeipa/ipatests/test_integration/test_cli_ipa_not_configured.py
from ipapython.admintool import SERVER_NOT_CONFIGURED from ipatests.test_integration.base import IntegrationTest class TestIPANotConfigured(IntegrationTest): """ Test class for CLI commands with ipa server not configured. Topology parameter is omitted in order to prevent IPA from configuring. """ def test_var_log_message_with_ipa_backup(self): """ Test for PG6843: ipa-backup does not create log file at /var/log Launches ipa backup command on system with ipa server not configured. As the server is not configured yet, command should fail and stderr should not contain link to /var/log, as no such log is created. Issue URl: https://pagure.io/freeipa/issue/6843 """ exp_str = "not configured on this system" unexp_str = "/var/log" cmd = self.master.run_command(["ipa-backup"], raiseonerr=False) assert (exp_str in cmd.stderr_text and cmd.returncode == SERVER_NOT_CONFIGURED and unexp_str not in cmd.stderr_text)
1,058
Python
.py
21
42.571429
77
0.692456
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,547
test_pkinit_install.py
freeipa_freeipa/ipatests/test_integration/test_pkinit_install.py
# # Copyright (C) 2022 FreeIPA Contributors see COPYING for license # """ Module provides tests for ipa-client-install with PKINIT """ import os from ipaplatform.paths import paths from ipatests.test_integration.base import IntegrationTest from ipatests.pytest_ipa.integration import tasks class TestPkinitClientInstall(IntegrationTest): num_clients = 1 certfile = "/etc/pki/tls/certs/client.pem" keyfile = "/etc/pki/tls/private/client.key" tmpbundle = "/tmp/kdc-ca-bundle.pme" @classmethod def install(cls, mh): tasks.install_master(cls.master) def enforce_password_and_otp(self): """enforce otp by default and password for admin """ self.master.run_command( [ "ipa", "config-mod", "--user-auth-type=otp", ] ) self.master.run_command( [ "ipa", "user-mod", "admin", "--user-auth-type=password", ] ) def add_certmaperule(self): """add certmap rule to map SAN dNSName to host entry""" self.master.run_command( [ "ipa", "certmaprule-add", "pkinit-host", "--matchrule=<ISSUER>CN=Certificate Authority,.*", "--maprule=(fqdn={subject_dns_name})", ] ) def add_host(self): """Add host entry for client Allow master to manage client so it can create a certificate. """ client = self.clients[0] self.master.run_command( ["ipa", "host-add", "--force", client.hostname] ) self.master.run_command( [ "ipa", "host-add-managedby", f"--hosts={self.master.hostname}", client.hostname, ] ) def create_cert(self): """Create and copy certificate for client""" client = self.clients[0] self.master.run_command( [ "mkdir", "-p", os.path.dirname(self.certfile), os.path.dirname(self.keyfile), ] ) self.master.run_command( [ "ipa-getcert", "request", "-w", # fmt: off "-f", self.certfile, "-k", self.keyfile, "-N", client.hostname, "-D", client.hostname, "-K", f"host/{client.hostname}", # fmt: on ] ) # copy cert, key, and bundle to client for filename in (self.certfile, self.keyfile): data = self.master.get_file_contents(filename) client.put_file_contents(filename, data) cabundle = self.master.get_file_contents(paths.KDC_CA_BUNDLE_PEM) client.put_file_contents(self.tmpbundle, cabundle) def test_restart_krb5kdc(self): tasks.kinit_admin(self.master) self.enforce_password_and_otp() self.master.run_command(['systemctl', 'stop', 'krb5kdc.service']) self.master.run_command(['systemctl', 'start', 'krb5kdc.service']) self.master.run_command(['systemctl', 'stop', 'kadmin.service']) self.master.run_command(['systemctl', 'start', 'kadmin.service']) def test_client_install_pkinit(self): tasks.kinit_admin(self.master) self.add_certmaperule() self.add_host() self.create_cert() tasks.install_client( self.master, self.clients[0], pkinit_identity=f"FILE:{self.certfile},{self.keyfile}", extra_args=[f"--pkinit-anchor=FILE:{self.tmpbundle}"], )
3,805
Python
.py
111
23.522523
74
0.537374
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,548
test_server_del.py
freeipa_freeipa/ipatests/test_integration/test_server_del.py
# # Copyright (C) 2016 FreeIPA Contributors see COPYING for license # from itertools import permutations import pytest from ipatests.test_integration.base import IntegrationTest from ipatests.pytest_ipa.integration import tasks from ipatests.pytest_ipa.integration.firewall import Firewall from ipalib.constants import DOMAIN_LEVEL_1, DOMAIN_SUFFIX_NAME, CA_SUFFIX_NAME REMOVAL_ERR_TEMPLATE = ("Removal of '{hostname}' leads to disconnected " "topology in suffix '{suffix}'") def check_master_removal(host, hostname_to_remove, force=False, ignore_topology_disconnect=False, ignore_last_of_role=False): result = tasks.run_server_del( host, hostname_to_remove, force=force, ignore_topology_disconnect=ignore_topology_disconnect, ignore_last_of_role=ignore_last_of_role) assert result.returncode == 0 if force: assert ("Forcing removal of {hostname}".format( hostname=hostname_to_remove) in result.stderr_text) if ignore_topology_disconnect: assert "Ignoring topology connectivity errors." in result.stderr_text if ignore_last_of_role: assert ("Ignoring these warnings and proceeding with removal" in result.stderr_text) tasks.assert_error( host.run_command( ['ipa', 'server-show', hostname_to_remove], raiseonerr=False ), "{}: server not found".format(hostname_to_remove), returncode=2 ) # Only run the pki command if there is a CA installed on the machine result = host.run_command( [ 'ipa', 'server-role-find', '--server', host.hostname, '--status', 'enabled', '--role', 'CA server', ], raiseonerr=False, ) if result.returncode == 0: host.run_command(['pki', 'client', 'init', '--force']) result = host.run_command( ['pki', 'securitydomain-host-find'], stdin_text='y\n', ).stdout_text assert hostname_to_remove not in result def check_removal_disconnects_topology( host, hostname_to_remove, affected_suffixes=(DOMAIN_SUFFIX_NAME,)): result = tasks.run_server_del(host, hostname_to_remove) assert len(affected_suffixes) <= 2 err_messages_by_suffix = { CA_SUFFIX_NAME: REMOVAL_ERR_TEMPLATE.format( hostname=hostname_to_remove, suffix=CA_SUFFIX_NAME ), DOMAIN_SUFFIX_NAME: REMOVAL_ERR_TEMPLATE.format( hostname=hostname_to_remove, suffix=DOMAIN_SUFFIX_NAME ) } for suffix, err_str in err_messages_by_suffix.items(): if suffix in affected_suffixes: tasks.assert_error(result, err_str, returncode=1) else: assert err_str not in result.stderr_text class ServerDelBase(IntegrationTest): num_replicas = 2 num_clients = 1 domain_level = DOMAIN_LEVEL_1 topology = 'star' @classmethod def install(cls, mh): super(ServerDelBase, cls).install(mh) cls.client = cls.clients[0] cls.replica1 = cls.replicas[0] cls.replica2 = cls.replicas[1] class TestServerDel(ServerDelBase): @classmethod def install(cls, mh): super(TestServerDel, cls).install(mh) # prepare topologysegments for negative test cases # it should look like this for DOMAIN_SUFFIX_NAME: # master # / # / # / # replica1------- replica2 # and like this for CA_SUFFIX_NAME # master # \ # \ # \ # replica1------- replica2 tasks.create_segment(cls.client, cls.replica1, cls.replica2) tasks.create_segment(cls.client, cls.replica1, cls.replica2, suffix=CA_SUFFIX_NAME) # try to delete all relevant segment connecting master and replica1/2 segment_name_fmt = '{p[0].hostname}-to-{p[1].hostname}' for domain_pair in permutations((cls.master, cls.replica2)): tasks.destroy_segment( cls.client, segment_name_fmt.format(p=domain_pair)) for ca_pair in permutations((cls.master, cls.replica1)): tasks.destroy_segment( cls.client, segment_name_fmt.format(p=ca_pair), suffix=CA_SUFFIX_NAME) def test_removal_of_nonexistent_master_raises_error(self): """ tests that removal of non-existent master raises an error """ hostname = u'bogus-master.bogus.domain' err_message = "{}: server not found".format(hostname) tasks.assert_error( tasks.run_server_del(self.client, hostname), err_message, returncode=2 ) def test_forced_removal_of_nonexistent_master(self): """ tests that removal of non-existent master with '--force' does not raise an error """ hostname = u'bogus-master.bogus.domain' result = tasks.run_server_del(self.client, hostname, force=True) assert result.returncode == 0 assert ('Deleted IPA server "{}"'.format(hostname) in result.stdout_text) assert ("Server has already been deleted" in result.stderr_text) def test_removal_of_replica1_disconnects_domain_topology(self): """ tests that given the used topology, attempted removal of replica1 fails with disconnected DOMAIN topology but not CA """ check_removal_disconnects_topology( self.client, self.replica1.hostname, affected_suffixes=(DOMAIN_SUFFIX_NAME,) ) def test_removal_of_replica2_disconnects_ca_topology(self): """ tests that given the used topology, attempted removal of replica2 fails with disconnected CA topology but not DOMAIN """ check_removal_disconnects_topology( self.client, self.replica2.hostname, affected_suffixes=(CA_SUFFIX_NAME,) ) def test_ignore_topology_disconnect_replica1(self): """ tests that removal of replica1 with '--ignore-topology-disconnect' destroys master for good """ check_master_removal( self.client, self.replica1.hostname, ignore_topology_disconnect=True ) # reinstall the replica tasks.uninstall_master(self.replica1) tasks.install_replica(self.master, self.replica1, setup_ca=True) def test_ignore_topology_disconnect_replica2(self): """ tests that removal of replica2 with '--ignore-topology-disconnect' destroys master for good with verbose option for uninstallation """ check_master_removal( self.client, self.replica2.hostname, ignore_topology_disconnect=True ) # reinstall the replica tasks.uninstall_master(self.replica2, verbose=True) tasks.install_replica(self.master, self.replica2, setup_ca=True) def test_removal_of_master_disconnects_both_topologies(self): """ tests that master removal will now raise errors in both suffixes. """ check_removal_disconnects_topology( self.client, self.master.hostname, affected_suffixes=(CA_SUFFIX_NAME, DOMAIN_SUFFIX_NAME) ) def test_removal_of_replica1(self): """ tests the removal of replica1 which should now pass without errors """ check_master_removal( self.client, self.replica1.hostname ) def test_removal_of_replica2(self): """ tests the removal of replica2 which should now pass without errors """ check_master_removal( self.client, self.replica2.hostname ) class TestLastServices(ServerDelBase): """ Test the checks for last services during server-del and their bypassing using when forcing the removal """ num_replicas = 1 domain_level = DOMAIN_LEVEL_1 topology = 'line' @pytest.fixture def restart_ipa(self): yield self.master.run_command(['ipactl', 'start']) @classmethod def install(cls, mh): tasks.install_topo( cls.topology, cls.master, cls.replicas, [], domain_level=cls.domain_level, setup_replica_cas=False) def test_removal_of_master_raises_error_about_last_dns(self): """ Now server-del should complain about the removal of last DNS server """ tasks.assert_error( tasks.run_server_del(self.replicas[0], self.master.hostname), "Deleting this server will leave your installation " "without a DNS.", 1 ) def test_install_dns_on_replica1_and_dnssec_on_master(self): """ install DNS server on replica and DNSSec on master """ tasks.install_dns(self.replicas[0]) args = [ "ipa-dns-install", "--dnssec-master", "--forwarder", self.master.config.dns_forwarder, "-U", ] self.master.run_command(args) Firewall(self.master).enable_service("dns") def test_removal_of_master_raises_error_about_dnssec(self): tasks.assert_error( tasks.run_server_del(self.replicas[0], self.master.hostname), "Replica is active DNSSEC key master. Uninstall " "could break your DNS system. Please disable or replace " "DNSSEC key master first.", 1 ) def test_disable_dnssec_on_master(self): """ Disable DNSSec master so that it is not tested anymore. Normal way would be to move the DNSSec master to replica, but that is tested in DNSSec tests. """ args = [ "ipa-dns-install", "--disable-dnssec-master", "--forwarder", self.master.config.dns_forwarder, "--force", "-U", ] self.master.run_command(args) def test_removal_of_master_raises_error_about_last_ca(self): """ test that removal of master fails on the last """ tasks.assert_error( tasks.run_server_del(self.replicas[0], self.master.hostname), "Deleting this server is not allowed as it would leave your " "installation without a CA.", 1 ) def test_removal_of_server_raises_error_about_last_kra(self, restart_ipa): """ test that removal of server fails on the last KRA We shut it down to verify that it can be removed if it failed. """ tasks.install_kra(self.master) self.master.run_command(['ipactl', 'stop']) tasks.assert_error( tasks.run_server_del(self.replicas[0], self.master.hostname), "Deleting this server is not allowed as it would leave your " "installation without a KRA.", 1 ) def test_forced_removal_of_master(self): """ Tests that we can still force remove the master using '--ignore-last-of-role' """ check_master_removal( self.replicas[0], self.master.hostname, ignore_last_of_role=True )
11,597
Python
.py
302
28.966887
79
0.607702
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,549
test_custom_plugins.py
freeipa_freeipa/ipatests/test_integration/test_custom_plugins.py
# # Copyright (C) 2021 FreeIPA Contributors see COPYING for license # """Tests for custom plugins """ from __future__ import absolute_import import logging import os import site from ipatests.test_integration.base import IntegrationTest from ipatests.pytest_ipa.integration import tasks logger = logging.getLogger(__name__) class TestCustomPlugin(IntegrationTest): """ Tests for user-generated custom plugins """ @classmethod def install(cls, mh): tasks.install_master(cls.master, setup_dns=True) def test_add_user_objectclass_with_custom_schema(self): """Test adding a custom userclass to new users Attributes should not be case-sensitive. Based heavily on the custom plugin and schema at https://github.com/Brandeis-CS-Systems/idm-unet-id-plugin """ schema = ( "dn: cn=schema\n" "attributeTypes: ( 2.16.840.1.113730.3.8.24.1.1 NAME 'customID' " "EQUALITY caseIgnoreMatch SUBSTR caseIgnoreSubstringsMatch SYNTAX " "1.3.6.1.4.1.1466.115.121.1.15 X-ORIGIN 'Testing' )\n" "objectClasses: ( 2.16.840.1.113730.3.8.24.2.1 NAME 'customUser' " "DESC 'custom user ID objectClass' AUXILIARY MAY ( customID ) " "X-ORIGIN 'Testing' )\n" ) plugin = ( "from ipalib.parameters import Str\n\n" "from ipaserver.plugins.user import user\n\n" "if 'customUser' not in user.possible_objectclasses:\n" " user.possible_objectclasses.append('customUser')\n" "customuser_attributes = ['customID']\n" "user.default_attributes.extend(customuser_attributes)\n" "takes_params = (\n" " Str('customid?',\n" " cli_name='customid',\n" " maxlength=64,\n" " label='User custom uid'),\n" ")\n" "user.takes_params += takes_params\n" ) tasks.kinit_admin(self.master) self.master.put_file_contents('/tmp/schema.ldif', schema) self.master.run_command(['ipa-ldap-updater', '-S', '/tmp/schema.ldif']) self.master.put_file_contents('/tmp/schema.ldif', schema) site_packages = site.getsitepackages()[-1] site_file = os.path.join( site_packages, "ipaserver", "plugins", "test.py" ) self.master.put_file_contents(site_file, plugin) self.master.run_command(['ipactl', 'restart']) self.master.run_command([ 'ipa', 'config-mod', '--userobjectclasses', 'top', '--userobjectclasses', 'person', '--userobjectclasses', 'organizationalperson', '--userobjectclasses', 'inetorgperson', '--userobjectclasses', 'inetuser', '--userobjectclasses', 'posixaccount', '--userobjectclasses', 'krbprincipalaux', '--userobjectclasses', 'krbticketpolicyaux', '--userobjectclasses', 'ipaobject', '--userobjectclasses', 'ipasshuser', '--userobjectclasses', 'customuser', ]) self.master.run_command(['rm', '-f', site_file])
3,201
Python
.py
74
33.891892
79
0.60424
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,550
test_uninstallation.py
freeipa_freeipa/ipatests/test_integration/test_uninstallation.py
# # Copyright (C) 2018 FreeIPA Contributors see COPYING for license # """ Module provides tests that uninstallation is successful. It is important not to leave the remote system in an inconsistent state. Every failed uninstall should successfully remove remaining pieces if possible. """ from __future__ import absolute_import from difflib import unified_diff import os from ipatests.test_integration.base import IntegrationTest from ipatests.pytest_ipa.integration import tasks from ipaplatform.paths import paths from ipapython.ipaldap import realm_to_serverid # from ipaserver.install.dsinstance DS_INSTANCE_PREFIX = 'slapd-' class TestUninstallBase(IntegrationTest): num_replicas = 1 @classmethod def install(cls, mh): tasks.install_master(cls.master, setup_dns=False) def test_uninstall_client_invalid_hostname(self): # using replica as client just for convenience client = self.replicas[0] client_inv_hostname = '{}.nonexistent'.format(client.hostname) tasks.install_client(self.master, client, extra_args=['--hostname', client_inv_hostname], nameservers=None) client.run_command(['ipa-client-install', '--uninstall', '-U']) client_uninstall_log = client.get_file_contents( paths.IPACLIENT_UNINSTALL_LOG, encoding='utf-8' ) assert "exception: ScriptError:" not in client_uninstall_log restore_state_path = os.path.join(paths.IPA_CLIENT_SYSRESTORE, 'sysrestore.state') result = client.run_command( ['ls', restore_state_path], raiseonerr=False) assert 'No such file or directory' in result.stderr_text def test_install_uninstall_replica(self): # Test that the sequence install replica / uninstall replica # properly removes the line # Include /etc/httpd/conf.d/ipa-rewrite.conf # from ssl.conf on the replica tasks.install_replica(self.master, self.replicas[0], extra_args=['--force-join'], nameservers=None) tasks.uninstall_replica(self.master, self.replicas[0]) errline = b'Include /etc/httpd/conf.d/ipa-rewrite.conf' ssl_conf = self.replicas[0].get_file_contents(paths.HTTPD_SSL_CONF) assert errline not in ssl_conf def test_failed_uninstall(self): self.master.run_command(['ipactl', 'stop']) serverid = realm_to_serverid(self.master.domain.realm) instance_name = ''.join([DS_INSTANCE_PREFIX, serverid]) try: # Moving the DS instance out of the way will cause the # uninstaller to raise an exception and return with a # non-zero return code. self.master.run_command([ '/bin/mv', '%s/%s' % (paths.ETC_DIRSRV, instance_name), '%s/%s.test' % (paths.ETC_DIRSRV, instance_name) ]) cmd = self.master.run_command([ 'ipa-server-install', '--uninstall', '-U'], raiseonerr=False ) assert cmd.returncode == 1 finally: # Be paranoid. If something really went wrong then DS may # be marked as uninstalled so server cert will still be # tracked and the instances may remain. This can cause # subsequent installations to fail so be thorough. dashed_domain = self.master.domain.realm.replace(".", '-') dirsrv_service = "dirsrv@%s.service" % dashed_domain self.master.run_command(['systemctl', 'stop', dirsrv_service]) # Moving it back should allow the uninstall to finish # successfully. self.master.run_command([ '/bin/mv', '%s/%s.test' % (paths.ETC_DIRSRV, instance_name), '%s/%s' % (paths.ETC_DIRSRV, instance_name) ]) cmd = self.master.run_command([ 'ipa-server-install', '--uninstall', '-U'], raiseonerr=False ) assert cmd.returncode == 0 self.master.run_command([ paths.IPA_GETCERT, 'stop-tracking', '-d', '%s/%s' % (paths.ETC_DIRSRV, instance_name), '-n', 'Server-Cert', ]) self.master.run_command([ paths.DSCTL, serverid, 'remove', '--do-it' ]) class TestUninstallWithoutDNS(IntegrationTest): @classmethod def install(cls, mh): tasks.install_master(cls.master, setup_dns=False) def test_uninstall_server_without_dns(self): """Test if server setup without dns uninstall properly IPA server uninstall was failing if dns was not setup. This test check if it uninstalls properly. related: https://pagure.io/freeipa/issue/8630 """ tasks.uninstall_master(self.master) class TestUninstallCleanup(IntegrationTest): """Test installer hostname validator.""" num_replicas = 0 before = None after = None @classmethod def install(cls, mh): # These create files on first start for svc in ('certmonger', 'sssd',): cls.master.run_command(['systemctl', 'start', svc]) cls.before = cls.master.run_command( "find /etc/ /run/ /var/ /root/ -mount | sort" ).stdout_text.split('\n') tasks.install_master(cls.master, setup_dns=True, setup_kra=True) tasks.install_dns( cls.master, extra_args=['--dnssec-master', '--no-dnssec-validation'] ) @classmethod def uninstall(cls, mh): pass def test_clean_uninstall(self): tasks.uninstall_master(self.master) self.after = self.master.run_command( "find /etc/ /run/ /var/ /root/ -mount | sort" ).stdout_text.split('\n') diff = unified_diff(self.before, self.after, fromfile='before', tofile='after') ALLOW_LIST = [ '/var/log', '/var/tmp/systemd-private', '/run/systemd', '/var/lib/authselect/backups/pre_ipaclient', '/var/named/data/named.run', paths.DNSSEC_SOFTHSM_PIN_SO, # See commit eb54814741 '/etc/selinux/targeted/contexts/files/file_contexts.local.bin', paths.SSSD_CONF_DELETED, # See commit dd72ed6212 '/root/.cache', '/root/.dogtag', '/root/.local', '/run/dirsrv', '/run/lock/dirsrv', '/var/lib/authselect/backups', '/var/lib/gssproxy/rcache/krb5_0.rcache2', '/var/lib/ipa/ipa-kasp.db.backup', '/var/lib/selinux/targeted/active/booleans.local', '/var/lib/selinux/targeted/active/file_contexts.local', '/var/lib/sss/pubconf/krb5.include.d/krb5_libdefaults', '/var/lib/sss/pubconf/krb5.include.d/localauth_plugin', '/var/named/dynamic/managed-keys.bind', '/var/named/dynamic/managed-keys.bind.jnl', '/var/lib/systemd/coredump/', ] leftovers = [] for line in diff: line = line.strip() if line.startswith('+'): if line.endswith('log'): continue if line.startswith('+++ after'): continue found = False for s in ALLOW_LIST: if s in line: found = True break if found: continue leftovers.append(line) assert len(leftovers) == 0 class TestUninstallReinstall(IntegrationTest): """Test install, uninstall, re-install. Reinstall with PKI 11.6.0 was failing https://pagure.io/freeipa/issue/9673 """ num_replicas = 0 @classmethod def install(cls, mh): tasks.install_master(cls.master, setup_dns=False) def test_uninstall_server(self): tasks.uninstall_master(self.master) def test_reinstall_server(self): tasks.install_master(self.master, setup_dns=False)
8,330
Python
.py
195
31.65641
76
0.589493
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,551
test_nfs.py
freeipa_freeipa/ipatests/test_integration/test_nfs.py
# # Copyright (C) 2018 FreeIPA Contributors see COPYING for license # """This module provides tests for NFS-related features like krb5 NFS and automount locations. Wishlist * add automount direct and indirect maps * add automount /home for the "seattle" location only * validate it is not available in another location * krb5 /home for IdM users in test_automount * store nfs configuration in a single place """ from __future__ import absolute_import import os import re import time import pytest from ipatests.test_integration.base import IntegrationTest from ipatests.pytest_ipa.integration import tasks # give some time for units to stabilize # otherwise we get transient errors WAIT_AFTER_INSTALL = 5 WAIT_AFTER_UNINSTALL = WAIT_AFTER_INSTALL class TestNFS(IntegrationTest): num_clients = 3 topology = 'line' def cleanup(self): nfssrv = self.clients[0] nfsclt = self.clients[1] automntclt = self.clients[2] time.sleep(WAIT_AFTER_UNINSTALL) nfsclt.run_command(["umount", "-a", "-t", "nfs4"]) nfsclt.run_command(["systemctl", "stop", "rpc-gssd"]) nfssrv.run_command(["systemctl", "stop", "nfs-server"]) nfssrv.run_command(["systemctl", "disable", "nfs-server"]) nfssrv.run_command([ "rm", "-f", "/etc/exports.d/krbnfs.exports", "/etc/exports.d/stdnfs.exports" ]) nfssrv.run_command(["rm", "-rf", "/exports"]) self.master.run_command([ "ipa", "host-mod", automntclt.hostname, "--location", "''" ]) # not strictly necessary, but this exercises automountlocation-del self.master.run_command([ "ipa", "automountlocation-del", "seattle" ]) nfsclt.run_command(["systemctl", "restart", "nfs-utils"]) nfssrv.run_command(["systemctl", "restart", "nfs-utils"]) def test_prepare_users(self): users = { "athena": "p", "euripides": "s" } temp_pass = 'temppass' for user, last in users.items(): self.master.run_command([ "ipa", "user-add", user, "--first", user, "--last", last, '--password'], stdin_text="%s\n%s\n" % (temp_pass, temp_pass) ) self.master.run_command(["kdestroy", "-A"]) password = "Secret123" user_kinit = "%s\n%s\n%s\n" % (temp_pass, password, password) self.master.run_command( ['kinit', user], stdin_text=user_kinit ) self.master.run_command(["kdestroy", "-A"]) tasks.kinit_admin(self.master) def test_krb5_nfsd(self): nfssrv = self.clients[0] # NFS keytab management self.master.run_command([ "ipa", "service-add", "nfs/%s" % nfssrv.hostname ]) nfssrv.run_command([ "ipa-getkeytab", "-p", "nfs/%s" % nfssrv.hostname, "-k", "/etc/krb5.keytab" ]) nfssrv.run_command(["systemctl", "restart", "nfs-server"]) nfssrv.run_command(["systemctl", "enable", "nfs-server"]) time.sleep(WAIT_AFTER_INSTALL) basedir = "exports" exports = { "krbnfs": "*(sec=krb5p,rw)", "stdnfs": "*(ro)", "home": "*(sec=krb5p,rw)" } for export, options in exports.items(): exportpath = os.sep.join(('', basedir, export)) exportfile = os.sep.join(( '', 'etc', 'exports.d', "%s.exports" % export )) exportline = " ".join((exportpath, options)) nfssrv.run_command(["mkdir", "-p", exportpath]) nfssrv.run_command(["chmod", "770", exportpath]) nfssrv.put_file_contents(exportfile, exportline) nfssrv.run_command(["cat", exportfile]) nfssrv.run_command(["exportfs", "-r"]) nfssrv.run_command(["exportfs", "-s"]) def test_krb5_nfs_manual_configuration(self): nfssrv = self.clients[0] nfsclt = self.clients[1] # for journalctl --since since = time.strftime('%Y-%m-%d %H:%M:%S') nfsclt.run_command(["systemctl", "restart", "rpc-gssd"]) time.sleep(WAIT_AFTER_INSTALL) mountpoints = ("/mnt/krb", "/mnt/std", "/home") for mountpoint in mountpoints: nfsclt.run_command(["mkdir", "-p", mountpoint]) nfsclt.run_command([ "systemctl", "status", "gssproxy" ]) nfsclt.run_command([ "systemctl", "status", "rpc-gssd" ]) nfsclt.run_command([ "mount", "-t", "nfs4", "-o", "sec=krb5p,vers=4.0", "%s:/exports/krbnfs" % nfssrv.hostname, "/mnt/krb", "-v" ]) nfsclt.run_command([ "mount", "-t", "nfs4", "-o", "sec=krb5p,vers=4.0", "%s:/exports/home" % nfssrv.hostname, "/home", "-v" ]) error = "Unspecified GSS failure" check_log = [ 'journalctl', '-u', 'gssproxy', '--since={}'.format(since)] result = nfsclt.run_command(check_log) assert error not in (result.stdout_text, result.stderr_text) def test_automount(self): """ Test if ipa-client-automount behaves as expected """ nfssrv = self.clients[0] automntclt = self.clients[2] self.master.run_command([ "ipa", "automountlocation-add", "seattle" ]) self.master.run_command([ "ipa", "automountmap-add", "seattle", "auto.home" ]) self.master.run_command([ "ipa", "automountkey-add", "seattle", "auto.home", "--key='*'", "--info=sec=krb5p,vers=4" " 'rhel8-nfsserver0.laptop.example.org:/export/home/&'" ]) self.master.run_command([ "ipa", "automountkey-add", "seattle", "auto.master", "--key=/home", "--info=auto.home" ]) self.master.run_command([ "ipa", "host-mod", automntclt.hostname, "--location", "seattle" ]) # systemctl non-fatal errors will only be displayed # if ipa-client-automount is launched with --debug result1 = automntclt.run_command([ 'ipa-client-automount', '--location', 'seattle', '-U', '--debug' ]) time.sleep(WAIT_AFTER_INSTALL) # systemctl non-fatal errors will show up like this: # stderr=Failed to restart nfs-secure.service: \ # Unit nfs-secure.service not found. # normal output: # stderr= m1 = re.search(r'(?<=stderr\=Failed).+', result1.stderr_text) # maybe re-use m1.group(0) if it exists. assert m1 is None # https://pagure.io/freeipa/issue/7918 # check whether idmapd.conf was setup using the IPA domain automntclt.run_command([ "grep", "Domain = %s" % self.master.domain.name, "/etc/idmapd.conf" ]) automntclt.run_command([ "mount", "-t", "nfs4", "-o", "sec=krb5p,vers=4.0", "%s:/exports/home" % nfssrv.hostname, "/home", "-v" ]) # TODO leverage users time.sleep(WAIT_AFTER_UNINSTALL) automntclt.run_command(["umount", "-a", "-t", "nfs4"]) result2 = automntclt.run_command([ 'ipa-client-automount', '--uninstall', '-U', '--debug' ]) m2 = re.search(r'(?<=stderr\=Failed).+', result2.stderr_text) assert m2 is None time.sleep(WAIT_AFTER_UNINSTALL) # https://pagure.io/freeipa/issue/7918 # test for --idmap-domain DNS automntclt.run_command([ 'ipa-client-automount', '--location', 'default', '-U', '--debug', "--idmap-domain", "DNS" ]) time.sleep(WAIT_AFTER_INSTALL) # check whether idmapd.conf was setup properly: # grep must not find any configured Domain. result = automntclt.run_command( ["grep", "^Domain =", "/etc/idmapd.conf"], raiseonerr=False ) assert result.returncode == 1 automntclt.run_command([ 'ipa-client-automount', '--uninstall', '-U', '--debug' ]) time.sleep(WAIT_AFTER_UNINSTALL) # https://pagure.io/freeipa/issue/7918 # test for --idmap-domain exampledomain.net nfs_domain = "exampledomain.net" automntclt.run_command([ 'ipa-client-automount', '--location', 'default', '-U', '--debug', "--idmap-domain", nfs_domain ]) # check whether idmapd.conf was setup using nfs_domain automntclt.run_command([ "grep", "Domain = %s" % nfs_domain, "/etc/idmapd.conf" ]) time.sleep(WAIT_AFTER_INSTALL) automntclt.run_command([ 'ipa-client-automount', '--uninstall', '-U', '--debug' ]) time.sleep(WAIT_AFTER_UNINSTALL) self.cleanup() class TestIpaClientAutomountFileRestore(IntegrationTest): num_clients = 1 topology = 'line' @classmethod def install(cls, mh): tasks.install_master(cls.master, setup_dns=True) @pytest.fixture(autouse=True) def automountfile_restore_setup(self, request): def fin(): tasks.uninstall_client(self.clients[0]) request.addfinalizer(fin) def nsswitch_backup_restore(self): # In order to get a more pure sum, one that ignores the Generated # header and any whitespace we have to do a bit of work... sha256nsswitch_cmd = \ 'egrep -v "Generated|^$" /etc/nsswitch.conf | sed "s/\\s//g" ' \ '| sort | sha256sum' cmd = self.clients[0].run_command(sha256nsswitch_cmd) orig_sha256 = cmd.stdout_text grep_automount_command = \ "grep automount /etc/nsswitch.conf | cut -d: -f2" tasks.install_client(self.master, self.clients[0]) cmd = self.clients[0].run_command(grep_automount_command) after_ipa_client_install = cmd.stdout_text.split() ipa_client_automount_command = [ "ipa-client-automount", "-U" ] self.clients[0].run_command(ipa_client_automount_command) cmd = self.clients[0].run_command(grep_automount_command) after_ipa_client_automount = cmd.stdout_text.split() # The default order depends on the authselect version # but we only care about the list of sources, not their order assert sorted(after_ipa_client_automount) == ['files', 'sss'] cmd = self.clients[0].run_command(grep_automount_command) assert cmd.stdout_text.split() == after_ipa_client_automount self.clients[0].run_command([ "ipa-client-automount", "--uninstall", "-U" ]) # https://pagure.io/freeipa/issue/8190 # check that no ipa_automount_location is left in sssd.conf # also check for autofs_provider for good measure grep_automount_in_sssdconf_cmd = \ "egrep ipa_automount_location\\|autofs_provider " \ "/etc/sssd/sssd.conf" cmd = self.clients[0].run_command( grep_automount_in_sssdconf_cmd, raiseonerr=False ) assert cmd.returncode == 1, \ "PG8190 regression found: ipa_automount_location still " \ "present in sssd.conf" cmd = self.clients[0].run_command(grep_automount_command) assert cmd.stdout_text.split() == after_ipa_client_install self.verify_checksum_after_ipaclient_uninstall( sha256nsswitch_cmd=sha256nsswitch_cmd, orig_sha256=orig_sha256 ) def verify_checksum_after_ipaclient_uninstall( self, sha256nsswitch_cmd, orig_sha256 ): tasks.uninstall_client(self.clients[0]) cmd = self.clients[0].run_command(sha256nsswitch_cmd) assert cmd.stdout_text == orig_sha256 def test_nsswitch_backup_restore_sssd(self): self.nsswitch_backup_restore()
12,066
Python
.py
289
32.179931
79
0.582116
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,552
test_automember.py
freeipa_freeipa/ipatests/test_integration/test_automember.py
# # Copyright (C) 2019 FreeIPA Contributors see COPYING for license # """This covers tests for automemberfeature.""" from __future__ import absolute_import import uuid from ipapython.dn import DN from ipatests.pytest_ipa.integration import tasks from ipatests.test_integration.base import IntegrationTest msg = ('IMPORTANT: In case of a high number of users, hosts or ' 'groups, the operation may require high CPU usage.') class TestAutounmembership(IntegrationTest): """Tests for autounmembership feature. This test class covers the tests for this feature described in https://pagure.io/389-ds-base/issue/50077 . """ topology = 'line' dn = DN( ('cn', 'Auto Membership Plugin'), ('cn', 'plugins'), ('cn', 'config') ) def automember_group_add(self, group): """Add group/automember entry.""" cmdlist = [['ipa', 'group-add', '--desc=%s' % group, group], ['ipa', 'automember-add', '--type=group', group], ['ipa', 'automember-add-condition', '--key=destinationindicator', '--type=group', '--inclusive-regex=%s' % group, group]] for cmd in cmdlist: self.master.run_command(cmd) def user_automember_setup(self, group, user, first, last): """Add user entry.""" self.master.run_command(['ipa', 'user-add', '--first=%s' % first, '--last=%s' % last, user, '--setattr=destinationindicator=%s' % group]) def user_automember_mod(self, group, user): """Modify user entry.""" self.master.run_command(['ipa', 'user-mod', user, '--setattr=destinationindicator=%s' % group]) def remove_user_automember(self, user, raiseonerr=True): """Delete user entry.""" self.master.run_command(['ipa', 'user-del', user], raiseonerr=raiseonerr) def automember_group_cleanup(self, group): """Cleanup of automember/group entry.""" cmdlist = [['ipa', 'automember-del', '--type=group', group], ['ipa', 'group-del', group]] for cmd in cmdlist: self.master.run_command(cmd, raiseonerr=False) def is_user_member_of_group(self, user, group): """Check membership of user in the group.""" result = self.master.run_command(['ipa', 'group-show', group]) return user in result.stdout_text def automember_hostgroup_add(self, hostgroup): """Add hostgroup/automember entry.""" cmdlist = [['ipa', 'hostgroup-add', '--desc=%s' % hostgroup, hostgroup], ['ipa', 'automember-add', '--type=hostgroup', hostgroup], ['ipa', 'automember-add-condition', '--key=nshostlocation', '--type=hostgroup', '--inclusive-regex=%s' % hostgroup, hostgroup]] for cmd in cmdlist: self.master.run_command(cmd) def host_automember_setup(self, hostgroup, host): """Add host entry.""" self.master.run_command(['ipa', 'host-add', host, '--location=%s' % hostgroup, '--force']) def host_automember_mod(self, hostgroup, host): """Modify host entry.""" self.master.run_command(['ipa', 'host-mod', host, '--location=%s' % hostgroup]) def remove_host_automember(self, host, raiseonerr=True): """Delete host entry.""" self.master.run_command(['ipa', 'host-del', host], raiseonerr=raiseonerr) def automember_hostgroup_cleanup(self, hostgroup): """Cleanup of automember/hostgroup entry.""" cmdlist = [['ipa', 'automember-del', '--type=hostgroup', hostgroup], ['ipa', 'hostgroup-del', hostgroup]] for cmd in cmdlist: self.master.run_command(cmd, raiseonerr=False) def is_host_member_of_hostgroup(self, host, hostgroup): """Check membership of host in the hostgroup.""" result = self.master.run_command(['ipa', 'hostgroup-show', hostgroup]) return host in result.stdout_text def check_autounmembership_in_ldap(self, state='on'): """Check autounmembership state.""" conn = self.master.ldap_connect() entry = conn.get_entry(self.dn) assert state == entry.single_value['automemberprocessmodifyops'] def disable_autounmembership_in_ldap(self): """Disable autounmembership.""" conn = self.master.ldap_connect() entry = conn.get_entry(self.dn) entry.single_value['automemberprocessmodifyops'] = 'off' conn.update_entry(entry) self.master.run_command(['ipactl', 'restart']) def test_modify_user_entry_unmembership(self): """Test when autounmembership feature is enabled. Test that an update on a user entry triggers a re-evaluation of the user's automember groups when auto-unmembership is active. """ try: # testcase setup tasks.kinit_admin(self.master) self.check_autounmembership_in_ldap(state='on') group1 = 'DallasUsers' group2 = 'HoustonUsers' user1 = 'user1' first = 'first' last = 'user' self.automember_group_add(group1) self.automember_group_add(group2) self.user_automember_setup(group1, user1, first, last) assert self.is_user_member_of_group(user1, group1) # Modifying the user group so that it becomes part of new group self.user_automember_mod(group2, user1) assert self.is_user_member_of_group(user1, group2) assert not self.is_user_member_of_group(user1, group1) # Deleting the user entry and checking its not part of group now self.remove_user_automember(user1) assert not self.is_user_member_of_group(user1, group2) finally: # testcase cleanup self.remove_user_automember(user1, raiseonerr=False) self.automember_group_cleanup(group1) self.automember_group_cleanup(group2) def test_modify_host_entry_unmembership(self): """Test when autounmembership feature is enabled. Test that an update on a host entry triggers a re-evaluation of the host's automember groups when auto-unmembership is active. """ try: # testcase setup self.check_autounmembership_in_ldap(state='on') hostgroup1 = 'Brno' hostgroup2 = 'Boston' host1 = 'host1.example.com' self.automember_hostgroup_add(hostgroup1) self.automember_hostgroup_add(hostgroup2) self.host_automember_setup(hostgroup1, host1) assert self.is_host_member_of_hostgroup(host1, hostgroup1) # Modifying the user group so that it becomes part of new group self.host_automember_mod(hostgroup2, host1) assert self.is_host_member_of_hostgroup(host1, hostgroup2) assert not self.is_host_member_of_hostgroup(host1, hostgroup1) # Deleting the user entry and checking its not part of group now self.remove_host_automember(host1) assert not self.is_host_member_of_hostgroup(host1, hostgroup2) finally: # testcase cleanup self.remove_host_automember(host1, raiseonerr=False) self.automember_hostgroup_cleanup(hostgroup1) self.automember_hostgroup_cleanup(hostgroup2) def test_modify_user_entry_unmembership_disabled(self): """Test when autounmembership feature is disabled. Test that an update on a user entry does not triggers re-evaluation of the user's automember groups when auto-unmembership is disabled. """ try: # testcase setup self.disable_autounmembership_in_ldap() self.check_autounmembership_in_ldap(state='off') group1 = 'PuneUsers' group2 = 'BrnoUsers' user2 = 'user2' first = 'second' last = 'user' self.automember_group_add(group1) self.automember_group_add(group2) self.user_automember_setup(group1, user2, first, last) assert self.is_user_member_of_group(user2, group1) # Modifying the user group so that it becomes part of new group self.user_automember_mod(group2, user2) assert not self.is_user_member_of_group(user2, group2) assert self.is_user_member_of_group(user2, group1) # Running automember-build so that user is part of correct group result = self.master.run_command(['ipa', 'automember-rebuild', '--users=%s' % user2]) assert msg in result.stdout_text # The additional --cleanup argument is required cleanup_ldif = ( "dn: cn={cn},cn=automember rebuild membership," "cn=tasks,cn=config\n" "changetype: add\n" "objectclass: top\n" "objectclass: extensibleObject\n" "basedn: cn=users,cn=accounts,{suffix}\n" "filter: (uid={user})\n" "cleanup: yes\n" "scope: sub" ).format(cn=str(uuid.uuid4()), suffix=str(self.master.domain.basedn), user=user2) tasks.ldapmodify_dm(self.master, cleanup_ldif) assert self.is_user_member_of_group(user2, group2) assert not self.is_user_member_of_group(user2, group1) finally: # testcase cleanup self.remove_user_automember(user2, raiseonerr=False) self.automember_group_cleanup(group1) self.automember_group_cleanup(group2) def test_modify_host_entry_unmembership_disabled(self): """Test when autounmembership feature is disabled. Test that an update on a host entry does not triggers re-evaluation of the host's automember groups when auto-unmembership is disabled. """ try: # testcase setup self.check_autounmembership_in_ldap(state='off') hostgroup1 = 'Pune' hostgroup2 = 'Raleigh' host2 = 'host2.example.com' self.automember_hostgroup_add(hostgroup1) self.automember_hostgroup_add(hostgroup2) self.host_automember_setup(hostgroup1, host2) assert self.is_host_member_of_hostgroup(host2, hostgroup1) # Modifying the user group so that it becomes part of new group self.host_automember_mod(hostgroup2, host2) assert not self.is_host_member_of_hostgroup(host2, hostgroup2) assert self.is_host_member_of_hostgroup(host2, hostgroup1) # Running the automember-build so host is part of correct hostgroup result = self.master.run_command( ['ipa', 'automember-rebuild', '--hosts=%s' % host2] ) assert msg in result.stdout_text # The additional --cleanup argument is required cleanup_ldif = ( "dn: cn={cn},cn=automember rebuild membership," "cn=tasks,cn=config\n" "changetype: add\n" "objectclass: top\n" "objectclass: extensibleObject\n" "basedn: cn=computers,cn=accounts,{suffix}\n" "filter: (fqdn={fqdn})\n" "cleanup: yes\n" "scope: sub" ).format(cn=str(uuid.uuid4()), suffix=str(self.master.domain.basedn), fqdn=host2) tasks.ldapmodify_dm(self.master, cleanup_ldif) assert self.is_host_member_of_hostgroup(host2, hostgroup2) assert not self.is_host_member_of_hostgroup(host2, hostgroup1) finally: # testcase cleanup self.remove_host_automember(host2, raiseonerr=False) self.automember_hostgroup_cleanup(hostgroup1) self.automember_hostgroup_cleanup(hostgroup2)
12,362
Python
.py
248
37.58871
79
0.599635
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,553
test_kerberos_flags.py
freeipa_freeipa/ipatests/test_integration/test_kerberos_flags.py
# Authors: # Ana Krivokapic <akrivoka@redhat.com> # # Copyright (C) 2013 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from ipatests.test_integration.base import IntegrationTest from ipatests.pytest_ipa.integration import tasks class TestKerberosFlags(IntegrationTest): """ Test Kerberos Flags http://www.freeipa.org/page/V3/Kerberos_Flags#Test_Plan """ topology = 'line' num_clients = 1 def test_set_flag_with_host_add(self): host = 'host.example.com' host_service = 'host/%s' % host host_keytab = '/tmp/host.keytab' for trusted in (True, False, None): self.add_object('host', host, trusted=trusted, force=True) self.check_flag_cli('host', host, trusted=trusted) self.rekinit() self.getkeytab(host_service, host_keytab) self.kvno(host_service) self.check_flag_klist(host_service, trusted=trusted) self.del_object('host', host) def test_set_and_clear_flag_with_host_mod(self): client_hostname = self.clients[0].hostname host_service = 'host/%s' % client_hostname self.kvno(host_service) self.check_flag_cli('host', client_hostname, trusted=False) self.check_flag_klist(host_service, trusted=False) for trusted in (True, False): self.mod_object_cli('host', client_hostname, trusted=trusted) self.check_flag_cli('host', client_hostname, trusted=trusted) self.rekinit() self.kvno(host_service) self.check_flag_klist(host_service, trusted=trusted) for trusted in (True, False): self.mod_service_kadmin_local(host_service, trusted=trusted) self.check_flag_cli('host', client_hostname, trusted=trusted) self.rekinit() self.kvno(host_service) self.check_flag_klist(host_service, trusted=trusted) def test_set_flag_with_service_add(self): ftp_service = 'ftp/%s' % self.master.hostname ftp_keytab = '/tmp/ftp.keytab' for trusted in (True, False, None): self.add_object('service', ftp_service, trusted=trusted) self.check_flag_cli('service', ftp_service, trusted=trusted) self.rekinit() self.getkeytab(ftp_service, ftp_keytab) self.kvno(ftp_service) self.check_flag_klist(ftp_service, trusted=trusted) self.del_object('service', ftp_service) def test_set_and_clear_flag_with_service_mod(self): http_service = 'HTTP/%s' % self.master.hostname self.kvno(http_service) self.check_flag_cli('service', http_service, trusted=False) self.check_flag_klist(http_service, trusted=False) for trusted in (True, False): self.mod_object_cli('service', http_service, trusted=trusted) self.check_flag_cli('service', http_service, trusted=trusted) self.rekinit() self.kvno(http_service) self.check_flag_klist(http_service, trusted=trusted) for trusted in (True, False): self.mod_service_kadmin_local(http_service, trusted=trusted) self.check_flag_cli('service', http_service, trusted=trusted) self.rekinit() self.kvno(http_service) self.check_flag_klist(http_service, trusted=trusted) def test_try_to_set_flag_using_unexpected_values(self): http_service = 'HTTP/%s' % self.master.hostname invalid_values = ['blah', 'yes', 'y', '2', '1.0', '$'] for v in invalid_values: self.mod_object_cli('service', http_service, trusted=v, expect_fail=True) def add_object(self, object_type, object_id, trusted=None, force=False): args = ['ipa', '%s-add' % object_type, object_id] if trusted is True: args.extend(['--ok-as-delegate', '1']) elif trusted is False: args.extend(['--ok-as-delegate', '0']) if force: args.append('--force') self.master.run_command(args) def del_object(self, object_type, object_id): self.master.run_command(['ipa', '%s-del' % object_type, object_id]) def mod_object_cli(self, object_type, object_id, trusted, expect_fail=False): args = ['ipa', '%s-mod' % object_type, object_id] if trusted is True: args.extend(['--ok-as-delegate', '1']) elif trusted is False: args.extend(['--ok-as-delegate', '0']) else: args.extend(['--ok-as-delegate', trusted]) result = self.master.run_command(args, raiseonerr=not expect_fail) if expect_fail: stderr_text = "invalid 'ipakrbokasdelegate': must be True or False" assert result.returncode == 1 assert stderr_text in result.stderr_text def mod_service_kadmin_local(self, service, trusted): sign = '+' if trusted else '-' stdin_text = '\n'.join([ 'modify_principal %sok_as_delegate %s' % (sign, service), 'q', '' ]) self.master.run_command('kadmin.local', stdin_text=stdin_text) def check_flag_cli(self, object_type, object_id, trusted): result = self.master.run_command( ['ipa', '%s-show' % object_type, object_id, '--all'] ) if trusted: assert 'Trusted for delegation: True' in result.stdout_text else: assert 'Trusted for delegation: False' in result.stdout_text def check_flag_klist(self, service, trusted): result = self.master.run_command(['klist', '-f']) output_lines = result.stdout_text.split('\n') flags = '' for line, next_line in zip(output_lines, output_lines[1:]): if service in line: flags = next_line.replace('Flags:', '').strip() if trusted: assert 'O' in flags else: assert 'O' not in flags def rekinit(self): self.master.run_command(['kdestroy']) tasks.kinit_admin(self.master) def getkeytab(self, service, keytab): result = self.master.run_command([ 'ipa-getkeytab', '-s', self.master.hostname, '-p', service, '-k', keytab ]) assert 'Keytab successfully retrieved' in result.stderr_text def kvno(self, service): self.master.run_command(['kvno', service])
7,160
Python
.py
156
36.5
79
0.620893
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,554
test_membermanager.py
freeipa_freeipa/ipatests/test_integration/test_membermanager.py
# # Copyright (C) 2019 FreeIPA Contributors see COPYING for license # """Tests for member manager feature """ from ipatests.test_integration.base import IntegrationTest from ipatests.pytest_ipa.integration import tasks PASSWORD = "DummyPassword123" # direct member manager USER_MM = "mmuser" # indirect member manager through group membership USER_INDIRECT = "indirect_mmuser" GROUP_INDIRECT = "group_indirect" USER1 = "testuser1" USER2 = "testuser2" GROUP1 = "testgroup1" GROUP2 = "testgroup2" HOSTGROUP1 = "testhostgroup1" class TestMemberManager(IntegrationTest): """Tests for member manager feature for groups and hostgroups """ topology = "line" @classmethod def install(cls, mh): super(TestMemberManager, cls).install(mh) master = cls.master tasks.create_active_user(master, USER_MM, PASSWORD) tasks.create_active_user(master, USER_INDIRECT, PASSWORD) tasks.create_active_user(master, USER1, PASSWORD) tasks.kinit_admin(master) tasks.group_add(master, GROUP_INDIRECT) master.run_command([ 'ipa', 'group-add-member', GROUP_INDIRECT, '--users', USER_INDIRECT ]) tasks.user_add(master, USER2) tasks.group_add(master, GROUP1) tasks.group_add(master, GROUP2) master.run_command(['ipa', 'hostgroup-add', HOSTGROUP1]) # make mmuser a member manager for group and hostgroup master.run_command([ 'ipa', 'group-add-member-manager', GROUP1, '--users', USER_MM ]) master.run_command([ 'ipa', 'hostgroup-add-member-manager', HOSTGROUP1, '--users', USER_MM ]) # make indirect group member manager for group and hostgroup master.run_command([ 'ipa', 'group-add-member-manager', GROUP1, '--groups', GROUP_INDIRECT ]) master.run_command([ 'ipa', 'hostgroup-add-member-manager', HOSTGROUP1, '--groups', GROUP_INDIRECT ]) tasks.kdestroy_all(master) def test_show_member_manager(self): master = self.master tasks.kinit_admin(master) result = master.run_command(['ipa', 'group-show', GROUP1]) out = result.stdout_text assert f"Membership managed by groups: {GROUP_INDIRECT}" in out assert f"Membership managed by users: {USER_MM}" in out result = master.run_command(['ipa', 'hostgroup-show', HOSTGROUP1]) out = result.stdout_text assert f"Membership managed by groups: {GROUP_INDIRECT}" in out assert f"Membership managed by users: {USER_MM}" in out tasks.kdestroy_all(master) def test_find_by_member_manager(self): master = self.master tasks.kinit_admin(master) result = master.run_command([ 'ipa', 'group-find', '--membermanager-users', USER_MM ]) assert GROUP1 in result.stdout_text result = master.run_command([ 'ipa', 'group-find', '--membermanager-groups', GROUP_INDIRECT ]) assert GROUP1 in result.stdout_text result = master.run_command( [ 'ipa', 'group-find', '--membermanager-users', USER1 ], raiseonerr=False ) assert result.returncode == 1 assert "0 groups matched" in result.stdout_text result = master.run_command([ 'ipa', 'hostgroup-find', '--membermanager-users', USER_MM ]) assert HOSTGROUP1 in result.stdout_text result = master.run_command([ 'ipa', 'hostgroup-find', '--membermanager-groups', GROUP_INDIRECT ]) assert HOSTGROUP1 in result.stdout_text result = master.run_command( [ 'ipa', 'hostgroup-find', '--membermanager-users', USER1 ], raiseonerr=False ) assert result.returncode == 1 assert "0 hostgroups matched" in result.stdout_text def test_group_member_manager_user(self): master = self.master # mmuser: add user1 to group tasks.kinit_as_user(master, USER_MM, PASSWORD) master.run_command([ 'ipa', 'group-add-member', GROUP1, '--users', USER1 ]) result = master.run_command(['ipa', 'group-show', GROUP1]) assert USER1 in result.stdout_text # indirect: add user2 to group tasks.kinit_as_user(master, USER_INDIRECT, PASSWORD) master.run_command([ 'ipa', 'group-add-member', GROUP1, '--users', USER2 ]) # verify master.run_command(['ipa', 'group-show', GROUP1]) result = master.run_command(['ipa', 'group-show', GROUP1]) assert USER2 in result.stdout_text def test_group_member_manager_group(self): master = self.master # mmuser: add group2 to group tasks.kinit_as_user(master, USER_MM, PASSWORD) master.run_command([ 'ipa', 'group-add-member', GROUP1, '--groups', GROUP2 ]) result = master.run_command(['ipa', 'group-show', GROUP1]) assert GROUP2 in result.stdout_text def test_group_member_manager_nopermission(self): master = self.master tasks.kinit_as_user(master, USER1, PASSWORD) result = master.run_command( [ 'ipa', 'group-add-member-manager', GROUP1, '--users', USER1 ], raiseonerr=False ) assert result.returncode != 0 expected = ( f"member user: {USER1}: Insufficient access: Insufficient " "'write' privilege to the 'memberManager' attribute of entry" ) assert expected in result.stdout_text def test_hostgroup_member_manager_user(self): master = self.master # mmuser: add a host to host group tasks.kinit_as_user(master, USER_MM, PASSWORD) master.run_command([ 'ipa', 'hostgroup-add-member', HOSTGROUP1, '--hosts', master.hostname ]) result = master.run_command(['ipa', 'hostgroup-show', HOSTGROUP1]) assert master.hostname in result.stdout_text master.run_command([ 'ipa', 'hostgroup-remove-member', HOSTGROUP1, '--hosts', master.hostname ]) result = master.run_command(['ipa', 'hostgroup-show', HOSTGROUP1]) assert master.hostname not in result.stdout_text # indirect: tasks.kinit_as_user(master, USER_INDIRECT, PASSWORD) master.run_command([ 'ipa', 'hostgroup-add-member', HOSTGROUP1, '--hosts', master.hostname ]) result = master.run_command(['ipa', 'hostgroup-show', HOSTGROUP1]) assert master.hostname in result.stdout_text def test_hostgroup_member_manager_nopermission(self): master = self.master tasks.kinit_as_user(master, USER1, PASSWORD) result = master.run_command( [ 'ipa', 'hostgroup-add-member-manager', HOSTGROUP1, '--users', USER1 ], raiseonerr=False ) assert result.returncode != 0 expected = ( f"member user: {USER1}: Insufficient access: Insufficient " "'write' privilege to the 'memberManager' attribute of entry" ) assert expected in result.stdout_text @tasks.pytest.fixture def prepare_mbr_manager_upgrade(self): user = "idmuser" password = "Secret123" group1 = "role-groupmanager" group2 = "role-usergroup-A" master = self.master tasks.kinit_admin(master) tasks.group_add(master, group1) tasks.group_add(master, group2) tasks.create_active_user(master, user, password) tasks.kinit_admin(master) tasks.group_add_member(master, group1, user) master.run_command(["ipa", "group-add-member-manager", "--groups", group1, group2]) yield user, password, group2 # cleanup tasks.kinit_admin(master) tasks.user_del(master, user) tasks.group_del(master, group1) tasks.group_del(master, group2) def test_member_manager_upgrade_scenario(self, prepare_mbr_manager_upgrade): """ Testing if manager whose rights defined by the group membership is able to add group members, after upgrade of ipa server. Using ACI modification to demonstrate unability before upgrading ipa server. Related: https://pagure.io/freeipa/issue/9286 """ user, password, group2 = prepare_mbr_manager_upgrade master = self.master base_dn = self.master.domain.basedn aci_hostgroup = ( '(targetattr = "member")(targetfilter = ' '"(objectclass=ipaHostGroup)")' '(version 3.0; acl "Allow member managers ' 'to modify members of host groups"; allow (write) userattr = ' '"memberManager#USERDN" or userattr = "memberManager#GROUPDN";)' ) aci_usergroup = ( '(targetattr = "member")(targetfilter = ' '"(objectclass=ipaUserGroup)")' '(version 3.0; acl "Allow member managers ' 'to modify members of user groups"; allow (write) userattr = ' '"memberManager#USERDN" or userattr = "memberManager#GROUPDN";)' ) ldif_entry = tasks.textwrap.dedent( """ dn: cn=hostgroups,cn=accounts,{base_dn} changetype: modify delete: aci aci: {aci_hostgroup} dn: cn=groups,cn=accounts,{base_dn} changetype: modify delete: aci aci: {aci_usergroup} """).format(base_dn=base_dn, aci_hostgroup=aci_hostgroup, aci_usergroup=aci_usergroup) tasks.ldapmodify_dm(master, ldif_entry) tasks.kinit_as_user(master, user, password) # in this point this command should fail result = tasks.group_add_member(master, group2, "admin", raiseonerr=False) assert result.returncode == 1 assert "Insufficient access" in result.stdout_text master.run_command(['ipa-server-upgrade']) tasks.group_add_member(master, group2, "admin")
10,366
Python
.py
254
31.224409
80
0.608976
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,555
test_caless.py
freeipa_freeipa/ipatests/test_integration/test_caless.py
# Authors: # Petr Viktorin <pviktori@redhat.com> # # Copyright (C) 2013 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from __future__ import absolute_import import functools import logging import os import re import tempfile import shutil import glob import contextlib import pytest import six from ipalib import x509 from ipapython import ipautil from ipaplatform.paths import paths from ipapython.dn import DN from ipatests.test_integration.base import IntegrationTest from ipatests.pytest_ipa.integration import tasks from ipatests.create_external_ca import ExternalCA from ipatests.pytest_ipa.integration import create_caless_pki from ipalib.constants import DOMAIN_LEVEL_0 if six.PY3: unicode = str logger = logging.getLogger(__name__) _DEFAULT = object() assert_error = tasks.assert_error NSS_INVALID_FMT = "certutil: certificate is invalid: %s" BAD_USAGE_MSG = NSS_INVALID_FMT % ("Certificate key usage inadequate for " "attempted operation.") def get_install_stdin(cert_passwords=()): lines = [ '', # Server host name (has default) ] lines.extend(cert_passwords) # Enter foo.p12 unlock password lines.extend('IPA') # NetBios name lines += [ 'no', # configure chrony with NTP server or pool address? 'yes', # Continue with these values? ] return '\n'.join(lines + ['']) def get_replica_prepare_stdin(cert_passwords=()): lines = list(cert_passwords) # Enter foo.p12 unlock password lines += [ 'yes', # Continue [no]? ] return '\n'.join(lines + ['']) def ipa_certs_cleanup(host): host.run_command(['certutil', '-d', paths.NSS_DB_DIR, '-D', '-n', 'External CA cert'], raiseonerr=False) # A workaround for https://fedorahosted.org/freeipa/ticket/4639 result = host.run_command(['certutil', '-L', '-d', paths.HTTPD_ALIAS_DIR], raiseonerr=False) for rawcert in result.stdout_text.split('\n')[4: -1]: cert = rawcert.split(' ')[0] host.run_command(['certutil', '-D', '-d', paths.HTTPD_ALIAS_DIR, '-n', cert], raiseonerr=False) def server_install_teardown(func): def wrapped(*args): master = args[0].master try: func(*args) finally: tasks.uninstall_master(master, clean=False) ipa_certs_cleanup(master) return wrapped def replica_install_teardown(func): def wrapped(*args): try: func(*args) finally: # Uninstall replica replica = args[0].replicas[0] master = args[0].master tasks.kinit_admin(master) tasks.clean_replication_agreement(master, replica, cleanup=True, raiseonerr=False) master.run_command(['ipa', 'host-del', replica.hostname], raiseonerr=False) tasks.uninstall_master(replica, clean=False) # Now let's uninstall client for the cases when client promotion # was not successful tasks.uninstall_client(replica) ipa_certs_cleanup(replica) return wrapped class CALessBase(IntegrationTest): # The teardown method is called even if all the tests are skipped # since the required PKI version is not present. # The teardown is trying to remove a non-existent directory. # Currently the cert_dir attribute is only present if IPA installation was # done. If IPA was not installed the attribute does not exist. # In order that the uninstall code finds the attribute a class attribute # is added. cert_dir = None @classmethod def install(cls, mh): cls.cert_dir = tempfile.mkdtemp(prefix="ipatest-") cls.pem_filename = os.path.join(cls.cert_dir, 'root.pem') cls.ca2_crt = 'ca2_crt.pem' cls.ca2_kdc_crt = 'ca2_kdc_crt.pem' cls.cert_password = cls.master.config.admin_password cls.crl_path = os.path.join(cls.master.config.test_dir, 'crl') if cls.replicas: replica_hostname = cls.replicas[0].hostname else: replica_hostname = 'unused-replica.test' if cls.clients: client_hostname = cls.clients[0].hostname else: client_hostname = 'unused-client.test' create_caless_pki.domain = unicode(cls.master.domain.name) create_caless_pki.realm = unicode(cls.master.domain.name.upper()) create_caless_pki.server1 = unicode(cls.master.hostname) create_caless_pki.server2 = unicode(replica_hostname) create_caless_pki.client = unicode(client_hostname) create_caless_pki.password = unicode(cls.master.config.dirman_password) create_caless_pki.cert_dir = unicode(cls.cert_dir) # here we generate our certificates (not yet converted to .p12) logger.info('Generating certificates to %s', cls.cert_dir) create_caless_pki.create_pki() for host in cls.get_all_hosts(): tasks.apply_common_fixes(host) # Copy CRLs over host.transport.mkdir_recursive(cls.crl_path) for source in glob.glob(os.path.join(cls.cert_dir, '*.crl')): dest = os.path.join(cls.crl_path, os.path.basename(source)) host.transport.put_file(source, dest) @classmethod def uninstall(cls, mh): # Remove the NSS database if cls.cert_dir: shutil.rmtree(cls.cert_dir) super(CALessBase, cls).uninstall(mh) @classmethod def install_server(cls, host=None, http_pkcs12='server.p12', dirsrv_pkcs12='server.p12', http_pkcs12_exists=True, dirsrv_pkcs12_exists=True, http_pin=_DEFAULT, dirsrv_pin=_DEFAULT, pkinit_pin=None, root_ca_file='root.pem', pkinit_pkcs12_exists=False, pkinit_pkcs12='server-kdc.p12', unattended=True, stdin_text=None, extra_args=[]): """Install a CA-less server Return value is the remote ipa-server-install command """ if host is None: host = cls.master destname = functools.partial(os.path.join, host.config.test_dir) std_args = [ '--http-cert-file', destname(http_pkcs12), '--dirsrv-cert-file', destname(dirsrv_pkcs12), '--ca-cert-file', destname(root_ca_file), '--ip-address', host.ip ] if extra_args: extra_args.extend(std_args) else: extra_args = std_args if http_pin is _DEFAULT: http_pin = cls.cert_password if dirsrv_pin is _DEFAULT: dirsrv_pin = cls.cert_password if pkinit_pin is _DEFAULT: pkinit_pin = cls.cert_password tasks.prepare_host(host) files_to_copy = ['root.pem'] if http_pkcs12_exists: files_to_copy.append(http_pkcs12) if dirsrv_pkcs12_exists: files_to_copy.append(dirsrv_pkcs12) if pkinit_pkcs12_exists: files_to_copy.append(pkinit_pkcs12) extra_args.extend( ['--pkinit-cert-file', destname(pkinit_pkcs12)] ) else: extra_args.append('--no-pkinit') for filename in set(files_to_copy): cls.copy_cert(host, filename) # Remove existing ca certs from default database to avoid conflicts args = [paths.CERTUTIL, "-D", "-d", "/etc/httpd/alias", "-n"] host.run_command(args + ["ca1"], raiseonerr=False) host.run_command(args + ["ca1/server"], raiseonerr=False) if http_pin is not None: extra_args.extend(['--http-pin', http_pin]) if dirsrv_pin is not None: extra_args.extend(['--dirsrv-pin', dirsrv_pin]) if pkinit_pin is not None: extra_args.extend(['--pkinit-pin', dirsrv_pin]) return tasks.install_master(host, extra_args=extra_args, unattended=unattended, stdin_text=stdin_text, raiseonerr=False) @classmethod def copy_cert(cls, host, filename): host.transport.put_file(os.path.join(cls.cert_dir, filename), os.path.join(host.config.test_dir, filename)) def prepare_replica(self, _replica_number=0, replica=None, master=None, http_pkcs12='replica.p12', dirsrv_pkcs12='replica.p12', http_pkcs12_exists=True, dirsrv_pkcs12_exists=True, http_pin=_DEFAULT, dirsrv_pin=_DEFAULT, pkinit_pin=None, root_ca_file='root.pem', pkinit_pkcs12_exists=False, pkinit_pkcs12='replica-kdc.p12', unattended=True, stdin_text=None, domain_level=None, force_setup_ca=False): """Prepare a CA-less replica Puts the bundle file into test_dir on the replica if successful, otherwise ensures it is missing. Return value is the remote ipa-replica-prepare command """ if replica is None: replica = self.replicas[_replica_number] if master is None: master = self.master if http_pin is _DEFAULT: http_pin = self.cert_password if dirsrv_pin is _DEFAULT: dirsrv_pin = self.cert_password if pkinit_pin is _DEFAULT: pkinit_pin = self.cert_password if domain_level is None: domain_level = tasks.domainlevel(master) tasks.check_domain_level(domain_level) files_to_copy = ['root.pem'] if http_pkcs12_exists: files_to_copy.append(http_pkcs12) if dirsrv_pkcs12_exists: files_to_copy.append(dirsrv_pkcs12) if pkinit_pkcs12_exists: files_to_copy.append(pkinit_pkcs12) if domain_level == DOMAIN_LEVEL_0: destination_host = master else: destination_host = replica # Both master and replica lack ipatests folder by this time, so we need # to re-create it tasks.prepare_host(master) tasks.prepare_host(replica) for filename in set(files_to_copy): try: destination_host.transport.put_file( os.path.join(self.cert_dir, filename), os.path.join(destination_host.config.test_dir, filename)) except (IOError, OSError): pass extra_args = [] if http_pkcs12_exists: extra_args.extend([ '--http-cert-file', os.path.join(destination_host.config.test_dir, http_pkcs12) ]) if dirsrv_pkcs12_exists: extra_args.extend([ '--dirsrv-cert-file', os.path.join(destination_host.config.test_dir, dirsrv_pkcs12) ]) if pkinit_pkcs12_exists and domain_level != DOMAIN_LEVEL_0: extra_args.extend([ '--pkinit-cert-file', os.path.join(destination_host.config.test_dir, pkinit_pkcs12) ]) else: extra_args.append('--no-pkinit') if http_pin is not None: extra_args.extend(['--http-pin', http_pin]) if dirsrv_pin is not None: extra_args.extend(['--dirsrv-pin', dirsrv_pin]) if pkinit_pin is not None: extra_args.extend(['--pkinit-pin', dirsrv_pin]) result = tasks.install_replica(master, replica, setup_ca=force_setup_ca, extra_args=extra_args, unattended=unattended, stdin_text=stdin_text, raiseonerr=False) return result @classmethod def create_pkcs12(cls, nickname, filename='server.p12', password=None): """Create a cert chain and generate pkcs12 cert""" if password is None: password = cls.cert_password fname_chain = [] key_fname = '{}.key'.format(os.path.join(cls.cert_dir, nickname)) certchain_fname = '{}.pem'.format(os.path.join(cls.cert_dir, nickname)) nick_chain = nickname.split('/') # to construct whole chain e.g "ca1 - ca1/sub - ca1/sub/server" for index, _value in enumerate(nick_chain): cert_nick = '/'.join(nick_chain[:index + 1]) cert_path = '{}.crt'.format(os.path.join(cls.cert_dir, cert_nick)) if os.path.isfile(cert_path): fname_chain.append(cert_path) # create the chain file with open(certchain_fname, 'w') as chain: for cert_fname in fname_chain: with open(cert_fname) as cert: chain.write(cert.read()) ipautil.run([paths.OPENSSL, "pkcs12", "-export", "-out", filename, "-inkey", key_fname, "-in", certchain_fname, "-passin", "pass:" + cls.cert_password, "-passout", "pass:" + password, "-name", nickname], cwd=cls.cert_dir) @classmethod def prepare_cacert(cls, nickname, filename=None): """ Prepare pem file for root_ca_file/ca-cert-file option """ if filename is None: filename = cls.pem_filename.split(os.sep)[-1] # create_caless_pki saves certificates with ".crt" extension by default fname_from_nick = '{}.crt'.format(os.path.join(cls.cert_dir, nickname)) shutil.copy(fname_from_nick, os.path.join(cls.cert_dir, filename)) @classmethod def get_pem(cls, nickname): """ Return PEM cert as base64 encoded ascii for TestIPACommands """ cacert_fname = '{}.crt'.format(os.path.join(cls.cert_dir, nickname)) with open(cacert_fname, 'r') as f: return f.read() def verify_installation(self): """Verify CA cert PEM file and LDAP entry created by install Called from every positive server install test """ with open(self.pem_filename, 'rb') as f: expected_cacrt = f.read() logger.debug('Expected /etc/ipa/ca.crt contents:\n%s', expected_cacrt.decode('utf-8')) expected_cacrt = x509.load_unknown_x509_certificate(expected_cacrt) logger.debug('Expected CA cert:\n%r', expected_cacrt.public_bytes(x509.Encoding.PEM)) for host in [self.master] + self.replicas: # Check the LDAP entry ldap = host.ldap_connect() entry = ldap.get_entry(DN(('cn', 'CACert'), ('cn', 'ipa'), ('cn', 'etc'), host.domain.basedn)) cert_from_ldap = entry.single_value['cACertificate'] logger.debug('CA cert from LDAP on %s:\n%r', host, cert_from_ldap.public_bytes(x509.Encoding.PEM)) assert cert_from_ldap == expected_cacrt result = host.run_command( ["/usr/bin/stat", "-c", "%U:%G:%a", paths.IPA_CA_CRT] ) (owner, group, mode) = result.stdout_text.strip().split(':') assert owner == "root" assert group == "root" assert mode == "644" # Verify certmonger was not started result = host.run_command(['getcert', 'list'], raiseonerr=False) assert result.returncode == 0 for host in self.get_all_hosts(): # Check the cert PEM file remote_cacrt = host.get_file_contents(paths.IPA_CA_CRT) logger.debug('%s:/etc/ipa/ca.crt contents:\n%s', host, remote_cacrt.decode('utf-8')) cacrt = x509.load_unknown_x509_certificate(remote_cacrt) logger.debug('%s: Decoded /etc/ipa/ca.crt:\n%r', host, cacrt.public_bytes(x509.Encoding.PEM)) assert expected_cacrt == cacrt class TestServerInstall(CALessBase): num_replicas = 0 @server_install_teardown def test_nonexistent_ca_pem_file(self): "IPA server install with non-existent CA PEM file " self.create_pkcs12('ca1/server') self.prepare_cacert('ca2') result = self.install_server(root_ca_file='does_not_exist') assert_error(result, 'Failed to open %s/does_not_exist: No such file ' 'or directory' % self.master.config.test_dir) @server_install_teardown def test_unknown_ca(self): "IPA server install with CA PEM file with unknown CA certificate" self.create_pkcs12('ca3/server') self.prepare_cacert('ca2') result = self.install_server() assert_error(result, 'The full certificate chain is not present in ' '%s/server.p12' % self.master.config.test_dir) @server_install_teardown def test_ca_server_cert(self): "IPA server install with CA PEM file with server certificate" self.create_pkcs12('noca') self.prepare_cacert('noca') result = self.install_server() assert_error(result, 'The full certificate chain is not present in ' '%s/server.p12' % self.master.config.test_dir) @server_install_teardown def test_ca_2_certs(self): "IPA server install with CA PEM file with 2 certificates" self.create_pkcs12('ca1/server') self.prepare_cacert('ca1') self.prepare_cacert('ca2', filename=self.ca2_crt) with open(self.pem_filename, 'a') as ca1: with open(os.path.join(self.cert_dir, self.ca2_crt), 'r') as ca2: ca1.write(ca2.read()) result = self.install_server() assert result.returncode == 0 # Check that ca2 has not been added to /etc/ipa/ca.crt # because it is not needed in the cert chain with open(os.path.join(self.cert_dir, self.ca2_crt), 'r') as ca2: ca2_body = ca2.read() result = self.master.run_command(['cat', '/etc/ipa/ca.crt']) assert ca2_body not in result.stdout_text @server_install_teardown def test_nonexistent_http_pkcs12_file(self): "IPA server install with non-existent HTTP PKCS#12 file" self.create_pkcs12('ca1/server') self.prepare_cacert('ca1') result = self.install_server(http_pkcs12='does_not_exist', http_pkcs12_exists=False) assert_error(result, 'Failed to open %s/does_not_exist' % self.master.config.test_dir) @server_install_teardown def test_nonexistent_ds_pkcs12_file(self): "IPA server install with non-existent DS PKCS#12 file" self.create_pkcs12('ca1/server') self.prepare_cacert('ca2') result = self.install_server(dirsrv_pkcs12='does_not_exist', dirsrv_pkcs12_exists=False) assert_error(result, 'Failed to open %s/does_not_exist' % self.master.config.test_dir) @server_install_teardown def test_missing_http_password(self): "IPA server install with missing HTTP PKCS#12 password (unattended)" self.create_pkcs12('ca1/server') self.prepare_cacert('ca1') result = self.install_server(http_pin=None) assert_error(result, 'ipa-server-install: error: You must specify --http-pin ' 'with --http-cert-file') @server_install_teardown def test_missing_ds_password(self): "IPA server install with missing DS PKCS#12 password (unattended)" self.create_pkcs12('ca1/server') self.prepare_cacert('ca1') result = self.install_server(dirsrv_pin=None) assert_error(result, 'ipa-server-install: error: You must specify ' '--dirsrv-pin with --dirsrv-cert-file') @server_install_teardown def test_incorect_http_pin(self): "IPA server install with incorrect HTTP PKCS#12 password" self.create_pkcs12('ca1/server') self.prepare_cacert('ca1') result = self.install_server(http_pin='bad<pin>') assert_error(result, 'incorrect password for pkcs#12 file %s' % os.path.join(self.master.config.test_dir, 'server.p12')) @server_install_teardown def test_incorect_ds_pin(self): "IPA server install with incorrect DS PKCS#12 password" self.create_pkcs12('ca1/server') self.prepare_cacert('ca1') result = self.install_server(dirsrv_pin='bad<pin>') assert_error(result, 'incorrect password for pkcs#12 file %s' % os.path.join(self.master.config.test_dir, 'server.p12')) @server_install_teardown def test_invalid_http_cn(self): "IPA server install with HTTP certificate with invalid CN" self.create_pkcs12('ca1/server-badname', filename='http.p12') self.create_pkcs12('ca1/server', filename='dirsrv.p12') self.prepare_cacert('ca1') result = self.install_server(http_pkcs12='http.p12', dirsrv_pkcs12='dirsrv.p12') assert_error(result, 'The server certificate in %s/http.p12 is not valid: ' 'invalid for server %s' % (self.master.config.test_dir, self.master.hostname)) @server_install_teardown def test_invalid_ds_cn(self): "IPA server install with DS certificate with invalid CN" self.create_pkcs12('ca1/server', filename='http.p12') self.create_pkcs12('ca1/server-badname', filename='dirsrv.p12') self.prepare_cacert('ca1') result = self.install_server(http_pkcs12='http.p12', dirsrv_pkcs12='dirsrv.p12') assert_error(result, 'The server certificate in %s/dirsrv.p12 is not valid: ' 'invalid for server %s' % (self.master.config.test_dir, self.master.hostname)) @server_install_teardown def test_expired_http(self): "IPA server install with expired HTTP certificate" self.create_pkcs12('ca1/server-expired', filename='http.p12') self.create_pkcs12('ca1/server', filename='dirsrv.p12') self.prepare_cacert('ca1') result = self.install_server(http_pkcs12='http.p12', dirsrv_pkcs12='dirsrv.p12') pattern = re.compile( r'The server certificate in {dir}/http\.p12 is not valid: ' '.*has expired'.format(dir=re.escape(self.master.config.test_dir)) ) assert_error(result, pattern) @server_install_teardown def test_expired_ds(self): "IPA server install with expired DS certificate" self.create_pkcs12('ca1/server', filename='http.p12') self.create_pkcs12('ca1/server-expired', filename='dirsrv.p12') self.prepare_cacert('ca1') result = self.install_server(http_pkcs12='http.p12', dirsrv_pkcs12='dirsrv.p12') pattern = re.compile( r'The server certificate in {dir}/dirsrv\.p12 is not valid: ' '.*has expired'.format(dir=re.escape(self.master.config.test_dir)) ) assert_error(result, pattern) @server_install_teardown def test_http_bad_usage(self): "IPA server install with HTTP certificate with invalid key usage" self.create_pkcs12('ca1/server-badusage', filename='http.p12') self.create_pkcs12('ca1/server', filename='dirsrv.p12') self.prepare_cacert('ca1') result = self.install_server(http_pkcs12='http.p12', dirsrv_pkcs12='dirsrv.p12') assert_error(result, 'The server certificate in {dir}/http.p12 is not ' 'valid: {err}'.format(dir=self.master.config.test_dir, err=BAD_USAGE_MSG)) @server_install_teardown def test_ds_bad_usage(self): "IPA server install with DS certificate with invalid key usage" self.create_pkcs12('ca1/server', filename='http.p12') self.create_pkcs12('ca1/server-badusage', filename='dirsrv.p12') self.prepare_cacert('ca1') result = self.install_server(http_pkcs12='http.p12', dirsrv_pkcs12='dirsrv.p12') assert_error(result, 'The server certificate in {dir}/dirsrv.p12 is not ' 'valid: {err}'.format(dir=self.master.config.test_dir, err=BAD_USAGE_MSG)) @server_install_teardown def test_http_intermediate_ca(self): "IPA server install with HTTP certificate issued by intermediate CA" self.create_pkcs12('ca1/subca/server', filename='http.p12') self.create_pkcs12('ca1/server', filename='dirsrv.p12') self.prepare_cacert('ca1') result = self.install_server(http_pkcs12='http.p12', dirsrv_pkcs12='dirsrv.p12') assert_error(result, 'Apache Server SSL certificate and' ' Directory Server SSL certificate are not' ' signed by the same CA certificate') @server_install_teardown def test_ds_intermediate_ca(self): "IPA server install with DS certificate issued by intermediate CA" self.create_pkcs12('ca1/server', filename='http.p12') self.create_pkcs12('ca1/subca/server', filename='dirsrv.p12') self.prepare_cacert('ca1') result = self.install_server(http_pkcs12='http.p12', dirsrv_pkcs12='dirsrv.p12') assert_error(result, 'Apache Server SSL certificate and Directory Server SSL' ' certificate are not signed by the same CA certificate') @server_install_teardown def test_ca_self_signed(self): "IPA server install with self-signed certificate" self.create_pkcs12('server-selfsign') self.prepare_cacert('server-selfsign') result = self.install_server() assert result.returncode > 0 @server_install_teardown def test_valid_certs(self): "IPA server install with valid certificates" self.create_pkcs12('ca1/server') self.prepare_cacert('ca1') result = self.install_server() assert result.returncode == 0 self.verify_installation() @server_install_teardown def test_wildcard_http(self): "IPA server install with wildcard HTTP certificate" self.create_pkcs12('ca1/wildcard', filename='http.p12') self.create_pkcs12('ca1/server', filename='dirsrv.p12') self.prepare_cacert('ca1') result = self.install_server(http_pkcs12='http.p12', dirsrv_pkcs12='dirsrv.p12') assert result.returncode == 0 self.verify_installation() @server_install_teardown def test_wildcard_ds(self): "IPA server install with wildcard DS certificate" self.create_pkcs12('ca1/server', filename='http.p12') self.create_pkcs12('ca1/wildcard', filename='dirsrv.p12') self.prepare_cacert('ca1') result = self.install_server(http_pkcs12='http.p12', dirsrv_pkcs12='dirsrv.p12') assert result.returncode == 0 self.verify_installation() @server_install_teardown def test_http_san(self): "IPA server install with HTTP certificate with SAN" self.create_pkcs12('ca1/server-altname', filename='http.p12') self.create_pkcs12('ca1/server', filename='dirsrv.p12') self.prepare_cacert('ca1') result = self.install_server(http_pkcs12='http.p12', dirsrv_pkcs12='dirsrv.p12') assert result.returncode == 0 self.verify_installation() @server_install_teardown def test_ds_san(self): "IPA server install with DS certificate with SAN" self.create_pkcs12('ca1/server', filename='http.p12') self.create_pkcs12('ca1/server-altname', filename='dirsrv.p12') self.prepare_cacert('ca1') result = self.install_server(http_pkcs12='http.p12', dirsrv_pkcs12='dirsrv.p12') assert result.returncode == 0 self.verify_installation() @server_install_teardown def test_interactive_missing_http_pkcs_password(self): "IPA server install with prompt for HTTP PKCS#12 password" self.create_pkcs12('ca1/server') self.prepare_cacert('ca1') stdin_text = get_install_stdin(cert_passwords=[self.cert_password]) result = self.install_server(http_pin=None, unattended=False, stdin_text=stdin_text) assert result.returncode == 0 self.verify_installation() assert ('Enter Apache Server private key unlock password' in result.stdout_text), result.stdout_text @server_install_teardown def test_interactive_missing_ds_pkcs_password(self): "IPA server install with prompt for DS PKCS#12 password" self.create_pkcs12('ca1/server') self.prepare_cacert('ca1') stdin_text = get_install_stdin(cert_passwords=[self.cert_password]) result = self.install_server(dirsrv_pin=None, unattended=False, stdin_text=stdin_text) assert result.returncode == 0 self.verify_installation() assert ('Enter Directory Server private key unlock password' in result.stdout_text), result.stdout_text @server_install_teardown def test_no_http_password(self): "IPA server install with empty HTTP password" self.create_pkcs12('ca1/server', filename='http.p12', password='') self.create_pkcs12('ca1/server', filename='dirsrv.p12') self.prepare_cacert('ca1') result = self.install_server(http_pkcs12='http.p12', dirsrv_pkcs12='dirsrv.p12', http_pin='') assert result.returncode == 0 self.verify_installation() @server_install_teardown def test_no_ds_password(self): "IPA server install with empty DS password" self.create_pkcs12('ca1/server', filename='http.p12') self.create_pkcs12('ca1/server', filename='dirsrv.p12', password='') self.prepare_cacert('ca1') result = self.install_server(http_pkcs12='http.p12', dirsrv_pkcs12='dirsrv.p12', dirsrv_pin='') assert result.returncode == 0 self.verify_installation() class TestReplicaInstall(CALessBase): num_replicas = 1 @classmethod def install(cls, mh): super(TestReplicaInstall, cls).install(mh) cls.create_pkcs12('ca1/server') cls.prepare_cacert('ca1') result = cls.install_server() assert result.returncode == 0 cls.domain_level = tasks.domainlevel(cls.master) @replica_install_teardown def test_no_certs(self): "IPA replica install without certificates" result = self.prepare_replica(http_pkcs12_exists=False, dirsrv_pkcs12_exists=False) assert_error(result, "Cannot issue certificates: a CA is not " "installed. Use the --http-cert-file, " "--dirsrv-cert-file options to provide " "custom certificates.") @replica_install_teardown def test_nonexistent_http_pkcs12_file(self): "IPA replica install with non-existent DS PKCS#12 file" self.create_pkcs12('ca1/replica', filename='http.p12') result = self.prepare_replica(dirsrv_pkcs12='does_not_exist', http_pkcs12='http.p12') assert_error(result, 'Failed to open %s/does_not_exist' % self.master.config.test_dir) @replica_install_teardown def test_nonexistent_ds_pkcs12_file(self): "IPA replica install with non-existent HTTP PKCS#12 file" self.create_pkcs12('ca1/replica', filename='dirsrv.p12') result = self.prepare_replica(http_pkcs12='does_not_exist', dirsrv_pkcs12='dirsrv.p12') assert_error(result, 'Failed to open %s/does_not_exist' % self.master.config.test_dir) @replica_install_teardown def test_incorect_http_pin(self): "IPA replica install with incorrect HTTP PKCS#12 password" self.create_pkcs12('ca1/replica', filename='replica.p12') result = self.prepare_replica(http_pin='bad<pin>') assert result.returncode > 0 assert_error(result, 'incorrect password for pkcs#12 file %s' % os.path.join(self.replicas[0].config.test_dir, 'replica.p12')) @replica_install_teardown def test_incorect_ds_pin(self): "IPA replica install with incorrect DS PKCS#12 password" self.create_pkcs12('ca1/replica', filename='replica.p12') result = self.prepare_replica(dirsrv_pin='bad<pin>') assert_error(result, 'incorrect password for pkcs#12 file %s' % os.path.join(self.replicas[0].config.test_dir, 'replica.p12')) @replica_install_teardown def test_http_unknown_ca(self): "IPA replica install with HTTP certificate issued by unknown CA" self.create_pkcs12('ca2/replica', filename='http.p12') self.create_pkcs12('ca1/replica', filename='dirsrv.p12') result = self.prepare_replica(http_pkcs12='http.p12', dirsrv_pkcs12='dirsrv.p12') assert_error(result, 'Apache Server SSL certificate and' ' Directory Server SSL certificate are not' ' signed by the same CA certificate') @replica_install_teardown def test_ds_unknown_ca(self): "IPA replica install with DS certificate issued by unknown CA" self.create_pkcs12('ca1/replica', filename='http.p12') self.create_pkcs12('ca2/replica', filename='dirsrv.p12') result = self.prepare_replica(http_pkcs12='http.p12', dirsrv_pkcs12='dirsrv.p12') assert_error(result, 'Apache Server SSL certificate and Directory Server SSL' ' certificate are not signed by the same CA certificate') @replica_install_teardown def test_invalid_http_cn(self): "IPA replica install with HTTP certificate with invalid CN" self.create_pkcs12('ca1/replica-badname', filename='http.p12') self.create_pkcs12('ca1/replica', filename='dirsrv.p12') result = self.prepare_replica(http_pkcs12='http.p12', dirsrv_pkcs12='dirsrv.p12') assert_error(result, 'The server certificate in %s/http.p12 is not valid: ' 'invalid for server %s' % (self.master.config.test_dir, self.replicas[0].hostname)) @replica_install_teardown def test_invalid_ds_cn(self): "IPA replica install with DS certificate with invalid CN" self.create_pkcs12('ca1/replica', filename='http.p12') self.create_pkcs12('ca1/replica-badname', filename='dirsrv.p12') result = self.prepare_replica(http_pkcs12='http.p12', dirsrv_pkcs12='dirsrv.p12') assert_error(result, 'The server certificate in %s/dirsrv.p12 is not valid: ' 'invalid for server %s' % (self.master.config.test_dir, self.replicas[0].hostname)) @replica_install_teardown def test_expired_http(self): "IPA replica install with expired HTTP certificate" self.create_pkcs12('ca1/replica-expired', filename='http.p12') self.create_pkcs12('ca1/replica', filename='dirsrv.p12') result = self.prepare_replica(http_pkcs12='http.p12', dirsrv_pkcs12='dirsrv.p12') pattern = re.compile( r'The server certificate in {dir}/http\.p12 is not valid: ' '.*has expired'.format(dir=re.escape(self.master.config.test_dir)) ) assert_error(result, pattern) @replica_install_teardown def test_expired_ds(self): "IPA replica install with expired DS certificate" self.create_pkcs12('ca1/replica', filename='http.p12') self.create_pkcs12('ca1/replica-expired', filename='dirsrv.p12') result = self.prepare_replica(http_pkcs12='http.p12', dirsrv_pkcs12='dirsrv.p12') pattern = re.compile( r'The server certificate in {dir}/dirsrv\.p12 is not valid: ' '.*has expired'.format(dir=re.escape(self.master.config.test_dir)) ) assert_error(result, pattern) @replica_install_teardown def test_http_bad_usage(self): "IPA replica install with HTTP certificate with invalid key usage" self.create_pkcs12('ca1/replica-badusage', filename='http.p12') self.create_pkcs12('ca1/replica', filename='dirsrv.p12') result = self.prepare_replica(http_pkcs12='http.p12', dirsrv_pkcs12='dirsrv.p12') assert_error(result, 'The server certificate in {dir}/http.p12 is not ' 'valid: {err}'.format(dir=self.master.config.test_dir, err=BAD_USAGE_MSG)) @replica_install_teardown def test_ds_bad_usage(self): "IPA replica install with DS certificate with invalid key usage" self.create_pkcs12('ca1/replica', filename='http.p12') self.create_pkcs12('ca1/replica-badusage', filename='dirsrv.p12') result = self.prepare_replica(http_pkcs12='http.p12', dirsrv_pkcs12='dirsrv.p12') assert_error(result, 'The server certificate in {dir}/dirsrv.p12 is not ' 'valid: {err}'.format(dir=self.master.config.test_dir, err=BAD_USAGE_MSG)) @replica_install_teardown def test_http_intermediate_ca(self): "IPA replica install with HTTP certificate issued by intermediate CA" self.create_pkcs12('ca1/subca/replica', filename='http.p12') self.create_pkcs12('ca1/replica', filename='dirsrv.p12') result = self.prepare_replica(http_pkcs12='http.p12', dirsrv_pkcs12='dirsrv.p12') assert_error(result, 'Apache Server SSL certificate and Directory Server SSL' ' certificate are not signed by the same CA certificate') @replica_install_teardown def test_ds_intermediate_ca(self): "IPA replica install with DS certificate issued by intermediate CA" self.create_pkcs12('ca1/replica', filename='http.p12') self.create_pkcs12('ca1/subca/replica', filename='dirsrv.p12') result = self.prepare_replica(http_pkcs12='http.p12', dirsrv_pkcs12='dirsrv.p12') assert_error(result, 'Apache Server SSL certificate and' ' Directory Server SSL certificate are not' ' signed by the same CA certificate') @replica_install_teardown def test_caless_with_incompatible_options(self): "IPA replica install with certificates but conflicting --setup-ca" self.create_pkcs12('ca1/replica', filename='server.p12') result = self.prepare_replica(http_pkcs12='server.p12', dirsrv_pkcs12='server.p12', force_setup_ca=True) assert_error(result, '--setup-ca and --*-cert-file options are ' 'mutually exclusive') @replica_install_teardown def test_valid_certs(self): "IPA replica install with valid certificates" self.create_pkcs12('ca1/replica', filename='server.p12') result = self.prepare_replica(http_pkcs12='server.p12', dirsrv_pkcs12='server.p12') assert result.returncode == 0 self.verify_installation() @replica_install_teardown def test_wildcard_http(self): "IPA replica install with wildcard HTTP certificate" self.create_pkcs12('ca1/wildcard', filename='http.p12') self.create_pkcs12('ca1/replica', filename='dirsrv.p12') result = self.prepare_replica(http_pkcs12='http.p12', dirsrv_pkcs12='dirsrv.p12') assert result.returncode == 0 self.verify_installation() @replica_install_teardown def test_wildcard_ds(self): "IPA replica install with wildcard DS certificate" self.create_pkcs12('ca1/wildcard', filename='http.p12') self.create_pkcs12('ca1/replica', filename='dirsrv.p12') result = self.prepare_replica(http_pkcs12='http.p12', dirsrv_pkcs12='dirsrv.p12') assert result.returncode == 0 self.verify_installation() @replica_install_teardown def test_http_san(self): "IPA replica install with HTTP certificate with SAN" self.create_pkcs12('ca1/replica-altname', filename='http.p12') self.create_pkcs12('ca1/replica', filename='dirsrv.p12') result = self.prepare_replica(http_pkcs12='http.p12', dirsrv_pkcs12='dirsrv.p12') assert result.returncode == 0 self.verify_installation() @replica_install_teardown def test_ds_san(self): "IPA replica install with DS certificate with SAN" self.create_pkcs12('ca1/replica', filename='http.p12') self.create_pkcs12('ca1/replica-altname', filename='dirsrv.p12') result = self.prepare_replica(http_pkcs12='http.p12', dirsrv_pkcs12='dirsrv.p12') assert result.returncode == 0 self.verify_installation() @replica_install_teardown def test_interactive_missing_http_pkcs_password(self): "IPA replica install with missing HTTP PKCS#12 password" self.create_pkcs12('ca1/replica', filename='replica.p12') stdin_text = get_replica_prepare_stdin( cert_passwords=[self.cert_password]) result = self.prepare_replica(http_pin=None, unattended=False, stdin_text=stdin_text) assert result.returncode == 0 self.verify_installation() @replica_install_teardown def test_interactive_missing_ds_pkcs_password(self): "IPA replica install with missing DS PKCS#12 password" self.create_pkcs12('ca1/replica', filename='replica.p12') stdin_text = get_replica_prepare_stdin( cert_passwords=[self.cert_password]) result = self.prepare_replica(dirsrv_pin=None, unattended=False, stdin_text=stdin_text) assert result.returncode == 0 self.verify_installation() @replica_install_teardown def test_no_http_password(self): "IPA replica install with empty HTTP password" self.create_pkcs12('ca1/replica', filename='http.p12', password='') self.create_pkcs12('ca1/replica', filename='dirsrv.p12') result = self.prepare_replica(http_pkcs12='http.p12', dirsrv_pkcs12='dirsrv.p12', http_pin='') assert result.returncode == 0 self.verify_installation() @replica_install_teardown def test_no_ds_password(self): "IPA replica install with empty DS password" self.create_pkcs12('ca1/replica', filename='http.p12') self.create_pkcs12('ca1/replica', filename='dirsrv.p12', password='') result = self.prepare_replica(http_pkcs12='http.p12', dirsrv_pkcs12='dirsrv.p12', dirsrv_pin='') assert result.returncode == 0 self.verify_installation() @replica_install_teardown def test_certs_with_no_password(self): # related to https://pagure.io/freeipa/issue/7274 self.create_pkcs12('ca1/replica', filename='http.p12', password='') self.create_pkcs12('ca1/replica', filename='dirsrv.p12', password='') self.prepare_cacert('ca1') self.prepare_replica(http_pkcs12='http.p12', dirsrv_pkcs12='dirsrv.p12', http_pin='', dirsrv_pin='') self.verify_installation() @replica_install_teardown def test_certs_with_no_password_interactive(self): # related to https://pagure.io/freeipa/issue/7274 self.create_pkcs12('ca1/replica', filename='http.p12', password='') self.create_pkcs12('ca1/replica', filename='dirsrv.p12', password='') self.prepare_cacert('ca1') stdin_text = '\n\nyes' result = self.prepare_replica(http_pkcs12='http.p12', dirsrv_pkcs12='dirsrv.p12', http_pin=None, dirsrv_pin=None, unattended=False, stdin_text=stdin_text) assert result.returncode == 0 self.verify_installation() class TestClientInstall(CALessBase): num_clients = 1 def test_client_install(self): "IPA client install" self.create_pkcs12('ca1/server') self.prepare_cacert('ca1') result = self.install_server() assert result.returncode == 0 self.clients[0].run_command(['ipa-client-install', '--domain', self.master.domain.name, '--server', self.master.hostname, '-p', self.master.config.admin_name, '-w', self.master.config.admin_password, '-U']) self.verify_installation() class TestIPACommands(CALessBase): @classmethod def install(cls, mh): super(TestIPACommands, cls).install(mh) cls.create_pkcs12('ca1/server') cls.prepare_cacert('ca1') result = cls.install_server() assert result.returncode == 0 tasks.kinit_admin(cls.master) cls.client_pem = ''.join(cls.get_pem('ca1/client').splitlines()[1:-1]) logger.debug('Client PEM:\n%r', cls.client_pem) cls.test_hostname = 'testhost.%s' % cls.master.domain.name cls.test_service = 'test/%s' % cls.test_hostname def check_ipa_command_not_available(self, command): "Verify that the given IPA subcommand is not available" result = self.master.run_command(['ipa', command], raiseonerr=False) assert_error(result, "ipa: ERROR: unknown command '%s'" % command) @contextlib.contextmanager def host(self): "Context manager that adds and removes a host entry with a certificate" self.master.run_command(['ipa', 'host-add', self.test_hostname, '--force', '--certificate', self.client_pem]) self.master.run_command(['ipa-getkeytab', '-s', self.master.hostname, '-p' "host/%s" % self.test_hostname, '-k', paths.HTTP_KEYTAB]) try: yield finally: self.master.run_command(['ipa', 'host-del', self.test_hostname], raiseonerr=False) @contextlib.contextmanager def service(self): "Context manager that adds and removes host & service entries" with self.host(): self.master.run_command(['ipa', 'service-add', self.test_service, '--force', '--certificate', self.client_pem]) self.master.run_command(['ipa-getkeytab', '-s', self.master.hostname, '-p', self.test_service, '-k', paths.HTTP_KEYTAB]) yield def test_service_mod_doesnt_revoke(self): "Verify that service-mod does not attempt to revoke certificate" with self.service(): self.master.run_command(['ipa', 'service-mod', self.test_service, '--certificate=']) def test_service_disable_doesnt_revoke(self): "Verify that service-disable does not attempt to revoke certificate" with self.service(): result = self.master.run_command(['ipa', 'service-disable', self.test_service], raiseonerr=False) assert(result.returncode == 0), ( "Failed to disable ipa-service: %s" % result.stderr_text) def test_service_del_doesnt_revoke(self): "Verify that service-del does not attempt to revoke certificate" with self.service(): self.master.run_command(['ipa', 'service-del', self.test_service]) def test_host_mod_doesnt_revoke(self): "Verify that host-mod does not attempt to revoke host's certificate" with self.host(): self.master.run_command(['ipa', 'host-mod', self.test_hostname, '--certificate=']) def test_host_disable_doesnt_revoke(self): "Verify that host-disable does not attempt to revoke host certificate" with self.host(): self.master.run_command(['ipa', 'host-disable', self.test_hostname]) def test_host_del_doesnt_revoke(self): "Verify that host-del does not attempt to revoke host's certificate" with self.host(): self.master.run_command(['ipa', 'host-del', self.test_hostname]) def test_invoke_upgrader(self): """Test that ipa-server-upgrade runs without error.""" self.master.run_command(['ipa-server-upgrade'], raiseonerr=True) class TestCertInstall(CALessBase): @classmethod def install(cls, mh): super(TestCertInstall, cls).install(mh) cls.create_pkcs12('ca1/server') cls.prepare_cacert('ca1') result = cls.install_server() assert result.returncode == 0 tasks.kinit_admin(cls.master) def certinstall(self, mode, cert_nick=None, cert_exists=True, filename='server.p12', pin=_DEFAULT, stdin_text=None, p12_pin=None, args=None): if cert_nick: self.create_pkcs12(cert_nick, password=p12_pin, filename=filename) if pin is _DEFAULT: pin = self.cert_password if cert_exists: self.copy_cert(self.master, filename) if not args: args = ['ipa-server-certinstall', '-p', self.master.config.dirman_password, '-%s' % mode, filename] if pin is not None: args += ['--pin', pin] return self.master.run_command(args, raiseonerr=False, stdin_text=stdin_text) def test_nonexistent_http_pkcs12_file(self): "Install new HTTP certificate from non-existent PKCS#12 file" result = self.certinstall('w', filename='does_not_exist', pin='none', cert_exists=False) assert_error(result, 'Failed to open does_not_exist') def test_nonexistent_ds_pkcs12_file(self): "Install new DS certificate from non-existent PKCS#12 file" result = self.certinstall('d', filename='does_not_exist', pin='none', cert_exists=False) assert_error(result, 'Failed to open does_not_exist') def test_incorect_http_pin(self): "Install new HTTP certificate with incorrect PKCS#12 password" result = self.certinstall('w', 'ca1/server', pin='bad<pin>') assert_error(result, 'incorrect password for pkcs#12 file server.p12') def test_incorect_dirsrv_pin(self): "Install new DS certificate with incorrect PKCS#12 password" result = self.certinstall('d', 'ca1/server', pin='bad<pin>') assert_error(result, 'incorrect password for pkcs#12 file server.p12') def test_invalid_http_cn(self): "Install new HTTP certificate with invalid CN " result = self.certinstall('w', 'ca1/server-badname') assert_error(result, 'The server certificate in server.p12 is not valid: ' 'invalid for server %s' % self.master.hostname) def test_invalid_ds_cn(self): "Install new DS certificate with invalid CN " result = self.certinstall('d', 'ca1/server-badname') assert_error(result, 'The server certificate in server.p12 is not valid: ' 'invalid for server %s' % self.master.hostname) def _test_expired_service_cert(self, w_or_d): """Install new expired HTTP/DS certificate.""" result = self.certinstall(w_or_d, 'ca1/server-expired') pattern = re.compile( r'The server certificate in server\.p12 is not valid: ' '.*has expired' ) assert_error(result, pattern) def test_expired_http(self): self._test_expired_service_cert('w') def test_expired_ds(self): self._test_expired_service_cert('d') def _test_not_yet_valid_service_cert(self, w_or_d): """Install new not-yet-valid HTTP/DS certificate.""" result = self.certinstall(w_or_d, 'ca1/server-not-yet-valid') pattern = re.compile( r'The server certificate in server\.p12 is not valid: ' '.*not valid before .* is in the future' ) assert_error(result, pattern) def test_not_yet_valid_http(self): self._test_not_yet_valid_service_cert('w') def test_not_yet_valid_ds(self): self._test_not_yet_valid_service_cert('d') def test_http_bad_usage(self): "Install new HTTP certificate with invalid key usage" result = self.certinstall('w', 'ca1/server-badusage') assert_error(result, 'The server certificate in server.p12 is not valid: {err}' .format(err=BAD_USAGE_MSG)) def test_ds_bad_usage(self): "Install new DS certificate with invalid key usage" result = self.certinstall('d', 'ca1/server-badusage') assert_error(result, 'The server certificate in server.p12 is not valid: {err}' .format(err=BAD_USAGE_MSG)) def test_http_intermediate_ca(self): "Install new HTTP certificate issued by intermediate CA" result = self.certinstall('w', 'ca1/subca/server') assert result.returncode == 0, result.stderr_text @pytest.mark.xfail(reason='freeipa ticket 6959', strict=True) def test_ds_intermediate_ca(self): "Install new DS certificate issued by intermediate CA" result = self.certinstall('d', 'ca1/subca/server') assert result.returncode == 0, result.stderr_text def test_self_signed(self): "Install new self-signed certificate" result = self.certinstall('w', 'server-selfsign') assert_error(result, 'The full certificate chain is not present in server.p12') def test_valid_http(self): "Install new valid HTTP certificate" result = self.certinstall('w', 'ca1/server') assert result.returncode == 0 def test_valid_ds(self): "Install new valid DS certificate" result = self.certinstall('d', 'ca1/server') assert result.returncode == 0 def test_wildcard_http(self): "Install new wildcard HTTP certificate" result = self.certinstall('w', 'ca1/wildcard') assert result.returncode == 0 def test_wildcard_ds(self): "Install new wildcard DS certificate" result = self.certinstall('d', 'ca1/wildcard') assert result.returncode == 0 def test_http_san(self): "Install new HTTP certificate with SAN" result = self.certinstall('w', 'ca1/server-altname') assert result.returncode == 0 def test_ds_san(self): "Install new DS certificate with SAN" result = self.certinstall('d', 'ca1/server-altname') assert result.returncode == 0 def test_interactive_missing_http_pkcs_password(self): "Install new HTTP certificate with missing PKCS#12 password" result = self.certinstall('w', 'ca1/server', pin=None, stdin_text=self.cert_password + '\n') assert result.returncode == 0 def test_interactive_missing_ds_pkcs_password(self): "Install new DS certificate with missing PKCS#12 password" result = self.certinstall('d', 'ca1/server', pin=None, stdin_text=self.cert_password + '\n') assert result.returncode == 0 def test_no_http_password(self): "Install new HTTP certificate with no PKCS#12 password" result = self.certinstall('w', 'ca1/server', pin='', p12_pin='') assert result.returncode == 0 def test_no_ds_password(self): "Install new DS certificate with no PKCS#12 password" result = self.certinstall('d', 'ca1/server', pin='', p12_pin='') assert result.returncode == 0 def test_http_old_options(self): "Install new valid DS certificate using pre-v3.3 CLI options" # http://www.freeipa.org/page/V3/ipa-server-certinstall_CLI_cleanup args = ['ipa-server-certinstall', '-w', 'server.p12', '--http-pin', self.cert_password] result = self.certinstall('w', 'ca1/server', args=args) assert_error(result, "no such option: --http-pin") def test_ds_old_options(self): "Install new valid DS certificate using pre-v3.3 CLI options" # http://www.freeipa.org/page/V3/ipa-server-certinstall_CLI_cleanup args = ['ipa-server-certinstall', '-d', 'server.p12', '--dirsrv-pin', self.cert_password] stdin_text = self.master.config.dirman_password + '\n' result = self.certinstall('d', 'ca1/server', args=args, stdin_text=stdin_text) assert_error(result, "no such option: --dirsrv-pin") def test_anon_pkinit_with_external_CA(self): test_dir = self.master.config.test_dir self.prepare_cacert('ca2', filename=self.ca2_crt) self.copy_cert(self.master, self.ca2_crt) result = self.master.run_command(['ipa-cacert-manage', 'install', os.path.join(test_dir, self.ca2_crt)] ) assert result.returncode == 0 result = self.master.run_command(['ipa-certupdate']) assert result.returncode == 0 result = self.certinstall('k', 'ca2/server-kdc', filename=self.ca2_kdc_crt) assert result.returncode == 0 result = self.master.run_command(['systemctl', 'restart', 'krb5kdc']) assert result.returncode == 0 result = self.master.run_command(['kinit', '-n']) assert result.returncode == 0 def verify_kdc_cert_perms(host): """Verify that the KDC cert pem file has 0644 perms""" cmd = host.run_command(['stat', '-c', '"%a %G:%U"', paths.KDC_CERT]) assert "644 root:root" in cmd.stdout_text class TestPKINIT(CALessBase): """Install master and replica with PKINIT""" num_replicas = 1 @classmethod def install(cls, mh): super(TestPKINIT, cls).install(mh) cls.create_pkcs12('ca1/server') cls.create_pkcs12('ca1/server-kdc', filename='server-kdc.p12') cls.prepare_cacert('ca1') result = cls.install_server(pkinit_pkcs12_exists=True, pkinit_pin=_DEFAULT) assert result.returncode == 0 verify_kdc_cert_perms(cls.master) @replica_install_teardown def test_server_replica_install_pkinit(self): self.create_pkcs12('ca1/replica', filename='replica.p12') self.create_pkcs12('ca1/replica-kdc', filename='replica-kdc.p12') result = self.prepare_replica(pkinit_pkcs12_exists=True, pkinit_pin=_DEFAULT) assert result.returncode == 0 self.verify_installation() verify_kdc_cert_perms(self.replicas[0]) class TestServerReplicaCALessToCAFull(CALessBase): """ Test server and replica caless to cafull scenario: Master (caless) / replica (caless) >> master (ca) / replica (ca) """ num_replicas = 1 def test_install_caless_server_replica(self): """Install CA-less master and replica""" self.create_pkcs12('ca1/server') self.prepare_cacert('ca1') master = self.install_server() assert master.returncode == 0 self.create_pkcs12('ca1/replica', filename='replica.p12') replica = self.prepare_replica() assert replica.returncode == 0 def test_server_ipa_ca_install(self): """Install CA on master""" tasks.install_ca(self.master) # We are not calling ipa-certupdate on replica here since the next step # installs CA clone there. ca_show = self.master.run_command(['ipa', 'ca-show', 'ipa']) assert 'Subject DN: CN=Certificate Authority,O={}'.format( self.master.domain.realm) in ca_show.stdout_text def test_replica_ipa_ca_install(self): """Install CA on replica""" replica = self.replicas[0] tasks.install_ca(replica) ca_show = replica.run_command(['ipa', 'ca-show', 'ipa']) assert 'Subject DN: CN=Certificate Authority,O={}'.format( self.master.domain.realm) in ca_show.stdout_text class TestReplicaCALessToCAFull(CALessBase): """ Test replica caless to cafull when master stays caless scenario: Master (caless) / replica (caless) >> replica (ca) """ num_replicas = 1 def test_install_caless_server_replica(self): """Install CA-less master and replica""" self.create_pkcs12('ca1/server') self.prepare_cacert('ca1') master = self.install_server() assert master.returncode == 0 self.create_pkcs12('ca1/replica', filename='replica.p12') replica = self.prepare_replica() assert replica.returncode == 0 def test_replica_ipa_ca_install(self): """Install CA on replica (master caless)""" ca_replica = tasks.install_ca(self.replicas[0]) assert ca_replica.returncode == 0 class TestServerCALessToExternalCA(CALessBase): """Test server caless to extarnal CA scenario""" def test_install_caless_server(self): """Install CA-less master""" self.create_pkcs12('ca1/server') self.prepare_cacert('ca1') master = self.install_server() assert master.returncode == 0 def test_server_ipa_ca_install_external(self): """Install external CA on master""" # First step of ipa-ca-install (get CSR) ca_master_pre = tasks.install_ca(self.master, external_ca=True) assert ca_master_pre.returncode == 0 # Create external CA external_ca = ExternalCA() root_ca = external_ca.create_ca() # Get IPA CSR as string ipa_csr = self.master.get_file_contents('/root/ipa.csr') # Have CSR signed by the external CA ipa_ca = external_ca.sign_csr(ipa_csr) test_dir = self.master.config.test_dir root_ca_fname = os.path.join(test_dir, 'root_ca.crt') ipa_ca_fname = os.path.join(test_dir, 'ipa_ca.crt') # Transport certificates (string > file) to master self.master.put_file_contents(root_ca_fname, root_ca) self.master.put_file_contents(ipa_ca_fname, ipa_ca) cert_files = [root_ca_fname, ipa_ca_fname] # Continue with ipa-ca-install ca_master_post = tasks.install_ca(self.master, cert_files=cert_files) assert ca_master_post.returncode == 0
66,148
Python
.py
1,331
37.543952
79
0.601353
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,556
test_smb.py
freeipa_freeipa/ipatests/test_integration/test_smb.py
# # Copyright (C) 2019 FreeIPA Contributors see COPYING for license # """This module provides tests for SMB-related features like configuring Samba file server and mounting SMB file system """ from __future__ import absolute_import from functools import partial import textwrap import re import os import pytest from ipatests.test_integration.base import IntegrationTest from ipatests.pytest_ipa.integration import tasks from ipaplatform.osinfo import osinfo from ipaplatform.paths import paths from ipatests.pytest_ipa.integration import skip_if_fips def wait_smbd_functional(host): """Wait smbd is functional after (re)start After start of smbd there is a 2-3 seconds delay before daemon is fully functional and clients can successfuly mount a share. The ping command effectively blocks until the daemon is ready. """ host.run_command(['smbcontrol', 'smbd', 'ping']) class TestSMB(IntegrationTest): topology = 'star' num_clients = 2 num_ad_domains = 1 ipa_user1 = 'user1' ipa_user1_password = 'SecretUser1' ipa_user2 = 'user2' ipa_user2_password = 'SecretUser2' ad_user_login = 'testuser' ad_user_password = 'Secret123' ipa_test_group = 'ipa_testgroup' ad_test_group = 'testgroup' @classmethod def install(cls, mh): if cls.domain_level is not None: domain_level = cls.domain_level else: domain_level = cls.master.config.domain_level tasks.install_topo(cls.topology, cls.master, cls.replicas, cls.clients, domain_level, clients_extra_args=('--mkhomedir',)) cls.ad = cls.ads[0] cls.smbserver = cls.clients[0] cls.smbclient = cls.clients[1] cls.ad_user = '{}@{}'.format(cls.ad_user_login, cls.ad.domain.name) tasks.install_adtrust(cls.master) tasks.configure_dns_for_trust(cls.master, cls.ad) tasks.configure_windows_dns_for_trust(cls.ad, cls.master) tasks.establish_trust_with_ad(cls.master, cls.ad.domain.name, extra_args=['--two-way=true']) tasks.create_active_user(cls.master, cls.ipa_user1, password=cls.ipa_user1_password) tasks.create_active_user(cls.master, cls.ipa_user2, password=cls.ipa_user2_password) # Trigger creation of home directories on the SMB server for user in [cls.ipa_user1, cls.ipa_user2, cls.ad_user]: tasks.run_command_as_user(cls.smbserver, user, ['stat', '.']) @pytest.fixture def samba_share_public(self): """Setup share outside /home on samba server.""" share_name = 'shared' share_path = '/srv/samba_shared' smbserver = self.smbserver smbserver.run_command(['mkdir', share_path]) smbserver.run_command(['chmod', '777', share_path]) # apply selinux context only if selinux is enabled if tasks.is_selinux_enabled(smbserver): smbserver.run_command(['chcon', '-t', 'samba_share_t', share_path]) with tasks.FileBackup(smbserver, paths.SMB_CONF): smb_conf = smbserver.get_file_contents( paths.SMB_CONF, encoding='utf-8') smb_conf += textwrap.dedent(''' [{name}] path = {path} writable = yes browsable=yes '''.format(name=share_name, path=share_path)) smbserver.put_file_contents(paths.SMB_CONF, smb_conf) smbserver.run_command(['systemctl', 'restart', 'smb']) wait_smbd_functional(smbserver) yield { 'name': share_name, 'server_path': share_path, 'unc': '//{}/{}'.format(smbserver.hostname, share_name) } smbserver.run_command(['systemctl', 'restart', 'smb']) wait_smbd_functional(smbserver) smbserver.run_command(['rmdir', share_path]) def mount_smb_share(self, user, password, share, mountpoint): tasks.kdestroy_all(self.smbclient) tasks.kinit_as_user(self.smbclient, user, password) self.smbclient.run_command(['mkdir', '-p', mountpoint]) self.smbclient.run_command([ 'mount', '-t', 'cifs', share['unc'], mountpoint, '-o', 'sec=krb5i,multiuser' ]) tasks.kdestroy_all(self.smbclient) def smb_sanity_check(self, user, client_mountpoint, share): test_dir = 'testdir_{}'.format(user) test_file = 'testfile_{}'.format(user) test_file_path = '{}/{}'.format(test_dir, test_file) test_string = 'Hello, world!' run_smb_client = partial(tasks.run_command_as_user, self.smbclient, user, cwd=client_mountpoint) run_smb_server = partial(self.smbserver.run_command, cwd=share['server_path']) try: # check creation of directory from client side run_smb_client(['mkdir', test_dir]) # check dir properties at client side res = run_smb_client(['stat', '-c', '%n %U %G', test_dir]) assert res.stdout_text == '{0} {1} {1}\n'.format(test_dir, user) # check dir properties at server side res = run_smb_server(['stat', '-c', '%n %U %G', test_dir]) assert res.stdout_text == '{0} {1} {1}\n'.format(test_dir, user) # check creation of file from client side run_smb_client('printf "{}" > {}'.format( test_string, test_file_path)) # check file is listed at client side res = run_smb_client(['ls', test_dir]) assert res.stdout_text == test_file + '\n' # check file is listed at server side res = run_smb_server(['ls', test_dir]) assert res.stdout_text == test_file + '\n' # check file properties at server side res = run_smb_server(['stat', '-c', '%n %s %U %G', test_file_path]) assert res.stdout_text == '{0} {1} {2} {2}\n'.format( test_file_path, len(test_string), user) # check file properties at client side res = run_smb_client(['stat', '-c', '%n %s %U %G', test_file_path]) assert res.stdout_text == '{0} {1} {2} {2}\n'.format( test_file_path, len(test_string), user) # check file contents at client side res = run_smb_client(['cat', test_file_path]) assert res.stdout_text == test_string # check file contents at server side file_contents_at_server = self.smbserver.get_file_contents( '{}/{}'.format(share['server_path'], test_file_path), encoding='utf-8') assert file_contents_at_server == test_string # Detect whether smbclient uses -k or --use-kerberos=required # https://pagure.io/freeipa/issue/8926 # then check access using smbclient. res = run_smb_client( [ "smbclient", "-h", ], raiseonerr=False ) if "[-k|--kerberos]" in res.stderr_text: smbclient_krb5_knob = "-k" else: smbclient_krb5_knob = "--use-kerberos=desired" res = run_smb_client( [ "smbclient", smbclient_krb5_knob, share["unc"], "-c", "dir", ] ) assert test_dir in res.stdout_text # check file and dir removal from client side run_smb_client(['rm', test_file_path]) run_smb_client(['rmdir', test_dir]) # check dir does not exist at client side res = run_smb_client(['stat', test_dir], raiseonerr=False) assert res.returncode == 1 assert 'No such file or directory' in res.stderr_text # check dir does not exist at server side res = run_smb_server(['stat', test_dir], raiseonerr=False) assert res.returncode == 1 assert 'No such file or directory' in res.stderr_text finally: run_smb_server(['rm', '-rf', test_dir], raiseonerr=False) def smb_installation_check(self, result): domain_regexp_tpl = r''' Domain\ name:\s*{domain}\n \s*NetBIOS\ name:\s*{netbios}\n \s*SID:\s*S-1-5-21-\d+-\d+-\d+\n \s+ID\ range:\s*\d+\s*-\s*\d+ ''' ipa_regexp = domain_regexp_tpl.format( domain=re.escape(self.master.domain.name), netbios=self.master.netbios) ad_regexp = domain_regexp_tpl.format( domain=re.escape(self.ad.domain.name), netbios=self.ad.netbios) output_regexp = r''' Discovered\ domains.* {} .* {} .* Samba.+configured.+check.+/etc/samba/smb\.conf '''.format(ipa_regexp, ad_regexp) assert re.search(output_regexp, result.stdout_text, re.VERBOSE | re.DOTALL) def cleanup_mount(self, mountpoint): self.smbclient.run_command(['umount', mountpoint], raiseonerr=False) self.smbclient.run_command(['rmdir', mountpoint], raiseonerr=False) def test_samba_uninstallation_without_installation(self): res = self.smbserver.run_command( ['ipa-client-samba', '--uninstall', '-U']) assert res.stdout_text == 'Samba domain member is not configured yet\n' def test_install_samba(self): samba_install_result = self.smbserver.run_command( ['ipa-client-samba', '-U']) # smb and winbind are expected to be not running for service in ['smb', 'winbind']: result = self.smbserver.run_command( ['systemctl', 'status', service], raiseonerr=False) assert result.returncode == 3 self.smbserver.run_command([ 'systemctl', 'enable', '--now', 'smb', 'winbind' ]) wait_smbd_functional(self.smbserver) # check that smb and winbind started successfully for service in ['smb', 'winbind']: self.smbserver.run_command(['systemctl', 'status', service]) # print status for debugging purposes self.smbserver.run_command(['smbstatus']) # checks postponed till the end of method to be sure services are # started - this way we prevent other tests from failing self.smb_installation_check(samba_install_result) def test_authentication_with_smb_cifs_principal_alias(self): """Test that we can auth as NetBIOS alias cifs/... principal on SMB server side has NetBIOS name of the SMB server as its alias. Test that we can actually initialize credentials using this alias. We don't need to use it anywhere in Samba, just verify that alias works. Test for https://pagure.io/freeipa/issue/8291""" netbiosname = self.smbserver.hostname.split('.')[0].upper() + '$' copier = tasks.KerberosKeyCopier(self.smbserver) principal = 'cifs/{hostname}@{realm}'.format( hostname=self.smbserver.hostname, realm=copier.realm) alias = '{netbiosname}@{realm}'.format( netbiosname=netbiosname, realm=copier.realm) replacement = {principal: alias} tmpname = tasks.create_temp_file(self.smbserver, create_file=False) try: copier.copy_keys(paths.SAMBA_KEYTAB, tmpname, principal=principal, replacement=replacement) self.smbserver.run_command(['kinit', '-kt', tmpname, netbiosname]) finally: self.smbserver.run_command(['rm', '-f', tmpname]) def test_samba_service_listed(self): """Check samba service is listed. Regression test for https://bugzilla.redhat.com/show_bug.cgi?id=1731433 """ service_name = 'cifs/{}@{}'.format( self.smbserver.hostname, self.smbserver.domain.name.upper()) tasks.kinit_admin(self.master) res = self.master.run_command( ['ipa', 'service-show', '--raw', service_name]) expected_output = 'krbprincipalname: {}\n'.format(service_name) assert expected_output in res.stdout_text res = self.master.run_command( ['ipa', 'service-find', '--raw', service_name]) assert expected_output in res.stdout_text def check_smb_access_at_ipa_client(self, user, password, samba_share): mount_point = '/mnt/smb' self.mount_smb_share(user, password, samba_share, mount_point) try: tasks.run_command_as_user(self.smbclient, user, ['kdestroy', '-A']) tasks.run_command_as_user(self.smbclient, user, ['kinit', user], stdin_text=password + '\n') self.smb_sanity_check(user, mount_point, samba_share) finally: self.cleanup_mount(mount_point) def test_smb_access_for_ipa_user_at_ipa_client(self): samba_share = { 'name': 'homes', 'server_path': '/home/{}'.format(self.ipa_user1), 'unc': '//{}/homes'.format(self.smbserver.hostname) } self.check_smb_access_at_ipa_client( self.ipa_user1, self.ipa_user1_password, samba_share) def test_smb_access_for_ad_user_at_ipa_client(self): samba_share = { 'name': 'homes', 'server_path': '/home/{}/{}'.format(self.ad.domain.name, self.ad_user_login), 'unc': '//{}/homes'.format(self.smbserver.hostname) } self.check_smb_access_at_ipa_client( self.ad_user, self.ad_user_password, samba_share) def test_smb_mount_and_access_by_different_users(self, samba_share_public): user1 = self.ipa_user1 password1 = self.ipa_user1_password user2 = self.ipa_user2 password2 = self.ipa_user2_password mount_point = '/mnt/smb' try: self.mount_smb_share(user1, password1, samba_share_public, mount_point) tasks.run_command_as_user(self.smbclient, user2, ['kdestroy', '-A']) tasks.run_command_as_user(self.smbclient, user2, ['kinit', user2], stdin_text=password2 + '\n') self.smb_sanity_check(user2, mount_point, samba_share_public) finally: self.cleanup_mount(mount_point) @pytest.mark.skipif( osinfo.id == 'fedora' and osinfo.version_number <= (31,), reason='Test requires krb 1.18') def test_smb_service_s4u2self(self): """Test S4U2Self operation by IPA service against both AD and IPA users """ script = textwrap.dedent("""export KRB5_TRACE=/dev/stderr kdestroy -A kinit -kt /etc/samba/samba.keytab {principal} klist -f {print_pac} -k /etc/samba/samba.keytab -E impersonate {user_princ} klist -f """) principal = 'cifs/{hostname}'.format( hostname=self.smbserver.hostname) # Copy ipa-print-pac to SMB server # We can do so because Samba and GSSAPI libraries # are present there print_pac = self.master.get_file_contents( os.path.join(paths.LIBEXEC_IPA_DIR, "ipa-print-pac")) result = self.smbserver.run_command(['mktemp']) tmpname = result.stdout_text.strip() self.smbserver.put_file_contents(tmpname, print_pac) self.smbserver.run_command(['chmod', 'a+x', tmpname]) for user in (self.ad_user, self.ipa_user1,): shell_script = script.format(principal=principal, user_princ=user, print_pac=tmpname) self.smbserver.run_command(['/bin/bash', '-s', '-e'], stdin_text=shell_script) self.smbserver.run_command(['rm', '-f', tmpname]) tasks.kdestroy_all(self.smbserver) def test_smb_mount_fails_without_kerberos_ticket(self, samba_share_public): mountpoint = '/mnt/smb' try: tasks.kdestroy_all(self.smbclient) self.smbclient.run_command(['mkdir', '-p', mountpoint]) res = self.smbclient.run_command([ 'mount', '-t', 'cifs', samba_share_public['unc'], mountpoint, '-o', 'sec=krb5i,multiuser' ], raiseonerr=False) assert res.returncode == 32 finally: self.cleanup_mount(mountpoint) def check_repeated_smb_mount(self, options): mountpoint = '/mnt/smb' unc = '//{}/homes'.format(self.smbserver.hostname) test_file = 'ntlm_test' test_file_server_path = '/home/{}/{}'.format(self.ipa_user1, test_file) test_file_client_path = '{}/{}'.format(mountpoint, test_file) self.smbclient.run_command(['mkdir', '-p', mountpoint]) self.smbserver.put_file_contents(test_file_server_path, '') try: for i in [1, 2]: res = self.smbclient.run_command([ 'mount', '-t', 'cifs', unc, mountpoint, '-o', options], raiseonerr=False) assert res.returncode == 0, ( 'Mount failed at iteration {}. Output: {}' .format(i, res.stdout_text + res.stderr_text)) assert self.smbclient.transport.file_exists( test_file_client_path) self.smbclient.run_command(['umount', mountpoint]) finally: self.cleanup_mount(mountpoint) self.smbserver.run_command(['rm', '-f', test_file_server_path]) @skip_if_fips() def test_ntlm_authentication_with_auto_domain(self): """Repeatedly try to authenticate with username and password with automatic domain discovery. This is a regression test for https://pagure.io/freeipa/issue/8636 """ tasks.kdestroy_all(self.smbclient) mount_options = 'user={user},pass={password},domainauto'.format( user=self.ipa_user1, password=self.ipa_user1_password ) self.check_repeated_smb_mount(mount_options) @skip_if_fips() def test_ntlm_authentication_with_upn_with_lowercase_domain(self): tasks.kdestroy_all(self.smbclient) mount_options = 'user={user}@{domain},pass={password}'.format( user=self.ipa_user1, password=self.ipa_user1_password, domain=self.master.domain.name.lower() ) self.check_repeated_smb_mount(mount_options) @skip_if_fips() def test_ntlm_authentication_with_upn_with_uppercase_domain(self): tasks.kdestroy_all(self.smbclient) mount_options = 'user={user}@{domain},pass={password}'.format( user=self.ipa_user1, password=self.ipa_user1_password, domain=self.master.domain.name.upper() ) self.check_repeated_smb_mount(mount_options) def test_uninstall_samba(self): self.smbserver.run_command(['ipa-client-samba', '--uninstall', '-U']) res = self.smbserver.run_command( ['systemctl', 'status', 'winbind'], raiseonerr=False) assert res.returncode == 3 res = self.smbserver.run_command( ['systemctl', 'status', 'smb'], raiseonerr=False) assert res.returncode == 3 def test_repeated_uninstall_samba(self): """Test samba uninstallation after successful uninstallation. Test for bug https://pagure.io/freeipa/issue/8019. """ self.smbserver.run_command(['ipa-client-samba', '--uninstall', '-U']) def test_samba_reinstall(self): """Test samba can be reinstalled. Test installation after uninstallation and do some sanity checks. Test for bug https://pagure.io/freeipa/issue/8021 """ self.test_install_samba() self.test_smb_access_for_ipa_user_at_ipa_client() def test_cleanup(self): tasks.unconfigure_windows_dns_for_trust(self.ad, self.master)
20,436
Python
.py
427
36.348946
79
0.586558
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,557
test_topology.py
freeipa_freeipa/ipatests/test_integration/test_topology.py
# # Copyright (C) 2015 FreeIPA Contributors see COPYING for license # import re import pytest from ipatests.test_integration.base import IntegrationTest from ipatests.pytest_ipa.integration import tasks from ipatests.pytest_ipa.integration.env_config import get_global_config from ipalib.constants import DOMAIN_SUFFIX_NAME from ipatests.util import assert_deepequal config = get_global_config() reasoning = "Topology plugin disabled due to domain level 0" def find_segment(master, replica, suffix=DOMAIN_SUFFIX_NAME): result = master.run_command(['ipa', 'topologysegment-find', suffix]).stdout_text segment_re = re.compile(r'Left node: (?P<left>\S+)\n.*Right node: ' r'(?P<right>\S+)\n') allsegments = segment_re.findall(result) for segment in allsegments: if master.hostname in segment and replica.hostname in segment: return '-to-'.join(segment) return None @pytest.mark.skipif(config.domain_level == 0, reason=reasoning) class TestTopologyOptions(IntegrationTest): num_replicas = 2 topology = 'star' rawsegment_re = (r'Segment name: (?P<name>.*?)', r'\s+Left node: (?P<lnode>.*?)', r'\s+Right node: (?P<rnode>.*?)', r'\s+Connectivity: (?P<connectivity>\S+)') segment_re = re.compile("\n".join(rawsegment_re)) noentries_re = re.compile(r"Number of entries returned (\d+)") segmentnames_re = re.compile(r'.*Segment name: (\S+?)\n.*') @classmethod def install(cls, mh): tasks.install_topo(cls.topology, cls.master, cls.replicas[:-1], cls.clients) def tokenize_topologies(self, command_output): """ takes an output of `ipa topologysegment-find` and returns an array of segment hashes """ segments = command_output.split("-----------------")[2] raw_segments = segments.split('\n\n') result = [] for i in raw_segments: matched = self.segment_re.search(i) if matched: result.append({'leftnode': matched.group('lnode'), 'rightnode': matched.group('rnode'), 'name': matched.group('name'), 'connectivity': matched.group('connectivity') } ) return result def test_topology_updated_on_replica_install_remove(self): """ Install and remove a replica and make sure topology information is updated on all other replicas Testcase: http://www.freeipa.org/page/V4/Manage_replication_topology/ Test_plan#Test_case: _Replication_topology_should_be_saved_in_the_LDAP_tree """ tasks.kinit_admin(self.master) result1 = self.master.run_command(['ipa', 'topologysegment-find', DOMAIN_SUFFIX_NAME]).stdout_text segment_name = self.segmentnames_re.findall(result1)[0] assert(self.master.hostname in segment_name), ( "Segment %s does not contain master hostname" % segment_name) assert(self.replicas[0].hostname in segment_name), ( "Segment %s does not contain replica hostname" % segment_name) tasks.install_replica(self.master, self.replicas[1], setup_ca=False, setup_dns=False) # We need to make sure topology information is consistent across all # replicas result2 = self.master.run_command(['ipa', 'topologysegment-find', DOMAIN_SUFFIX_NAME]) result3 = self.replicas[0].run_command(['ipa', 'topologysegment-find', DOMAIN_SUFFIX_NAME]) result4 = self.replicas[1].run_command(['ipa', 'topologysegment-find', DOMAIN_SUFFIX_NAME]) segments = self.tokenize_topologies(result2.stdout_text) assert(len(segments) == 2), "Unexpected number of segments found" assert_deepequal(result2.stdout_text, result3.stdout_text) assert_deepequal(result3.stdout_text, result4.stdout_text) # Now let's check that uninstalling the replica will update the # topology info on the rest of replicas. # first step of uninstallation is removal of the replica on other # master, then it can be uninstalled. Doing it the other way is also # possible, but not reliable - some data might not be replicated. tasks.clean_replication_agreement(self.master, self.replicas[1]) tasks.uninstall_master(self.replicas[1]) result5 = self.master.run_command(['ipa', 'topologysegment-find', DOMAIN_SUFFIX_NAME]) num_entries = self.noentries_re.search(result5.stdout_text).group(1) assert(num_entries == "1"), "Incorrect number of entries displayed" def test_add_remove_segment(self): """ Make sure a topology segment can be manually created and deleted with the influence on the real topology Testcase http://www.freeipa.org/page/V4/Manage_replication_topology/ Test_plan#Test_case:_Basic_CRUD_test """ tasks.kinit_admin(self.master) # Install the second replica tasks.install_replica(self.master, self.replicas[1], setup_ca=False, setup_dns=False) # turn a star into a ring segment, err = tasks.create_segment(self.master, self.replicas[0], self.replicas[1]) assert err == "", err # At this point we have replicas[1] <-> master <-> replicas[0] # ^--------------------------^ # Make sure the new segment is shown by `ipa topologysegment-find` result1 = self.master.run_command(['ipa', 'topologysegment-find', DOMAIN_SUFFIX_NAME]).stdout_text assert(segment['name'] in result1), ( "%s: segment not found" % segment['name']) # Remove master <-> replica2 segment and make sure that the changes get # there through replica1 # Since segment name can be one of master-to-replica2 or # replica2-to-master, we need to determine the segment name dynamically deleteme = find_segment(self.master, self.replicas[1]) returncode, error = tasks.destroy_segment(self.master, deleteme) assert returncode == 0, error # At this point we have master <-> replicas[0] <-> replicas[1] # Wait till replication ends and make sure replica1 does not have # segment that was deleted on master master_ldap = self.master.ldap_connect() repl_ldap = self.replicas[0].ldap_connect() tasks.wait_for_replication(master_ldap) result3 = self.replicas[0].run_command(['ipa', 'topologysegment-find', DOMAIN_SUFFIX_NAME]).stdout_text assert(deleteme not in result3), "%s: segment still exists" % deleteme # Create test data on master and make sure it gets all the way down to # replica2 through replica1 self.master.run_command(['ipa', 'user-add', 'someuser', '--first', 'test', '--last', 'user']) tasks.wait_for_replication(master_ldap) tasks.wait_for_replication(repl_ldap) result4 = self.replicas[1].run_command(['ipa', 'user-find']) assert('someuser' in result4.stdout_text), 'User not found: someuser' # We end up having a line topology: master <-> replica1 <-> replica2 def test_remove_the_only_connection(self): """ Testcase: http://www.freeipa.org/page/V4/Manage_replication_topology/ Test_plan#Test_case: _Removal_of_a_topology_segment_is_allowed_only_if_there_is_at_least_one_more_segment_connecting_the_given_replica """ text = "Removal of Segment disconnects topology" error1 = "The system should not have let you remove the segment" error2 = "Wrong error message thrown during segment removal: \"%s\"" replicas = (self.replicas[0].hostname, self.replicas[1].hostname) returncode, error = tasks.destroy_segment( self.master, "%s-to-%s" % replicas) assert returncode != 0, error1 assert error.count(text) == 1, error2 % error _newseg, err = tasks.create_segment( self.master, self.master, self.replicas[1]) assert err == "", err returncode, error = tasks.destroy_segment( self.master, "%s-to-%s" % replicas) assert returncode == 0, error @pytest.mark.skipif(config.domain_level == 0, reason=reasoning) class TestCASpecificRUVs(IntegrationTest): num_replicas = 2 topology = 'star' username = 'testuser' user_firstname = 'test' user_lastname = 'user' def test_delete_ruvs(self): """ http://www.freeipa.org/page/V4/Manage_replication_topology_4_4/ Test_Plan#Test_case:_clean-ruv_subcommand """ replica = self.replicas[0] master = self.master res1 = master.run_command(['ipa-replica-manage', 'list-ruv', '-p', master.config.dirman_password]) assert(res1.stdout_text.count(replica.hostname) == 2 and "Certificate Server Replica" " Update Vectors" in res1.stdout_text), ( "CA-specific RUVs are not displayed") ruvid_re = re.compile(r".*%s:389: (\d+).*" % replica.hostname) replica_ruvs = ruvid_re.findall(res1.stdout_text) # Find out the number of RUVids assert(len(replica_ruvs) == 2), ( "The output should display 2 RUV ids of the selected replica") # Block replication to preserve replica-specific RUVs dashed_domain = master.domain.realm.replace(".", '-') dirsrv_service = "dirsrv@%s.service" % dashed_domain replica.run_command(['systemctl', 'stop', dirsrv_service]) try: master.run_command(['ipa-replica-manage', 'clean-ruv', replica_ruvs[1], '-p', master.config.dirman_password, '-f']) res2 = master.run_command(['ipa-replica-manage', 'list-ruv', '-p', master.config.dirman_password]) assert(res2.stdout_text.count(replica.hostname) == 1), ( "CA RUV of the replica is still displayed") master.run_command(['ipa-replica-manage', 'clean-ruv', replica_ruvs[0], '-p', master.config.dirman_password, '-f']) res3 = master.run_command(['ipa-replica-manage', 'list-ruv', '-p', master.config.dirman_password]) assert(replica.hostname not in res3.stdout_text), ( "replica's RUV is still displayed") finally: replica.run_command(['systemctl', 'start', dirsrv_service]) def test_replica_uninstall_deletes_ruvs(self): """ http://www.freeipa.org/page/V4/Manage_replication_topology_4_4/Test_Plan #Test_case:_.2A-ruv_subcommands_of_ipa-replica-manage_are_extended _to_handle_CA-specific_RUVs """ master = self.master replica = self.replicas[1] res1 = master.run_command(['ipa-replica-manage', 'list-ruv', '-p', master.config.dirman_password]).stdout_text assert(res1.count(replica.hostname) == 2), ( "Did not find proper number of replica hostname (%s) occurrencies" " in the command output: %s" % (replica.hostname, res1)) master.run_command(['ipa-replica-manage', 'del', replica.hostname, '-p', master.config.dirman_password]) tasks.uninstall_master(replica) # ipa-replica-manage del launches a clean-ruv task which is # ASYNCHRONOUS # wait for the task to finish before checking list-ruv tasks.wait_for_cleanallruv_tasks(self.master.ldap_connect()) res2 = master.run_command(['ipa-replica-manage', 'list-ruv', '-p', master.config.dirman_password]).stdout_text assert(replica.hostname not in res2), ( "Replica RUVs were not clean during replica uninstallation")
12,745
Python
.py
237
41.122363
121
0.594008
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,558
test_hsm.py
freeipa_freeipa/ipatests/test_integration/test_hsm.py
# # Copyright (C) 2023 FreeIPA Contributors see COPYING for license # import os.path import pytest import random import re import string import time from ipalib.constants import KRA_TRACKING_REQS from ipapython.ipaldap import realm_to_serverid from ipatests.test_integration.base import IntegrationTest from ipatests.test_integration.test_acme import ( prepare_acme_client, certbot_register, certbot_standalone_cert, get_selinux_status, skip_certbot_tests, skip_mod_md_tests, ) from ipatests.test_integration.test_caless import CALessBase from ipatests.test_integration.test_cert import get_certmonger_fs_id from ipatests.test_integration.test_external_ca import ( install_server_external_ca_step1, install_server_external_ca_step2, check_CA_flag, verify_caentry ) from ipatests.test_integration.test_ipa_cert_fix import ( check_status, needs_resubmit, get_cert_expiry ) from ipatests.test_integration.test_ipahealthcheck import ( run_healthcheck, set_excludes ) from ipatests.pytest_ipa.integration import tasks from ipatests.pytest_ipa.integration.env_config import get_global_config from ipalib import x509 as ipa_x509 from ipaplatform.paths import paths config = get_global_config() hsm_lib_path = '' if config.token_library: hsm_lib_path = config.token_library else: hsm_lib_path = '/usr/lib64/pkcs11/libsofthsm2.so' def get_hsm_token(host): """Helper method to get an hsm token This method creates a softhsm token if the hsm hardware token is not found. """ if host.config.token_name: return (host.config.token_name, host.config.token_password) token_name = ''.join( random.choice(string.ascii_letters) for i in range(10) ) token_passwd = ''.join( random.choice(string.ascii_letters) for i in range(10) ) # remove the token if already exist host.run_command( ['softhsm2-util', '--delete-token', '--token', token_name], raiseonerr=False ) host.run_command( ['runuser', '-u', 'pkiuser', '--', 'softhsm2-util', '--init-token', '--free', '--pin', token_passwd, '--so-pin', token_passwd, '--label', token_name] ) return (token_name, token_passwd) def delete_hsm_token(hosts, token_name): for host in hosts: if host.config.token_name: # assumption: for time being /root/cleantoken.sh is copied # host manually. This should be removed in final iteration. host.run_command(['sh', '/root/cleantoken.sh']) else: host.run_command( ['softhsm2-util', '--delete-token', '--token', token_name], raiseonerr=False ) def find_softhsm_token_files(host, token): if not host.transport.file_exists(paths.PKI_TOMCAT_ALIAS_DIR): return None, [] result = host.run_command([ paths.MODUTIL, '-list', 'libsofthsm2', '-dbdir', paths.PKI_TOMCAT_ALIAS_DIR ]) serial = None state = 'token_name' for line in result.stdout_text.split('\n'): if state == 'token_name' and 'Token Name:' in line.strip(): (_label, tokenname) = line.split(':', 1) if tokenname.strip() == token: state = 'serial' elif state == 'serial' and 'Token Serial Number' in line.strip(): (_label, serial) = line.split(':', 1) serial = serial.strip() serial = "{}-{}".format(serial[0:4], serial[4:]) break if serial is None: raise RuntimeError("can't find softhsm token serial for %s" % token) result = host.run_command( ['ls', '-l', '/var/lib/softhsm/tokens/']) serialdir = None for r in result.stdout_text.split('\n'): if serial in r: dirname = r.split()[-1:][0] serialdir = f'/var/lib/softhsm/tokens/{dirname}' break if serialdir is None: raise RuntimeError("can't find softhsm token directory for %s" % serial) result = host.run_command(['ls', '-1', serialdir]) return serialdir, [ os.path.join(serialdir, file) for file in result.stdout_text.strip().split('\n') ] def copy_token_files(src_host, dest_host, token_name): """Helper method to copy the token files to replica""" # copy the token files to replicas if not src_host.config.token_name: serialdir, token_files = find_softhsm_token_files( src_host, token_name ) if serialdir: for host in dest_host: tasks.copy_files(src_host, host, token_files) host.run_command(['usermod', 'pkiuser', '-a', '-G', 'ods']) host.run_command( ['chown', '-R', 'pkiuser:pkiuser', serialdir] ) def check_version(host): if tasks.get_pki_version(host) < tasks.parse_version('11.5.0'): raise pytest.skip("PKI HSM support is not available") class BaseHSMTest(IntegrationTest): master_with_dns = True master_with_kra = False master_with_ad = False master_extra_args = [] token_password = None token_name = None token_password_file = '/tmp/token_password' random_serial = False @classmethod def install(cls, mh): check_version(cls.master) # Enable pkiuser to read softhsm tokens cls.master.run_command(['usermod', 'pkiuser', '-a', '-G', 'ods']) cls.token_name, cls.token_password = get_hsm_token(cls.master) cls.master.put_file_contents( cls.token_password_file, cls.token_password ) tasks.install_master( cls.master, setup_dns=cls.master_with_dns, setup_kra=cls.master_with_kra, setup_adtrust=cls.master_with_ad, extra_args=( '--token-name', cls.token_name, '--token-library-path', hsm_lib_path, '--token-password', cls.token_password ) ) cls.sync_tokens(cls.master) @classmethod def uninstall(cls, mh): check_version(cls.master) super(BaseHSMTest, cls).uninstall(mh) delete_hsm_token([cls.master] + cls.replicas, cls.token_name) @classmethod def sync_tokens(cls, source, token_name=None): """Synchronize non-networked HSM tokens between machines source: source host for the token data """ if ( hsm_lib_path and 'nfast' in hsm_lib_path ): for host in [cls.master] + cls.replicas: if host == source: continue tasks.copy_nfast_data(source, host) for host in [cls.master] + cls.replicas: if host == source: continue copy_token_files(source, [host], token_name if token_name else cls.token_name) class TestHSMInstall(BaseHSMTest): num_replicas = 3 num_clients = 1 topology = 'star' def test_hsm_install_replica0_ca_less_install(self): check_version(self.master) tasks.install_replica( self.master, self.replicas[0], setup_ca=False, setup_dns=True, ) def test_hsm_install_replica0_ipa_ca_install(self): check_version(self.master) self.sync_tokens(self.master) tasks.install_ca( self.replicas[0], extra_args=('--token-password', self.token_password,), ) def test_hsm_install_replica0_ipa_kra_install(self): check_version(self.master) tasks.install_kra( self.replicas[0], first_instance=True, extra_args=('--token-password', self.token_password,) ) self.sync_tokens(self.replicas[0]) def test_hsm_install_replica0_ipa_dns_install(self): tasks.install_dns(self.replicas[0]) def test_hsm_install_replica1_with_ca_install(self): check_version(self.master) tasks.install_replica( self.master, self.replicas[1], setup_ca=True, extra_args=('--token-password', self.token_password,) ) def test_hsm_install_replica1_ipa_kra_install(self): check_version(self.master) tasks.install_kra( self.replicas[1], extra_args=('--token-password', self.token_password,) ) def test_hsm_install_replica1_ipa_dns_install(self): check_version(self.master) tasks.install_dns(self.replicas[1]) def test_hsm_install_replica2_with_ca_kra_dns_install(self): check_version(self.master) tasks.install_replica( self.master, self.replicas[2], setup_ca=True, setup_kra=True, setup_dns=True, extra_args=('--token-password', self.token_password,) ) def test_hsm_install_master_ipa_kra_install(self): check_version(self.master) tasks.install_kra( self.master, extra_args=('--token-password', self.token_password,) ) def test_hsm_install_client(self): check_version(self.master) tasks.install_client(self.master, self.clients[0]) def test_hsm_install_issue_user_cert(self): check_version(self.master) user = 'testuser1' csr_file = f'{user}.csr' key_file = f'{user}.key' cert_file = f'{user}.crt' tasks.kinit_admin(self.master) tasks.user_add(self.master, user) openssl_cmd = [ 'openssl', 'req', '-newkey', 'rsa:2048', '-keyout', key_file, '-nodes', '-out', csr_file, '-subj', '/CN=' + user] self.master.run_command(openssl_cmd) cmd_args = ['ipa', 'cert-request', '--principal', user, '--certificate-out', cert_file, csr_file] self.master.run_command(cmd_args) def test_hsm_install_healthcheck(self): check_version(self.master) set_excludes(self.master, "key", "DSCLE0004") tasks.install_packages(self.master, ['*ipa-healthcheck']) returncode, output = run_healthcheck( self.master, output_type="human", failures_only=True ) assert returncode == 0 assert output == "No issues found." class TestHSMInstallPasswordFile(BaseHSMTest): num_replicas = 1 @classmethod def install(cls, mh): check_version(cls.master) # Enable pkiuser to read softhsm tokens cls.master.run_command(['usermod', 'pkiuser', '-a', '-G', 'ods']) cls.token_name, cls.token_password = get_hsm_token(cls.master) cls.master.put_file_contents( cls.token_password_file, cls.token_password ) cls.replicas[0].put_file_contents( cls.token_password_file, cls.token_password ) def test_hsm_install_server_password_file(self): check_version(self.master) tasks.install_master( self.master, setup_dns=self.master_with_dns, setup_kra=self.master_with_kra, setup_adtrust=self.master_with_ad, extra_args=( '--token-name', self.token_name, '--token-library-path', hsm_lib_path, '--token-password-file', self.token_password_file ) ) self.sync_tokens(self.master, token_name=self.token_name) def test_hsm_install_replica0_password_file(self): check_version(self.master) tasks.install_replica( self.master, self.replicas[0], setup_ca=True, extra_args=('--token-password-file', self.token_password_file,) ) def test_hsm_install_replica0_kra_password_file(self): check_version(self.master) tasks.install_kra( self.replicas[0], extra_args=('--token-password-file', self.token_password_file,) ) class TestHSMInstallADTrustBase(BaseHSMTest): """ Base test for builtin AD trust installation in combination with other components with HSM support """ num_replicas = 1 master_with_dns = False master_with_kra = True def test_hsm_adtrust_replica0_all_components(self): check_version(self.master) tasks.install_replica( self.master, self.replicas[0], setup_ca=True, setup_adtrust=False, setup_kra=True, setup_dns=True, nameservers='master' if self.master_with_dns else None, extra_args=('--token-password', self.token_password,) ) class TestADTrustInstallWithDNS_KRA_ADTrust(BaseHSMTest): num_replicas = 1 master_with_dns = True master_with_kra = True master_with_ad = True def test_hsm_adtrust_replica0(self): check_version(self.master) tasks.install_replica( self.master, self.replicas[0], setup_ca=True, setup_kra=True, extra_args=('--token-password', self.token_password,) ) class TestHSMcertRenewal(BaseHSMTest): master_with_kra = True def test_certs_renewal(self): """ Test that the KRA subsystem certificates renew properly """ check_version(self.master) CA_TRACKING_REQS = { 'ocspSigningCert cert-pki-ca': 'caocspSigningCert', 'subsystemCert cert-pki-ca': 'casubsystemCert', 'auditSigningCert cert-pki-ca': 'caauditSigningCert' } CA_TRACKING_REQS.update(KRA_TRACKING_REQS) self.master.put_file_contents(self.token_password_file, self.token_password) for nickname in CA_TRACKING_REQS: cert = tasks.certutil_fetch_cert( self.master, paths.PKI_TOMCAT_ALIAS_DIR, self.token_password_file, nickname, token_name=self.token_name, ) starting_serial = int(cert.serial_number) cmd_arg = [ 'ipa-getcert', 'resubmit', '-v', '-w', '-d', paths.PKI_TOMCAT_ALIAS_DIR, '-n', nickname, ] result = self.master.run_command(cmd_arg) request_id = re.findall(r'\d+', result.stdout_text) status = tasks.wait_for_request(self.master, request_id[0], 120) assert status == "MONITORING" args = ['-L', '-h', self.token_name, '-f', self.token_password_file,] tasks.run_certutil(self.master, args, paths.PKI_TOMCAT_ALIAS_DIR) cert = tasks.certutil_fetch_cert( self.master, paths.PKI_TOMCAT_ALIAS_DIR, self.token_password_file, nickname, token_name=self.token_name, ) assert starting_serial != int(cert.serial_number) class TestHSMCALessToExternalToSelfSignedCA(CALessBase, BaseHSMTest): """Test server caless to external CA to self signed scenario""" num_replicas = 1 @classmethod def install(cls, mh): check_version(cls.master) super(TestHSMCALessToExternalToSelfSignedCA, cls).install(mh) # Enable pkiuser to read softhsm tokens cls.master.run_command(['usermod', 'pkiuser', '-a', '-G', 'ods']) cls.token_name, cls.token_password = get_hsm_token(cls.master) @classmethod def uninstall(cls, mh): check_version(cls.master) super(TestHSMCALessToExternalToSelfSignedCA, cls).uninstall(mh) delete_hsm_token([cls.master] + cls.replicas, cls.token_name) def test_hsm_caless_server(self): """Install CA-less master""" check_version(self.master) self.create_pkcs12('ca1/server') self.prepare_cacert('ca1') master = self.install_server() assert master.returncode == 0 def test_hsm_caless_to_ca_full(self): check_version(self.master) tasks.install_ca( self.master, extra_args=( '--token-name', self.token_name, '--token-library-path', hsm_lib_path, '--token-password', self.token_password ), ) self.sync_tokens(self.master) ca_show = self.master.run_command(['ipa', 'ca-show', 'ipa']) assert 'Subject DN: CN=Certificate Authority,O={}'.format( self.master.domain.realm) in ca_show.stdout_text def test_hsm_caless_selfsigned_to_external_ca_install(self): # Install external CA on master result = self.master.run_command([paths.IPA_CACERT_MANAGE, 'renew', '--external-ca']) assert result.returncode == 0 # Sign CA, transport it to the host and get ipa a root ca paths. root_ca_fname, ipa_ca_fname = tasks.sign_ca_and_transport( self.master, paths.IPA_CA_CSR, ROOT_CA, IPA_CA) # renew CA with externally signed one result = self.master.run_command([paths.IPA_CACERT_MANAGE, 'renew', '--external-cert-file={}'. format(ipa_ca_fname), '--external-cert-file={}'. format(root_ca_fname)]) assert result.returncode == 0 # update IPA certificate databases result = self.master.run_command([paths.IPA_CERTUPDATE]) assert result.returncode == 0 # Check if external CA have "C" flag after the switch result = check_CA_flag(self.master) assert bool(result), ('External CA does not have "C" flag') # Check that ldap entries for the CA have been updated remote_cacrt = self.master.get_file_contents(ipa_ca_fname) cacrt = ipa_x509.load_pem_x509_certificate(remote_cacrt) verify_caentry(self.master, cacrt) def test_hsm_caless_external_to_self_signed_ca(self): check_version(self.master) self.master.run_command([paths.IPA_CACERT_MANAGE, 'renew', '--self-signed']) self.master.run_command([paths.IPA_CERTUPDATE]) def test_hsm_caless_replica0_with_ca_install(self): check_version(self.master) self.sync_tokens(self.master) tasks.install_replica( self.master, self.replicas[0], setup_ca=True, extra_args=('--token-password', self.token_password,) ) IPA_CA = "ipa_ca.crt" ROOT_CA = "root_ca.crt" class TestHSMExternalToSelfSignedCA(BaseHSMTest): """ Test of FreeIPA server installation with external CA then renew it to self-signed """ num_replicas = 1 @classmethod def install(cls, mh): check_version(cls.master) # Enable pkiuser to read softhsm tokens cls.master.run_command(['usermod', 'pkiuser', '-a', '-G', 'ods']) cls.token_name, cls.token_password = get_hsm_token(cls.master) @classmethod def uninstall(cls, mh): check_version(cls.master) super(TestHSMExternalToSelfSignedCA, cls).uninstall(mh) delete_hsm_token([cls.master] + cls.replicas, cls.token_name) def test_hsm_external_ca_install(self): check_version(self.master) # Step 1 of ipa-server-install. result = install_server_external_ca_step1( self.master, extra_args=[ '--external-ca-type=ms-cs', '--token-name', self.token_name, '--token-library-path', hsm_lib_path, '--token-password', self.token_password ] ) assert result.returncode == 0 root_ca_fname, ipa_ca_fname = tasks.sign_ca_and_transport( self.master, paths.ROOT_IPA_CSR, ROOT_CA, IPA_CA ) # Step 2 of ipa-server-install. result = install_server_external_ca_step2( self.master, ipa_ca_fname, root_ca_fname, extra_args=[ '--token-name', self.token_name, '--token-library-path', hsm_lib_path, '--token-password', self.token_password ] ) assert result.returncode == 0 self.sync_tokens(self.master) def test_hsm_external_kra_install(self): check_version(self.master) tasks.install_kra( self.master, first_instance=True, extra_args=('--token-password', self.token_password,) ) self.sync_tokens(self.master) def test_hsm_external_to_self_signed_ca(self): check_version(self.master) self.master.run_command([paths.IPA_CACERT_MANAGE, 'renew', '--self-signed']) self.master.run_command([paths.IPA_CERTUPDATE]) def test_hsm_external_ca_replica0_install(self): check_version(self.master) tasks.install_replica( self.master, self.replicas[0], setup_kra=True, extra_args=('--token-password', self.token_password,) ) @pytest.fixture def expire_cert_critical(): """ Fixture to expire the certs by moving the system date using date -s command and revert it back """ hosts = dict() def _expire_cert_critical(host): hosts['host'] = host # move date to expire certs tasks.move_date(host, 'stop', '+3Years+1day') host.run_command( ['ipactl', 'restart', '--ignore-service-failures'] ) yield _expire_cert_critical host = hosts.pop('host') # Prior to uninstall remove all the cert tracking to prevent # errors from certmonger trying to check the status of certs # that don't matter because we are uninstalling. host.run_command(['systemctl', 'stop', 'certmonger']) # Important: run_command with a str argument is able to # perform shell expansion but run_command with a list of # arguments is not host.run_command('rm -fv ' + paths.CERTMONGER_REQUESTS_DIR + '*') tasks.uninstall_master(host) tasks.move_date(host, 'start', '-3Years-1day') class TestHSMcertFix(BaseHSMTest): master_with_dns = False def test_hsm_renew_expired_cert_on_master(self, expire_cert_critical): check_version(self.master) expire_cert_critical(self.master) # wait for cert expiry check_status(self.master, 8, "CA_UNREACHABLE") self.master.run_command(['ipa-cert-fix', '-v'], stdin_text='yes\n') check_status(self.master, 9, "MONITORING", timeout=1000) # second iteration of ipa-cert-fix result = self.master.run_command( ['ipa-cert-fix', '-v'], stdin_text='yes\n' ) assert "Nothing to do" in result.stdout_text check_status(self.master, 9, "MONITORING") class TestHSMcertFixKRA(BaseHSMTest): master_with_dns = False master_with_kra = True def test_hsm_renew_expired_cert_with_kra(self, expire_cert_critical): check_version(self.master) expire_cert_critical(self.master) # check if all subsystem cert expired check_status(self.master, 11, "CA_UNREACHABLE") self.master.run_command(['ipa-cert-fix', '-v'], stdin_text='yes\n') self.master.run_command(['systemctl', 'restart', 'certmonger']) check_status(self.master, 12, "MONITORING") class TestHSMcertFixReplica(BaseHSMTest): num_replicas = 1 master_with_dns = False @classmethod def install(cls, mh): super(TestHSMcertFixReplica, cls).install(mh) tasks.install_replica( cls.master, cls.replicas[0], setup_ca=True, nameservers='master' if cls.master_with_dns else None, extra_args=('--token-password', cls.token_password,) ) @pytest.fixture def expire_certs(self): # move system date to expire certs for host in self.master, self.replicas[0]: tasks.move_date(host, 'stop', '+3years+1days') host.run_command( ['ipactl', 'restart', '--ignore-service-failures'] ) yield # move date back on replica and master for host in self.replicas[0], self.master: tasks.uninstall_master(host) tasks.move_date(host, 'start', '-3years-1days') def test_hsm_renew_expired_cert_replica(self, expire_certs): check_version(self.master) # wait for cert expiry self.master.run_command(['systemctl', 'restart', 'certmonger']) check_status(self.master, 8, "CA_UNREACHABLE") self.master.run_command(['ipa-cert-fix', '-v'], stdin_text='yes\n') check_status(self.master, 9, "MONITORING") # replica operations # 'Server-Cert cert-pki-ca' cert will be in CA_UNREACHABLE state cmd = self.replicas[0].run_command( ['getcert', 'list', '-d', paths.PKI_TOMCAT_ALIAS_DIR, '-n', 'Server-Cert cert-pki-ca'] ) req_id = get_certmonger_fs_id(cmd.stdout_text) tasks.wait_for_certmonger_status( self.replicas[0], ('CA_UNREACHABLE'), req_id, timeout=600 ) # get initial expiry date to compare later with renewed cert initial_expiry = get_cert_expiry( self.replicas[0], paths.PKI_TOMCAT_ALIAS_DIR, 'Server-Cert cert-pki-ca' ) # check that HTTP,LDAP,PKINIT are renewed and in MONITORING state instance = realm_to_serverid(self.master.domain.realm) dirsrv_cert = paths.ETC_DIRSRV_SLAPD_INSTANCE_TEMPLATE % instance for cert in (paths.KDC_CERT, paths.HTTPD_CERT_FILE): cmd = self.replicas[0].run_command( ['getcert', 'list', '-f', cert] ) req_id = get_certmonger_fs_id(cmd.stdout_text) tasks.wait_for_certmonger_status( self.replicas[0], ('MONITORING'), req_id, timeout=600 ) cmd = self.replicas[0].run_command( ['getcert', 'list', '-d', dirsrv_cert] ) req_id = get_certmonger_fs_id(cmd.stdout_text) tasks.wait_for_certmonger_status( self.replicas[0], ('MONITORING'), req_id, timeout=600 ) # check if replication working fine testuser = 'testuser1' password = 'Secret@123' stdin = (f"{self.master.config.admin_password}\n" f"{self.master.config.admin_password}\n" f"{self.master.config.admin_password}\n") self.master.run_command(['kinit', 'admin'], stdin_text=stdin) tasks.user_add(self.master, testuser, password=password) self.replicas[0].run_command(['kinit', 'admin'], stdin_text=stdin) self.replicas[0].run_command(['ipa', 'user-show', testuser]) # renew shared certificates by resubmitting to certmonger cmd = self.replicas[0].run_command( ['getcert', 'list', '-f', paths.RA_AGENT_PEM] ) req_id = get_certmonger_fs_id(cmd.stdout_text) if needs_resubmit(self.replicas[0], req_id): self.replicas[0].run_command( ['getcert', 'resubmit', '-i', req_id] ) tasks.wait_for_certmonger_status( self.replicas[0], ('MONITORING'), req_id, timeout=600 ) for cert_nick in ('auditSigningCert cert-pki-ca', 'ocspSigningCert cert-pki-ca', 'subsystemCert cert-pki-ca'): cmd = self.replicas[0].run_command( ['getcert', 'list', '-d', paths.PKI_TOMCAT_ALIAS_DIR, '-n', cert_nick] ) req_id = get_certmonger_fs_id(cmd.stdout_text) if needs_resubmit(self.replicas[0], req_id): self.replicas[0].run_command( ['getcert', 'resubmit', '-i', req_id] ) tasks.wait_for_certmonger_status( self.replicas[0], ('MONITORING'), req_id, timeout=600 ) self.replicas[0].run_command( ['ipa-cert-fix', '-v'], stdin_text='yes\n' ) check_status(self.replicas[0], 9, "MONITORING") # Sometimes certmonger takes time to update the cert status # So check in nssdb instead of relying on getcert command renewed_expiry = get_cert_expiry( self.replicas[0], paths.PKI_TOMCAT_ALIAS_DIR, 'Server-Cert cert-pki-ca' ) assert renewed_expiry > initial_expiry class TestHSMNegative(IntegrationTest): master_with_dns = False token_password_file = '/tmp/token_password' @classmethod def install(cls, mh): check_version(cls.master) # Enable pkiuser to read softhsm tokens cls.master.run_command(['usermod', 'pkiuser', '-a', '-G', 'ods']) cls.token_name, cls.token_password = get_hsm_token(cls.master) @classmethod def uninstall(cls, mh): check_version(cls.master) cls.master.run_command( ['softhsm2-util', '--delete-token', '--token', cls.token_name], raiseonerr=False ) def test_hsm_negative_wrong_token_details(self): check_version(self.master) # wrong token name result = tasks.install_master( self.master, raiseonerr=False, extra_args=( '--token-name', 'random_token', '--token-library-path', hsm_lib_path, '--token-password', self.token_password ) ) assert result.returncode != 0 # wrong token password result = tasks.install_master( self.master, raiseonerr=False, extra_args=( '--token-name', self.token_name, '--token-library-path', hsm_lib_path, '--token-password', 'token_passwd' ) ) assert result.returncode != 0 # wrong token lib result = tasks.install_master( self.master, raiseonerr=False, extra_args=( '--token-name', self.token_name, '--token-library-path', '/tmp/non_existing_hsm_lib_path', '--token-password', self.token_password ) ) assert result.returncode != 0 def test_hsm_negative_bad_token_dir_permissions(self): """Create an unreadable softhsm2 token and install should fail. This is most often seen on replicas where the pkiuser is not a member of the ods group. """ check_version(self.master) token_name = 'bad_perms' token_passwd = 'Secret123' self.master.run_command( ['softhsm2-util', '--delete-token', '--token', token_name], raiseonerr=False ) self.master.run_command( ['usermod', 'pkiuser', '-a', '-G', 'ods'] ) self.master.run_command( ['softhsm2-util', '--init-token', '--free', '--pin', token_passwd, '--so-pin', token_passwd, '--label', token_name] ) self.master.run_command( ['gpasswd', '-d', 'pkiuser', 'ods'] ) result = tasks.install_master( self.master, raiseonerr=False, extra_args=( '--token-name', token_name, '--token-library-path', hsm_lib_path, '--token-password', token_passwd ) ) self.master.run_command( ['usermod', 'pkiuser', '-a', '-G', 'ods'] ) self.master.run_command( ['softhsm2-util', '--delete-token', '--token', token_name], raiseonerr=False ) assert result.returncode != 0 assert ( f"Token named '{token_name}' was not found" in result.stderr_text ) def test_hsm_negative_special_char_token_name(self): check_version(self.master) token_name = 'hsm:token' token_passwd = 'Secret123' self.master.run_command( ['softhsm2-util', '--delete-token', '--token', token_name], raiseonerr=False ) self.master.run_command( ['runuser', '-u', 'pkiuser', '--', 'softhsm2-util', '--init-token', '--free', '--pin', token_passwd, '--so-pin', token_passwd, '--label', token_name] ) # special character in token name result = tasks.install_master( self.master, raiseonerr=False, extra_args=( '--token-name', token_name, '--token-library-path', hsm_lib_path, '--token-password', token_passwd ) ) assert result.returncode != 0 def test_hsm_negative_token_password_and_file(self): """Test token-password and token-password-file at same time Test if command fails when --token-password and --token-password-file provided at the same time results into command failure. """ check_version(self.master) self.master.put_file_contents( self.token_password_file, self.token_password ) result = tasks.install_master( self.master, raiseonerr=False, extra_args=( '--token-name', self.token_name, '--token-library-path', hsm_lib_path, '--token-password', self.token_password, '--token-password-file', self.token_password_file ) ) self.master.run_command( ['softhsm2-util', '--delete-token', '--token', self.token_name], raiseonerr=False ) # assert 'error message non existing token lib' in result.stderr_text assert result.returncode != 0 class TestHSMACME(CALessBase): num_clients = 1 @classmethod def install(cls, mh): check_version(cls.master) super(TestHSMACME, cls).install(mh) # install packages before client install in case of IPA DNS problems cls.acme_server = prepare_acme_client(cls.master, cls.clients[0]) # Enable pkiuser to read softhsm tokens cls.master.run_command(['usermod', 'pkiuser', '-a', '-G', 'ods']) cls.token_name, cls.token_password = get_hsm_token(cls.master) tasks.install_master( cls.master, setup_dns=True, extra_args=( '--token-name', cls.token_name, '--token-library-path', hsm_lib_path, '--token-password', cls.token_password ) ) tasks.install_client(cls.master, cls.clients[0]) @classmethod def uninstall(cls, mh): check_version(cls.master) super(TestHSMACME, cls).uninstall(mh) delete_hsm_token([cls.master], cls.token_name) @pytest.mark.skipif(skip_certbot_tests, reason='certbot not available') def test_certbot_certonly_standalone(self): check_version(self.master) # enable ACME on server tasks.kinit_admin(self.master) self.master.run_command(['ipa-acme-manage', 'enable']) # register account to certbot certbot_register(self.clients[0], self.acme_server) # request ACME cert with certbot certbot_standalone_cert(self.clients[0], self.acme_server) @pytest.mark.skipif(skip_mod_md_tests, reason='mod_md not available') def test_mod_md(self): check_version(self.master) if get_selinux_status(self.clients[0]): # mod_md requires its own SELinux policy to grant perms to # maintaining ACME registration and cert state. raise pytest.skip("SELinux is enabled, this will fail") # write config self.clients[0].run_command(['mkdir', '-p', '/etc/httpd/conf.d']) self.clients[0].run_command(['mkdir', '-p', '/etc/httpd/md']) self.clients[0].put_file_contents( '/etc/httpd/conf.d/md.conf', '\n'.join([ f'MDCertificateAuthority {self.acme_server}', 'MDCertificateAgreement accepted', 'MDStoreDir /etc/httpd/md', f'MDomain {self.clients[0].hostname}', '<VirtualHost *:443>', f' ServerName {self.clients[0].hostname}', ' SSLEngine on', '</VirtualHost>\n', ]), ) # To check for successful cert issuance means knowing how mod_md # stores certificates, or looking for specific log messages. # If the thing we are inspecting changes, the test will break. # So I prefer a conservative sleep. # self.clients[0].run_command(['systemctl', 'restart', 'httpd']) time.sleep(15) # We expect mod_md has acquired the certificate by now. # Perform a graceful restart to begin using the cert. # (If mod_md ever learns to start using newly acquired # certificates /without/ the second restart, then both # of these sleeps can be replaced by "loop until good".) # self.clients[0].run_command(['systemctl', 'reload', 'httpd']) time.sleep(3) # HTTPS request from server to client (should succeed) self.master.run_command( ['curl', f'https://{self.clients[0].hostname}']) # clean-up self.clients[0].run_command(['rm', '-rf', '/etc/httpd/md']) self.clients[0].run_command(['rm', '-f', '/etc/httpd/conf.d/md.conf']) class TestHSMBackupRestore(BaseHSMTest): def test_hsm_backup_restore(self): check_version(self.master) backup_path = tasks.get_backup_dir(self.master) self.master.run_command(['ipa-server-install', '--uninstall', '-U']) assert not self.master.transport.file_exists( paths.IPA_CUSTODIA_KEYS) assert not self.master.transport.file_exists( paths.IPA_CUSTODIA_CONF) self.master.run_command( ['ipa-restore', backup_path], stdin_text=f'{self.master.config.dirman_password}\nyes' ) @pytest.fixture def issue_and_expire_acme_cert(): """Fixture to expire cert by moving date past expiry of acme cert""" hosts = [] def _issue_and_expire_acme_cert( master, client, acme_server_url, no_of_cert=1 ): hosts.append(master) hosts.append(client) # enable the ACME service on master master.run_command(['ipa-acme-manage', 'enable']) # register the account with certbot certbot_register(client, acme_server_url) # request a standalone acme cert certbot_standalone_cert(client, acme_server_url, no_of_cert) # move system date to expire acme cert for host in hosts: tasks.kdestroy_all(host) tasks.move_date(host, 'stop', '+90days+2hours') # restart ipa services as date moved and wait to get things settle time.sleep(10) master.run_command(['ipactl', 'restart']) time.sleep(10) tasks.get_kdcinfo(master) # Note raiseonerr=False: # the assert is located after kdcinfo retrieval. # run kinit command repeatedly until sssd gets settle # after date change tasks.run_repeatedly( master, "KRB5_TRACE=/dev/stdout kinit admin", stdin_text='{0}\n{0}\n{0}\n'.format( master.config.admin_password ) ) # Retrieve kdc.$REALM after the password change, just in case SSSD # domain status flipped to online during the password change. tasks.get_kdcinfo(master) yield _issue_and_expire_acme_cert # move back date for host in hosts: tasks.move_date(host, 'start', '-90days-2hours') # restart ipa services as date moved and wait to get things settle # if the internal fixture was not called (for instance because the test # was skipped), hosts = [] and hosts[0] would produce an IndexError # exception. if hosts: time.sleep(10) hosts[0].run_command(['ipactl', 'restart']) time.sleep(10) class TestHSMACMEPrune(IntegrationTest): """Validate that ipa-acme-manage configures dogtag for pruning""" num_clients = 1 @classmethod def install(cls, mh): check_version(cls.master) super(TestHSMACMEPrune, cls).install(mh) # install packages before client install in case of IPA DNS problems cls.acme_server = prepare_acme_client(cls.master, cls.clients[0]) # Enable pkiuser to read softhsm tokens cls.master.run_command(['usermod', 'pkiuser', '-a', '-G', 'ods']) cls.token_name, cls.token_password = get_hsm_token(cls.master) tasks.install_master( cls.master, setup_dns=True, random_serial=True, extra_args=( '--token-name', cls.token_name, '--token-library-path', hsm_lib_path, '--token-password', cls.token_password ) ) tasks.install_client(cls.master, cls.clients[0]) @classmethod def uninstall(cls, mh): check_version(cls.master) super(TestHSMACMEPrune, cls).uninstall(mh) delete_hsm_token([cls.master], cls.token_name) def test_hsm_prune_cert_manual(self, issue_and_expire_acme_cert): """Test to prune expired certificate by manual run""" if (tasks.get_pki_version(self.master) < tasks.parse_version('11.3.0')): raise pytest.skip("Certificate pruning is not available") issue_and_expire_acme_cert( self.master, self.clients[0], self.acme_server) # check that the certificate issued for the client result = self.master.run_command( ['ipa', 'cert-find', '--subject', self.clients[0].hostname] ) assert f'CN={self.clients[0].hostname}' in result.stdout_text # We moved time forward 90 days + 2 hours. Configure it to # prune after an hour then run it. self.master.run_command( ['ipa-acme-manage', 'pruning', '--enable', '--certretention=60', '--certretentionunit=minute',] ) self.master.run_command(['ipactl', 'restart']) self.master.run_command(['ipa-acme-manage', 'pruning', '--run']) # wait for cert to get prune time.sleep(50) # check if client cert is removed result = self.master.run_command( ['ipa', 'cert-find', '--subject', self.clients[0].hostname], raiseonerr=False ) assert f'CN={self.clients[0].hostname}' not in result.stdout_text def test_hsm_prune_cert_cron(self, issue_and_expire_acme_cert): """Test to prune expired certificate by cron job""" if (tasks.get_pki_version(self.master) < tasks.parse_version('11.3.0')): raise pytest.skip("Certificate pruning is not available") issue_and_expire_acme_cert( self.master, self.clients[0], self.acme_server) # check that the certificate issued for the client result = self.master.run_command( ['ipa', 'cert-find', '--subject', self.clients[0].hostname] ) assert f'CN={self.clients[0].hostname}' in result.stdout_text # enable pruning self.master.run_command(['ipa-acme-manage', 'pruning', '--enable']) # cron would be set to run the next minute cron_minute = self.master.run_command( [ "python3", "-c", ( "from datetime import datetime, timedelta; " "print(int((datetime.now() + " "timedelta(minutes=5)).strftime('%M')))" ), ] ).stdout_text.strip() self.master.run_command( ['ipa-acme-manage', 'pruning', f'--cron={cron_minute} * * * *'] ) self.master.run_command(['ipactl', 'restart']) # wait for 5 minutes to cron to execute and 20 sec for just in case time.sleep(320) # check if client cert is removed result = self.master.run_command( ['ipa', 'cert-find', '--subject', self.clients[0].hostname], raiseonerr=False ) assert f'CN={self.clients[0].hostname}' not in result.stdout_text class TestHSMVault(BaseHSMTest): """Validate that vault works properly""" num_clients = 1 master_with_kra = True @classmethod def install(cls, mh): super(TestHSMVault, cls).install(mh) tasks.install_client(cls.master, cls.clients[0]) def test_hsm_vault_create_and_retrieve_master(self): vault_name = "testvault" vault_password = "password" vault_data = "SSBsb3ZlIENJIHRlc3RzCg==" # create vault on master tasks.kinit_admin(self.master) self.master.run_command([ "ipa", "vault-add", vault_name, "--password", vault_password, "--type", "symmetric", ]) # archive vault self.master.run_command([ "ipa", "vault-archive", vault_name, "--password", vault_password, "--data", vault_data, ]) # wait after archival time.sleep(45) # retrieve vault on master self.master.run_command([ "ipa", "vault-retrieve", vault_name, "--password", vault_password, ]) # retrieve on client tasks.kinit_admin(self.clients[0]) self.clients[0].run_command([ "ipa", "vault-retrieve", vault_name, "--password", vault_password, ])
45,816
Python
.py
1,103
31.519492
79
0.595825
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,559
test_ipa_idrange_fix.py
freeipa_freeipa/ipatests/test_integration/test_ipa_idrange_fix.py
# # Copyright (C) 2024 FreeIPA Contributors see COPYING for license # """ Module provides tests for ipa-idrange-fix CLI. """ import logging import re from ipatests.pytest_ipa.integration import tasks from ipatests.test_integration.base import IntegrationTest logger = logging.getLogger(__name__) class TestIpaIdrangeFix(IntegrationTest): topology = 'line' @classmethod def install(cls, mh): super(TestIpaIdrangeFix, cls).install(mh) tasks.kinit_admin(cls.master) def test_no_issues(self): """Test ipa-idrange-fix command with no issues.""" result = self.master.run_command(["ipa-idrange-fix", "--unattended"]) expected_under1000 = "No IDs under 1000 found" expected_nochanges = "No changes proposed for existing ranges" expected_newrange = "No new ranges proposed" expected_noissues = "No changes proposed, nothing to do." assert expected_under1000 in result.stderr_text assert expected_nochanges in result.stderr_text assert expected_newrange in result.stderr_text assert expected_noissues in result.stderr_text def test_idrange_no_rid_bases(self): """Test ipa-idrange-fix command with IDrange with no RID bases.""" self.master.run_command([ "ipa", "idrange-add", "idrange_no_rid_bases", "--base-id", '10000', "--range-size", '20000', ]) result = self.master.run_command(["ipa-idrange-fix", "--unattended"]) expected_text = "RID bases updated for range 'idrange_no_rid_bases'" # Remove IDrange with no rid bases self.master.run_command(["ipa", "idrange-del", "idrange_no_rid_bases"]) assert expected_text in result.stderr_text def test_idrange_no_rid_bases_reversed(self): """ Test ipa-idrange-fix command with IDrange with no RID bases, but we previously had a range with RID bases reversed - secondary lower than primary. It is a valid configuration, so we should fix no-RID range. """ self.master.run_command([ "ipa", "idrange-add", "idrange_no_rid_bases", "--base-id", '10000', "--range-size", '20000', ]) self.master.run_command([ "ipa", "idrange-add", "idrange_reversed", "--base-id", '50000', "--range-size", '20000', "--rid-base", '100300000', "--secondary-rid-base", '301000' ]) result = self.master.run_command(["ipa-idrange-fix", "--unattended"]) expected_text = "RID bases updated for range 'idrange_no_rid_bases'" # Remove test IDranges self.master.run_command(["ipa", "idrange-del", "idrange_no_rid_bases"]) self.master.run_command(["ipa", "idrange-del", "idrange_reversed"]) assert expected_text in result.stderr_text def test_users_outofrange(self): """Test ipa-idrange-fix command with users out of range.""" for i in range(1, 20): self.master.run_command([ "ipa", "user-add", "testuser{}".format(i), "--first", "Test", "--last", "User {}".format(i), "--uid", str(100000 + i * 10), ]) result = self.master.run_command(["ipa-idrange-fix", "--unattended"]) expected_text = r"Range '[\w\.]+_id_range_\d{3}' created successfully" match = re.search(expected_text, result.stderr_text) # Remove users out of range and created IDrange for i in range(1, 20): self.master.run_command([ "ipa", "user-del", "testuser{}".format(i) ]) if match is not None: self.master.run_command([ "ipa", "idrange-del", match.group(0).split(" ")[1].replace("'", "") ]) assert match is not None def test_user_outlier(self): """Test ipa-idrange-fix command with outlier user.""" self.master.run_command([ "ipa", "user-add", "testuser_outlier", "--first", "Outlier", "--last", "User", "--uid", '500000', ]) result = self.master.run_command(["ipa-idrange-fix", "--unattended"]) expected_text = "Identities that don't fit the criteria to get a new \ range found!" expected_user = "user 'Outlier User', uid=500000" # Remove outlier user self.master.run_command(["ipa", "user-del", "testuser_outlier"]) assert expected_text in result.stderr_text assert expected_user in result.stderr_text def test_user_under1000(self): """Test ipa-idrange-fix command with user under 1000.""" self.master.run_command([ "ipa", "user-add", "testuser_under1000", "--first", "Under", "--last", "1000", "--uid", '999', ]) result = self.master.run_command(["ipa-idrange-fix", "--unattended"]) expected_text = "IDs under 1000:" expected_user = "user 'Under 1000', uid=999" # Remove user under 1000 self.master.run_command(["ipa", "user-del", "testuser_under1000"]) assert expected_text in result.stderr_text assert expected_user in result.stderr_text def test_user_preserved(self): """Test ipa-idrange-fix command with preserved user.""" self.master.run_command([ "ipa", "user-add", "testuser_preserved", "--first", "Preserved", "--last", "User", "--uid", '9999', ]) self.master.run_command([ "ipa", "user-del", "testuser_preserved", "--preserve" ]) result = self.master.run_command(["ipa-idrange-fix", "--unattended"]) expected_text = "Identities that don't fit the criteria to get a new \ range found!" expected_user = "user 'Preserved User', uid=9999" # Remove preserved user self.master.run_command(["ipa", "user-del", "testuser_preserved"]) assert expected_text in result.stderr_text assert expected_user in result.stderr_text
6,407
Python
.py
157
30.796178
79
0.57506
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,560
test_netgroup.py
freeipa_freeipa/ipatests/test_integration/test_netgroup.py
# # Copyright (C) 2017 FreeIPA Contributors see COPYING for license # import pytest from ipatests.test_integration.base import IntegrationTest from ipatests.pytest_ipa.integration.tasks import clear_sssd_cache test_data = [] for i in range(3): data = { 'user': { 'login': 'testuser_{}'.format(i), 'first': 'Test_{}'.format(i), 'last': 'User_{}'.format(i), }, 'netgroup': 'testgroup_{}'.format(i), 'nested_netgroup': 'testgroup_{}'.format(i-1) if i > 0 else None } test_data.append(data) members = [d['user']['login'] for d in test_data] test_data[-1]['netgroup_nested_members'] = members @pytest.fixture() def three_netgroups(request): """Prepare basic netgroups with users""" for d in test_data: request.cls.master.run_command(['ipa', 'user-add', d['user']['login'], '--first', d['user']['first'], '--last', d['user']['last']], raiseonerr=False) request.cls.master.run_command(['ipa', 'netgroup-add', d['netgroup']], raiseonerr=False) user_opt = '--users={u[login]}'.format(u=d['user']) request.cls.master.run_command(['ipa', 'netgroup-add-member', user_opt, d['netgroup']], raiseonerr=False) def teardown_three_netgroups(): """Clean basic netgroups with users""" for d in test_data: request.cls.master.run_command(['ipa', 'user-del', d['user']['login']], raiseonerr=False) request.cls.master.run_command(['ipa', 'netgroup-del', d['netgroup']], raiseonerr=False) request.addfinalizer(teardown_three_netgroups) class TestNetgroups(IntegrationTest): """ Test Netgroups """ topology = 'line' def check_users_in_netgroups(self): """Check if users are in groups, no nested things""" master = self.master clear_sssd_cache(master) for d in test_data: result = master.run_command(['getent', 'passwd', d['user']['login']], raiseonerr=False) assert result.returncode == 0 user = '{u[first]} {u[last]}'.format(u=d['user']) assert user in result.stdout_text result = master.run_command(['getent', 'netgroup', d['netgroup']], raiseonerr=False) assert result.returncode == 0 netgroup = '(-,{},{})'.format(d['user']['login'], self.master.domain.name) assert netgroup in result.stdout_text def check_nested_netgroup_hierarchy(self): """Check if nested netgroups hierarchy is complete""" master = self.master clear_sssd_cache(master) for d in test_data: result = master.run_command(['getent', 'netgroup', d['netgroup']], raiseonerr=False) assert result.returncode == 0 for member in d['netgroup_nested_members']: if not member: continue netgroup = '(-,{},{})'.format(member, self.master.domain.name) assert netgroup in result.stdout_text def prepare_nested_netgroup_hierarchy(self): """Prepares nested netgroup hierarchy from basic netgroups""" for d in test_data: if not d['nested_netgroup']: continue netgroups_opt = '--netgroups={}'.format(d['nested_netgroup']) self.master.run_command(['ipa', 'netgroup-add-member', netgroups_opt, d['netgroup']]) def test_add_nested_netgroup(self, three_netgroups): """Test of adding nested groups""" self.check_users_in_netgroups() self.prepare_nested_netgroup_hierarchy() self.check_nested_netgroup_hierarchy() def test_remove_nested_netgroup(self, three_netgroups): """Test of removing nested groups""" master = self.master trinity = ['(-,{},{})'.format(d['user']['login'], self.master.domain.name) for d in test_data] self.check_users_in_netgroups() self.prepare_nested_netgroup_hierarchy() self.check_nested_netgroup_hierarchy() # Removing of testgroup_1 from testgroup_2 netgroups_opt = '--netgroups={n[netgroup]}'.format(n=test_data[0]) result = self.master.run_command(['ipa', 'netgroup-remove-member', netgroups_opt, test_data[1]['netgroup']], raiseonerr=False) assert result.returncode == 0 clear_sssd_cache(master) result = master.run_command(['getent', 'netgroup', test_data[1]['netgroup']], raiseonerr=False) assert result.returncode == 0 assert trinity[1] in result.stdout_text result = master.run_command(['getent', 'netgroup', test_data[2]['netgroup']], raiseonerr=False) assert result.returncode == 0 assert trinity[0] not in result.stdout_text assert trinity[1] in result.stdout_text assert trinity[2] in result.stdout_text # Removing of testgroup_2 from testgroup_3 netgroups_opt = '--netgroups={n[netgroup]}'.format(n=test_data[1]) result = self.master.run_command(['ipa', 'netgroup-remove-member', netgroups_opt, test_data[2]['netgroup']], raiseonerr=False) assert result.returncode == 0 clear_sssd_cache(master) result = master.run_command(['getent', 'netgroup', test_data[2]['netgroup']], raiseonerr=False) assert result.returncode == 0 assert trinity[0] not in result.stdout_text assert trinity[1] not in result.stdout_text assert trinity[2] in result.stdout_text
6,553
Python
.py
134
33.410448
79
0.523653
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,561
example_cli.py
freeipa_freeipa/ipatests/test_integration/example_cli.py
import os import ipalib from ipaplatform.paths import paths # authenticate with host keytab and custom ccache os.environ.update( KRB5_CLIENT_KTNAME=paths.KRB5_KEYTAB, ) # custom options overrides = {"context": "example_cli"} ipalib.api.bootstrap(**overrides) with ipalib.api as api: user = api.Command.user_show("admin") print(user) assert not api.Backend.rpcclient.isconnected()
397
Python
.py
14
26.142857
49
0.785714
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,562
test_resolvers_manager.py
freeipa_freeipa/ipatests/test_integration/test_resolvers_manager.py
import pytest import re from contextlib import contextmanager from ipatests.pytest_ipa.integration import tasks from ipatests.test_integration.base import IntegrationTest class TestResolverManager(IntegrationTest): topology = 'line' num_clients = 1 invalid_resolver = '2.3.4.5' @classmethod def install(cls, mh): test_record = 'test1234' cls.client = cls.clients[0] cls.test_record = '{}.{}'.format(test_record, cls.master.domain.name) cls.test_record_address = '1.2.3.4' if cls.domain_level is not None: domain_level = cls.domain_level else: domain_level = cls.master.config.domain_level tasks.install_topo(cls.topology, cls.master, [], [], domain_level) tasks.kinit_admin(cls.master) cls.master.run_command([ 'ipa', 'dnsrecord-add', cls.master.domain.name, test_record, '--a-ip-address={}'.format(cls.test_record_address)]) def is_resolver_operational(self): res = self.client.run_command(['dig', '+short', 'redhat.com']) return re.match(r'\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}', res.stdout_text.strip()) def is_ipa_dns_used(self): res = self.client.run_command(['dig', '+short', self.test_record]) output = res.stdout_text.strip() error = res.stderr_text.strip() if output == self.test_record_address: return True if output == '' and error == '': return False raise Exception('Unexpected result of dig command') def check_ipa_name_resolution_fails(self): res = self.client.run_command(['dig', '+short', self.test_record], ok_returncode=9) assert 'connection timed out' in res.stdout_text @contextmanager def start_end_checks(self): assert not self.client.resolver.has_backups() assert self.is_resolver_operational() assert not self.is_ipa_dns_used() yield assert self.is_resolver_operational() assert not self.is_ipa_dns_used() assert not self.client.resolver.has_backups() def test_ipa_dns_not_used_by_default(self): assert self.is_resolver_operational() assert not self.is_ipa_dns_used() def test_changing_config_without_backup_not_allowed(self): with pytest.raises(Exception, match='without backup'): self.client.resolver.setup_resolver(self.master.ip) def test_change_resolver(self): with self.start_end_checks(): self.client.resolver.backup() self.client.resolver.setup_resolver(self.master.ip) assert self.is_resolver_operational() assert self.is_ipa_dns_used() self.client.resolver.restore() def test_nested_change_resolver(self): with self.start_end_checks(): self.client.resolver.backup() self.client.resolver.setup_resolver(self.master.ip) assert self.is_resolver_operational() assert self.is_ipa_dns_used() self.client.resolver.backup() self.client.resolver.setup_resolver(self.invalid_resolver) self.check_ipa_name_resolution_fails() self.client.resolver.restore() assert self.is_resolver_operational() assert self.is_ipa_dns_used() self.client.resolver.restore() def test_nested_change_resolver_with_context(self): with self.start_end_checks(): self.client.resolver.backup() self.client.resolver.setup_resolver(self.master.ip) assert self.is_resolver_operational() assert self.is_ipa_dns_used() with self.client.resolver: self.client.resolver.setup_resolver(self.invalid_resolver) self.check_ipa_name_resolution_fails() self.client.resolver.restore() def test_repeated_changing_resolver(self): with self.start_end_checks(): self.client.resolver.backup() self.client.resolver.setup_resolver(self.master.ip) assert self.is_resolver_operational() assert self.is_ipa_dns_used() self.client.resolver.setup_resolver(self.invalid_resolver) self.check_ipa_name_resolution_fails() self.client.resolver.setup_resolver(self.master.ip) assert self.is_resolver_operational() assert self.is_ipa_dns_used() self.client.resolver.restore() @pytest.mark.parametrize('reverse', [True, False]) def test_multiple_resolvers(self, reverse): resolvers = [self.invalid_resolver, self.master.ip] if reverse: resolvers.reverse() with self.start_end_checks(): self.client.resolver.backup() self.client.resolver.setup_resolver(resolvers) assert self.is_resolver_operational() assert self.is_ipa_dns_used() self.client.resolver.restore() @classmethod def uninstall(cls, mh): tasks.uninstall_master(cls.master)
5,139
Python
.py
113
35.19469
77
0.632126
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,563
test_pwpolicy.py
freeipa_freeipa/ipatests/test_integration/test_pwpolicy.py
# # Copyright (C) 2020 FreeIPA Contributors see COPYING for license # """Misc test for 'ipa' CLI regressions """ from __future__ import absolute_import import pytest from ipatests.test_integration.base import IntegrationTest from ipatests.pytest_ipa.integration import tasks USER = 'tuser' PASSWORD = 'Secret123' POLICY = 'test' class TestPWPolicy(IntegrationTest): """ Test password policy in action. """ num_replicas = 1 topology = 'line' @classmethod def install(cls, mh): super(TestPWPolicy, cls).install(mh) tasks.kinit_admin(cls.master) cls.master.run_command(['ipa', 'user-add', USER, '--first', 'Test', '--last', 'User']) cls.master.run_command(['ipa', 'group-add', POLICY]) cls.master.run_command(['ipa', 'group-add-member', POLICY, '--users', USER]) cls.master.run_command(['ipa', 'pwpolicy-add', POLICY, '--priority', '1', '--gracelimit', '-1', '--minlength', '6']) cls.master.run_command(['ipa', 'passwd', USER], stdin_text='{password}\n{password}\n'.format( password=PASSWORD )) def kinit_as_user(self, host, old_password, new_password, user=USER, raiseonerr=True): """kinit to an account with an expired password""" return host.run_command( ['kinit', user], raiseonerr=raiseonerr, stdin_text='{old}\n{new}\n{new}\n'.format( old=old_password, new=new_password ), ) def reset_password(self, host, user=USER, password=PASSWORD): tasks.kinit_admin(host) host.run_command( ['ipa', 'passwd', user], stdin_text='{password}\n{password}\n'.format(password=password), ) def set_pwpolicy(self, minlength=None, maxrepeat=None, maxsequence=None, dictcheck=None, usercheck=None, minclasses=None): tasks.kinit_admin(self.master) args = ["ipa", "pwpolicy-mod", POLICY] if minlength is not None: args.append("--minlength={}".format(minlength)) if maxrepeat is not None: args.append("--maxrepeat={}".format(maxrepeat)) if maxsequence is not None: args.append("--maxsequence={}".format(maxsequence)) if dictcheck is not None: args.append("--dictcheck={}".format(dictcheck)) if usercheck is not None: args.append("--usercheck={}".format(usercheck)) if minclasses is not None: args.append("--minclasses={}".format(minclasses)) self.master.run_command(args) self.reset_password(self.master) def clean_pwpolicy(self): """Set all policy values we care about to zero/false""" self.master.run_command( ["ipa", "pwpolicy-mod", POLICY, "--maxrepeat", "0", "--maxsequence", "0", "--usercheck", "false", "--dictcheck" ,"false", "--minlife", "0", "--minlength", "0", "--minclasses", "0",], ) # minlength => 6 is required for any of the libpwquality settings self.master.run_command( ["ipa", "pwpolicy-mod", POLICY, "--minlength", "6"], raiseonerr=False, ) @pytest.fixture def reset_pwpolicy(self): """Fixture to ensure policy is reset between tests""" yield tasks.kinit_admin(self.master) self.clean_pwpolicy() def test_maxrepeat(self, reset_pwpolicy): self.set_pwpolicy(maxrepeat=2) # good passwords for password in ('Secret123', 'Password'): self.reset_password(self.master) self.kinit_as_user(self.master, PASSWORD, password) self.reset_password(self.master) tasks.ldappasswd_user_change(USER, PASSWORD, password, self.master) self.reset_password(self.master) # bad passwords for password in ('Secret1111', 'passsword'): result = self.kinit_as_user(self.master, PASSWORD, password, raiseonerr=False) assert result.returncode == 1 result = tasks.ldappasswd_user_change(USER, PASSWORD, password, self.master, raiseonerr=False) assert result.returncode == 1 assert 'Password has too many consecutive characters' in \ result.stdout_text def test_maxsequence(self, reset_pwpolicy): self.set_pwpolicy(maxsequence=3) # good passwords for password in ('Password123', 'Passwordabc'): self.reset_password(self.master) self.kinit_as_user(self.master, PASSWORD, password) self.reset_password(self.master) tasks.ldappasswd_user_change(USER, PASSWORD, password, self.master) self.reset_password(self.master) # bad passwords for password in ('Password1234', 'Passwordabcde'): result = self.kinit_as_user(self.master, PASSWORD, password, raiseonerr=False) assert result.returncode == 1 result = tasks.ldappasswd_user_change(USER, PASSWORD, password, self.master, raiseonerr=False) assert result.returncode == 1 assert 'Password contains a monotonic sequence' in \ result.stdout_text def test_usercheck(self, reset_pwpolicy): self.set_pwpolicy(usercheck=True) for password in ('tuserpass', 'passoftuser'): result = self.kinit_as_user(self.master, PASSWORD, password, raiseonerr=False) assert result.returncode == 1 result = tasks.ldappasswd_user_change(USER, PASSWORD, password, self.master, raiseonerr=False) assert result.returncode == 1 assert 'Password contains username' in \ result.stdout_text # test with valid password self.kinit_as_user(self.master, PASSWORD, 'bamOncyftAv0') def test_dictcheck(self, reset_pwpolicy): self.set_pwpolicy(dictcheck=True) for password in ('password', 'bookends', 'BaLtim0re'): result = self.kinit_as_user(self.master, PASSWORD, password, raiseonerr=False) assert result.returncode == 1 result = tasks.ldappasswd_user_change(USER, PASSWORD, password, self.master, raiseonerr=False) assert result.returncode == 1 assert 'Password is based on a dictionary word' in \ result.stdout_text # test with valid password self.kinit_as_user(self.master, PASSWORD, 'bamOncyftAv0') def test_minclasses(self, reset_pwpolicy): self.set_pwpolicy(minclasses=2) for password in ('password', 'bookends'): result = self.kinit_as_user(self.master, PASSWORD, password, raiseonerr=False) assert result.returncode == 1 assert 'Password does not contain enough character' in \ result.stdout_text result = tasks.ldappasswd_user_change(USER, PASSWORD, password, self.master, raiseonerr=False) assert result.returncode == 1 assert 'Password is too simple' in \ result.stdout_text # test with valid password for valid in ('Password', 'password1', 'password!'): self.kinit_as_user(self.master, PASSWORD, valid) self.reset_password(self.master) self.set_pwpolicy(minclasses=3) for password in ('password1', 'Bookends'): result = self.kinit_as_user(self.master, PASSWORD, password, raiseonerr=False) assert result.returncode == 1 assert 'Password does not contain enough character' in \ result.stdout_text result = tasks.ldappasswd_user_change(USER, PASSWORD, password, self.master, raiseonerr=False) assert result.returncode == 1 assert 'Password is too simple' in \ result.stdout_text self.reset_password(self.master) # test with valid password for valid in ('Passw0rd', 'password1!', 'Password!'): self.kinit_as_user(self.master, PASSWORD, valid) self.reset_password(self.master) def test_minlength_mod(self, reset_pwpolicy): """Test that the pwpolicy minlength overrides our policy """ # With a minlength of 4 all settings of pwq should fail self.master.run_command( ["ipa", "pwpolicy-mod", POLICY, "--minlength", "4",] ) for values in (('--maxrepeat', '4'), ('--maxsequence', '4'), ('--dictcheck', 'true'), ('--usercheck', 'true')): args = ["ipa", "pwpolicy-mod", POLICY] args.extend(values) result = self.master.run_command(args, raiseonerr=False) assert result.returncode != 0 assert 'minlength' in result.stderr_text # With any pwq value set, setting minlife < 6 should fail for values in (('--maxrepeat', '4'), ('--maxsequence', '4'), ('--dictcheck', 'true'), ('--usercheck', 'true')): self.clean_pwpolicy() args = ["ipa", "pwpolicy-mod", POLICY] args.extend(values) self.master.run_command(args) result = self.master.run_command( ["ipa", "pwpolicy-mod", POLICY, "--minlength", "4",], raiseonerr=False ) assert result.returncode != 0 assert 'minlength' in result.stderr_text def test_minlength_empty(self, reset_pwpolicy): """Test that the pwpolicy minlength can be blank """ # Ensure it is set to a non-zero value to avoid EmptyModlist self.master.run_command( ["ipa", "pwpolicy-mod", POLICY, "--minlength", "10",] ) # Enable one of the libpwquality options, removing minlength # should fail. self.master.run_command( ["ipa", "pwpolicy-mod", POLICY, "--maxrepeat", "4",] ) result = self.master.run_command( ["ipa", "pwpolicy-mod", POLICY, "--minlength", "",], raiseonerr=False ) assert result.returncode != 0 # Remove the blocking value self.master.run_command( ["ipa", "pwpolicy-mod", POLICY, "--maxrepeat", "",] ) # Now erase it result = self.master.run_command( ["ipa", "pwpolicy-mod", POLICY, "--minlength", "",] ) assert result.returncode == 0 assert 'minlength' not in result.stderr_text def test_minlength_add(self): """Test that adding a new policy with minlength is caught. """ result = self.master.run_command( ["ipa", "pwpolicy-add", "test_add", "--maxrepeat", "4", "--minlength", "4", "--priority", "2"], raiseonerr=False ) assert result.returncode != 0 assert 'minlength' in result.stderr_text def test_graceperiod_expired(self): """Test the LDAP bind grace period""" dn = "uid={user},cn=users,cn=accounts,{base_dn}".format( user=USER, base_dn=str(self.master.domain.basedn)) self.master.run_command( ["ipa", "pwpolicy-mod", POLICY, "--gracelimit", "3", ], ) # Resetting the password will mark it as expired self.reset_password(self.master) for i in range(2, -1, -1): result = self.master.run_command( ["ldapsearch", "-e", "ppolicy", "-D", dn, "-w", PASSWORD, "-b", dn], raiseonerr=False ) # We're in grace, this will succeed assert result.returncode == 0 # verify that we get the expected ppolicy output assert 'Password expired, {} grace logins remain'.format(i) \ in result.stderr_text # Now grace is done and binds should fail. result = self.master.run_command( ["ldapsearch", "-e", "ppolicy", "-D", dn, "-w", PASSWORD, "-b", dn], raiseonerr=False ) assert result.returncode == 49 assert 'Password is expired' in result.stderr_text assert 'Password expired, 0 grace logins remain' in result.stderr_text # Test that resetting the password resets the grace counter self.reset_password(self.master) result = tasks.ldapsearch_dm( self.master, dn, ['passwordgraceusertime',], ) assert 'passwordgraceusertime: 0' in result.stdout_text.lower() def test_graceperiod_not_replicated(self): """Test that the grace period is reset on password reset""" dn = "uid={user},cn=users,cn=accounts,{base_dn}".format( user=USER, base_dn=str(self.master.domain.basedn)) # Resetting the password will mark it as expired self.reset_password(self.master) # Generate some logins but don't exceed the limit for _i in range(2, -1, -1): result = self.master.run_command( ["ldapsearch", "-e", "ppolicy", "-D", dn, "-w", PASSWORD, "-b", dn], raiseonerr=False ) # Verify that passwordgraceusertime is not replicated result = tasks.ldapsearch_dm( self.master, dn, ['passwordgraceusertime',], ) assert 'passwordgraceusertime: 3' in result.stdout_text.lower() result = tasks.ldapsearch_dm( self.replicas[0], dn, ['passwordgraceusertime',], ) # Never been set at all so won't return assert 'passwordgraceusertime' not in result.stdout_text.lower() # Resetting the password should reset passwordgraceusertime self.reset_password(self.master) result = tasks.ldapsearch_dm( self.master, dn, ['passwordgraceusertime',], ) assert 'passwordgraceusertime: 0' in result.stdout_text.lower() self.reset_password(self.master) def test_graceperiod_zero(self): """Test the LDAP bind with zero grace period""" dn = "uid={user},cn=users,cn=accounts,{base_dn}".format( user=USER, base_dn=str(self.master.domain.basedn)) self.master.run_command( ["ipa", "pwpolicy-mod", POLICY, "--gracelimit", "0", ], ) # Resetting the password will mark it as expired self.reset_password(self.master) # Now grace is done and binds should fail. result = self.master.run_command( ["ldapsearch", "-e", "ppolicy", "-D", dn, "-w", PASSWORD, "-b", dn], raiseonerr=False ) assert result.returncode == 49 assert 'Password is expired' in result.stderr_text assert 'Password expired, 0 grace logins remain' in result.stderr_text def test_graceperiod_disabled(self): """Test the LDAP bind with grace period disabled (-1)""" str(self.master.domain.basedn) dn = "uid={user},cn=users,cn=accounts,{base_dn}".format( user=USER, base_dn=str(self.master.domain.basedn)) # This can fail if gracelimit is already -1 so ignore it self.master.run_command( ["ipa", "pwpolicy-mod", POLICY, "--gracelimit", "-1",], raiseonerr=False, ) # Ensure the password is expired self.reset_password(self.master) result = self.kinit_as_user(self.master, PASSWORD, PASSWORD) for _i in range(0, 10): result = self.master.run_command( ["ldapsearch", "-e", "ppolicy", "-D", dn, "-w", PASSWORD, "-b", dn] ) # With graceperiod disabled it should not increment result = tasks.ldapsearch_dm( self.master, dn, ['passwordgraceusertime',], ) assert 'passwordgraceusertime: 0' in result.stdout_text.lower()
17,118
Python
.py
373
32.761394
79
0.554217
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,564
test_random_serial_numbers.py
freeipa_freeipa/ipatests/test_integration/test_random_serial_numbers.py
# # Copyright (C) 2022 FreeIPA Contributors see COPYING for license # import pytest from ipaplatform.paths import paths from ipatests.pytest_ipa.integration import tasks from ipatests.test_integration.test_installation import ( TestInstallWithCA_DNS1, TestInstallWithCA_KRA1, ) from ipatests.test_integration.test_caless import TestServerCALessToExternalCA from ipatests.test_integration.test_vault import TestInstallKRA from ipatests.test_integration.test_commands import TestIPACommand def pki_supports_RSNv3(host): """ Return whether the host supports RNSv3 based on the pki version """ script = ("from ipaserver.install.ca import " "random_serial_numbers_version; " "print(random_serial_numbers_version(True))") result = host.run_command(['python3', '-c', script]) if 'true' in result.stdout_text.strip().lower(): return True return False def check_pki_config_params(host): # Check CS.cfg try: cs_cfg = host.get_file_contents(paths.CA_CS_CFG_PATH) kra_cfg = host.get_file_contents(paths.KRA_CS_CFG_PATH) assert "dbs.cert.id.generator=random".encode() in cs_cfg assert "dbs.request.id.generator=random".encode() in cs_cfg assert "dbs.key.id.generator=random".encode() in kra_cfg except IOError: pytest.skip("PKI config not present.Skipping test") class TestInstallWithCA_DNS1_RSN(TestInstallWithCA_DNS1): random_serial = True @classmethod def install(cls, mh): if not pki_supports_RSNv3(mh.master): raise pytest.skip("RNSv3 not supported") super(TestInstallWithCA_DNS1_RSN, cls).install(mh) class TestInstallWithCA_KRA1_RSN(TestInstallWithCA_KRA1): random_serial = True @classmethod def install(cls, mh): if not pki_supports_RSNv3(mh.master): raise pytest.skip("RNSv3 not supported") super(TestInstallWithCA_KRA1_RSN, cls).install(mh) class TestIPACommand_RSN(TestIPACommand): random_serial = True @classmethod def install(cls, mh): if not pki_supports_RSNv3(mh.master): raise pytest.skip("RNSv3 not supported") super(TestIPACommand_RSN, cls).install(mh) class TestServerCALessToExternalCA_RSN(TestServerCALessToExternalCA): random_serial = True @classmethod def install(cls, mh): if not pki_supports_RSNv3(mh.master): raise pytest.skip("RNSv3 not supported") super(TestServerCALessToExternalCA_RSN, cls).install(mh) @classmethod def uninstall(cls, mh): if not pki_supports_RSNv3(mh.master): raise pytest.skip("RSNv3 not supported") super(TestServerCALessToExternalCA_RSN, cls).uninstall(mh) class TestRSNPKIConfig(TestInstallWithCA_KRA1): random_serial = True num_replicas = 3 @classmethod def install(cls, mh): if not pki_supports_RSNv3(mh.master): raise pytest.skip("RSNv3 not supported") super(TestRSNPKIConfig, cls).install(mh) def test_check_pki_config(self): check_pki_config_params(self.master) check_pki_config_params(self.replicas[0]) check_pki_config_params(self.replicas[1]) def test_check_rsn_version(self): tasks.kinit_admin(self.master) res = self.master.run_command(['ipa', 'ca-find']) assert 'RSN Version: 3' in res.stdout_text tasks.kinit_admin(self.replicas[0]) res = self.replicas[0].run_command(['ipa', 'ca-find']) assert 'RSN Version: 3' in res.stdout_text class TestRSNVault(TestInstallKRA): random_serial = True @classmethod def install(cls, mh): if not pki_supports_RSNv3(mh.master): raise pytest.skip("RSNv3 not supported") super(TestRSNVault, cls).install(mh)
3,811
Python
.py
93
34.387097
78
0.7
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,565
test_ntp_options.py
freeipa_freeipa/ipatests/test_integration/test_ntp_options.py
# # Copyright (C) 2018 FreeIPA Contributors see COPYING for license # import pytest from ipatests.test_integration.base import IntegrationTest from ipatests.pytest_ipa.integration import tasks from ipaplatform.paths import paths class TestNTPoptions(IntegrationTest): """ Test NTP Options: --no-ntp / -N --ntp-server --ntp-pool """ num_clients = 1 num_replicas = 1 ntp_pool = "pool.ntp.org" ntp_server1 = "1.pool.ntp.org" ntp_server2 = "2.pool.ntp.org" print_chrony_conf = ['cat', paths.CHRONY_CONF] exp_records_msg = "No SRV records of NTP servers found and " \ "no NTP server or pool address was provided." exp_chrony_msg = "Using default chrony configuration." exp_exclude_msg = "Excluded by options:" exp_default_msg = "Using default chrony configuration." exp_change_msg = "Configuration of chrony was changed by installer." exp_srv_err = "error: --ntp-server cannot be used " \ "together with --no-ntp" exp_pool_err = "error: --ntp-pool cannot be used " \ "together with --no-ntp" exp_prom_err = "NTP configuration cannot be updated during promotion" @pytest.fixture(autouse=True) def ntpoptions_setup(self, request): def fin(): """ Uninstall ipa-server, ipa-replica and ipa-client """ tasks.uninstall_client(self.client) tasks.uninstall_master(self.replica) tasks.uninstall_master(self.master) request.addfinalizer(fin) @classmethod def install(cls, mh): cls.client = cls.clients[0] cls.replica = cls.replicas[0] def test_server_client_install_without_options(self): """ test to verify that ipa-server and ipa-client install uses default chrony configuration without any NTP options specified """ server_install = tasks.install_master(self.master, setup_dns=False) assert self.exp_records_msg in server_install.stderr_text assert self.exp_chrony_msg in server_install.stdout_text client_install = tasks.install_client(self.master, self.client, nameservers=None) assert self.exp_records_msg in client_install.stderr_text assert self.exp_chrony_msg in client_install.stdout_text def test_server_client_install_no_ntp(self): """ test to verify that ipa-server and ipa-client install invoked with option -N uses system defined NTP daemon configuration """ server_install = tasks.install_master(self.master, setup_dns=False, extra_args=['-N']) assert self.exp_exclude_msg in server_install.stdout_text assert self.exp_default_msg not in server_install.stdout_text client_install = tasks.install_client(self.master, self.client, extra_args=['--no-ntp'], nameservers=None) assert self.exp_default_msg not in client_install.stdout_text def test_server_client_install_with_multiple_ntp_srv(self): """ test to verify that ipa-server-install passes with multiple --ntp-server option used """ args = ['--ntp-server=%s' % self.ntp_server1, '--ntp-server=%s' % self.ntp_server2] server_install = tasks.install_master(self.master, setup_dns=False, extra_args=args) assert self.exp_change_msg in server_install.stderr_text cmd = self.master.run_command(['cat', paths.CHRONY_CONF]) assert self.ntp_server1 in cmd.stdout_text assert self.ntp_server2 in cmd.stdout_text client_install = tasks.install_client(self.master, self.client, extra_args=args, nameservers=None) assert self.exp_change_msg in client_install.stderr_text cmd = self.client.run_command(['cat', paths.CHRONY_CONF]) assert self.ntp_server1 in cmd.stdout_text assert self.ntp_server2 in cmd.stdout_text def test_server_replica_client_install_with_pool_and_srv(self): """ test to verify that ipa-server, ipa-replica and ipa-client install passes with options --ntp-pool and --ntp-server together """ args = ['--ntp-pool=%s' % self.ntp_pool, '--ntp-server=%s' % self.ntp_server1] server_install = tasks.install_master(self.master, setup_dns=False, extra_args=args) assert self.exp_change_msg in server_install.stderr_text cmd = self.master.run_command(['cat', paths.CHRONY_CONF]) assert self.ntp_pool in cmd.stdout_text assert self.ntp_server1 in cmd.stdout_text replica_install = tasks.install_replica(self.master, self.replica, extra_args=args, promote=False, nameservers=None) assert self.exp_change_msg in replica_install.stderr_text cmd = self.replica.run_command(['cat', paths.CHRONY_CONF]) assert self.ntp_pool in cmd.stdout_text assert self.ntp_server1 in cmd.stdout_text client_install = tasks.install_client(self.master, self.client, extra_args=args, nameservers=None) assert self.exp_change_msg in client_install.stderr_text cmd = self.client.run_command(['cat', paths.CHRONY_CONF]) assert self.ntp_pool in cmd.stdout_text assert self.ntp_server1 in cmd.stdout_text def test_server_promoted_replica_client_install_with_srv(self): """ test to verify that ipa-server, promotion of ipa-replica and ipa-client install passes with options --ntp-server """ args = ['--ntp-server=%s' % self.ntp_server1] server_install = tasks.install_master(self.master, setup_dns=False, extra_args=args) assert self.exp_change_msg in server_install.stderr_text cmd = self.master.run_command(['cat', paths.CHRONY_CONF]) assert self.ntp_server1 in cmd.stdout_text replica_install = tasks.install_replica(self.master, self.replica, extra_args=args, promote=True, nameservers=None) # while promoting with tasks expected_msg will not be in output assert self.exp_change_msg not in replica_install.stderr_text cmd = self.replica.run_command(['cat', paths.CHRONY_CONF]) assert self.ntp_server1 in cmd.stdout_text client_install = tasks.install_client(self.master, self.client, extra_args=args, nameservers=None) assert self.exp_change_msg in client_install.stderr_text cmd = self.client.run_command(['cat', paths.CHRONY_CONF]) assert self.ntp_server1 in cmd.stdout_text def test_server_client_install_mixed_options(self): """ test to verify that ipa-server and ipa-client install with --ntp-server and -N options would fail """ args1 = ['ipa-server-install', '-N', '--ntp-server=%s' % self.ntp_server1] server_install = self.master.run_command(args1, raiseonerr=False) assert server_install.returncode == 2 assert self.exp_srv_err in server_install.stderr_text args2 = ['ipa-client-install', '--no-ntp', '--ntp-server=%s' % self.ntp_server2] client_install = self.client.run_command(args2, raiseonerr=False) assert client_install.returncode == 2 assert self.exp_srv_err in client_install.stderr_text args3 = ['ipa-client-install', '-N', '--ntp-pool=%s' % self.ntp_pool] client_install = self.client.run_command(args3, raiseonerr=False) assert client_install.returncode == 2 assert self.exp_pool_err in client_install.stderr_text def test_replica_promotion_with_ntp_options(self): """ test to verify that replica promotion with ntp --ntp-server, --ntp-pool and -N or --no-ntp option would fail """ tasks.install_master(self.master, setup_dns=False) tasks.install_client(self.master, self.replica, nameservers=None) replica_install = self.replica.run_command( ['ipa-replica-install', '--no-ntp'], raiseonerr=False) assert replica_install.returncode == 1 assert self.exp_prom_err in replica_install.stderr_text replica_install = self.replica.run_command( ['ipa-replica-install', '--ntp-server=%s' % self.ntp_server1], raiseonerr=False) assert replica_install.returncode == 1 assert self.exp_prom_err in replica_install.stderr_text replica_install = self.replica.run_command( ['ipa-replica-install', '--ntp-pool=%s' % self.ntp_pool], raiseonerr=False) assert replica_install.returncode == 1 assert self.exp_prom_err in replica_install.stderr_text def test_replica_promotion_without_ntp(self): """ test to verify that replica promotion without ntp options - ipa-client-install with ntp option - ipa-replica-install without ntp option will be successful """ ntp_args = ['--ntp-pool=%s' % self.ntp_pool] server_install = tasks.install_master(self.master, setup_dns=False, extra_args=ntp_args) assert self.exp_change_msg in server_install.stderr_text client_install = tasks.install_client(self.master, self.replica, extra_args=ntp_args, nameservers=None) assert self.exp_change_msg in client_install.stderr_text replica_install = tasks.install_replica(self.master, self.replica, promote=False, nameservers=None) assert "ipa-replica-install command was successful" in \ replica_install.stderr_text cmd = self.replica.run_command(['cat', paths.CHRONY_CONF]) assert self.ntp_pool in cmd.stdout_text def test_interactive_ntp_set_opt(self): """ Test to verify that ipa installations with ntp options passed interactively (without -U/--nattended) will be successful - ipa-server-install - ipa-client-install Both NTP servers and pool passed interactively to options. """ server_input = ( # Do you want to configure integrated DNS (BIND)? [no]: "No\n" # Server host name [hostname]: "\n" # Enter the NetBIOS name for the IPA domain "IPA\n" # Do you want to configure chrony with NTP server # or pool address? [no]: "Yes\n" # Enter NTP source server addresses separated by comma, # or press Enter to skip: "{},{}\n".format(self.ntp_server2, self.ntp_server1) + # Enter a NTP source pool address, or press Enter to skip: "{}\n".format(self.ntp_pool) + # Continue to configure the system with these values? [no]: "Yes" ) client_input = ( # Proceed with fixed values and no DNS discovery? [no]: "Yes\n" # Do you want to configure chrony with NTP server # or pool address? [no]: "Yes\n" # Enter NTP source server addresses separated by comma, # or press Enter to skip: "{},{}\n".format(self.ntp_server2, self.ntp_server1) + # Enter a NTP source pool address, or press Enter to skip: "{}\n".format(self.ntp_pool) + # Continue to configure the system with these values? [no]: "Yes" ) server_install = tasks.install_master(self.master, setup_dns=False, unattended=False, stdin_text=server_input) assert server_install.returncode == 0 assert self.ntp_pool in server_install.stdout_text assert self.ntp_server1 in server_install.stdout_text assert self.ntp_server2 in server_install.stdout_text cmd = self.master.run_command(self.print_chrony_conf) assert self.ntp_pool in cmd.stdout_text assert self.ntp_server1 in cmd.stdout_text assert self.ntp_server2 in cmd.stdout_text client_install = tasks.install_client(self.master, self.client, unattended=False, stdin_text=client_input, nameservers=None) assert client_install.returncode == 0 cmd = self.client.run_command(self.print_chrony_conf) assert self.ntp_pool in cmd.stdout_text assert self.ntp_server1 in cmd.stdout_text assert self.ntp_server2 in cmd.stdout_text def test_interactive_ntp_no_opt(self): """ Test to verify that ipa installations without ntp options passed interactively (without -U/--nattended) will be successful - ipa-server-install - ipa-client-install Both NTP servers and pool configuration skipped interactively. """ server_input = ( "No\n" "\n" "Yes\n" "\n" "\n" "Yes" ) client_input = ( "Yes\n" "Yes\n" "\n" "\n" "Yes" ) server_install = tasks.install_master(self.master, setup_dns=False, unattended=False, stdin_text=server_input) assert server_install.returncode == 0 assert self.exp_records_msg in server_install.stderr_text assert self.exp_chrony_msg in server_install.stdout_text client_install = tasks.install_client(self.master, self.client, unattended=False, stdin_text=client_input, nameservers=None) assert client_install.returncode == 0 assert self.exp_records_msg in client_install.stderr_text assert self.exp_chrony_msg in client_install.stdout_text def test_interactive_ntp_no_conf(self): """ Test to verify that ipa installations without selecting to configure ntp options interactively (without -U/--nattended) will be successful - ipa-server-install - ipa-client-install """ server_input = ( "\n" + "\n" "IPA\n" "No\n" "Yes" ) client_input = ( "Yes\n" "No\n" "Yes" ) server_install = tasks.install_master(self.master, setup_dns=False, unattended=False, stdin_text=server_input) assert server_install.returncode == 0 assert self.exp_records_msg in server_install.stderr_text assert self.exp_chrony_msg in server_install.stdout_text client_install = tasks.install_client(self.master, self.client, unattended=False, stdin_text=client_input, nameservers=None) assert client_install.returncode == 0 assert self.exp_records_msg in client_install.stderr_text assert self.exp_chrony_msg in client_install.stdout_text @classmethod def uninstall(cls, mh): # Cleanup already done in teardown_method pass
16,595
Python
.py
340
34.902941
80
0.576645
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,566
test_cert.py
freeipa_freeipa/ipatests/test_integration/test_cert.py
# # Copyright (C) 2020 FreeIPA Contributors see COPYING for license # """ Module provides tests which testing ability of various certificate related scenarios. """ import os import ipaddress import pytest import random import re import string import time import textwrap from ipaplatform.paths import paths from ipapython.dn import DN from cryptography import x509 from cryptography.x509.oid import ExtensionOID from cryptography.hazmat.backends import default_backend from pkg_resources import parse_version from ipatests.pytest_ipa.integration import tasks from ipatests.test_integration.base import IntegrationTest from ipatests.util import xfail_context DEFAULT_RA_AGENT_SUBMITTED_VAL = '19700101000000' def get_certmonger_fs_id(input_str): """Get certmonger FS ID from the `getcert list -f /var/lib/ipa/ra-agent.pem` output command output :return request ID string """ request_id = re.findall(r'\d+', input_str) return request_id[1] def get_certmonger_request_value(host, requestid, state): """Get certmonger submitted value from /var/lib/certmonger/requests/<timestamp> :return submitted timestamp value """ result = host.run_command( ['grep', '-rl', 'id={0}'.format(requestid), paths.CERTMONGER_REQUESTS_DIR] ) assert result.stdout_text is not None filename = result.stdout_text.strip() request_file = host.get_file_contents(filename, encoding='utf-8') val = None for line in request_file.split('\n'): if line.startswith('%s=' % state): _unused, val = line.partition("=")[::2] break return val class TestInstallMasterClient(IntegrationTest): num_clients = 1 topology = 'line' @classmethod def install(cls, mh): super().install(mh) # time to look into journal logs in # test_certmonger_ipa_responder_jsonrpc cls.since = time.strftime('%Y-%m-%d %H:%M:%S') def test_cacert_file_appear_with_option_F(self): """Test if getcert creates cacert file with -F option It took longer to create the cacert file in older version. restarting the certmonger service creates the file at the location specified by -F option. This fix is to check that cacert file creates immediately after certificate goes into MONITORING state. related: https://pagure.io/freeipa/issue/8105 """ cmd_arg = [ "ipa-getcert", "request", "-f", os.path.join(paths.OPENSSL_CERTS_DIR, "test.pem"), "-k", os.path.join(paths.OPENSSL_PRIVATE_DIR, "test.key"), "-K", "test/%s" % self.clients[0].hostname, "-F", os.path.join(paths.OPENSSL_DIR, "test.CA"), ] result = self.clients[0].run_command(cmd_arg) request_id = re.findall(r'\d+', result.stdout_text) # check if certificate is in MONITORING state status = tasks.wait_for_request(self.clients[0], request_id[0], 50) assert status == "MONITORING" self.clients[0].run_command( ["ls", "-l", os.path.join(paths.OPENSSL_DIR, "test.CA")] ) def test_certmonger_ipa_responder_jsonrpc(self): """Test certmonger IPA responder switched to JSONRPC This is to test if certmonger IPA responder swithed to JSONRPC from XMLRPC This test utilizes the cert request made in previous test. (test_cacert_file_appear_with_option_F) related: https://pagure.io/freeipa/issue/3299 """ # check that request is made against /ipa/json so that # IPA enforce json data type exp_str = 'Submitting request to "https://{}/ipa/json"'.format( self.master.hostname ) result = self.clients[0].run_command([ 'journalctl', '-u', 'certmonger', '--since={}'.format(self.since) ]) assert exp_str in result.stdout_text def test_ipa_getcert_san_aci(self): """Test for DNS and IP SAN extensions + ACIs """ hostname = self.clients[0].hostname certfile = os.path.join(paths.OPENSSL_CERTS_DIR, "test2.pem") tasks.kinit_admin(self.master) zone = tasks.prepare_reverse_zone(self.master, self.clients[0].ip)[0] # add PTR dns record for cert request with SAN extention rec = str(self.clients[0].ip).split('.')[3] result = self.master.run_command( ['ipa', 'dnsrecord-add', zone, rec, '--ptr-rec', hostname] ) assert 'Record name: {}'.format(rec) in result.stdout_text assert 'PTR record: {}'.format(hostname) in result.stdout_text name, zone = hostname.split('.', 1) self.master.run_command(['ipa', 'dnsrecord-show', zone, name]) tasks.kdestroy_all(self.master) cmd_arg = [ 'ipa-getcert', 'request', '-v', '-w', '-f', certfile, '-k', os.path.join(paths.OPENSSL_PRIVATE_DIR, "test2.key"), '-K', f'test/{hostname}', '-D', hostname, '-A', self.clients[0].ip, ] result = self.clients[0].run_command(cmd_arg) request_id = re.findall(r'\d+', result.stdout_text) # check if certificate is in MONITORING state status = tasks.wait_for_request(self.clients[0], request_id[0], 50) assert status == "MONITORING" certdata = self.clients[0].get_file_contents(certfile) cert = x509.load_pem_x509_certificate( certdata, default_backend() ) ext = cert.extensions.get_extension_for_oid( ExtensionOID.SUBJECT_ALTERNATIVE_NAME ) dnsnames = ext.value.get_values_for_type(x509.DNSName) assert dnsnames == [self.clients[0].hostname] ipaddrs = ext.value.get_values_for_type(x509.IPAddress) assert ipaddrs == [ipaddress.ip_address(self.clients[0].ip)] def test_getcert_list_profile(self): """ Test that getcert list command displays the profile for the cert """ result = self.master.run_command( ["getcert", "list", "-f", paths.HTTPD_CERT_FILE] ) assert "profile: caIPAserviceCert" in result.stdout_text result = self.master.run_command( ["getcert", "list", "-n", "Server-Cert cert-pki-ca"] ) assert "profile: caServerCert" in result.stdout_text def test_multiple_user_certificates(self): """Test that a user may be issued multiple certificates""" ldap = self.master.ldap_connect() user = 'user1' tasks.kinit_admin(self.master) tasks.user_add(self.master, user) for id in (0, 1): csr_file = f'{id}.csr' key_file = f'{id}.key' cert_file = f'{id}.crt' openssl_cmd = [ 'openssl', 'req', '-newkey', 'rsa:2048', '-keyout', key_file, '-nodes', '-out', csr_file, '-subj', '/CN=' + user] self.master.run_command(openssl_cmd) cmd_args = ['ipa', 'cert-request', '--principal', user, '--certificate-out', cert_file, csr_file] self.master.run_command(cmd_args) # easier to count by pulling the LDAP entry entry = ldap.get_entry(DN(('uid', user), ('cn', 'users'), ('cn', 'accounts'), self.master.domain.basedn)) assert len(entry.get('usercertificate')) == 2 @pytest.fixture def test_subca_certs(self): """ Fixture to add subca, stop tracking request, followed by removing SUB CA along with cert keys """ sub_name = "CN=SUBCA" tasks.kinit_admin(self.master) self.master.run_command( ["ipa", "ca-add", "mysubca", "--subject={}".format(sub_name)] ) self.master.run_command( [ "ipa", "caacl-add-ca", "hosts_services_caIPAserviceCert", "--cas=mysubca", ] ) yield self.master.run_command( ["getcert", "stop-tracking", "-i", "test-request"] ) self.master.run_command(["ipa", "ca-disable", "mysubca"]) self.master.run_command(["ipa", "ca-del", "mysubca"]) self.master.run_command( ["rm", "-fv", os.path.join(paths.OPENSSL_PRIVATE_DIR, "test.key")] ) self.master.run_command( ["rm", "-fv", os.path.join(paths.OPENSSL_CERTS_DIR, "test.pem")] ) def test_getcert_list_profile_using_subca(self, test_subca_certs): """ Test that getcert list command displays the profile for the cert requests generated, with a SubCA configured on the IPA server. """ cmd_arg = [ "getcert", "request", "-c", "ipa", "-I", "test-request", "-k", os.path.join(paths.OPENSSL_PRIVATE_DIR, "test.key"), "-f", os.path.join(paths.OPENSSL_CERTS_DIR, "test.pem"), "-D", self.master.hostname, "-K", "host/%s" % self.master.hostname, "-N", "CN={}".format(self.master.hostname), "-U", "id-kp-clientAuth", "-X", "mysubca", "-T", "caIPAserviceCert", ] result = self.master.run_command(cmd_arg) assert ( 'New signing request "test-request" added.\n' in result.stdout_text ) status = tasks.wait_for_request(self.master, "test-request", 300) if status == "MONITORING": result = self.master.run_command( ["getcert", "list", "-i", "test-request"] ) assert "profile: caIPAserviceCert" in result.stdout_text else: raise AssertionError("certmonger request is " "in state {}". format(status)) def test_getcert_notafter_output(self): """Test that currrent certmonger includes NotBefore in output""" result = self.master.run_command(["certmonger", "-v"]).stdout_text if parse_version(result.split()[1]) < parse_version('0.79.14'): raise pytest.skip("not_before not provided in this version") result = self.master.run_command( ["getcert", "list", "-f", paths.HTTPD_CERT_FILE] ).stdout_text assert 'issued:' in result class TestCertmongerRekey(IntegrationTest): @classmethod def install(cls, mh): tasks.install_master(cls.master, setup_dns=True) @pytest.fixture def request_cert(self): """Fixture to request and remove a certificate""" self.request_id = ''.join( random.choice( string.ascii_lowercase ) for i in range(10) ) self.master.run_command( [ 'ipa-getcert', 'request', '-f', os.path.join( paths.OPENSSL_CERTS_DIR, f"{self.request_id}.pem", ), '-k', os.path.join( paths.OPENSSL_PRIVATE_DIR, f"{self.request_id}.key" ), '-I', self.request_id, '-K', 'test/{}'.format(self.master.hostname) ] ) status = tasks.wait_for_request(self.master, self.request_id, 100) assert status == "MONITORING" yield self.master.run_command(['getcert', 'stop-tracking', '-i', self.request_id]) self.master.run_command( [ "rm", "-rf", os.path.join( paths.OPENSSL_CERTS_DIR, f"{self.request_id}.pem" ), ] ) self.master.run_command( [ "rm", "-rf", os.path.join( paths.OPENSSL_PRIVATE_DIR, f"{self.request_id}.key" ), ] ) def test_certmonger_rekey_keysize(self, request_cert): """Test certmonger rekey command works fine Certmonger's rekey command was throwing an error as unrecognized command. Test is to check if -g (keysize) option is working fine. related: https://bugzilla.redhat.com/show_bug.cgi?id=1249165 """ certdata = self.master.get_file_contents( os.path.join(paths.OPENSSL_CERTS_DIR, f"{self.request_id}.pem") ) cert = x509.load_pem_x509_certificate( certdata, default_backend() ) assert cert.public_key().key_size == 2048 # rekey with key size 3072 self.master.run_command(['getcert', 'rekey', '-i', self.request_id, '-g', '3072']) status = tasks.wait_for_request(self.master, self.request_id, 100) assert status == "MONITORING" certdata = self.master.get_file_contents( os.path.join(paths.OPENSSL_CERTS_DIR, f"{self.request_id}.pem") ) cert = x509.load_pem_x509_certificate( certdata, default_backend() ) # check if rekey command updated the key size assert cert.public_key().key_size == 3072 def test_rekey_keytype_RSA(self, request_cert): """Test certmonger rekey command works fine Certmonger's rekey command was throwing an error as unrecognized command. Test is to check if -G (keytype) option is working fine. Currently only RSA type is supported related: https://bugzilla.redhat.com/show_bug.cgi?id=1249165 """ # rekey with RSA key type self.master.run_command(['getcert', 'rekey', '-i', self.request_id, '-g', '3072', '-G', 'RSA']) status = tasks.wait_for_request(self.master, self.request_id, 100) assert status == "MONITORING" def test_rekey_request_id(self, request_cert): """Test certmonger rekey command works fine Test is to check if -I (request id name) option is working fine. related: https://bugzilla.redhat.com/show_bug.cgi?id=1249165 """ new_req_id = 'newtest' # rekey with -I option result = self.master.run_command(['getcert', 'rekey', '-i', self.request_id, '-I', new_req_id]) # above command output: Resubmitting "newtest" to "IPA". assert new_req_id in result.stdout_text # rename back the request id for fixture to delete it result = self.master.run_command(['getcert', 'rekey', '-i', new_req_id, '-I', self.request_id]) assert self.request_id in result.stdout_text class TestCertmongerInterruption(IntegrationTest): num_replicas = 1 @classmethod def install(cls, mh): tasks.install_master(cls.master) tasks.install_replica(cls.master, cls.replicas[0]) def test_certmomger_tracks_renewed_certs_during_interruptions(self): """Test that CA renewal handles early CA_WORKING and restarts A non-renewal master CA might submit a renewal request before the renewal master actually updating the certs. This is expected. The tracking request will result in CA_WORKING. This would trigger a different path within the IPA renewal scripts which differentiate between a SUBMIT (new request) and a POLL (resume request). The script was requiring a cookie value for POLL requests which wasn't available and was erroring out unrecoverably without restarting certmonger. Submit a request for renewal early and wait for it to go into CA_WORKING. Resubmit the request to ensure that the request remains in CA_WORKING without reporting any ca_error like Invalid cookie: '' Use the submitted value in the certmonger request to validate that the request was resubmitted and not rely on catching the states directly. Pagure Issue: https://pagure.io/freeipa/issue/8164 """ cmd = ['getcert', 'list', '-f', paths.RA_AGENT_PEM] result = self.replicas[0].run_command(cmd) # Get Request ID and Submitted Values request_id = get_certmonger_fs_id(result.stdout_text) start_val = get_certmonger_request_value(self.replicas[0], request_id, "submitted") # at this point submitted value for RA agent cert should be # 19700101000000 since it has never been submitted for renewal. assert start_val == DEFAULT_RA_AGENT_SUBMITTED_VAL cmd = ['getcert', 'resubmit', '-f', paths.RA_AGENT_PEM] self.replicas[0].run_command(cmd) tasks.wait_for_certmonger_status(self.replicas[0], ('CA_WORKING', 'MONITORING'), request_id) resubmit_val = get_certmonger_request_value(self.replicas[0], request_id, "submitted") if resubmit_val == DEFAULT_RA_AGENT_SUBMITTED_VAL: pytest.fail("Request was not resubmitted") ca_error = get_certmonger_request_value(self.replicas[0], request_id, "ca_error") state = get_certmonger_request_value(self.replicas[0], request_id, "state") assert ca_error is None assert state == 'CA_WORKING' cmd = ['getcert', 'resubmit', '-f', paths.RA_AGENT_PEM] self.replicas[0].run_command(cmd) tasks.wait_for_certmonger_status(self.replicas[0], ('CA_WORKING', 'MONITORING'), request_id) resubmit2_val = get_certmonger_request_value(self.replicas[0], request_id, "submitted") if resubmit_val == DEFAULT_RA_AGENT_SUBMITTED_VAL: pytest.fail("Request was not resubmitted") assert resubmit2_val > resubmit_val ca_error = get_certmonger_request_value(self.replicas[0], request_id, "ca_error") state = get_certmonger_request_value(self.replicas[0], request_id, "state") assert ca_error is None assert state == 'CA_WORKING' class TestCAShowErrorHandling(IntegrationTest): num_replicas = 1 @classmethod def install(cls, mh): tasks.install_master(cls.master) tasks.install_replica(cls.master, cls.replicas[0]) def test_ca_show_error_handling(self): """ Test to verify if the case of a request for /ca/rest/authority/{id}/cert (or .../chain) where {id} is an unknown authority ID. Test Steps: 1. Setup a freeipa server and a replica 2. Stop ipa-custodia service on replica 3. Create a LWCA on the replica 4. Verify LWCA is recognized on the server 5. Run `ipa ca-show <LWCA>` PKI Github Link: https://github.com/dogtagpki/pki/pull/3605/ """ self.replicas[0].run_command(['systemctl', 'stop', 'ipa-custodia']) lwca = 'lwca1' result = self.replicas[0].run_command([ 'ipa', 'ca-add', lwca, '--subject', 'CN=LWCA 1' ]) assert 'Created CA "{}"'.format(lwca) in result.stdout_text result = self.master.run_command(['ipa', 'ca-find']) assert 'Name: {}'.format(lwca) in result.stdout_text result = self.master.run_command( ['ipa', 'ca-show', lwca, ], raiseonerr=False ) error_msg = 'ipa: ERROR: The certificate for ' \ '{} is not available on this server.'.format(lwca) bad_version = (tasks.get_pki_version(self.master) >= tasks.parse_version('11.5.0')) with xfail_context(bad_version, reason="https://pagure.io/freeipa/issue/9606"): assert error_msg in result.stderr_text def test_certmonger_empty_cert_not_segfault(self): """Test empty cert request doesn't force certmonger to segfault Test scenario: create a cert request file in /var/lib/certmonger/requests which is missing most of the required information, and ask request a new certificate to certmonger. The wrong request file should not make certmonger crash. related: https://pagure.io/certmonger/issue/191 """ empty_cert_req_content = textwrap.dedent(""" id=dogtag-ipa-renew-agent key_type=UNSPECIFIED key_gen_type=UNSPECIFIED key_size=0 key_gen_size=0 key_next_type=UNSPECIFIED key_next_gen_type=UNSPECIFIED key_next_size=0 key_next_gen_size=0 key_preserve=0 key_storage_type=NONE key_perms=0 key_requested_count=0 key_issued_count=0 cert_storage_type=FILE cert_perms=0 cert_is_ca=0 cert_ca_path_length=0 cert_no_ocsp_check=0 last_need_notify_check=19700101000000 last_need_enroll_check=19700101000000 template_is_ca=0 template_ca_path_length=-1 template_no_ocsp_check=0 state=NEED_KEY_PAIR autorenew=0 monitor=0 submitted=19700101000000 """) # stop certmonger service self.master.run_command(['systemctl', 'stop', 'certmonger']) # place an empty cert request file to certmonger request dir self.master.put_file_contents( os.path.join(paths.CERTMONGER_REQUESTS_DIR, '20211125062617'), empty_cert_req_content ) # start certmonger, it should not fail self.master.run_command(['systemctl', 'start', 'certmonger']) # request a new cert, should succeed and certmonger doesn't goes # to segfault result = self.master.run_command([ "ipa-getcert", "request", "-f", os.path.join(paths.OPENSSL_CERTS_DIR, "test.pem"), "-k", os.path.join(paths.OPENSSL_PRIVATE_DIR, "test.key"), ]) request_id = re.findall(r'\d+', result.stdout_text) # check if certificate is in MONITORING state status = tasks.wait_for_request(self.master, request_id[0], 50) assert status == "MONITORING" self.master.run_command( ['ipa-getcert', 'stop-tracking', '-i', request_id[0]] ) self.master.run_command([ 'rm', '-rf', os.path.join(paths.CERTMONGER_REQUESTS_DIR, '20211125062617'), os.path.join(paths.OPENSSL_CERTS_DIR, 'test.pem'), os.path.join(paths.OPENSSL_PRIVATE_DIR, 'test.key') ])
23,323
Python
.py
539
32.107607
79
0.579219
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,567
test_installation.py
freeipa_freeipa/ipatests/test_integration/test_installation.py
# # Copyright (C) 2015 FreeIPA Contributors see COPYING for license # """ Module provides tests which testing ability of various subsystems to be installed. """ from __future__ import absolute_import import os import re import textwrap import time from datetime import datetime, timedelta import pytest from cryptography.hazmat.primitives import hashes from cryptography import x509 as crypto_x509 from ipalib import x509 from ipalib.constants import DOMAIN_LEVEL_0, KRA_TRACKING_REQS from ipalib.constants import IPA_CA_RECORD from ipalib.constants import ALLOWED_NETBIOS_CHARS from ipalib.sysrestore import SYSRESTORE_STATEFILE, SYSRESTORE_INDEXFILE from ipapython.dn import DN from ipaplatform.constants import constants from ipaplatform.osinfo import osinfo from ipaplatform.paths import paths from ipaplatform.tasks import tasks as platformtasks from ipapython import ipautil from ipatests.pytest_ipa.integration import tasks from ipatests.pytest_ipa.integration.env_config import get_global_config from ipatests.test_integration.base import IntegrationTest from ipatests.test_integration.test_caless import CALessBase, ipa_certs_cleanup from ipatests.test_integration.test_cert import get_certmonger_fs_id from ipatests.pytest_ipa.integration import skip_if_fips from ipaplatform import services config = get_global_config() def create_broken_resolv_conf(master): # Force a broken resolv.conf to simulate a bad response to # reverse zone lookups master.resolver.backup() master.resolver.setup_resolver('127.0.0.2') def server_install_setup(func): def wrapped(*args): master = args[0].master create_broken_resolv_conf(master) try: func(*args) finally: tasks.uninstall_master(master, clean=False) ipa_certs_cleanup(master) return wrapped @pytest.fixture def server_cleanup(request): """ Fixture to uninstall ipa server before and after the test """ host = request.cls.master tasks.uninstall_master(host) yield tasks.uninstall_master(host) def create_netbios_name(host): """ Create a NetBIOS name based on the provided host """ netbios = ''.join( c for c in host.domain.name.split('.')[0].upper() \ if c in ALLOWED_NETBIOS_CHARS )[:15] return netbios class InstallTestBase1(IntegrationTest): num_replicas = 3 topology = 'star' master_with_dns = False @classmethod def install(cls, mh): tasks.install_master(cls.master, setup_dns=cls.master_with_dns) def test_replica0_ca_less_install(self): tasks.install_replica( self.master, self.replicas[0], setup_ca=False, nameservers='master' if self.master_with_dns else None) def test_replica0_ipa_ca_install(self): tasks.install_ca(self.replicas[0]) def test_replica0_ipa_kra_install(self): tasks.install_kra(self.replicas[0], first_instance=True) def test_replica0_ipa_dns_install(self): tasks.install_dns(self.replicas[0]) def test_replica1_with_ca_install(self): tasks.install_replica( self.master, self.replicas[1], setup_ca=True, nameservers='master' if self.master_with_dns else None) def test_replica1_ipa_kra_install(self): tasks.install_kra(self.replicas[1]) def test_replica1_ipa_dns_install(self): tasks.install_dns(self.replicas[1]) def test_replica2_with_ca_kra_install(self): tasks.install_replica( self.master, self.replicas[2], setup_ca=True, setup_kra=True, nameservers='master' if self.master_with_dns else None) def test_replica2_ipa_dns_install(self): tasks.install_dns(self.replicas[2]) class InstallTestBase2(IntegrationTest): num_replicas = 3 topology = 'star' master_with_dns = False @classmethod def install(cls, mh): tasks.install_master(cls.master, setup_dns=cls.master_with_dns) def test_replica1_with_ca_dns_install(self): tasks.install_replica( self.master, self.replicas[1], setup_ca=True, setup_dns=True, nameservers='master' if self.master_with_dns else None) def test_replica1_ipa_kra_install(self): tasks.install_kra(self.replicas[1]) def test_replica2_with_dns_install(self): tasks.install_replica( self.master, self.replicas[2], setup_ca=False, setup_dns=True, nameservers='master' if self.master_with_dns else None) def test_replica2_ipa_ca_install(self): tasks.install_ca(self.replicas[2]) def test_replica2_ipa_kra_install(self): tasks.install_kra(self.replicas[2]) class ADTrustInstallTestBase(IntegrationTest): """ Base test for builtin AD trust installation im combination with other components """ num_replicas = 2 topology = 'star' master_with_dns = False @classmethod def install(cls, mh): tasks.install_master(cls.master, setup_dns=cls.master_with_dns) def install_replica(self, replica, **kwargs): tasks.install_replica(self.master, replica, setup_adtrust=True, **kwargs) def test_replica0_only_adtrust(self): self.install_replica( self.replicas[0], setup_ca=False, nameservers='master' if self.master_with_dns else None) def test_replica1_all_components_adtrust(self): self.install_replica( self.replicas[1], setup_ca=True, nameservers='master' if self.master_with_dns else None) ## # Master X Replicas installation tests ## class TestInstallWithCA1(InstallTestBase1): master_with_dns = False @classmethod def install(cls, mh): tasks.install_master(cls.master, setup_dns=cls.master_with_dns) @pytest.mark.skipif(config.domain_level == DOMAIN_LEVEL_0, reason='does not work on DOMAIN_LEVEL_0 by design') def test_replica1_ipa_kra_install(self): super(TestInstallWithCA1, self).test_replica1_ipa_kra_install() @pytest.mark.skipif(config.domain_level == DOMAIN_LEVEL_0, reason='does not work on DOMAIN_LEVEL_0 by design') def test_replica2_with_ca_kra_install(self): super(TestInstallWithCA1, self).test_replica2_with_ca_kra_install() @pytest.mark.skipif(config.domain_level == DOMAIN_LEVEL_0, reason='does not work on DOMAIN_LEVEL_0 by design') def test_replica2_ipa_dns_install(self): super(TestInstallWithCA1, self).test_replica2_ipa_dns_install() def test_install_with_bad_ldap_conf(self): """ Test a client install with a non standard ldap.config https://pagure.io/freeipa/issue/7418 """ ldap_conf = paths.OPENLDAP_LDAP_CONF base_dn = self.master.domain.basedn client = self.replicas[0] tasks.uninstall_replica(self.master, client) expected_msg1 = "contains deprecated and unsupported " \ "entries: HOST, PORT" file_backup = client.get_file_contents(ldap_conf, encoding='utf-8') constants = "URI ldaps://{}\nBASE {}\nHOST {}\nPORT 636".format( self.master.hostname, base_dn, self.master.hostname) modifications = "{}\n{}".format(file_backup, constants) client.put_file_contents(paths.OPENLDAP_LDAP_CONF, modifications) result = client.run_command(['ipa-client-install', '-U', '--domain', client.domain.name, '--realm', client.domain.realm, '-p', client.config.admin_name, '-w', client.config.admin_password, '--server', self.master.hostname], raiseonerr=False) assert expected_msg1 in result.stderr_text client.put_file_contents(ldap_conf, file_backup) class TestInstallWithCA2(InstallTestBase2): master_with_dns = False @classmethod def install(cls, mh): tasks.install_master(cls.master, setup_dns=cls.master_with_dns) @pytest.mark.skipif(config.domain_level == DOMAIN_LEVEL_0, reason='does not work on DOMAIN_LEVEL_0 by design') def test_replica1_ipa_kra_install(self): super(TestInstallWithCA2, self).test_replica1_ipa_kra_install() @pytest.mark.skipif(config.domain_level == DOMAIN_LEVEL_0, reason='does not work on DOMAIN_LEVEL_0 by design') def test_replica2_ipa_kra_install(self): super(TestInstallWithCA2, self).test_replica2_ipa_kra_install() class TestInstallCA(IntegrationTest): """ Tests for CA installation on a replica """ num_replicas = 2 @classmethod def install(cls, mh): cls.master.put_file_contents( os.path.join(paths.IPA_CCACHES, 'foo'), 'somerandomstring' ) cls.master.run_command( ['mkdir', os.path.join(paths.IPA_CCACHES, 'bar')] ) tasks.install_master(cls.master, setup_dns=False) def test_ccaches_cleanup(self): """ The IPA ccaches directory is cleaned up on install. Verify that the file we created is now gone. """ assert os.path.exists(os.path.join(paths.IPA_CCACHES, 'foo')) is False assert os.path.exists(os.path.join(paths.IPA_CCACHES, 'bar')) is False def test_replica_ca_install_with_no_host_dns(self): """ Test for ipa-ca-install --no-host-dns on a replica """ tasks.install_replica(self.master, self.replicas[0], setup_ca=False) tasks.install_ca(self.replicas[0], extra_args=["--no-host-dns"]) def test_replica_ca_install_with_skip_schema_check(self): """ Test for ipa-ca-install --skip-schema-check on a replica """ tasks.install_replica(self.master, self.replicas[1], setup_ca=False) tasks.install_ca(self.replicas[1], extra_args=["--skip-schema-check"]) @skip_if_fips() def test_certmonger_reads_token_HSM(self): """Test if certmonger reads the token in HSM This is to ensure added HSM support for FreeIPA. This test adds certificate with sofhsm token and checks if certmonger is tracking it. related : https://pagure.io/certmonger/issue/125 """ test_service = 'test/%s' % self.master.hostname pkcs_passwd = 'Secret123' pin = '123456' noisefile = '/tmp/noisefile' self.master.put_file_contents(noisefile, os.urandom(64)) tasks.kinit_admin(self.master) tasks.install_dns(self.master) self.master.run_command(['ipa', 'service-add', test_service]) # create a csr cmd_args = ['certutil', '-d', paths.NSS_DB_DIR, '-R', '-a', '-o', '/root/ipa.csr', '-s', "CN=%s" % self.master.hostname, '-z', noisefile] self.master.run_command(cmd_args) # request certificate cmd_args = ['ipa', 'cert-request', '--principal', test_service, '--certificate-out', '/root/test.pem', '/root/ipa.csr'] self.master.run_command(cmd_args) # adding trust flag cmd_args = ['certutil', '-A', '-d', paths.NSS_DB_DIR, '-n', 'test', '-a', '-i', '/root/test.pem', '-t', 'u,u,u'] self.master.run_command(cmd_args) # export pkcs12 file cmd_args = ['pk12util', '-o', '/root/test.p12', '-d', paths.NSS_DB_DIR, '-n', 'test', '-W', pkcs_passwd] self.master.run_command(cmd_args) # add softhsm lib cmd_args = ['modutil', '-dbdir', paths.NSS_DB_DIR, '-add', 'softhsm', '-libfile', '/usr/lib64/softhsm/libsofthsm.so'] self.master.run_command(cmd_args, stdin_text="\n\n") # create a token cmd_args = ['softhsm2-util', '--init-token', '--label', 'test', '--pin', pin, '--so-pin', pin, '--free'] self.master.run_command(cmd_args) self.master.run_command(['softhsm2-util', '--show-slots']) cmd_args = ['certutil', '-F', '-d', paths.NSS_DB_DIR, '-n', 'test'] self.master.run_command(cmd_args) cmd_args = ['pk12util', '-i', '/root/test.p12', '-d', paths.NSS_DB_DIR, '-h', 'test', '-W', pkcs_passwd, '-K', pin] self.master.run_command(cmd_args) cmd_args = ['certutil', '-A', '-d', paths.NSS_DB_DIR, '-n', 'IPA CA', '-t', 'CT,,', '-a', '-i', paths.IPA_CA_CRT] self.master.run_command(cmd_args) # validate the certificate self.master.put_file_contents('/root/pinfile', pin) cmd_args = ['certutil', '-V', '-u', 'V', '-e', '-d', paths.NSS_DB_DIR, '-h', 'test', '-n', 'test:test', '-f', '/root/pinfile'] result = self.master.run_command(cmd_args) assert 'certificate is valid' in result.stdout_text # add certificate tracking to certmonger cmd_args = ['ipa-getcert', 'start-tracking', '-d', paths.NSS_DB_DIR, '-n', 'test', '-t', 'test', '-P', pin, '-K', test_service] result = self.master.run_command(cmd_args) request_id = re.findall(r'\d+', result.stdout_text) # check if certificate is tracked by certmonger status = tasks.wait_for_request(self.master, request_id[0], 300) assert status == "MONITORING" # ensure if key and token are re-usable cmd_args = ['getcert', 'resubmit', '-i', request_id[0]] self.master.run_command(cmd_args) status = tasks.wait_for_request(self.master, request_id[0], 300) assert status == "MONITORING" def test_ipa_ca_crt_permissions(self): """Verify that /etc/ipa/ca.cert is mode 0644 root:root""" result = self.master.run_command( ["/usr/bin/stat", "-c", "%U:%G:%a", paths.IPA_CA_CRT] ) out = str(result.stdout_text.strip()) (owner, group, mode) = out.split(':') assert mode == "644" assert owner == "root" assert group == "root" def test_cert_install_with_IPA_issued_cert(self): """ Test replacing an IPA-issued server cert ipa-server-certinstall can replace the web and LDAP certs. A slightly different code path is taken when the replacement certs are issued by IPA. Exercise that path by replacing the web cert with itself. """ self.master.run_command(['cp', '-p', paths.HTTPD_CERT_FILE, '/tmp']) self.master.run_command(['cp', '-p', paths.HTTPD_KEY_FILE, '/tmp']) passwd = self.master.get_file_contents( paths.HTTPD_PASSWD_FILE_FMT.format(host=self.master.hostname) ) self.master.run_command([ 'ipa-server-certinstall', '-p', self.master.config.dirman_password, '-w', '--pin', passwd, '/tmp/httpd.crt', '/tmp/httpd.key', ]) def test_is_ipa_configured(self): """Verify that the old and new methods of is_ipa_installed works If there is an installation section then it is the status. If not then it will fall back to looking for configured services and files and use that for determination. """ def set_installation_state(host, state): """ Update the complete value in the installation section """ host.run_command( ['python3', '-c', 'from ipalib.install import sysrestore; ' 'from ipaplatform.paths import paths;' 'sstore = sysrestore.StateFile(paths.SYSRESTORE); ' 'sstore.backup_state("installation", "complete", ' '{state})'.format(state=state)]) def get_installation_state(host): """ Retrieve the installation state from new install method """ result = host.run_command( ['python3', '-c', 'from ipalib.install import sysrestore; ' 'from ipaplatform.paths import paths;' 'sstore = sysrestore.StateFile(paths.SYSRESTORE); ' 'print(sstore.get_state("installation", "complete"))']) return result.stdout_text.strip() # a string # This comes from freeipa.spec and is used to determine whether # an upgrade is required. cmd = ['python3', '-c', 'import sys; from ipalib import facts; sys.exit(0 ' 'if facts.is_ipa_configured() else 1);'] # This will use the new method since this is a fresh install, # verify that it is true. self.master.run_command(cmd) assert get_installation_state(self.master) == 'True' # Set complete to False which should cause the command to fail # This tests the state of a failed or in-process installation. set_installation_state(self.master, False) result = self.master.run_command(cmd, raiseonerr=False) assert result.returncode == 1 set_installation_state(self.master, True) # Tweak sysrestore.state to drop installation section self.master.run_command( ['sed', '-i', r's/\[installation\]/\[badinstallation\]/', os.path.join(paths.SYSRESTORE, SYSRESTORE_STATEFILE)]) # Re-run installation check and it should fall back to old method # and be successful. self.master.run_command(cmd) assert get_installation_state(self.master) == 'None' # Restore installation section. self.master.run_command( ['sed', '-i', r's/\[badinstallation\]/\[installation\]/', os.path.join(paths.SYSRESTORE, SYSRESTORE_STATEFILE)]) # Uninstall and confirm that the old method reports correctly # on uninstalled servers. It will exercise the old method since # there is no state. tasks.uninstall_master(self.master) # ensure there is no stale state result = self.master.run_command(r'test -f {}'.format( os.path.join(paths.SYSRESTORE, SYSRESTORE_STATEFILE)), raiseonerr=False ) assert result.returncode == 1 result = self.master.run_command(r'test -f {}'.format( os.path.join(paths.SYSRESTORE, SYSRESTORE_INDEXFILE)), raiseonerr=False ) assert result.returncode == 1 # Now run is_ipa_configured() and it should be False result = self.master.run_command(cmd, raiseonerr=False) assert result.returncode == 1 class TestInstallWithCA_KRA1(InstallTestBase1): master_with_dns = False @classmethod def install(cls, mh): tasks.install_master(cls.master, setup_dns=cls.master_with_dns, setup_kra=True, random_serial=cls.random_serial) def test_replica0_ipa_kra_install(self): tasks.install_kra(self.replicas[0], first_instance=False) class TestInstallWithCA_KRA2(InstallTestBase2): master_with_dns = False @classmethod def install(cls, mh): tasks.install_master(cls.master, setup_dns=cls.master_with_dns, setup_kra=True) class TestInstallWithCA_DNS1(InstallTestBase1): master_with_dns = True @classmethod def install(cls, mh): tasks.install_master(cls.master, setup_dns=cls.master_with_dns, random_serial=cls.random_serial) @pytest.mark.skipif(config.domain_level == DOMAIN_LEVEL_0, reason='does not work on DOMAIN_LEVEL_0 by design') def test_replica1_ipa_kra_install(self): super(TestInstallWithCA_DNS1, self).test_replica1_ipa_kra_install() @pytest.mark.skipif(config.domain_level == DOMAIN_LEVEL_0, reason='does not work on DOMAIN_LEVEL_0 by design') def test_replica2_with_ca_kra_install(self): super(TestInstallWithCA_DNS1, self).test_replica2_with_ca_kra_install() @pytest.mark.skipif(config.domain_level == DOMAIN_LEVEL_0, reason='does not work on DOMAIN_LEVEL_0 by design') def test_replica2_ipa_dns_install(self): super(TestInstallWithCA_DNS1, self).test_replica2_ipa_dns_install() class TestInstallWithCA_DNS2(InstallTestBase2): master_with_dns = True @classmethod def install(cls, mh): tasks.install_master(cls.master, setup_dns=cls.master_with_dns) @pytest.mark.skipif(config.domain_level == DOMAIN_LEVEL_0, reason='does not work on DOMAIN_LEVEL_0 by design') def test_replica1_ipa_kra_install(self): super(TestInstallWithCA_DNS2, self).test_replica1_ipa_kra_install() @pytest.mark.skipif(config.domain_level == DOMAIN_LEVEL_0, reason='does not work on DOMAIN_LEVEL_0 by design') def test_replica2_ipa_kra_install(self): super(TestInstallWithCA_DNS2, self).test_replica2_ipa_kra_install() class TestInstallWithCA_DNS3(CALessBase): """ Test an install with a bad DNS resolver configured to force a timeout trying to verify the existing zones. In the case of a reverse zone it is skipped unless --allow-zone-overlap is set regardless of the value of --auto-reverse. Confirm that --allow-zone-overlap lets the reverse zone be created. ticket 7239 """ @pytest.mark.xfail( osinfo.id == 'fedora' and osinfo.version_number >= (36,), reason='freeipa ticket 9135', strict=True) @server_install_setup def test_number_of_zones(self): """There should be two zones: one forward, one reverse""" self.create_pkcs12('ca1/server') self.prepare_cacert('ca1') self.install_server(extra_args=['--allow-zone-overlap']) result = self.master.run_command([ 'ipa', 'dnszone-find']) assert "in-addr.arpa." in result.stdout_text assert "returned 2" in result.stdout_text class TestInstallWithCA_DNS4(CALessBase): """ Test an install with a bad DNS resolver configured to force a timeout trying to verify the existing zones. In the case of a reverse zone it is skipped unless --allow-zone-overlap is set regardless of the value of --auto-reverse. Confirm that without --allow-reverse-zone only the forward zone is created. ticket 7239 """ @server_install_setup def test_number_of_zones(self): """There should be one zone, a forward because rev timed-out""" self.create_pkcs12('ca1/server') self.prepare_cacert('ca1') # no zone overlap by default self.install_server() result = self.master.run_command([ 'ipa', 'dnszone-find']) assert "in-addr.arpa." not in result.stdout_text assert "returned 1" in result.stdout_text @pytest.mark.cs_acceptance class TestInstallWithCA_KRA_DNS1(InstallTestBase1): master_with_dns = True @classmethod def install(cls, mh): tasks.install_master(cls.master, setup_dns=cls.master_with_dns, setup_kra=True) def test_replica0_ipa_kra_install(self): tasks.install_kra(self.replicas[0], first_instance=False) class TestInstallWithCA_KRA_DNS2(InstallTestBase2): master_with_dns = True @classmethod def install(cls, mh): tasks.install_master(cls.master, setup_dns=cls.master_with_dns, setup_kra=True) class TestADTrustInstall(ADTrustInstallTestBase): """ Tests built-in AD trust installation in various combinations (see the base class for more details) against plain IPA master (no DNS, no KRA, no AD trust) """ class TestADTrustInstallWithDNS_KRA_ADTrust(ADTrustInstallTestBase): """ Tests built-in AD trust installation in various combinations (see the base class for more details) against fully equipped (DNS, CA, KRA, ADtrust) master. Additional two test cases were added to test interplay including KRA installer """ master_with_dns = True @classmethod def install(cls, mh): tasks.install_master(cls.master, setup_dns=cls.master_with_dns, setup_kra=True, setup_adtrust=True) def test_replica1_all_components_adtrust(self): self.install_replica(self.replicas[1], setup_ca=True, setup_kra=True) def get_pki_tomcatd_pid(host): pid = '' cmd = host.run_command(['systemctl', 'status', 'pki-tomcatd@pki-tomcat']) for line in cmd.stdout_text.split('\n'): if "Main PID" in line: pid = line.split()[2] break return(pid) def get_ipa_services_pids(host): ipa_services_name = [ "krb5kdc", "kadmin", "named", "httpd", "ipa-custodia", "pki_tomcatd" ] pids_of_ipa_services = {} for name in ipa_services_name: service_name = services.knownservices[name].systemd_name result = host.run_command( ["systemctl", "-p", "MainPID", "--value", "show", service_name] ) pids_of_ipa_services[service_name] = int(result.stdout_text.strip()) return pids_of_ipa_services ## # Rest of master installation tests ## class TestInstallMaster(IntegrationTest): num_replicas = 0 @classmethod def install(cls, mh): pass def test_install_master(self): tasks.install_master(self.master, setup_dns=False) @pytest.mark.skip_if_platform( "debian", reason="This test hardcodes the httpd service name" ) def test_smoke_test_for_debug_mode(self): """Test if an IPA server works in debug mode. Related: https://pagure.io/freeipa/issue/8891 Note: this test hardcodes the "httpd" service name. """ target_fname = paths.IPA_SERVER_CONF assert not self.master.transport.file_exists(target_fname) # set the IPA server in debug mode server_conf = "[global]\ndebug=True" self.master.put_file_contents(target_fname, server_conf) self.master.run_command(["systemctl", "restart", "httpd"]) # smoke test in debug mode tasks.kdestroy_all(self.master) tasks.kinit_admin(self.master) self.master.run_command(["ipa", "user-show", "admin"]) # rollback self.master.run_command(["rm", target_fname]) self.master.run_command(["systemctl", "restart", "httpd"]) def test_schema_compat_attribute_and_tree_disable(self): """Test if schema-compat-entry-attribute is set This is to ensure if said entry is set after installation. It also checks if compat tree is disable. related: https://pagure.io/freeipa/issue/8193 """ conn = self.master.ldap_connect() entry = conn.get_entry(DN( "cn=groups,cn=Schema Compatibility,cn=plugins,cn=config")) entry_list = list(entry['schema-compat-entry-attribute']) value = (r'ipaexternalmember=%deref_r(' '"member","ipaexternalmember")') assert value in entry_list assert 'schema-compat-lookup-nsswitch' not in entry_list def test_install_kra(self): tasks.install_kra(self.master, first_instance=True) def test_install_dns(self): tasks.install_dns( self.master, extra_args=['--dnssec-master', '--no-dnssec-validation'] ) def test_ipactl_restart_pki_tomcat(self): """ Test if ipactl restart restarts the pki-tomcatd Wrong logic was triggering the start instead of restart for pki-tomcatd. This test validates that restart called on pki-tomcat properly. related ticket : https://pagure.io/freeipa/issue/7927 """ # get process id of pki-tomcatd pki_pid = get_pki_tomcatd_pid(self.master) # check if pki-tomcad restarted cmd = self.master.run_command(['ipactl', 'restart']) assert "Restarting pki-tomcatd Service" in cmd.stdout_text # check if pid for pki-tomcad changed pki_pid_after_restart = get_pki_tomcatd_pid(self.master) assert pki_pid != pki_pid_after_restart # check if pki-tomcad restarted cmd = self.master.run_command(['ipactl', 'restart']) assert "Restarting pki-tomcatd Service" in cmd.stdout_text # check if pid for pki-tomcad changed pki_pid_after_restart_2 = get_pki_tomcatd_pid(self.master) assert pki_pid_after_restart != pki_pid_after_restart_2 def test_ipactl_scenario_check(self): """ Test if ipactl starts services stopped by systemctl This will first check if all services are running then it will stop few service. After that it will restart all services and then check the status and pid of services.It will also compare pid after ipactl start and restart in case of start it will remain unchanged on the other hand in case of restart it will change. """ # listing all services ipa_services_name = [ "Directory", "krb5kdc", "kadmin", "named", "httpd", "ipa-custodia", "pki-tomcatd", "ipa-otpd", "ipa-dnskeysyncd" ] # checking the service status cmd = self.master.run_command(['ipactl', 'status']) for service in ipa_services_name: assert f"{service} Service: RUNNING" in cmd.stdout_text # stopping few services service_stop = ["krb5kdc", "kadmin", "httpd"] for service in service_stop: service_name = services.knownservices[service].systemd_name self.master.run_command(['systemctl', 'stop', service_name]) # checking service status service_start = [ svcs for svcs in ipa_services_name if svcs not in service_stop ] cmd = self.master.run_command(['ipactl', 'status'], raiseonerr=False) assert cmd.returncode == 3 for service in service_start: assert f"{service} Service: RUNNING" in cmd.stdout_text for service in service_stop: assert f'{service} Service: STOPPED' in cmd.stdout_text # starting all services again self.master.run_command(['ipactl', 'start']) # checking service status cmd = self.master.run_command(['ipactl', 'status']) for service in ipa_services_name: assert f"{service} Service: RUNNING" in cmd.stdout_text # get process id of services ipa_services_pids = get_ipa_services_pids(self.master) # restarting all services again self.master.run_command(['ipactl', 'restart']) # checking service status cmd = self.master.run_command(['ipactl', 'status']) for service in ipa_services_name: assert f"{service} Service: RUNNING" in cmd.stdout_text # check if pid for services are different svcs_pids_after_restart = get_ipa_services_pids(self.master) assert ipa_services_pids != svcs_pids_after_restart # starting all services again self.master.run_command(['ipactl', 'start']) # checking service status cmd = self.master.run_command(['ipactl', 'status']) for service in ipa_services_name: assert f"{service} Service: RUNNING" in cmd.stdout_text # check if pid for services are same svcs_pids_after_start = get_ipa_services_pids(self.master) assert svcs_pids_after_restart == svcs_pids_after_start def test_WSGI_worker_process(self): """ Test if WSGI worker process count is set to 4 related ticket : https://pagure.io/freeipa/issue/7587 """ # check process count in httpd conf file i.e expected string exp = b'WSGIDaemonProcess ipa processes=%d' % constants.WSGI_PROCESSES httpd_conf = self.master.get_file_contents(paths.HTTPD_IPA_CONF) assert exp in httpd_conf # check the process count cmd = self.master.run_command('ps -eF') wsgi_count = cmd.stdout_text.count('wsgi:ipa') assert constants.WSGI_PROCESSES == wsgi_count def test_error_for_yubikey(self): """ Test error when yubikey hardware not present In order to work with IPA and Yubikey, libyubikey is required. Before the fix, if yubikey added without having packages, it used to result in traceback. Now it the exception is handeled properly. It needs Yubikey hardware to make command successfull. This test just check of proper error thrown when hardware is not attached. related ticket : https://pagure.io/freeipa/issue/6979 """ # try to add yubikey to the user args = ['ipa', 'otptoken-add-yubikey', '--owner=admin'] cmd = self.master.run_command(args, raiseonerr=False) assert cmd.returncode != 0 exp_str = ("ipa: ERROR: No YubiKey found") assert exp_str in cmd.stderr_text def test_pki_certs(self): certs, keys = tasks.certutil_certs_keys( self.master, paths.PKI_TOMCAT_ALIAS_DIR, paths.PKI_TOMCAT_ALIAS_PWDFILE_TXT ) expected_certs = { # CA 'caSigningCert cert-pki-ca': 'CTu,Cu,Cu', 'ocspSigningCert cert-pki-ca': 'u,u,u', 'subsystemCert cert-pki-ca': 'u,u,u', 'auditSigningCert cert-pki-ca': 'u,u,Pu', # why P? # KRA 'transportCert cert-pki-kra': 'u,u,u', 'storageCert cert-pki-kra': 'u,u,u', 'auditSigningCert cert-pki-kra': 'u,u,Pu', # server 'Server-Cert cert-pki-ca': 'u,u,u', } assert certs == expected_certs assert len(certs) == len(keys) for nickname in sorted(certs): cert = tasks.certutil_fetch_cert( self.master, paths.PKI_TOMCAT_ALIAS_DIR, paths.PKI_TOMCAT_ALIAS_PWDFILE_TXT, nickname ) key_size = cert.public_key().key_size if nickname == 'caSigningCert cert-pki-ca': assert key_size == 3072 else: assert key_size == 2048 assert cert.signature_hash_algorithm.name == hashes.SHA256.name def test_http_cert(self): """ Test that HTTP certificate contains ipa-ca.$DOMAIN DNS name. """ data = self.master.get_file_contents(paths.HTTPD_CERT_FILE) cert = x509.load_pem_x509_certificate(data) name = f'ipa-ca.{self.master.domain.name}' assert crypto_x509.DNSName(name) in cert.san_general_names def test_ipa_cert_in_store(self): """ Test that IPA cert has been added to trust store. """ assert "IPA CA" in self.master.run_command( ['trust', 'list'], raiseonerr=False).stdout_text def test_p11_kit_softhsm2(self): # check that p11-kit-proxy does not inject SoftHSM2 result = self.master.run_command([ "modutil", "-dbdir", paths.PKI_TOMCAT_ALIAS_DIR, "-list" ]) assert "softhsm" not in result.stdout_text.lower() assert "opendnssec" not in result.stdout_text.lower() @pytest.mark.skipif( not platformtasks.is_selinux_enabled(), reason="Test needs SELinux enabled") def test_selinux_avcs(self): # Use journalctl instead of ausearch. The ausearch command is not # installed by default and journalctl gives us all AVCs. result = self.master.run_command([ "journalctl", "--full", "--grep=AVC", "--since=yesterday" ], raiseonerr=False) avcs = list( line.strip() for line in result.stdout_text.split('\n') if "AVC avc:" in line ) if avcs: print('\n'.join(avcs)) # Use expected failure until all SELinux violations are fixed pytest.xfail("{} AVCs found".format(len(avcs))) def test_file_permissions(self): args = [ "rpm", "-V", "python3-ipaclient", "python3-ipalib", "python3-ipaserver" ] if osinfo.id == 'fedora': args.extend([ "freeipa-client", "freeipa-client-common", "freeipa-common", "freeipa-server", "freeipa-server-common", "freeipa-server-dns", "freeipa-server-trust-ad" ]) else: args.extend([ "ipa-client", "ipa-client-common", "ipa-common", "ipa-server", "ipa-server-common", "ipa-server-dns" ]) result = self.master.run_command(args, raiseonerr=False) if result.returncode != 0: # Check the mode errors mode_warnings = re.findall( r"^.M....... [cdglr ]+ (?P<filename>.*)$", result.stdout_text, re.MULTILINE) msg = "rpm -V found mode issues for the following files: {}" assert mode_warnings == [], msg.format(mode_warnings) # Check the owner errors user_warnings = re.findall( r"^.....U... [cdglr ]+ (?P<filename>.*)$", result.stdout_text, re.MULTILINE) msg = "rpm -V found ownership issues for the following files: {}" assert user_warnings == [], msg.format(user_warnings) # Check the group errors group_warnings = re.findall( r"^......G.. [cdglr ]+ (?P<filename>.*)$", result.stdout_text, re.MULTILINE) msg = "rpm -V found group issues for the following files: {}" assert group_warnings == [], msg.format(group_warnings) def test_ds_disable_upgrade_hash(self): # Test case for https://pagure.io/freeipa/issue/8315 # Disable password schema migration on LDAP bind result = tasks.ldapsearch_dm( self.master, "cn=config", ldap_args=["nsslapd-enable-upgrade-hash"], scope="base" ) assert "nsslapd-enable-upgrade-hash: off" in result.stdout_text def test_ldbm_tuning(self): # check db-locks in new cn=bdb subentry (1.4.3+) result = tasks.ldapsearch_dm( self.master, "cn=bdb,cn=config,cn=ldbm database,cn=plugins,cn=config", ["nsslapd-db-locks"], scope="base" ) assert "nsslapd-db-locks: 50000" in result.stdout_text # no db-locks configuration in old global entry result = tasks.ldapsearch_dm( self.master, "cn=config,cn=ldbm database,cn=plugins,cn=config", ["nsslapd-db-locks"], scope="base" ) assert "nsslapd-db-locks" not in result.stdout_text def test_nsslapd_sizelimit(self): """ Test for default value of nsslapd-sizelimit. Related : https://pagure.io/freeipa/issue/8962 """ result = tasks.ldapsearch_dm( self.master, "cn=config", ["nsslapd-sizelimit"], scope="base" ) assert "nsslapd-sizelimit: 100000" in result.stdout_text def test_admin_root_alias_CVE_2020_10747(self): # Test for CVE-2020-10747 fix # https://bugzilla.redhat.com/show_bug.cgi?id=1810160 rootprinc = "root@{}".format(self.master.domain.realm) result = self.master.run_command(["ipa", "user-show", "admin"]) assert rootprinc in result.stdout_text result = self.master.run_command( ["ipa", "user-add", "root", "--first", "root", "--last", "root"], raiseonerr=False ) assert result.returncode != 0 assert 'user with name "root" already exists' in result.stderr_text def test_dirsrv_no_ssca(self): # verify that lib389 installer no longer creates self-signed CA result = self.master.run_command( ["stat", "/etc/dirsrv/ssca"], raiseonerr=False ) assert result.returncode != 0 def test_ipa_custodia_check(self): # check local key retrieval self.master.run_command( [paths.IPA_CUSTODIA_CHECK, self.master.hostname] ) @pytest.mark.skipif( paths.SEMODULE is None, reason="test requires semodule command" ) def test_ipa_selinux_policy(self): # check that freeipa-selinux's policy module is loaded and # not disabled result = self.master.run_command( [paths.SEMODULE, "-lfull"] ) # prio module pp [disabled] # 100: default priority # 200: decentralized SELinux policy priority entries = { tuple(line.split()) for line in result.stdout_text.split('\n') if line.strip() } assert ('200', 'ipa', 'pp') in entries def test_ipaca_no_redirect(self): """Test that ipa-ca.$DOMAIN does not redirect ipa-ca is a valid name for an IPA server. It should not require a redirect. CRL generation does not need to be enabled for this test. We aren't exactly testing that a CRL can be retrieved, just that the redirect doesn't happen. """ def run_request(url, expected_stdout=None, expected_stderr=None): result = self.master.run_command(['curl', '-s', '-v', url]) if expected_stdout: assert expected_stdout in result.stdout_text if expected_stderr: assert expected_stderr in result.stderr_text # CRL publishing on start-up is disabled so drop a file there crlfile = os.path.join(paths.PKI_CA_PUBLISH_DIR, 'MasterCRL.bin') self.master.put_file_contents(crlfile, 'secret') hosts = ( f'{IPA_CA_RECORD}.{self.master.domain.name}', self.master.hostname, ) # Positive tests. Both hosts can serve these. urls = ( 'http://{host}/ipa/crl/MasterCRL.bin', 'http://{host}/ca/ocsp', 'https://{host}/ca/admin/ca/getCertChain', 'https://{host}/acme/', ) for url in urls: for host in hosts: run_request( url.format(host=host), expected_stderr='HTTP/1.1 200' ) # Negative tests. ipa-ca cannot serve these and will redirect and # test that existing redirect for unencrypted still works urls = ( 'http://{host}/', 'http://{host}/ipa/json', 'http://{carecord}.{domain}/ipa/json', 'https://{carecord}.{domain}/ipa/json', 'http://{carecord}.{domain}/ipa/config/ca.crt', ) for url in urls: run_request( url.format(host=self.master.hostname, domain=self.master.domain.name, carecord=IPA_CA_RECORD), expected_stdout=f'href="https://{self.master.hostname}/' ) def test_pac_configuration_enabled(self): """ This testcase checks that the default PAC type is added to configuration. """ base_dn = str(self.master.domain.basedn) dn = DN( ("cn", "ipaConfig"), ("cn", "etc"), base_dn ) result = tasks.ldapsearch_dm(self.master, str(dn), ["ipaKrbAuthzData"]) assert 'ipaKrbAuthzData: MS-PAC' in result.stdout_text def test_hostname_parameter(self, server_cleanup): """ Test that --hostname parameter is respected in interactive mode. https://pagure.io/freeipa/issue/2692 """ original_hostname = self.master.hostname new_hostname = 'new.' + original_hostname # New hostname is added into /etc/hosts as the installer # is looking for it for resolution. Without it, an installation # fails with `Unable to resolve host name, check /etc/hosts or DNS # name resolution`. hosts = self.master.get_file_contents(paths.HOSTS, encoding='utf-8') new_hosts = hosts.replace(original_hostname, new_hostname) self.master.put_file_contents(paths.HOSTS, new_hosts) netbios = create_netbios_name(self.master) try: cmd = ['ipa-server-install', '--hostname', new_hostname] with self.master.spawn_expect(cmd, default_timeout=100) as e: e.expect_exact('Do you want to configure integrated ' 'DNS (BIND)? [no]: ') e.sendline('no') e.expect_exact('Please confirm the domain name [{}]: '.format( original_hostname # DN is computed from new hostname )) e.sendline(self.master.domain.name) e.expect_exact('Please provide a realm name [{}]: '.format( self.master.domain.realm )) e.sendline(self.master.domain.realm) e.expect_exact('Directory Manager password: ') e.sendline(self.master.config.dirman_password) e.expect_exact('Password (confirm): ') e.sendline(self.master.config.dirman_password) e.expect_exact('IPA admin password: ') e.sendline(self.master.config.admin_password) e.expect_exact('Password (confirm): ') e.sendline(self.master.config.admin_password) e.expect_exact('NetBIOS domain name [{}]: '.format(netbios)) e.sendline(netbios) e.expect_exact('Do you want to configure chrony with ' 'NTP server or pool address? [no]: ') e.sendline('no') e.expect_exact('Continue to configure the system ' 'with these values? [no]: ') e.sendline('yes') e.expect_exit(ignore_remaining_output=True, timeout=720) hostname = self.master.run_command([ 'hostname', '-f']).stdout_text.strip() assert hostname == new_hostname finally: # no need to restore the hostname as the installer # does it during uninstallation self.master.put_file_contents(paths.HOSTS, hosts) def test_ad_subpackage_dependency(self, server_cleanup): """ Test if the installer is not dependant on trust-ad package and succeeds even when AD subpackage is not installed https://pagure.io/freeipa/issue/4011 """ if osinfo.id == 'fedora': package_name = 'freeipa-server-trust-ad' else: package_name = 'ipa-server-trust-ad' reinstall = False if tasks.is_package_installed(self.master, package_name): tasks.uninstall_packages(self.master, [package_name]) reinstall = True try: # Disable dnssec-validation as the test is calling dnf install # and mirrors.fedoraproject.org have a broken trust chain tasks.install_master(self.master, extra_args=['--no-dnssec-validation']) finally: if reinstall: tasks.install_packages(self.master, [package_name]) def test_backup_of_cs_cfg_is_created(self, server_cleanup): """ Test that the installer backs up CS.cfg configuration before it's being modified. https://pagure.io/freeipa/issue/4166 """ bcp_location = paths.CA_CS_CFG_PATH + '.ipabkp' original_cfg_content = None if self.master.transport.file_exists(paths.CA_CS_CFG_PATH): original_cfg_content = self.master.get_file_contents( paths.CA_CS_CFG_PATH, encoding='utf-8') time_before_install = int(self.master.run_command( ['date', '+%s']).stdout_text.strip()) tasks.install_master(self.master) ipaserver_install_log = self.master.get_file_contents( paths.IPASERVER_INSTALL_LOG, encoding='utf-8') assert 'backing up CS.cfg' in ipaserver_install_log assert self.master.transport.file_exists(bcp_location) cfg_mod_time = int(self.master.run_command( ['stat', '-c', '%Y', paths.CA_CS_CFG_PATH]).stdout_text.strip()) bcp_mod_time = int(self.master.run_command( ['stat', '-c', '%Y', bcp_location]).stdout_text.strip()) # check if the backup file was modified/created during the installation # and before the original file was modified assert time_before_install <= bcp_mod_time <= cfg_mod_time bcp_cfg_content = self.master.get_file_contents( paths.CA_CS_CFG_PATH + '.ipabkp', encoding='utf-8') if original_cfg_content is not None: assert original_cfg_content == bcp_cfg_content class TestInstallMasterKRA(IntegrationTest): num_replicas = 0 @classmethod def install(cls, mh): pass def test_install_master(self): tasks.install_master(self.master, setup_dns=False, setup_kra=True) def test_ipa_ccache_sweep_timer_enabled(self): """Test ipa-ccache-sweep.timer enabled by default during installation This test checks that ipa-ccache-sweep.timer is enabled by default during the ipa installation. related: https://pagure.io/freeipa/issue/9107 """ result = self.master.run_command( ['systemctl', 'is-enabled', 'ipa-ccache-sweep.timer'], raiseonerr=False ) assert 'enabled' in result.stdout_text def test_install_dns(self): tasks.install_dns(self.master) def test_kra_certs_renewal(self): """ Test that the KRA subsystem certificates renew properly """ for nickname in KRA_TRACKING_REQS: cert = tasks.certutil_fetch_cert( self.master, paths.PKI_TOMCAT_ALIAS_DIR, paths.PKI_TOMCAT_ALIAS_PWDFILE_TXT, nickname ) starting_serial = int(cert.serial_number) cmd_arg = [ 'ipa-getcert', 'resubmit', '-v', '-w', '-d', paths.PKI_TOMCAT_ALIAS_DIR, '-n', nickname, ] result = self.master.run_command(cmd_arg) request_id = re.findall(r'\d+', result.stdout_text) status = tasks.wait_for_request(self.master, request_id[0], 120) assert status == "MONITORING" cert = tasks.certutil_fetch_cert( self.master, paths.PKI_TOMCAT_ALIAS_DIR, paths.PKI_TOMCAT_ALIAS_PWDFILE_TXT, nickname ) assert starting_serial != int(cert.serial_number) class TestInstallMasterDNS(IntegrationTest): num_replicas = 0 @classmethod def install(cls, mh): pass def test_install_master(self): tasks.install_master( self.master, setup_dns=True, extra_args=['--zonemgr', 'me@example.org'], ) tasks.kinit_admin(self.master) result = self.master.run_command( ['ipa', 'dnszone-show', self.master.domain.name] ).stdout_text assert "Administrator e-mail address: me.example.org" in result def test_server_install_lock_bind_recursion(self): """Test if server installer lock Bind9 recursion This test is to check if recursion can be configured. It checks if newly added file /etc/named/ipa-ext.conf exists and /etc/named.conf should not have 'allow-recursion { any; };'. It also checks if ipa-backup command backup the /etc/named/ipa-ext.conf file as well related : https://pagure.io/freeipa/issue/8079 """ # check of /etc/named/ipa-ext.conf exist assert self.master.transport.file_exists(paths.NAMED_CUSTOM_CONF) # check if /etc/named.conf does not contain 'allow-recursion { any; };' string_to_check = 'allow-recursion { any; };' named_contents = self.master.get_file_contents(paths.NAMED_CONF, encoding='utf-8') assert string_to_check not in named_contents # check if ipa-backup command backups the /etc/named/ipa-ext.conf result = self.master.run_command(['ipa-backup', '-v']) assert paths.NAMED_CUSTOM_CONF in result.stderr_text def test_install_kra(self): tasks.install_kra(self.master, first_instance=True) def test_installer_wizard_prompts_for_DNS(self, server_cleanup): """ Installer wizard should prompt for DNS even if --setup-dns is not provided as an argument. https://pagure.io/freeipa/issue/2575 """ cmd = ['ipa-server-install'] netbios = create_netbios_name(self.master) with self.master.spawn_expect(cmd, default_timeout=100) as e: e.expect_exact('Do you want to configure integrated ' 'DNS (BIND)? [no]: ') e.sendline('yes') e.expect_exact('Server host name [{}]: '.format( self.master.hostname)) e.sendline(self.master.hostname) e.expect_exact('Please confirm the domain name [{}]: '.format( self.master.domain.name)) e.sendline(self.master.domain.name) e.expect_exact('Please provide a realm name [{}]: '.format( self.master.domain.realm )) e.sendline(self.master.domain.realm) e.expect_exact('Directory Manager password: ') e.sendline(self.master.config.dirman_password) e.expect_exact('Password (confirm): ') e.sendline(self.master.config.dirman_password) e.expect_exact('IPA admin password: ') e.sendline(self.master.config.admin_password) e.expect_exact('Password (confirm): ') e.sendline(self.master.config.admin_password) e.expect_exact( 'Do you want to configure DNS forwarders? [yes]: ') e.sendline('no') # irrelevant for this test e.expect_exact('Do you want to search for missing reverse ' 'zones? [yes]: ') e.sendline('no') # irrelevant for this test e.expect_exact('NetBIOS domain name [{}]: '.format(netbios)) e.sendline(netbios) e.expect_exact('Do you want to configure chrony with NTP ' 'server or pool address? [no]: ') e.sendline('no') # irrelevant for this test e.expect_exact('Continue to configure the system with these ' 'values? [no]: ') e.sendline('yes') e.expect_exit(ignore_remaining_output=True, timeout=720) tasks.kinit_admin(self.master) result = self.master.run_command( ['ipa', 'dnszone-show', self.master.domain.name] ).stdout_text assert 'Active zone: True' in result class TestInstallMasterDNSRepeatedly(IntegrationTest): """ Test that a repeated installation of the primary with DNS enabled will lead to a already installed message and not in "DNS zone X already exists in DNS" in check_zone_overlap. The error is only occuring if domain is set explicitly in the command line installer as check_zone_overlap is used in the domain_name validator. """ num_replicas = 0 @classmethod def install(cls, mh): tasks.install_master(cls.master, setup_dns=True) def test_install_master_releatedly(self): cmd = tasks.install_master(self.master, setup_dns=True, raiseonerr=False) exp_str = ("already exists in DNS") assert (exp_str not in cmd.stderr_text and cmd.returncode != 2) class TestInstallMasterReservedIPasForwarder(IntegrationTest): """Test to check if IANA reserved IP doesn't accepted as DNS forwarder IANA reserved IP address can not be used as a forwarder. This test checks if ipa server installation throws an error when 0.0.0.0 is specified as forwarder IP address. related ticket: https://pagure.io/freeipa/issue/6894 """ def test_reserved_ip_as_forwarder(self): args = [ 'ipa-server-install', '-n', self.master.domain.name, '-r', self.master.domain.realm, '-p', self.master.config.dirman_password, '-a', self.master.config.admin_password, '--setup-dns', '--forwarder', '0.0.0.0', '--auto-reverse'] cmd = self.master.run_command(args, raiseonerr=False) assert cmd.returncode == 2 exp_str = ("error: option --forwarder: invalid IP address 0.0.0.0: " "cannot use IANA reserved IP address 0.0.0.0") assert exp_str in cmd.stderr_text server_install_options = ( "yes\n" "{hostname}\n" "{dmname}\n\n" "{dm_pass}\n{dm_pass}" "\n{admin_pass}\n{admin_pass}\n" "yes\nyes\n0.0.0.0\n".format( dm_pass=self.master.config.dirman_password, admin_pass=self.master.config.admin_password, dmname=self.master.domain.name, hostname=self.master.hostname)) cmd = self.master.run_command(['ipa-server-install'], stdin_text=server_install_options, raiseonerr=False) exp_str = ("Invalid IP Address 0.0.0.0: cannot use IANA reserved " "IP address 0.0.0.0") assert exp_str in cmd.stdout_text class TestKRAinstallAfterCertRenew(IntegrationTest): """ Test KRA installtion after ca agent cert renewal KRA installation was failing after ca-agent cert gets renewed. This test checks if the symptoms no longer exist. related ticket: https://pagure.io/freeipa/issue/7288 """ def test_KRA_install_after_cert_renew(self): tasks.install_master(self.master) # get ca-agent cert and load as pem dm_pass = self.master.config.dirman_password admin_pass = self.master.config.admin_password args = [paths.OPENSSL, "pkcs12", "-in", paths.DOGTAG_ADMIN_P12, "-nodes", "-passin", "pass:{}".format(dm_pass)] cmd = self.master.run_command(args) certs = x509.load_certificate_list(cmd.stdout_text.encode('utf-8')) # get expiry date of agent cert cert_expiry = certs[0].not_valid_after_utc # move date to grace period so that certs get renewed self.master.run_command(['systemctl', 'stop', 'chronyd']) grace_date = cert_expiry - timedelta(days=10) grace_date = datetime.strftime(grace_date, "%Y-%m-%d %H:%M:%S") self.master.run_command(['date', '-s', grace_date]) # restart service after date change self.master.run_command(['ipactl', 'restart']) # get the count of certs track by certmonger cmd = self.master.run_command(['getcert', 'list']) cert_count = cmd.stdout_text.count('Request ID') timeout = 600 count = 0 start = time.time() # wait sometime for cert renewal while time.time() - start < timeout: cmd = self.master.run_command(['getcert', 'list']) count = cmd.stdout_text.count('status: MONITORING') if count == cert_count: break time.sleep(100) else: # timeout raise AssertionError('TimeOut: Failed to renew all the certs') # move date after 3 days of actual expiry cert_expiry = cert_expiry + timedelta(days=3) cert_expiry = datetime.strftime(cert_expiry, "%Y-%m-%d %H:%M:%S") self.master.run_command(['date', '-s', cert_expiry]) # restart service after date change self.master.run_command(['ipactl', 'restart']) passwd = "{passwd}\n{passwd}\n{passwd}".format(passwd=admin_pass) self.master.run_command(['kinit', 'admin'], stdin_text=passwd) cmd = self.master.run_command(['ipa-kra-install', '-p', dm_pass, '-U']) self.master.run_command(['systemctl', 'start', 'chronyd']) class TestKRAinstallOnReplicaWithCAHost(IntegrationTest): """ Test that KRA install on replica with ca_host overriden fails KRA install on a replica should fail if the ca_host line in /etc/ipa/default.conf is present Related: https://pagure.io/freeipa/issue/8245 """ num_replicas = 1 def test_kra_install_on_replica_with_ca_host_overriden(self): tasks.install_master(self.master) tasks.install_replica(self.master, self.replicas[0]) content = self.replicas[0].get_file_contents(paths.IPA_DEFAULT_CONF, encoding='utf-8') ca_host_line = "ca_host = %s" % self.master.hostname new_content = content + '\n' + ca_host_line self.replicas[0].put_file_contents(paths.IPA_DEFAULT_CONF, new_content) self.master.run_command(['firewall-cmd', '--add-port=8443/tcp']) result = tasks.install_kra(self.replicas[0], raiseonerr=False) err_str = "KRA can not be installed when 'ca_host' is overriden in IPA" "configuration file." assert result.returncode == 1 assert err_str in result.stderr_text class TestMaskInstall(IntegrationTest): """ Test master and replica installation with wrong mask This test checks that master/replica installation fails (expectedly) if mask > 022. related ticket: https://pagure.io/freeipa/issue/7193 """ topology = 'star' @classmethod def install(cls, mh): super(TestMaskInstall, cls).install(mh) cls.bashrc_file = cls.master.get_file_contents('/root/.bashrc') def test_install_master(self): self.master.run_command('echo "umask 0027" >> /root/.bashrc') result = self.master.run_command(['umask']) assert '0027' in result.stdout_text cmd = tasks.install_master( self.master, setup_dns=False, raiseonerr=False ) exp_str = ("Unexpected system mask") assert (exp_str in cmd.stderr_text and cmd.returncode != 0) def test_install_replica(self): result = self.master.run_command(['umask']) assert '0027' in result.stdout_text cmd = self.master.run_command([ 'ipa-replica-install', '-w', self.master.config.admin_password, '-n', self.master.domain.name, '-r', self.master.domain.realm, '--server', 'dummy_master.%s' % self.master.domain.name, '-U'], raiseonerr=False ) exp_str = ("Unexpected system mask") assert (exp_str in cmd.stderr_text and cmd.returncode != 0) def test_files_ownership_and_permission_teardown(self): """ Method to restore the default bashrc contents""" if self.bashrc_file is not None: self.master.put_file_contents('/root/.bashrc', self.bashrc_file) class TestInstallMasterReplica(IntegrationTest): """https://pagure.io/freeipa/issue/7929 Problem: If a replica installation fails before all the services have been enabled then it could leave things in a bad state. ipa-replica-manage del --cleanup --force invalid 'PKINIT enabled server': all masters must have IPA master role enabled Root cause was that configuredServices were being considered when determining what masters provide what services, so a partially installed master could cause operations to fail on other masters, to the point where a broken master couldn't be removed. """ num_replicas = 1 topology = 'star' @classmethod def install(cls, mh): tasks.install_master(cls.master, setup_kra=True) # do not install KRA on replica, it is part of test tasks.install_replica(cls.master, cls.replicas[0], setup_kra=False) def test_replicamanage_del(self): """Test Steps: 1. Setup server 2. Setup replica 3. modify the replica entry on Master: ldapmodify -D cn="Directory Manager"-w <passwd> dn: cn=KDC,cn=<replicaFQDN>,cn=masters,cn=ipa,cn=etc,<baseDN> changetype: modify delete: ipaconfigstring ipaconfigstring: enabledService dn: cn=KDC,cn=<replicaFQDN>,cn=masters,cn=ipa,cn=etc,<baseDN> add: ipaconfigstring ipaconfigstring: configuredService 4. On master, run ipa-replica-manage del <replicaFQDN> --cleanup --force """ # https://pagure.io/freeipa/issue/7929 # modify the replica entry on Master cmd_output = None dn_entry = 'dn: cn=KDC,cn=%s,cn=masters,cn=ipa,' \ 'cn=etc,%s' % \ (self.replicas[0].hostname, ipautil.realm_to_suffix( self.replicas[0].domain.realm).ldap_text()) entry_ldif = textwrap.dedent(""" {dn} changetype: modify delete: ipaconfigstring ipaconfigstring: enabledService {dn} add: ipaconfigstring ipaconfigstring: configuredService """).format(dn=dn_entry) cmd_output = tasks.ldapmodify_dm(self.master, entry_ldif) assert 'modifying entry' in cmd_output.stdout_text cmd_output = self.master.run_command([ 'ipa-replica-manage', 'del', self.replicas[0].hostname, '--cleanup', '--force' ]) assert_text = 'Deleted IPA server "%s"' % self.replicas[0].hostname assert assert_text in cmd_output.stdout_text class TestInstallReplicaAgainstSpecificServer(IntegrationTest): """Installation of replica against a specific server Test to check replica install against specific server. It uses master and replica1 without CA and having custodia service stopped. Then try to install replica2 from replica1 and expect it to get fail as specified server is not providing all the services. related ticket: https://pagure.io/freeipa/issue/7566 """ num_replicas = 2 @classmethod def install(cls, mh): tasks.install_master(cls.master, setup_kra=True) # install replica1 without CA cmd = tasks.install_replica(cls.master, cls.replicas[0], setup_ca=False, setup_dns=True, promote=False) # check for warning that CA is not installed on server warn = 'WARNING: The CA service is only installed on one server' assert warn in cmd.stderr_text def test_replica_install_against_server_without_ca(self): """Replica install will fail complaining about CA role and exit code 4""" # stop custodia service on replica1 self.replicas[0].run_command('systemctl stop ipa-custodia.service') # check if custodia service is stopped cmd = self.replicas[0].run_command('ipactl status', raiseonerr=False) assert 'ipa-custodia Service: STOPPED' in cmd.stdout_text try: # install replica2 against replica1, as CA is not installed on # replica1, installation on replica2 should fail cmd = tasks.install_replica(self.replicas[0], self.replicas[1], promote=False, raiseonerr=False) assert cmd.returncode == 4 error = "please provide a server with the CA role" assert error in cmd.stderr_text finally: tasks.uninstall_master(self.replicas[1], ignore_topology_disconnect=True, ignore_last_of_role=True) def test_replica_install_against_server_without_kra(self): """Replica install will fail complaining about KRA role and exit code 4""" # install ca on replica1 tasks.install_ca(self.replicas[0]) try: # install replica2 against replica1, as KRA is not installed on # replica1(CA installed), installation should fail on replica2 cmd = tasks.install_replica(self.replicas[0], self.replicas[1], promote=False, setup_kra=True, raiseonerr=False) assert cmd.returncode == 4 error = "please provide a server with the KRA role" assert error in cmd.stderr_text finally: tasks.uninstall_master(self.replicas[1], ignore_topology_disconnect=True, ignore_last_of_role=True) def test_replica_install_against_server(self): """Replica install should succeed if specified server provide all the services""" tasks.install_replica(self.master, self.replicas[1], setup_dns=True, promote=False) # check if replication agreement stablished between master # and replica2 only. cmd = self.replicas[1].run_command(['ipa-replica-manage', 'list', self.replicas[0].hostname]) assert self.replicas[0].hostname not in cmd.stdout_text dirman_password = self.master.config.dirman_password cmd = self.replicas[1].run_command(['ipa-csreplica-manage', 'list', self.replicas[0].hostname], stdin_text=dirman_password) assert self.replicas[0].hostname not in cmd.stdout_text def test_replica_install_existing_agreement(self): """When the replication agreement already exists, the installer should print an error message with the information on where and how to remove it""" # master and replica_1 already installed by class' install() method # stop the main server in order to preserve the replication agreement # when removing the replica tasks.stop_ipa_server(self.master) # intentionally using ipa-server-install --uninstall # instead of replica-manage self.replicas[0].run_command(['ipa-server-install', '--uninstall', '--force', '-U']) tasks.start_ipa_server(self.master) result = tasks.install_replica(self.master, self.replicas[0], setup_ca=False, setup_dns=True, promote=False, raiseonerr=False, extra_args=('--force-join',)) assert result.returncode != 0 assert self.replicas[0].hostname in result.stderr_text assert "server-del" in result.stderr_text # delete the agreement based on the error message # and retry the installation self.master.run_command(['ipa', 'server-del', self.replicas[0].hostname, '--force']) result = tasks.install_replica(self.master, self.replicas[0], setup_ca=False, setup_dns=True, promote=False) assert result.returncode == 0 class TestInstallWithoutSudo(IntegrationTest): num_clients = 1 num_replicas = 1 no_sudo_str = "The sudo binary does not seem to be present on this" sudo_version_str = "Sudo version" @classmethod def install(cls, mh): pass def test_sudo_removal(self): # ipa-client makes sudo depend on libsss_sudo. # --nodeps is mandatory because dogtag uses sudo at install # time until commit 49585867207922479644a03078c29548de02cd03 # which is scheduled to land in 10.10. # This also means sudo+libsss_sudo cannot be uninstalled on # IPA servers with a CA. assert tasks.is_package_installed(self.clients[0], 'sudo') assert tasks.is_package_installed(self.clients[0], 'libsss_sudo') tasks.uninstall_packages( self.clients[0], ['sudo', 'libsss_sudo'], nodeps=True ) def test_ipa_installation_without_sudo(self): # FixMe: When Dogtag 10.10 is out, test installation without sudo tasks.install_master(self.master, setup_dns=True) def test_replica_installation_without_sudo(self): # FixMe: When Dogtag 10.10 is out, test replica installation # without sudo and with CA tasks.uninstall_packages( self.replicas[0], ['sudo', 'libsss_sudo'], nodeps=True ) # One-step install is needed. # With promote=True, two-step install is done and that only captures # the ipa-replica-install stdout/stderr, not ipa-client-install's. result = tasks.install_replica( self.master, self.replicas[0], promote=False, setup_dns=True, setup_ca=False ) assert self.no_sudo_str in result.stderr_text def test_client_installation_without_sudo(self): result = tasks.install_client(self.master, self.clients[0]) assert self.no_sudo_str in result.stderr_text def test_remove_sudo_on_ipa(self): tasks.uninstall_packages( self.master, ['sudo', 'libsss_sudo'], nodeps=True ) self.master.run_command( ['ipactl', 'restart'] ) def test_install_sudo_on_client(self): """ Check that installing sudo pulls libsss_sudo in""" for pkg in ('sudo', 'libsss_sudo'): assert tasks.is_package_installed(self.clients[0], pkg) is False tasks.uninstall_client(self.clients[0]) tasks.install_packages(self.clients[0], ['sudo']) for pkg in ('sudo', 'libsss_sudo'): assert tasks.is_package_installed(self.clients[0], pkg) result = tasks.install_client(self.master, self.clients[0]) assert self.no_sudo_str not in result.stderr_text assert self.sudo_version_str not in result.stdout_text class TestInstallWithoutNamed(IntegrationTest): num_replicas = 1 @classmethod def remove_named(cls, host): # remove the bind package and make sure the named user does not exist. # https://pagure.io/freeipa/issue/8936 result = host.run_command(['id', 'named'], raiseonerr=False) if result.returncode == 0: tasks.uninstall_packages(host, ['bind']) host.run_command(['userdel', constants.NAMED_USER]) assert host.run_command( ['id', 'named'], raiseonerr=False ).returncode == 1 @classmethod def install(cls, mh): for tgt in (cls.master, cls.replicas[0]): cls.remove_named(tgt) tasks.install_master(cls.master, setup_dns=False) def test_replica0_install(self): tasks.install_replica( self.master, self.replicas[0], setup_ca=False, setup_dns=False ) class TestInstallwithSHA384withRSA(IntegrationTest): num_replicas = 0 def test_install_master_withalgo_sha384withrsa(self, server_cleanup): tasks.install_master( self.master, extra_args=['--ca-signing-algorithm=SHA384withRSA'], ) # check Signing Algorithm post installation dashed_domain = self.master.domain.realm.replace(".", '-') cmd_args = ['certutil', '-L', '-d', '/etc/dirsrv/slapd-{}/'.format(dashed_domain), '-n', 'Server-Cert'] result = self.master.run_command(cmd_args) assert 'SHA-384 With RSA Encryption' in result.stdout_text def test_install_master_modify_existing(self, server_cleanup): """ Setup a master Stop services Modify default.params.signingAlg in CS.cfg Restart services Resubmit cert (Resubmitted cert should have new Algorithm) """ tasks.install_master(self.master) self.master.run_command(['ipactl', 'stop']) cs_cfg_content = self.master.get_file_contents(paths.CA_CS_CFG_PATH, encoding='utf-8') new_lines = [] replace_str = "ca.signing.defaultSigningAlgorithm=SHA384withRSA" ocsp_rep_str = "ca.ocsp_signing.defaultSigningAlgorithm=SHA384withRSA" for line in cs_cfg_content.split('\n'): if line.startswith('ca.signing.defaultSigningAlgorithm'): new_lines.append(replace_str) elif line.startswith('ca.ocsp_signing.defaultSigningAlgorithm'): new_lines.append(ocsp_rep_str) else: new_lines.append(line) self.master.put_file_contents(paths.CA_CS_CFG_PATH, '\n'.join(new_lines)) self.master.run_command(['ipactl', 'start']) cmd = ['getcert', 'list', '-f', paths.RA_AGENT_PEM] result = self.master.run_command(cmd) request_id = get_certmonger_fs_id(result.stdout_text) # resubmit RA Agent cert cmd = ['getcert', 'resubmit', '-f', paths.RA_AGENT_PEM] self.master.run_command(cmd) tasks.wait_for_certmonger_status(self.master, ('CA_WORKING', 'MONITORING'), request_id) cmd_args = ['openssl', 'x509', '-in', paths.RA_AGENT_PEM, '-noout', '-text'] result = self.master.run_command(cmd_args) assert_str = 'Signature Algorithm: sha384WithRSAEncryption' assert assert_str in result.stdout_text class TestHostnameValidator(IntegrationTest): """Test installer hostname validator.""" num_replicas = 0 def get_args(self, host): return [ 'ipa-server-install', '-n', host.domain.name, '-r', host.domain.realm, '-p', host.config.dirman_password, '-a', host.config.admin_password, '--setup-dns', '--forwarder', host.config.dns_forwarder, '--auto-reverse', '--netbios-name', 'EXAMPLE', ] def test_user_input_hostname(self): # https://pagure.io/freeipa/issue/9111 # Validate the user-provided hostname self.master.run_command(['hostname', 'fedora']) result = self.master.run_command( self.get_args(self.master), raiseonerr=False, stdin_text=self.master.hostname + '\nn\nn\nn\n', ) # Scrape the output for the summary which is only displayed # if the hostname is validated. hostname = None for line in result.stdout_text.split('\n'): print(line) m = re.match( r"Hostname:\s+({})".format(self.master.hostname), line ) if m: hostname = m.group(1) break assert hostname == self.master.hostname def test_hostname_with_dot(self): # https://pagure.io/freeipa/issue/9111 # Validate the user-provided hostname self.master.run_command(['hostname', 'fedora']) result = self.master.run_command( self.get_args(self.master), raiseonerr=False, stdin_text=self.master.hostname + '.\nn\nn\nn\n', ) # Scrape the output for the summary which is only displayed # if the hostname is validated. hostname = None for line in result.stdout_text.split('\n'): print(line) m = re.match( r"Hostname:\s+({})".format(self.master.hostname), line ) if m: hostname = m.group(1) break assert hostname == self.master.hostname def test_hostname_matching_domain(self): # https://pagure.io/freeipa/issue/9003 # Prevent hostname from matching the domain self.master.run_command(['hostname', self.master.hostname]) args = self.get_args(self.master) args.extend(['--hostname', self.master.domain.name]) result = self.master.run_command( args, raiseonerr=False, ) assert result.returncode == 1 assert 'hostname cannot be the same as the domain name' \ in result.stderr_text class TestNsslapdIgnoreTimeSkew(IntegrationTest): """ Test to check nsslapd-ignore-time-skew is not disabled. """ num_replicas = 1 topology = 'line' @pytest.fixture def update_time_skew(self): """ Fixture enables nsslapd-ignore-time-skew parameter and reverts it back """ ldap = self.replicas[0].ldap_connect() dn = DN( ("cn", "config"), ) entry = ldap.get_entry(dn) entry.single_value["nsslapd-ignore-time-skew"] = 'on' ldap.update_entry(entry) yield entry = ldap.get_entry(dn) entry.single_value["nsslapd-ignore-time-skew"] = 'off' ldap.update_entry(entry) def test_check_nsslapd_ignore_time_skew(self): """ This testcase checks that the ignore time skew parameter is set to on during the directory server replica installation (replication of the suffix) and during the CA replica (replication of o=ipaca). It also checks that the time skew is reverted during pki_tomcat setup stage. """ DIRSRV_LOG = ( "ignore time skew for initial replication" ) PKI_TOMCAT_LOG = ( "revert time skew after initial replication" ) install_msg = self.replicas[0].get_file_contents( paths.IPAREPLICA_INSTALL_LOG, encoding="utf-8" ) dirsrv_msg = re.findall(DIRSRV_LOG, install_msg) assert len(dirsrv_msg) == 2 assert PKI_TOMCAT_LOG in install_msg def test_forcesync_does_not_overwrite_ignore_time_skew( self, update_time_skew): """ This testcase checks that calling ipa-replica-manage force-sync does not overwrite the value of ignore time skew """ result = self.replicas[0].run_command( ["ipa-replica-manage", "force-sync", "--from", self.master.hostname, "--no-lookup", "-v"]) assert result.returncode == 0 conn = self.replicas[0].ldap_connect() ldap_entry = conn.get_entry(DN("cn=config")) assert ldap_entry.single_value['nsslapd-ignore-time-skew'] == "on"
83,696
Python
.py
1,812
35.520971
79
0.609609
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,568
test_subids.py
freeipa_freeipa/ipatests/test_integration/test_subids.py
# # Copyright (C) 2021 FreeIPA Contributors see COPYING for license # """Tests for subordinate ids """ import os from ipalib.constants import ( SUBID_COUNT, SUBID_RANGE_START, SUBID_RANGE_MAX, SUBID_DNA_THRESHOLD ) from ipaplatform.paths import paths from ipapython.dn import DN from ipatests.pytest_ipa.integration import tasks from ipatests.test_integration.base import IntegrationTest class TestSubordinateId(IntegrationTest): num_replicas = 0 num_clients = 1 topology = "star" def _parse_result(self, result): # ipa CLI should get an --outform json option info = {} for line in result.stdout_text.split("\n"): line = line.strip() if line: if ":" not in line: continue k, v = line.split(":", 1) k = k.strip() v = v.strip() try: v = int(v, 10) except ValueError: if v == "FALSE": v = False elif v == "TRUE": v = True info.setdefault(k.lower(), []).append(v) for k, v in info.items(): if len(v) == 1: info[k] = v[0] else: info[k] = set(v) return info def assert_subid_info(self, uid, info): assert info["ipauniqueid"] basedn = self.master.domain.basedn assert info["ipaowner"] == f"uid={uid},cn=users,cn=accounts,{basedn}" assert info["ipasubuidnumber"] == info["ipasubuidnumber"] assert info["ipasubuidnumber"] >= SUBID_RANGE_START assert info["ipasubuidnumber"] <= SUBID_RANGE_MAX assert info["ipasubuidcount"] == SUBID_COUNT assert info["ipasubgidnumber"] == info["ipasubgidnumber"] assert info["ipasubgidnumber"] == info["ipasubuidnumber"] assert info["ipasubgidcount"] == SUBID_COUNT def assert_subid(self, uid, *, match): cmd = ["ipa", "subid-find", "--raw", "--owner", uid] result = self.master.run_command(cmd, raiseonerr=False) if not match: assert result.returncode >= 1 if result.returncode == 1: assert "0 subordinate ids matched" in result.stdout_text elif result.returncode == 2: assert "user not found" in result.stderr_text return None else: assert result.returncode == 0 assert "1 subordinate id matched" in result.stdout_text info = self._parse_result(result) self.assert_subid_info(uid, info) self.master.run_command( ["ipa", "subid-show", info["ipauniqueid"]] ) return info def subid_generate(self, uid, **kwargs): cmd = ["ipa", "subid-generate"] if uid is not None: cmd.extend(("--owner", uid)) return self.master.run_command(cmd, **kwargs) def test_dna_config(self): conn = self.master.ldap_connect() dna_cfg = DN( "cn=Subordinate IDs,cn=Distributed Numeric Assignment Plugin," "cn=plugins,cn=config" ) entry = conn.get_entry(dna_cfg) def single_int(key): return int(entry.single_value[key]) assert single_int("dnaInterval") == SUBID_COUNT assert single_int("dnaThreshold") == SUBID_DNA_THRESHOLD assert single_int("dnaMagicRegen") == -1 assert single_int("dnaMaxValue") == SUBID_RANGE_MAX assert set(entry["dnaType"]) == {"ipasubgidnumber", "ipasubuidnumber"} def test_auto_generate_subid(self): uid = "testuser_auto1" passwd = "Secret123" tasks.create_active_user(self.master, uid, password=passwd) tasks.kinit_admin(self.master) self.assert_subid(uid, match=False) # add subid by name self.subid_generate(uid) info = self.assert_subid(uid, match=True) # second generate fails due to unique index on ipaowner result = self.subid_generate(uid, raiseonerr=False) assert result.returncode > 0 assert f'for user "{uid}" already exists' in result.stderr_text # check matching subuid = info["ipasubuidnumber"] for offset in (0, 1, 65535): result = self.master.run_command( ["ipa", "subid-match", f"--subuid={subuid + offset}", "--raw"] ) match = self._parse_result(result) self.assert_subid_info(uid, match) def test_ipa_subid_script(self): tasks.kinit_admin(self.master) tool = os.path.join(paths.LIBEXEC_IPA_DIR, "ipa-subids") users = [] for i in range(1, 11): uid = f"testuser_script{i}" users.append(uid) tasks.user_add(self.master, uid) self.assert_subid(uid, match=False) cmd = [tool, "--verbose", "--group", "ipausers"] self.master.run_command(cmd) for uid in users: self.assert_subid(uid, match=True) def test_subid_selfservice(self): uid1 = "testuser_selfservice1" uid2 = "testuser_selfservice2" password = "Secret123" role = "Subordinate ID Selfservice User" tasks.create_active_user(self.master, uid1, password=password) tasks.create_active_user(self.master, uid2, password=password) tasks.kinit_user(self.master, uid1, password=password) self.assert_subid(uid1, match=False) result = self.subid_generate(uid1, raiseonerr=False) assert result.returncode > 0 result = self.subid_generate(None, raiseonerr=False) assert result.returncode > 0 tasks.kinit_admin(self.master) self.master.run_command( ["ipa", "role-add-member", role, "--groups=ipausers"] ) try: tasks.kinit_user(self.master, uid1, password) self.subid_generate(uid1) self.assert_subid(uid1, match=True) # add subid from whoami tasks.kinit_as_user(self.master, uid2, password=password) self.subid_generate(None) self.assert_subid(uid2, match=True) finally: tasks.kinit_admin(self.master) self.master.run_command( ["ipa", "role-remove-member", role, "--groups=ipausers"] ) def test_subid_useradmin(self): tasks.kinit_admin(self.master) uid_useradmin = "testuser_usermgr_mgr1" role = "User Administrator" uid = "testuser_usermgr_user1" password = "Secret123" # create user administrator tasks.create_active_user( self.master, uid_useradmin, password=password ) # add user to user admin group tasks.kinit_admin(self.master) self.master.run_command( ["ipa", "role-add-member", role, f"--users={uid_useradmin}"], ) # kinit as user admin tasks.kinit_user(self.master, uid_useradmin, password) # create new user as user admin tasks.user_add(self.master, uid) # assign new subid to user (with useradmin credentials) self.subid_generate(uid) # test that user admin can preserve and delete users with subids self.master.run_command(["ipa", "user-del", "--preserve", uid]) # XXX does not work, see subordinate-ids.md # subid should still exist # self.assert_subid(uid, match=True) # final delete should remove the user and subid self.master.run_command(["ipa", "user-del", uid]) self.assert_subid(uid, match=False) def tset_subid_auto_assign(self): tasks.kinit_admin(self.master) uid = "testuser_autoassign_user1" self.master.run_command( ["ipa", "config-mod", "--user-default-subid=true"] ) try: tasks.user_add(self.master, uid) self.assert_subid(uid, match=True) finally: self.master.run_command( ["ipa", "config-mod", "--user-default-subid=false"] ) def test_idrange_subid(self): tasks.kinit_admin(self.master) range_name = f"{self.master.domain.realm}_subid_range" result = self.master.run_command( ["ipa", "idrange-show", range_name, "--raw"] ) info = self._parse_result(result) # see https://github.com/SSSD/sssd/issues/5571 assert info["iparangetype"] == "ipa-ad-trust" assert info["ipabaseid"] == SUBID_RANGE_START assert info["ipaidrangesize"] == SUBID_RANGE_MAX - SUBID_RANGE_START assert info["ipabaserid"] < SUBID_RANGE_START assert "ipasecondarybaserid" not in info assert info["ipanttrusteddomainsid"].startswith( "S-1-5-21-738065-838566-" ) def test_subid_stats(self): tasks.kinit_admin(self.master) self.master.run_command(["ipa", "subid-stats"]) def test_sudid_match_shows_uid(self): """ Test if subid-match command shows UID of the owner instead of DN https://pagure.io/freeipa/issue/8977 """ uid = "admin" self.subid_generate(uid) info = self.assert_subid(uid, match=True) subuid = info["ipasubuidnumber"] result = self.master.run_command(["ipa", "subid-match", f"--subuid={subuid}"]) owner = self._parse_result(result)["owner"] assert owner == uid def test_nsswitch_doesnot_contain_subid_entry(self): """ This testcase checks that when ipa-client-install is installed without subid option, the nsswitch.conf does not contain subid entry or does not use sss as source for subid """ cmd = self.clients[0].run_command( ["grep", "^subid", "/etc/nsswitch.conf"], raiseonerr=False ) # a source is defined for the subid database. # Ensure it is not "sss" if cmd.returncode == 0: assert 'sss' not in cmd.stdout_text else: # grep command returncode 1 means no matching line # was found = no source is defined for the subid database, # which is valid other return codes would # mean an error occurred assert cmd.returncode == 1 def test_nsswitch_is_updated_with_subid_entry(self): """ This test case checks that when ipa-client-install is installed with --subid option, the nsswitch.conf file is modified with the entry 'subid: sss' """ tasks.uninstall_client(self.clients[0]) tasks.install_client(self.master, self.clients[0], extra_args=['--subid']) cmd = self.clients[0].run_command( ["grep", "^subid", "/etc/nsswitch.conf"] ) subid = cmd.stdout_text.split() assert ['subid:', 'sss'] == subid
11,046
Python
.py
264
31.526515
78
0.589682
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,569
test_commands.py
freeipa_freeipa/ipatests/test_integration/test_commands.py
# # Copyright (C) 2018 FreeIPA Contributors see COPYING for license # """Misc test for 'ipa' CLI regressions """ from __future__ import absolute_import import base64 import re import os import logging import random import shlex import ssl from itertools import chain, repeat import sys import textwrap import time import pytest from subprocess import CalledProcessError from cryptography.hazmat.backends import default_backend from cryptography import x509 from datetime import datetime, timedelta from ipalib.constants import IPAAPI_USER from ipaplatform.paths import paths from ipapython.dn import DN from ipapython.certdb import get_ca_nickname from ipatests.test_integration.base import IntegrationTest from ipatests.pytest_ipa.integration import tasks from ipaplatform.tasks import tasks as platform_tasks from ipatests.create_external_ca import ExternalCA from ipatests.test_ipalib.test_x509 import good_pkcs7, badcert from ipapython.ipautil import realm_to_suffix, ipa_generate_password from ipaserver.install.installutils import realm_to_serverid from pkg_resources import parse_version logger = logging.getLogger(__name__) # from ipaserver.masters CONFIGURED_SERVICE = u'configuredService' ENABLED_SERVICE = u'enabledService' HIDDEN_SERVICE = u'hiddenService' DIRSRV_SLEEP = 5 isrgrootx1 = ( b'-----BEGIN CERTIFICATE-----\n' b'MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw\n' b'TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh\n' b'cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4\n' b'WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu\n' b'ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY\n' b'MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc\n' b'h77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+\n' b'0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U\n' b'A5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sW\n' b'T8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyH\n' b'B5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55tukmi8mxdAQ4Q7e2RCOFvu396j3x+UC\n' b'B5iPNgiV5+I3lg02dZ77DnKxHZu8A/lJBdiB3QW0KtZB6awBdpUKD9jf1b0SHzUv\n' b'KBds0pjBqAlkd25HN7rOrFleaJ1/ctaJxQZBKT5ZPt0m9STJEadao0xAH0ahmbWn\n' b'OlFuhjuefXKnEgV4We0+UXgVCwOPjdAvBbI+e0ocS3MFEvzG6uBQE3xDk3SzynTn\n' b'jh8BCNAw1FtxNrQHusEwMFxIt4I7mKZ9YIqioymCzLq9gwQbooMDQaHWBfEbwrbw\n' b'qHyGO0aoSCqI3Haadr8faqU9GY/rOPNk3sgrDQoo//fb4hVC1CLQJ13hef4Y53CI\n' b'rU7m2Ys6xt0nUW7/vGT1M0NPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n' b'HRMBAf8EBTADAQH/MB0GA1UdDgQWBBR5tFnme7bl5AFzgAiIyBpY9umbbjANBgkq\n' b'hkiG9w0BAQsFAAOCAgEAVR9YqbyyqFDQDLHYGmkgJykIrGF1XIpu+ILlaS/V9lZL\n' b'ubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ\n' b'3BebYhtF8GaV0nxvwuo77x/Py9auJ/GpsMiu/X1+mvoiBOv/2X/qkSsisRcOj/KK\n' b'NFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5\n' b'ORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7Ur\n' b'TkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdC\n' b'jNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc\n' b'oyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq\n' b'4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA\n' b'mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d\n' b'emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc=\n' b'-----END CERTIFICATE-----\n' ) isrgrootx1_nick = 'CN=ISRG Root X1,O=Internet Security Research Group,C=US' # This sub-CA expires on Sep 15, 2025 and will need to be replaced # after this date. Otherwise TestIPACommand::test_cacert_manage fails. letsencryptauthorityr3 = ( b'-----BEGIN CERTIFICATE-----\n' b'MIIFFjCCAv6gAwIBAgIRAJErCErPDBinU/bWLiWnX1owDQYJKoZIhvcNAQELBQAw\n' b'TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh\n' b'cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMjAwOTA0MDAwMDAw\n' b'WhcNMjUwOTE1MTYwMDAwWjAyMQswCQYDVQQGEwJVUzEWMBQGA1UEChMNTGV0J3Mg\n' b'RW5jcnlwdDELMAkGA1UEAxMCUjMwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK\n' b'AoIBAQC7AhUozPaglNMPEuyNVZLD+ILxmaZ6QoinXSaqtSu5xUyxr45r+XXIo9cP\n' b'R5QUVTVXjJ6oojkZ9YI8QqlObvU7wy7bjcCwXPNZOOftz2nwWgsbvsCUJCWH+jdx\n' b'sxPnHKzhm+/b5DtFUkWWqcFTzjTIUu61ru2P3mBw4qVUq7ZtDpelQDRrK9O8Zutm\n' b'NHz6a4uPVymZ+DAXXbpyb/uBxa3Shlg9F8fnCbvxK/eG3MHacV3URuPMrSXBiLxg\n' b'Z3Vms/EY96Jc5lP/Ooi2R6X/ExjqmAl3P51T+c8B5fWmcBcUr2Ok/5mzk53cU6cG\n' b'/kiFHaFpriV1uxPMUgP17VGhi9sVAgMBAAGjggEIMIIBBDAOBgNVHQ8BAf8EBAMC\n' b'AYYwHQYDVR0lBBYwFAYIKwYBBQUHAwIGCCsGAQUFBwMBMBIGA1UdEwEB/wQIMAYB\n' b'Af8CAQAwHQYDVR0OBBYEFBQusxe3WFbLrlAJQOYfr52LFMLGMB8GA1UdIwQYMBaA\n' b'FHm0WeZ7tuXkAXOACIjIGlj26ZtuMDIGCCsGAQUFBwEBBCYwJDAiBggrBgEFBQcw\n' b'AoYWaHR0cDovL3gxLmkubGVuY3Iub3JnLzAnBgNVHR8EIDAeMBygGqAYhhZodHRw\n' b'Oi8veDEuYy5sZW5jci5vcmcvMCIGA1UdIAQbMBkwCAYGZ4EMAQIBMA0GCysGAQQB\n' b'gt8TAQEBMA0GCSqGSIb3DQEBCwUAA4ICAQCFyk5HPqP3hUSFvNVneLKYY611TR6W\n' b'PTNlclQtgaDqw+34IL9fzLdwALduO/ZelN7kIJ+m74uyA+eitRY8kc607TkC53wl\n' b'ikfmZW4/RvTZ8M6UK+5UzhK8jCdLuMGYL6KvzXGRSgi3yLgjewQtCPkIVz6D2QQz\n' b'CkcheAmCJ8MqyJu5zlzyZMjAvnnAT45tRAxekrsu94sQ4egdRCnbWSDtY7kh+BIm\n' b'lJNXoB1lBMEKIq4QDUOXoRgffuDghje1WrG9ML+Hbisq/yFOGwXD9RiX8F6sw6W4\n' b'avAuvDszue5L3sz85K+EC4Y/wFVDNvZo4TYXao6Z0f+lQKc0t8DQYzk1OXVu8rp2\n' b'yJMC6alLbBfODALZvYH7n7do1AZls4I9d1P4jnkDrQoxB3UqQ9hVl3LEKQ73xF1O\n' b'yK5GhDDX8oVfGKF5u+decIsH4YaTw7mP3GFxJSqv3+0lUFJoi5Lc5da149p90Ids\n' b'hCExroL1+7mryIkXPeFM5TgO9r0rvZaBFOvV2z0gp35Z0+L4WPlbuEjN/lxPFin+\n' b'HlUjr8gRsI3qfJOQFy/9rKIJR0Y/8Omwt/8oTWgy1mdeHmmjk7j1nYsvC9JSQ6Zv\n' b'MldlTTKB3zhThV1+XWYp6rjd5JW1zbVWEkLNxE7GJThEUG3szgBVGP7pSWTUTsqX\n' b'nLRbwHOoq7hHwg==\n' b'-----END CERTIFICATE-----\n' ) le_r3_nick = "CN=R3,O=Let's Encrypt,C=US" class TestIPACommand(IntegrationTest): """ A lot of commands can be executed against a single IPA installation so provide a generic class to execute one-off commands that need to be tested without having to fire up a full server to run one command. """ topology = 'line' num_replicas = 1 num_clients = 1 @pytest.fixture def pwpolicy_global(self): """Fixture to change global password history policy and reset it""" tasks.kinit_admin(self.master) self.master.run_command( ["ipa", "pwpolicy-mod", "--history=5", "--minlife=0"], ) yield self.master.run_command( ["ipa", "pwpolicy-mod", "--history=0", "--minlife=1"], ) def get_cert_base64(self, host, path): """Retrieve cert and return content as single line, base64 encoded """ cacrt = host.get_file_contents(path, encoding='ascii') cader = ssl.PEM_cert_to_DER_cert(cacrt) return base64.b64encode(cader).decode('ascii') def test_aes_sha_kerberos_enctypes(self): """Test AES SHA 256 and 384 Kerberos enctypes enabled AES SHA 256 and 384-bit enctypes supported by MIT kerberos but was not enabled in IPA. This test is to check if these types are enabled. related: https://pagure.io/freeipa/issue/8110 """ tasks.kinit_admin(self.master) dn = DN(("cn", self.master.domain.realm), ("cn", "kerberos"), realm_to_suffix(self.master.domain.realm)) result = tasks.ldapsearch_dm(self.master, str(dn), ["krbSupportedEncSaltTypes"], scope="base") assert "aes128-sha2:normal" in result.stdout_text assert "aes128-sha2:special" in result.stdout_text assert "aes256-sha2:normal" in result.stdout_text assert "aes256-sha2:special" in result.stdout_text def test_certmap_match_issue7520(self): # https://pagure.io/freeipa/issue/7520 tasks.kinit_admin(self.master) result = self.master.run_command( ['ipa', 'certmap-match', paths.IPA_CA_CRT], raiseonerr=False ) assert result.returncode == 1 assert not result.stderr_text assert "0 users matched" in result.stdout_text cab64 = self.get_cert_base64(self.master, paths.IPA_CA_CRT) result = self.master.run_command( ['ipa', 'certmap-match', '--certificate', cab64], raiseonerr=False ) assert result.returncode == 1 assert not result.stderr_text assert "0 users matched" in result.stdout_text def test_cert_find_issue7520(self): # https://pagure.io/freeipa/issue/7520 tasks.kinit_admin(self.master) subject = 'CN=Certificate Authority,O={}'.format( self.master.domain.realm) # by cert file result = self.master.run_command( ['ipa', 'cert-find', '--file', paths.IPA_CA_CRT] ) assert subject in result.stdout_text assert '1 certificate matched' in result.stdout_text # by base64 cert cab64 = self.get_cert_base64(self.master, paths.IPA_CA_CRT) result = self.master.run_command( ['ipa', 'cert-find', '--certificate', cab64] ) assert subject in result.stdout_text assert '1 certificate matched' in result.stdout_text def test_add_permission_failure_issue5923(self): # https://pagure.io/freeipa/issue/5923 # error response used to contain bytes instead of text tasks.kinit_admin(self.master) # neither privilege nor permission exists result = self.master.run_command( ["ipa", "privilege-add-permission", "loc", "--permission='System: Show IPA Locations"], raiseonerr=False ) assert result.returncode == 2 err = result.stderr_text.strip() assert err == "ipa: ERROR: loc: privilege not found" # add privilege result = self.master.run_command( ["ipa", "privilege-add", "loc"], ) assert 'Added privilege "loc"' in result.stdout_text # permission is still missing result = self.master.run_command( ["ipa", "privilege-add-permission", "loc", "--permission='System: Show IPA Locations"], raiseonerr=False ) assert result.returncode == 1 assert "Number of permissions added 0" in result.stdout_text def test_change_sysaccount_password_issue7561(self): sysuser = 'system' original_passwd = 'Secret123' new_passwd = 'userPasswd123' master = self.master base_dn = str(master.domain.basedn) entry_ldif = textwrap.dedent(""" dn: uid={sysuser},cn=sysaccounts,cn=etc,{base_dn} changetype: add objectclass: account objectclass: simplesecurityobject uid: {sysuser} userPassword: {original_passwd} passwordExpirationTime: 20380119031407Z nsIdleTimeout: 0 """).format( base_dn=base_dn, original_passwd=original_passwd, sysuser=sysuser) tasks.ldapmodify_dm(master, entry_ldif) tasks.ldappasswd_sysaccount_change(sysuser, original_passwd, new_passwd, master) def get_krbinfo(self, user): base_dn = str(self.master.domain.basedn) result = tasks.ldapsearch_dm( self.master, 'uid={user},cn=users,cn=accounts,{base_dn}'.format( user=user, base_dn=base_dn), ['krblastpwdchange', 'krbpasswordexpiration'], scope='base' ) output = result.stdout_text.lower() # extract krblastpwdchange and krbpasswordexpiration krbchg_pattern = 'krblastpwdchange: (.+)\n' krbexp_pattern = 'krbpasswordexpiration: (.+)\n' krblastpwdchange = re.findall(krbchg_pattern, output)[0] krbexp = re.findall(krbexp_pattern, output)[0] return krblastpwdchange, krbexp def test_ldapmodify_password_issue7601(self): user = 'ipauser' original_passwd = 'Secret123' new_passwd = 'userPasswd123' new_passwd2 = 'mynewPwd123' master = self.master base_dn = str(master.domain.basedn) # Create a user with a password tasks.kinit_admin(master) add_password_stdin_text = "{pwd}\n{pwd}".format(pwd=original_passwd) master.run_command(['ipa', 'user-add', user, '--first', user, '--last', user, '--password'], stdin_text=add_password_stdin_text) # kinit as that user in order to modify the pwd user_kinit_stdin_text = "{old}\n%{new}\n%{new}\n".format( old=original_passwd, new=original_passwd) master.run_command(['kinit', user], stdin_text=user_kinit_stdin_text) # Retrieve krblastpwdchange and krbpasswordexpiration krblastpwdchange, krbexp = self.get_krbinfo(user) # sleep 1 sec (krblastpwdchange and krbpasswordexpiration have at most # a 1s precision) time.sleep(1) # perform ldapmodify on userpassword as dir mgr entry_ldif = textwrap.dedent(""" dn: uid={user},cn=users,cn=accounts,{base_dn} changetype: modify replace: userpassword userpassword: {new_passwd} """).format( user=user, base_dn=base_dn, new_passwd=new_passwd) tasks.ldapmodify_dm(master, entry_ldif) # Test new password with kinit master.run_command(['kinit', user], stdin_text=new_passwd) # both should have changed newkrblastpwdchange, newkrbexp = self.get_krbinfo(user) assert newkrblastpwdchange != krblastpwdchange assert newkrbexp != krbexp # Now test passwd modif with ldappasswd time.sleep(1) master.run_command([ paths.LDAPPASSWD, '-D', str(master.config.dirman_dn), '-w', master.config.dirman_password, '-a', new_passwd, '-s', new_passwd2, '-x', '-ZZ', '-H', 'ldap://{hostname}'.format(hostname=master.hostname), 'uid={user},cn=users,cn=accounts,{base_dn}'.format( user=user, base_dn=base_dn)] ) # Test new password with kinit master.run_command(['kinit', user], stdin_text=new_passwd2) # both should have changed newkrblastpwdchange2, newkrbexp2 = self.get_krbinfo(user) assert newkrblastpwdchange != newkrblastpwdchange2 assert newkrbexp != newkrbexp2 def test_change_sysaccount_pwd_history_issue7181(self, pwpolicy_global): """ Test that a sysacount user maintains no password history because they do not have a Kerberos identity. """ sysuser = 'sysuser' original_passwd = 'Secret123' new_passwd = 'userPasswd123' master = self.master # Add a system account and add it to a group managed by the policy base_dn = str(master.domain.basedn) entry_ldif = textwrap.dedent(""" dn: uid={account_name},cn=sysaccounts,cn=etc,{base_dn} changetype: add objectclass: account objectclass: simplesecurityobject uid: {account_name} userPassword: {original_passwd} passwordExpirationTime: 20380119031407Z nsIdleTimeout: 0 """).format( account_name=sysuser, base_dn=base_dn, original_passwd=original_passwd) tasks.ldapmodify_dm(master, entry_ldif) # Now change the password. It should succeed since password # policy doesn't apply to non-Kerberos users. tasks.ldappasswd_sysaccount_change(sysuser, original_passwd, new_passwd, master) tasks.ldappasswd_sysaccount_change(sysuser, new_passwd, original_passwd, master) tasks.ldappasswd_sysaccount_change(sysuser, original_passwd, new_passwd, master) def test_change_user_pwd_history_issue7181(self, pwpolicy_global): """ Test that password history for a normal IPA user is honored. """ user = 'user1' original_passwd = 'Secret123' new_passwd = 'userPasswd123' master = self.master tasks.user_add(master, user, password=original_passwd) tasks.ldappasswd_user_change(user, original_passwd, new_passwd, master) tasks.ldappasswd_user_change(user, new_passwd, original_passwd, master) try: tasks.ldappasswd_user_change(user, original_passwd, new_passwd, master) except CalledProcessError as e: if e.returncode != 1: raise else: pytest.fail("Password change violating policy did not fail") def test_dm_change_user_pwd_history_issue7181(self, pwpolicy_global): """ Test that password policy is not applied with Directory Manager. The minimum lifetime of the password is set to 1 hour. Confirm that the user cannot re-change their password immediately but the DM can. """ user = 'user1' original_passwd = 'Secret123' new_passwd = 'newPasswd123' master = self.master # reset minimum life to 1 hour. self.master.run_command( ["ipa", "pwpolicy-mod", "--minlife=1"], ) try: tasks.ldappasswd_user_change(user, original_passwd, new_passwd, master) except CalledProcessError as e: if e.returncode != 1: raise else: pytest.fail("Password change violating policy did not fail") # DM should be able to change any password regardless of policy try: tasks.ldappasswd_user_change(user, new_passwd, original_passwd, master, use_dirman=True) except CalledProcessError: pytest.fail("Password change failed when it should not") def test_huge_password(self): user = 'toolonguser' hostname = 'toolong.{}'.format(self.master.domain.name) huge_password = ipa_generate_password(min_len=1536) original_passwd = 'Secret123' master = self.master base_dn = str(master.domain.basedn) # Create a user with a password that is too long tasks.kinit_admin(master) add_password_stdin_text = "{pwd}\n{pwd}".format(pwd=huge_password) result = master.run_command(['ipa', 'user-add', user, '--first', user, '--last', user, '--password'], stdin_text=add_password_stdin_text, raiseonerr=False) assert result.returncode != 0 # Try again with a normal password add_password_stdin_text = "{pwd}\n{pwd}".format(pwd=original_passwd) master.run_command(['ipa', 'user-add', user, '--first', user, '--last', user, '--password'], stdin_text=add_password_stdin_text) # kinit as that user in order to modify the pwd user_kinit_stdin_text = "{old}\n%{new}\n%{new}\n".format( old=original_passwd, new=original_passwd) master.run_command(['kinit', user], stdin_text=user_kinit_stdin_text) # sleep 1 sec (krblastpwdchange and krbpasswordexpiration have at most # a 1s precision) time.sleep(1) # perform ldapmodify on userpassword as dir mgr entry_ldif = textwrap.dedent(""" dn: uid={user},cn=users,cn=accounts,{base_dn} changetype: modify replace: userpassword userpassword: {new_passwd} """).format( user=user, base_dn=base_dn, new_passwd=huge_password) result = tasks.ldapmodify_dm(master, entry_ldif, raiseonerr=False) assert result.returncode != 0 # ask_password in ipa-getkeytab will complain about too long password keytab_file = os.path.join(self.master.config.test_dir, 'user.keytab') password_stdin_text = "{pwd}\n{pwd}".format(pwd=huge_password) result = self.master.run_command(['ipa-getkeytab', '-p', user, '-P', '-k', keytab_file, '-s', self.master.hostname], stdin_text=password_stdin_text, raiseonerr=False) assert result.returncode != 0 assert "clear-text password is too long" in result.stderr_text # Create a host with a user-set OTP that is too long tasks.kinit_admin(master) result = master.run_command(['ipa', 'host-add', '--force', hostname, '--password', huge_password], raiseonerr=False) assert result.returncode != 0 # Try again with a valid password result = master.run_command(['ipa', 'host-add', '--force', hostname, '--password', original_passwd], raiseonerr=False) assert result.returncode == 0 def test_cleartext_password_httpd_log(self): """Test to check password leak in apache error log Host enrollment with OTP used to log the password in cleartext to apache error log. This test ensures that the password should not be log in cleartext. related: https://pagure.io/freeipa/issue/8017 """ hostname = 'test.{}'.format(self.master.domain.name) passwd = 'Secret123' self.master.run_command(['ipa', 'host-add', '--force', hostname, '--password', passwd]) # remove added host i.e cleanup self.master.run_command(['ipa', 'host-del', hostname]) result = self.master.run_command(['grep', hostname, paths.VAR_LOG_HTTPD_ERROR]) assert passwd not in result.stdout_text def test_change_selinuxusermaporder(self): """ An update file meant to ensure a more sane default was overriding any customization done to the order. """ maporder = "unconfined_u:s0-s0:c0.c1023" # set a new default tasks.kinit_admin(self.master) result = self.master.run_command( ["ipa", "config-mod", "--ipaselinuxusermaporder={}".format(maporder)], raiseonerr=False ) assert result.returncode == 0 # apply the update result = self.master.run_command( ["ipa-server-upgrade"], raiseonerr=False ) assert result.returncode == 0 # ensure result is the same result = self.master.run_command( ["ipa", "config-show"], raiseonerr=False ) assert result.returncode == 0 assert "SELinux user map order: {}".format( maporder) in result.stdout_text def test_ipa_console(self): tasks.kinit_admin(self.master) result = self.master.run_command( ["ipa", "console"], stdin_text="api.env" ) assert "ipalib.config.Env" in result.stdout_text filename = tasks.upload_temp_contents( self.master, "print(api.env)\n" ) result = self.master.run_command( ["ipa", "console", filename], ) assert "ipalib.config.Env" in result.stdout_text def test_list_help_topics(self): tasks.kinit_admin(self.master) result = self.master.run_command( ["ipa", "help", "topics"], raiseonerr=False ) assert result.returncode == 0 def test_ssh_key_connection(self, tmpdir): """ Integration test for https://pagure.io/SSSD/sssd/issue/3747 """ test_user = 'test-ssh' pub_keys = [] for i in range(40): ssh_key_pair = tasks.generate_ssh_keypair() pub_keys.append(ssh_key_pair[1]) with open(os.path.join( tmpdir, 'ssh_priv_{}'.format(i)), 'w') as fp: fp.write(ssh_key_pair[0]) fp.write(os.linesep) tasks.kinit_admin(self.master) self.master.run_command(['ipa', 'user-add', test_user, '--first=tester', '--last=tester']) keys_opts = ' '.join(['--ssh "{}"'.format(k) for k in pub_keys]) self.master.run_command( shlex.split('ipa user-mod {} {}'.format(test_user, keys_opts)) ) # connect with first SSH key first_priv_key_path = os.path.join(tmpdir, 'ssh_priv_1') # change private key permission to comply with SS rules os.chmod(first_priv_key_path, 0o600) # Make sure that / has rwxr-xr-x permissions on the master # otherwise sshd will deny login using private key # https://access.redhat.com/solutions/6798261 self.master.run_command(['chmod', '755', '/']) # start to look at logs a bit before "now" # https://pagure.io/freeipa/issue/8432 since = time.strftime( '%Y-%m-%d %H:%M:%S', (datetime.now() - timedelta(seconds=10)).timetuple() ) # Wait for sssd to be back online, hence test-user to become available tasks.wait_for_sssd_domain_status_online(self.master) tasks.run_ssh_cmd( to_host=self.master.external_hostname, username=test_user, auth_method="key", private_key_path=first_priv_key_path ) expected_missing_msg = "exited on signal 13" # closing session marker(depends on PAM stack of sshd) expected_msgs = [ f"session closed for user {test_user}", f"Disconnected from user {test_user}", ] def test_cb(stdout): # check if expected message logged and expected missing one not return ( any(m in stdout for m in expected_msgs) and expected_missing_msg not in stdout ) # sshd don't flush its logs to syslog immediately cmd = ["journalctl", "-u", "sshd", f"--since={since}"] tasks.run_repeatedly(self.master, command=cmd, test=test_cb) # cleanup self.master.run_command(['ipa', 'user-del', test_user]) def test_ssh_leak(self): """ Integration test for https://pagure.io/SSSD/sssd/issue/3794 """ def count_pipes(): res = self.master.run_command(['pidof', 'sssd_ssh']) pid = res.stdout_text.strip() proc_path = '/proc/{}/fd'.format(pid) res = self.master.run_command(['ls', '-la', proc_path]) fds_text = res.stdout_text.strip() return sum((1 for _ in re.finditer(r'pipe', fds_text))) test_user = 'test-ssh' tasks.kinit_admin(self.master) self.master.run_command(['ipa', 'user-add', test_user, '--first=tester', '--last=tester']) certs = [] # we are ok with whatever certificate for this test external_ca = ExternalCA() for _dummy in range(3): cert = external_ca.create_ca() cert = tasks.strip_cert_header(cert.decode('utf-8')) certs.append('"{}"'.format(cert)) cert_args = list( chain.from_iterable(list(zip(repeat('--certificate'), certs)))) cmd = 'ipa user-add-cert {} {}'.format(test_user, ' '.join(cert_args)) self.master.run_command(cmd) tasks.clear_sssd_cache(self.master) num_of_pipes = count_pipes() for _dummy in range(3): self.master.run_command([paths.SSS_SSH_AUTHORIZEDKEYS, test_user]) current_num_of_pipes = count_pipes() assert current_num_of_pipes == num_of_pipes # cleanup self.master.run_command(['ipa', 'user-del', test_user]) def test_certificate_out_write_to_file(self): # commands to test; name of temporary file will be appended result = self.master.run_command([ 'openssl', 'x509', '-serial', '-noout', '-in', paths.IPA_CA_CRT ]) serial = result.stdout_text.strip().split('=', maxsplit=1)[1] commands = [ ['ipa', 'cert-show', serial, '--certificate-out'], ['ipa', 'cert-show', serial, '--chain', '--certificate-out'], ['ipa', 'ca-show', 'ipa', '--certificate-out'], ['ipa', 'ca-show', 'ipa', '--chain', '--certificate-out'], ] for command in commands: cmd = self.master.run_command(['mktemp']) filename = cmd.stdout_text.strip() self.master.run_command(command + [filename]) # Check that a PEM file was written. If --chain was # used, load_pem_x509_certificate will return the # first certificate, which is fine for this test. data = self.master.get_file_contents(filename) x509.load_pem_x509_certificate(data, backend=default_backend()) self.master.run_command(['rm', '-f', filename]) # Ensure that ca/cert-show doesn't leave an empty file when # the requested ca/cert does not exist. commands = [ ['ipa', 'cert-show', '0xdeadbeef', '--certificate-out'], ['ipa', 'ca-show', 'notfound', '--certificate-out'], ] for command in commands: cmd = self.master.run_command(['mktemp', '--dry-run']) filename = cmd.stdout_text.strip() result = self.master.run_command(command + [filename], raiseonerr=False) assert result.returncode == 2 result = self.master.run_command( ['stat', filename], raiseonerr=False ) assert result.returncode == 1 def test_sssd_ifp_access_ipaapi(self): # check that ipaapi is allowed to access sssd-ifp for smartcard auth # https://pagure.io/freeipa/issue/7751 username = 'admin' # get UID for user result = self.master.run_command(['ipa', 'user-show', username]) mo = re.search(r'UID: (\d+)', result.stdout_text) assert mo is not None, result.stdout_text uid = mo.group(1) cmd = [ 'dbus-send', '--print-reply', '--system', '--dest=org.freedesktop.sssd.infopipe', '/org/freedesktop/sssd/infopipe/Users', 'org.freedesktop.sssd.infopipe.Users.FindByName', 'string:{}'.format(username) ] # test IFP as root result = self.master.run_command(cmd) assert uid in result.stdout_text # test IFP as ipaapi result = self.master.run_command( ['runuser', '-u', IPAAPI_USER, '--'] + cmd ) assert uid in result.stdout_text def test_ipa_cacert_manage_install(self): # Re-install the IPA CA self.master.run_command([ paths.IPA_CACERT_MANAGE, 'install', paths.IPA_CA_CRT]) # Test a non-existent file result = self.master.run_command([ paths.IPA_CACERT_MANAGE, 'install', '/run/cert_not_found'], raiseonerr=False) assert result.returncode == 1 cmd = self.master.run_command(['mktemp']) filename = cmd.stdout_text.strip() for contents in (good_pkcs7,): self.master.put_file_contents(filename, contents) result = self.master.run_command([ paths.IPA_CACERT_MANAGE, 'install', filename]) for contents in (badcert,): self.master.put_file_contents(filename, contents) result = self.master.run_command([ paths.IPA_CACERT_MANAGE, 'install', filename], raiseonerr=False) assert result.returncode == 1 self.master.run_command(['rm', '-f', filename]) def test_hbac_systemd_user(self): # https://pagure.io/freeipa/issue/7831 tasks.kinit_admin(self.master) # check for presence self.master.run_command( ['ipa', 'hbacsvc-show', 'systemd-user'] ) result = self.master.run_command( ['ipa', 'hbacrule-show', 'allow_systemd-user', '--all'] ) lines = set(l.strip() for l in result.stdout_text.split('\n')) assert 'User category: all' in lines assert 'Host category: all' in lines assert 'Enabled: True' in lines assert 'HBAC Services: systemd-user' in lines assert 'accessruletype: allow' in lines # delete both self.master.run_command( ['ipa', 'hbacrule-del', 'allow_systemd-user'] ) self.master.run_command( ['ipa', 'hbacsvc-del', 'systemd-user'] ) # run upgrade result = self.master.run_command(['ipa-server-upgrade']) assert 'Created hbacsvc systemd-user' in result.stderr_text assert 'Created hbac rule allow_systemd-user' in result.stderr_text # check for presence result = self.master.run_command( ['ipa', 'hbacrule-show', 'allow_systemd-user', '--all'] ) lines = set(l.strip() for l in result.stdout_text.split('\n')) assert 'User category: all' in lines assert 'Host category: all' in lines assert 'Enabled: True' in lines assert 'HBAC Services: systemd-user' in lines assert 'accessruletype: allow' in lines self.master.run_command( ['ipa', 'hbacsvc-show', 'systemd-user'] ) # only delete rule self.master.run_command( ['ipa', 'hbacrule-del', 'allow_systemd-user'] ) # run upgrade result = self.master.run_command(['ipa-server-upgrade']) assert ( 'hbac service systemd-user already exists' in result.stderr_text ) assert ( 'Created hbac rule allow_systemd-user' not in result.stderr_text ) result = self.master.run_command( ['ipa', 'hbacrule-show', 'allow_systemd-user'], raiseonerr=False ) assert result.returncode != 0 assert 'HBAC rule not found' in result.stderr_text def test_config_show_configured_services(self): # https://pagure.io/freeipa/issue/7929 states = {CONFIGURED_SERVICE, ENABLED_SERVICE, HIDDEN_SERVICE} dn = DN( ('cn', 'HTTP'), ('cn', self.master.hostname), ('cn', 'masters'), ('cn', 'ipa'), ('cn', 'etc'), self.master.domain.basedn ) conn = self.master.ldap_connect() entry = conn.get_entry(dn) # original setting and all settings without state orig_cfg = list(entry['ipaConfigString']) other_cfg = [item for item in orig_cfg if item not in states] try: # test with hidden cfg = [HIDDEN_SERVICE] cfg.extend(other_cfg) entry['ipaConfigString'] = cfg conn.update_entry(entry) self.master.run_command(['ipa', 'config-show']) # test with configured cfg = [CONFIGURED_SERVICE] cfg.extend(other_cfg) entry['ipaConfigString'] = cfg conn.update_entry(entry) self.master.run_command(['ipa', 'config-show']) finally: # reset entry['ipaConfigString'] = orig_cfg conn.update_entry(entry) def test_ssh_from_controller(self): """https://pagure.io/SSSD/sssd/issue/3979 Test ssh from test controller after adding ldap_deref_threshold=0 to sssd.conf on master Steps: 1. setup a master 2. add ldap_deref_threshold=0 to sssd.conf on master 3. add an ipa user 4. ssh from controller to master using the user created in step 3 """ cmd = self.master.run_command(['sssd', '--version']) sssd_version = platform_tasks.parse_ipa_version( cmd.stdout_text.strip()) if sssd_version < platform_tasks.parse_ipa_version('2.2.0'): pytest.xfail(reason="sssd 2.2.0 unavailable in F29 nightly") # add ldap_deref_threshold=0 to /etc/sssd/sssd.conf sssd_conf_backup = tasks.FileBackup(self.master, paths.SSSD_CONF) with tasks.remote_sssd_config(self.master) as sssd_config: sssd_config.edit_domain( self.master.domain, 'ldap_deref_threshold', 0) test_user = "testuser" + str(random.randint(200000, 9999999)) password = "Secret123" try: self.master.run_command(['systemctl', 'restart', 'sssd.service']) # kinit admin tasks.kinit_admin(self.master) # add ipa user tasks.create_active_user( self.master, test_user, password=password ) tasks.kdestroy_all(self.master) tasks.kinit_as_user( self.master, test_user, password ) tasks.kdestroy_all(self.master) tasks.run_ssh_cmd( to_host=self.master.external_hostname, username=test_user, auth_method="password", password=password ) finally: sssd_conf_backup.restore() self.master.run_command(['systemctl', 'restart', 'sssd.service']) def test_user_mod_change_capitalization_issue5879(self): """ Test that an existing user which has been modified using ipa user-mod and has the first and last name beginning with caps does not throw the error 'ipa: ERROR: Type or value exists:' and instead gets modified This is a test case for Pagure issue https://pagure.io/freeipa/issue/5879 Steps: 1. setup a master 2. add ipa user on master 3. now run ipa user-mod and specifying capital letters in names 4. user details should be modified 5. ipa: ERROR: Type or value exists is not displayed on console. """ # Create an ipa-user tasks.kinit_admin(self.master) ipauser = 'ipauser1' first = 'ipauser' modfirst = 'IpaUser' last = 'test' modlast = 'Test' password = 'Secret123' self.master.run_command( ['ipa', 'user-add', ipauser, '--first', first, '--last', last, '--password'], stdin_text="%s\n%s\n" % (password, password)) cmd = self.master.run_command( ['ipa', 'user-mod', ipauser, '--first', modfirst, '--last', modlast]) assert 'Modified user "%s"' % (ipauser) in cmd.stdout_text assert 'First name: %s' % (modfirst) in cmd.stdout_text assert 'Last name: %s' % (modlast) in cmd.stdout_text @pytest.mark.skip_if_platform( "debian", reason="Crypto policy is not supported on Debian" ) def test_enabled_tls_protocols(self): """Check Apache has same TLS versions enabled as crypto policy This is the regression test for issue https://pagure.io/freeipa/issue/7995. """ def is_tls_version_enabled(tls_version): res = self.master.run_command( ['openssl', 's_client', '-connect', '{}:443'.format(self.master.hostname), '-{}'.format(tls_version)], stdin_text='\n', ok_returncode=[0, 1] ) return res.returncode == 0 # get minimum version from current crypto-policy openssl_cnf = self.master.get_file_contents( paths.CRYPTO_POLICY_OPENSSLCNF_FILE, encoding="utf-8" ) mo = re.search(r"MinProtocol\s*=\s*(TLSv[0-9.]+)", openssl_cnf) assert mo min_tls = mo.group(1) # Fedora DEFAULT has TLS 1.0 enabled, NEXT has TLS 1.2 # even FUTURE crypto policy has TLS 1.2 as minimum version assert min_tls in {"TLSv1", "TLSv1.2"} # On Fedora FreeIPA still disables TLS 1.0 and 1.1 in ssl.conf. assert not is_tls_version_enabled('tls1') assert not is_tls_version_enabled('tls1_1') assert is_tls_version_enabled('tls1_2') assert is_tls_version_enabled('tls1_3') def test_sss_ssh_authorizedkeys(self): """Login via Ssh using private-key for ipa-user should work. Test for : https://pagure.io/SSSD/sssd/issue/3937 Steps: 1) setup user with ssh-key and certificate stored in ipaserver 2) simulate p11_child timeout 3) try to login via ssh using private key. """ user = 'testsshuser' passwd = 'Secret123' user_key = tasks.create_temp_file(self.master, create_file=False) pem_file = tasks.create_temp_file(self.master) # Create a user with a password tasks.create_active_user(self.master, user, passwd, extra_args=[ '--homedir', '/home/{}'.format(user)]) tasks.kinit_admin(self.master) tasks.run_command_as_user( self.master, user, ['ssh-keygen', '-N', '', '-f', user_key]) ssh_pub_key = self.master.get_file_contents('{}.pub'.format( user_key), encoding='utf-8') openssl_cmd = [ 'openssl', 'req', '-x509', '-newkey', 'rsa:2048', '-days', '365', '-nodes', '-out', pem_file, '-subj', '/CN=' + user] self.master.run_command(openssl_cmd) cert_b64 = self.get_cert_base64(self.master, pem_file) sssd_p11_child = '/usr/libexec/sssd/p11_child' backup = tasks.FileBackup(self.master, sssd_p11_child) try: content = '#!/bin/bash\nsleep 999999' # added sleep to simulate the timeout for p11_child self.master.put_file_contents(sssd_p11_child, content) self.master.run_command( ['ipa', 'user-mod', user, '--ssh', ssh_pub_key]) self.master.run_command([ 'ipa', 'user-add-cert', user, '--certificate', cert_b64]) # clear cache to avoid SSSD to check the user in old lookup tasks.clear_sssd_cache(self.master) result = self.master.run_command( [paths.SSS_SSH_AUTHORIZEDKEYS, user]) assert ssh_pub_key in result.stdout_text # login to the system self.master.run_command( ['ssh', '-v', '-o', 'PasswordAuthentication=no', '-o', 'IdentitiesOnly=yes', '-o', 'StrictHostKeyChecking=no', '-o', 'ConnectTimeout=10', '-l', user, '-i', user_key, self.master.hostname, 'true']) finally: # cleanup self.master.run_command(['ipa', 'user-del', user]) backup.restore() self.master.run_command(['rm', '-f', pem_file, user_key, '{}.pub'.format(user_key)]) def test_cacert_manage(self): """Exercise ipa-cacert-manage delete""" # deletion without nickname result = self.master.run_command( ['ipa-cacert-manage', 'delete'], raiseonerr=False ) assert result.returncode != 0 # deletion with an unknown nickname result = self.master.run_command( ['ipa-cacert-manage', 'delete', 'unknown'], raiseonerr=False ) assert result.returncode != 0 assert "Unknown CA 'unknown'" in result.stderr_text # deletion of IPA CA ipa_ca_nickname = get_ca_nickname(self.master.domain.realm) result = self.master.run_command( ['ipa-cacert-manage', 'delete', ipa_ca_nickname], raiseonerr=False ) assert result.returncode != 0 assert 'The IPA CA cannot be removed with this tool' in \ result.stderr_text # Install 3rd party CA's, Let's Encrypt in this case for cert in (isrgrootx1, letsencryptauthorityr3): certfile = os.path.join(self.master.config.test_dir, 'cert.pem') self.master.put_file_contents(certfile, cert) result = self.master.run_command( ['ipa-cacert-manage', 'install', certfile], ) # deletion of a root CA needed by a subCA, without -f option result = self.master.run_command( ['ipa-cacert-manage', 'delete', isrgrootx1_nick], raiseonerr=False ) assert result.returncode != 0 assert "Verifying \'%s\' failed. Removing part of the " \ "chain? certutil: certificate is invalid: Peer's " \ "Certificate issuer is not recognized." \ % isrgrootx1_nick in result.stderr_text # deletion of a root CA needed by a subCA, with -f option result = self.master.run_command( ['ipa-cacert-manage', 'delete', isrgrootx1_nick, '-f'], raiseonerr=False ) assert result.returncode == 0 # deletion of a subca result = self.master.run_command( ['ipa-cacert-manage', 'delete', le_r3_nick], raiseonerr=False ) assert result.returncode == 0 def test_ipa_adtrust_install_with_locale_issue8066(self): """ This test checks that ipa-adtrust-install command runs successfully on a system with locale en_IN.UTF-8 without displaying error below 'IndexError: list index out of range' This is a testcase for Pagure issue https://pagure.io/freeipa/issue/8066 """ # Set locale to en_IN.UTF-8 in .bashrc file to avoid reboot tasks.kinit_admin(self.master) BASHRC_CFG = "/root/.bashrc" bashrc_backup = tasks.FileBackup(self.master, BASHRC_CFG) exp_msg = "en_IN.UTF-8" try: self.master.run_command( 'echo "export LC_TIME=en_IN.UTF-8" >> ' + BASHRC_CFG ) result = self.master.run_command('echo "$LC_TIME"') assert result.stdout_text.rstrip() == exp_msg # Install ipa-server-adtrust and check status msg1 = ( "Unexpected error - see /var/log/ipaserver-install.log" "for details" ) msg2 = "IndexError: list index out of range" tasks.install_packages(self.master, ["*ipa-server-trust-ad"]) result = self.master.run_command( ["ipa-adtrust-install", "-U"], raiseonerr=False ) assert msg1 not in result.stderr_text assert msg2 not in result.stderr_text finally: bashrc_backup.restore() @pytest.fixture def user_creation_deletion(self): # create user self.testuser = 'testuser' tasks.create_active_user(self.master, self.testuser, 'Secret123') yield # cleanup tasks.kinit_admin(self.master) self.master.run_command(['ipa', 'user-del', self.testuser]) def test_login_wrong_password(self, user_creation_deletion): """Test ipa user login with wrong password When ipa user login to machine using wrong password, it should log proper message related: https://github.com/SSSD/sssd/issues/5139 """ # try to login with wrong password sssd_version = tasks.get_sssd_version(self.master) if (sssd_version < tasks.parse_version('2.3.0')): pytest.xfail('Fix is part of sssd 2.3.0 and is' ' available from fedora32 onwards') # start to look at logs a bit before "now" # https://pagure.io/freeipa/issue/8432 since = time.strftime( '%Y-%m-%d %H:%M:%S', (datetime.now() - timedelta(seconds=10)).timetuple() ) password = 'WrongPassword' tasks.run_ssh_cmd( to_host=self.master.external_hostname, username=self.testuser, auth_method="password", password=password, expect_auth_failure=True ) expected_msg = ( f"pam_sss(sshd:auth): received for user {self.testuser}: 7" " (Authentication failure)" ) def test_cb(stdout): # check if proper message logged return expected_msg in stdout # sshd don't flush its logs to syslog immediately cmd = ["journalctl", "-u", "sshd", f"--since={since}"] tasks.run_repeatedly(self.master, command=cmd, test=test_cb) def get_dirsrv_id(self): serverid = realm_to_serverid(self.master.domain.realm) return ("dirsrv@%s.service" % serverid) def test_pkispawn_log_is_present(self): """ This testcase checks if pkispawn logged properly. It is a candidate from being moved out of test_commands. """ result = self.master.run_command( ["ls", "/var/log/pki/"] ) pkispawnlogfile = None for file in result.stdout_text.splitlines(): if file.startswith("pki-ca-spawn"): pkispawnlogfile = file break assert pkispawnlogfile is not None pkispawnlogfile = os.path.sep.join(("/var/log/pki", pkispawnlogfile)) pkispawnlog = self.master.get_file_contents( pkispawnlogfile, encoding='utf-8' ) # Totally arbitrary. pkispawn debug logs tend to be > 10KiB. assert len(pkispawnlog) > 1024 assert "DEBUG" in pkispawnlog assert "INFO" in pkispawnlog def test_reset_password_unlock(self): """ Test that when a user is also unlocked when their password is administratively reset. """ user = 'tuser' original_passwd = 'Secret123' new_passwd = 'newPasswd123' bad_passwd = 'foo' tasks.kinit_admin(self.master) tasks.user_add(self.master, user, password=original_passwd) tasks.kinit_user( self.master, user, '{0}\n{1}\n{1}\n'.format(original_passwd, new_passwd) ) # Lock out the user on master for _i in range(0, 7): tasks.kinit_user(self.master, user, bad_passwd, raiseonerr=False) tasks.kinit_admin(self.replicas[0]) # Administrative reset on a different server self.replicas[0].run_command( ['ipa', 'passwd', user], stdin_text='{0}\n{0}\n'.format(original_passwd) ) # Wait for the password update to be replicated from replicas[0] # to other servers ldap = self.replicas[0].ldap_connect() tasks.wait_for_replication(ldap) # The user can log in again tasks.kinit_user( self.master, user, '{0}\n{1}\n{1}\n'.format(original_passwd, new_passwd) ) def test_certupdate_no_schema(self): """Test that certupdate without existing API schema. With no existing credentials the API schema download would cause the whole command to fail. """ tasks.kdestroy_all(self.master) self.master.run_command( ["rm", "-rf", "/root/.cache/ipa/servers", "/root/.cache/ipa/schema"] ) # It first has to retrieve schema then can run self.master.run_command(["ipa-certupdate"]) # Run it again for good measure self.master.run_command(["ipa-certupdate"]) def test_proxycommand_invalid_shell(self): """Test that ssh works with a user with an invalid shell. Specifically for this use-case: # getent passwd test test:x:1001:1001::/home/test:/sbin/nologin # sudo -u user ssh -v root@ipa.example.test ruser is our restricted user tuser1 is a regular user we ssh to remotely as """ password = 'Secret123' restricted_user = 'ruser' regular_user = 'tuser1' tasks.kinit_admin(self.master) tasks.user_add(self.master, restricted_user, extra_args=["--shell", "/sbin/nologin"], password=password) tasks.user_add(self.master, regular_user, password=password) user_kinit = "{password}\n{password}\n{password}\n".format( password=password) self.master.run_command([ 'kinit', regular_user], stdin_text=user_kinit) self.master.run_command([ 'kinit', restricted_user], stdin_text=user_kinit) tasks.kdestroy_all(self.clients[0]) # ssh as a restricted user to a user with a valid shell should # work self.clients[0].run_command( ['sudo', '-u', restricted_user, 'sshpass', '-p', password, 'ssh', '-v', '-o', 'StrictHostKeyChecking=no', 'tuser1@%s' % self.master.hostname, 'cat /etc/hosts'], ) # Some versions of nologin do not support the -c option. # ssh will still fail in a Match properly since it will return # non-zero but we don't get the account failure message. nologin = self.clients[0].run_command( ['nologin', '-c', '/bin/true',], raiseonerr=False ) # ssh as a restricted user to a restricted user should fail result = self.clients[0].run_command( ['sudo', '-u', restricted_user, 'sshpass', '-p', password, 'ssh', '-v', '-o', 'StrictHostKeyChecking=no', 'ruser@%s' % self.master.hostname, 'cat /etc/hosts'], raiseonerr=False ) assert result.returncode == 1 if 'invalid option' not in nologin.stderr_text: assert 'This account is currently not available' in \ result.stdout_text def test_ipa_getkeytab_server(self): """ Exercise the ipa-getkeytab server options This relies on the behavior that without a TGT ipa-getkeytab will quit and not do much of anything. A bogus keytab and principal are passed in to satisfy the minimum requirements. """ tasks.kdestroy_all(self.master) # Pass in a server name to use result = self.master.run_command( [ paths.IPA_GETKEYTAB, "-k", "/tmp/keytab", "-p", "foo", "-s", self.master.hostname, "-v", ], raiseonerr=False).stderr_text assert 'Using provided server %s' % self.master.hostname in result # Don't pass in a name, should use /etc/ipa/default.conf result = self.master.run_command( [ paths.IPA_GETKEYTAB, "-k", "/tmp/keytab", "-p", "foo", "-v", ], raiseonerr=False).stderr_text assert ( 'Using server from config %s' % self.master.hostname in result ) # Use DNS SRV lookup result = self.master.run_command( [ paths.IPA_GETKEYTAB, "-k", "/tmp/keytab", "-p", "foo", "-s", "_srv_", "-v", ], raiseonerr=False).stderr_text assert 'Discovered server %s' % self.master.hostname in result def test_ipa_context_manager(self): """Exercise ipalib.api context manager and KRB5_CLIENT_KTNAME auth The example_cli.py script uses the context manager to connect and disconnect the global ipalib.api object. The test also checks whether KRB5_CLIENT_KTNAME env var automatically acquires a TGT. """ host = self.clients[0] tasks.kdestroy_all(host) here = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(here, "example_cli.py")) as f: contents = f.read() # upload script and run with Python executable script = "/tmp/example_cli.py" host.put_file_contents(script, contents) # Important: this test is date-sensitive and may fail if executed # around Feb 28 or Feb 29 on a leap year. # The previous tests are playing with the date by jumping in the # future and back to the (expected) current date but calling # date -s +15Years and then date -s -15Years doesn't # bring the date back to the original value if called around Feb 29. # As a consequence, client and server are not synchronized any more # and client API authentication may fail with the following error: # ipalib.errors.KerberosError: # No valid Negotiate header in server response # If you see this failure, just ignore and relaunch on March 1. result = host.run_command([sys.executable, script]) # script prints admin account admin_princ = f"admin@{host.domain.realm}" assert admin_princ in result.stdout_text # verify that auto-login did use correct principal host_princ = f"host/{host.hostname}@{host.domain.realm}" result = host.run_command([paths.KLIST]) assert host_princ in result.stdout_text def test_delete_last_enabled_admin(self): """ The admin user may be disabled. Don't allow all other members of admins to be removed if the admin user is disabled which would leave the install with no usable admins users """ user = 'adminuser2' passwd = 'Secret123' tasks.create_active_user(self.master, user, passwd) tasks.kinit_admin(self.master) self.master.run_command(['ipa', 'group-add-member', 'admins', '--users', user]) tasks.kinit_user(self.master, user, passwd) self.master.run_command(['ipa', 'user-disable', 'admin']) result = self.master.run_command( ['ipa', 'user-del', user], raiseonerr=False ) self.master.run_command(['ipa', 'user-enable', 'admin']) tasks.kdestroy_all(self.master) assert result.returncode == 1 assert 'cannot be deleted or disabled' in result.stderr_text def test_ipa_cacert_manage_prune(self): """Test for ipa-cacert-manage prune""" certfile = os.path.join(self.master.config.test_dir, 'cert.pem') self.master.put_file_contents(certfile, isrgrootx1) result = self.master.run_command( [paths.IPA_CACERT_MANAGE, 'install', certfile]) certs_before_prune = self.master.run_command( [paths.IPA_CACERT_MANAGE, 'list'], raiseonerr=False ).stdout_text assert isrgrootx1_nick in certs_before_prune # Jump in time to make sure the cert is expired self.master.run_command(['date', '-s', '+15Years']) result = self.master.run_command( [paths.IPA_CACERT_MANAGE, 'prune'], raiseonerr=False ).stdout_text self.master.run_command(['date', '-s', '-15Years']) assert isrgrootx1_nick in result class TestIPACommandWithoutReplica(IntegrationTest): """ Execute tests with scenarios having only single IPA server and no replica """ @classmethod def install(cls, mh): tasks.install_master(cls.master, setup_dns=True) def test_client_doesnot_throw_responsenotready_error(self): """ This testcase checks that ipa command doesn't throw http.client.ResponseNotReady error when current users session is deleted from the cache """ user = 'ipauser1' orig_pwd = 'Password123' tasks.kinit_admin(self.master) tasks.user_add(self.master, user, password=orig_pwd) # kinit as admin on ipa-server and run ipa command tasks.kinit_admin(self.master, raiseonerr=False) self.master.run_command(['ipa', 'user-show', "ipauser1"]) # Delete the current user session cache on IPA server self.master.run_command( "rm -fv /run/ipa/ccaches/admin@{}-*".format( self.master.domain.realm ) ) # Run the command again after cache is removed self.master.run_command(['ipa', 'user-show', 'ipauser1']) def test_basesearch_compat_tree(self): """Test ldapsearch against compat tree is working This to ensure that ldapsearch with base scope is not failing. related: https://bugzilla.redhat.com/show_bug.cgi?id=1958909 """ version = self.master.run_command( ["rpm", "-qa", "--qf", "%{VERSION}", "slapi-nis"] ) if tasks.get_platform(self.master) == "fedora" and parse_version( version.stdout_text) <= parse_version("0.56.7"): pytest.skip("Test requires slapi-nis with fix on fedora") tasks.kinit_admin(self.master) base_dn = str(self.master.domain.basedn) base = "cn=admins,cn=groups,cn=compat,{basedn}".format(basedn=base_dn) tasks.ldapsearch_dm(self.master, base, ldap_args=[], scope='sub') tasks.ldapsearch_dm(self.master, base, ldap_args=[], scope='base') def test_sid_generation(self): """ Test SID generation Check that new users are created with a SID and PAC data is added in their Kerberos tickets. """ user = "pacuser" passwd = "Secret123" try: # Create a nonadmin user tasks.create_active_user( self.master, user, passwd, first=user, last=user, krb5_trace=True) # Check SID is present in the new entry base_dn = str(self.master.domain.basedn) result = tasks.ldapsearch_dm( self.master, 'uid={user},cn=users,cn=accounts,{base_dn}'.format( user=user, base_dn=base_dn), ['ipantsecurityidentifier'], scope='base' ) assert 'ipantsecurityidentifier' in result.stdout_text # Defaults: host/... principal for service # keytab in /etc/krb5.keytab self.master.run_command(["kinit", '-k']) result = self.master.run_command( [os.path.join(paths.LIBEXEC_IPA_DIR, "ipa-print-pac"), "ticket", user], stdin_text=(passwd + '\n') ) assert "PAC_DATA" in result.stdout_text finally: tasks.kinit_admin(self.master) self.master.run_command(['ipa', 'user-del', user]) @pytest.fixture def cleanupgroups(self): """Fixture to remove any groups added as part of the tests. It isn't necessary to remove all groupss created. Ignore all errors. """ yield for group in ["testgroup1", "testgroup2", "testgroup3"]: try: self.master.run_command(['ipa', 'group-del', group]) except Exception: pass def test_sequence_processing_ipaexternalgroup(self, cleanupgroups): """Test for sequence processing failures Issues have been found for group_add sequence processing with server context. This test checks that groups have correct userclass when external is set to true or false with group-add. related: https://pagure.io/freeipa/issue/9349 """ user_code_script = textwrap.dedent(""" from ipalib import api, errors api.bootstrap_with_global_options(context='server') api.finalize() api.Backend.ldap2.connect() api.Command["group_add"]("testgroup1", external=True) api.Command["group_add"]("testgroup2", external=False) result1 = api.Command["group_show"]("testgroup1", all=True)["result"] # noqa: E501 result2 = api.Command["group_show"]("testgroup2", all=True)["result"] # noqa: E501 print("'testgroup2' userclass: %s" % repr(result2["objectclass"])) """) self.master.put_file_contents("/tmp/reproducer1_code.py", user_code_script) result = self.master.run_command(['python3', '/tmp/reproducer1_code.py']) assert "ipaexternalgroup" not in result.stdout_text def test_sequence_processing_nonposix_group(self, cleanupgroups): """Test for sequence processing failures Issues have been found for group_add sequence processing with server context after creating a nonposix group. This test checks that all following group_add calls to add posix groups calls are not failing with missing attribute. related: https://pagure.io/freeipa/issue/9349 """ user_code_script2 = textwrap.dedent(""" from ipalib import api, errors api.bootstrap_with_global_options(context='server') api.finalize() api.Backend.ldap2.connect() api.Command["group_add"]("testgroup1", nonposix=False) try: api.Command["group_add"]("testgroup2", nonposix=True) except Exception as e: print("testgroup2: %s" % e) try: api.Command["group_add"]("testgroup3", external=True) except Exception as e: print("testgroup3: %s" % e) """) self.master.put_file_contents("/tmp/reproducer2_code.py", user_code_script2) result = self.master.run_command(['python3', '/tmp/reproducer2_code.py']) assert "missing attribute" not in result.stdout_text def test_sidgen_task_continue_on_error(self): """Verify that SIDgen task continue even if it fails to assign sid scenario: - add a user with no uid (it will be auto-assigned inside the range) - add a user with uid 2000 - add a user with no uid (it will be auto-assigned inside the range) - edit the first and 3rd users, remove the objectclass ipaNTUserAttrs and the attribute ipaNTSecurityIdentifier - run the sidgen task - verify that user1 and user3 have a ipaNTSecurityIdentifier - verify that old error message is not seen in dirsrv error log - verify that new error message is seen in dirsrv error log related: https://pagure.io/freeipa/issue/9618 """ test_user1 = 'test_user1' test_user2 = 'test_user2' test_user2000 = 'test_user2000' base_dn = str(self.master.domain.basedn) old_err_msg = 'Cannot add SID to existing entry' new_err_msg = r'Finished with [0-9]+ failures, please check the log' tasks.kinit_admin(self.master) tasks.user_add(self.master, test_user1) self.master.run_command( ['ipa', 'user-add', test_user2000, '--first', 'test', '--last', 'user', '--uid', '2000'] ) tasks.user_add(self.master, test_user2) for user in (test_user1, test_user2): entry_ldif = textwrap.dedent(""" dn: uid={user},cn=users,cn=accounts,{base_dn} changetype: modify delete: ipaNTSecurityIdentifier - delete: objectclass objectclass: ipaNTUserAttrs """).format( user=user, base_dn=base_dn) tasks.ldapmodify_dm(self.master, entry_ldif) # run sidgen task self.master.run_command( ['ipa', 'config-mod', '--add-sids', '--enable-sid'] ) # ensure that sidgen have added the attr removed above for user in (test_user1, test_user2): result = tasks.ldapsearch_dm( self.master, 'uid={user},cn=users,cn=accounts,{base_dn}'.format( user=user, base_dn=base_dn), ['ipaNTSecurityIdentifier'] ) assert 'ipaNTSecurityIdentifier' in result.stdout_text dashed_domain = self.master.domain.realm.replace(".", '-') dirsrv_error_log = self.master.get_file_contents( paths.SLAPD_INSTANCE_ERROR_LOG_TEMPLATE % (dashed_domain), encoding='utf-8' ) assert old_err_msg not in dirsrv_error_log assert re.search(new_err_msg, dirsrv_error_log) class TestIPAautomount(IntegrationTest): @classmethod def install(cls, mh): tasks.install_master(cls.master, setup_dns=True) def test_tofiles_orphan_keys(self): """ Validate automountlocation-tofiles output automount in LDAP is difficult to keep straight so a client-side map generator was created. """ tasks.kinit_admin(self.master) self.master.run_command( [ 'ipa', 'automountmap-add', 'default', 'auto.test' ] ) self.master.run_command( [ 'ipa', 'automountkey-add', 'default', 'auto.test', '--key', '/test', '--info', 'nfs.example.com:/exports/test' ] ) self.master.run_command( [ 'ipa', 'automountkey-add', 'default', 'auto.test', '--key', '/test2', '--info', 'nfs.example.com:/exports/test2' ] ) result = self.master.run_command( [ 'ipa', 'automountlocation-tofiles', 'default' ] ).stdout_text assert '/test' in result assert '/test2' in result
71,293
Python
.py
1,592
33.672111
94
0.598765
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,570
test_user_permissions.py
freeipa_freeipa/ipatests/test_integration/test_user_permissions.py
# # Copyright (C) 2018 FreeIPA Contributors see COPYING for license # from __future__ import absolute_import import pytest from ipaplatform.osinfo import osinfo from ipaplatform.paths import paths from ipaplatform.tasks import tasks as platformtasks from ipatests.test_integration.base import IntegrationTest from ipatests.pytest_ipa.integration import tasks class TestUserPermissions(IntegrationTest): topology = 'star' altadmin = "altadmin" @classmethod def install(cls, mh): super(TestUserPermissions, cls).install(mh) tasks.kinit_admin(cls.master) # Create a new user altadmin password_confirmation = "%s\n%s\n" % (cls.master.config.admin_password, cls.master.config.admin_password) cls.master.run_command(['ipa', 'user-add', cls.altadmin, '--first', cls.altadmin, '--last', cls.altadmin, '--password'], stdin_text=password_confirmation) # Add altadmin to the group cn=admins cls.master.run_command(['ipa', 'group-add-member', 'admins', '--users', cls.altadmin]) # kinit as altadmin to initialize the password altadmin_kinit = "%s\n%s\n%s\n" % (cls.master.config.admin_password, cls.master.config.admin_password, cls.master.config.admin_password) cls.master.run_command(['kinit', cls.altadmin], stdin_text=altadmin_kinit) cls.master.run_command(['kdestroy', '-A']) def test_delete_preserve_as_alternate_admin(self): """ Test that a user member of admins group can call delete --preserve. This is a test case for issue 7342 """ # kinit admin tasks.kinit_admin(self.master) # Create a new user 'testuser' with a password testuser = 'testuser' password = 'Secret123' testuser_password_confirmation = "%s\n%s\n" % (password, password) self.master.run_command(['ipa', 'user-add', testuser, '--first', testuser, '--last', testuser, '--password'], stdin_text=testuser_password_confirmation) try: # kinit as altadmin self.master.run_command( ['kinit', self.altadmin], stdin_text=self.master.config.admin_password ) # call ipa user-del --preserve self.master.run_command(['ipa', 'user-del', '--preserve', testuser] ) finally: self.master.run_command(['ipa', 'user-del', testuser]) @pytest.mark.skipif( not platformtasks.is_selinux_enabled(), reason="Test needs SELinux enabled") @pytest.mark.xfail( osinfo.id == 'fedora' and osinfo.version_number <= (28,), reason='sssd ticket 3819', strict=True) def test_selinux_user_optimized(self): """ Check that SELinux login context is set on first login for the user, even if the user is not mapped to a specific SELinux user. Related ticket https://pagure.io/SSSD/sssd/issue/3819. """ # Scenario: add an IPA user with non-default home dir, login through # ssh as this user and check that there is a SELinux user mapping # for the user with `semanage login -l`. test_user = 'testuser_selinux' password = 'Secret123' tasks.kinit_admin(self.master) tasks.create_active_user( self.master, test_user, password=password, extra_args=['--homedir', '/root/{}'.format(test_user)] ) tasks.run_ssh_cmd( to_host=self.master.external_hostname, username=test_user, auth_method="password", password=password ) # check if user listed in output cmd = self.master.run_command(['semanage', 'login', '-l']) assert test_user in cmd.stdout_text # call ipa user-del tasks.kinit_admin(self.master) self.master.run_command(['ipa', 'user-del', test_user]) def test_stageuser_show_as_alternate_admin(self): """ Test that a user member of admins group can call stageuser-show and read the 'Kerberos Keys available' information. This is a test case for issue 7342 """ # kinit admin tasks.kinit_admin(self.master) # Create a new stage user 'stageuser' with a password stageuser = 'stageuser' password = 'Secret123' stageuser_password_confirmation = "%s\n%s\n" % (password, password) self.master.run_command(['ipa', 'stageuser-add', stageuser, '--first', stageuser, '--last', stageuser, '--password'], stdin_text=stageuser_password_confirmation) # kinit as altadmin self.master.run_command(['kinit', self.altadmin], stdin_text=self.master.config.admin_password) # call ipa stageuser-show # the field Kerberos Keys available must contain True result = self.master.run_command(['ipa', 'stageuser-show', stageuser]) assert 'Kerberos keys available: True' in result.stdout_text def test_user_add_withradius(self): """ Test that a user with User Administrator role can call ipa user-add --radius myradius to create a user with an assigned Radius Proxy Server. This is a test case for issue 7570 """ # kinit admin tasks.kinit_admin(self.master) # Create a radius proxy server radiusproxy = 'myradius' secret = 'Secret123' radius_secret_confirmation = "%s\n%s\n" % (secret, secret) self.master.run_command( ['ipa', 'radiusproxy-add', radiusproxy, '--server', 'radius.example.com', '--secret'], stdin_text=radius_secret_confirmation) # Create a user with 'User Administrator' role altuser = 'specialuser' password = 'SpecialUser123' password_confirmation = "%s\n%s\n" % (password, password) self.master.run_command( ['ipa', 'user-add', altuser, '--first', altuser, '--last', altuser, '--password'], stdin_text=password_confirmation) self.master.run_command( ['ipa', 'role-add-member', "User Administrator", '--user', altuser]) # kinit as altuser to initialize the password altuser_kinit = "%s\n%s\n%s\n" % (password, password, password) self.master.run_command(['kinit', altuser], stdin_text=altuser_kinit) # call ipa user-add with --radius=... # this call requires read access to radius proxy servers self.master.run_command( ['ipa', 'user-add', '--first', 'test', '--last', 'test', '--user-auth-type', 'radius', '--radius-username', 'testradius', 'testradius', '--radius', radiusproxy]) def test_delete_group_by_user_administrator(self): """ Test that a user with sufficient privileges can delete group This is a Automation for issue 6884 """ # Create a new testadmin user with a password testadmin = 'tuser' password = 'Secret123' testgroup = 'gtest' try: tasks.create_active_user(self.master, testadmin, password) # Add testadmin user to role "User Administrator" tasks.kinit_admin(self.master) self.master.run_command(['ipa', 'role-add-member', '--users', testadmin, 'User Administrator']) tasks.kdestroy_all(self.master) # Create a test group tasks.kinit_as_user(self.master, testadmin, password) self.master.run_command(['ipa', 'group-add', testgroup]) # Call ipa-group-del to check if user can delete group self.master.run_command(['ipa', 'group-del', testgroup]) finally: # Cleanup tasks.kinit_admin(self.master) self.master.run_command(['ipa', 'user-del', testadmin]) self.master.run_command(['ipa', 'group-del', testgroup, '--continue']) def test_search_hbacrule_nonadminuser(self): """ Test that non admin user can search hbac rule. Related : https://pagure.io/freeipa/issue/5130 """ user = 'hbacuser' password = 'Secret123' hrule = 'rule1' try: tasks.create_active_user(self.master, user, password) tasks.kinit_admin(self.master) self.master.run_command(["ipa", "hbacrule-add", hrule]) tasks.kdestroy_all(self.master) tasks.kinit_as_user(self.master, user, password) rule = "Rule name: {0}".format(hrule) result = self.master.run_command(["ipa", "hbacrule-find", hrule]) assert rule in result.stdout_text result2 = self.master.run_command(["ipa", "hbacrule-find"]) assert rule in result2.stdout_text finally: # Cleanup tasks.kinit_admin(self.master) self.master.run_command(['ipa', 'user-del', user]) self.master.run_command(["ipa", "hbacrule-del", hrule]) class TestInstallClientNoAdmin(IntegrationTest): num_clients = 1 def test_installclient_as_user_admin(self): """ipa-client-install should not use hardcoded admin for principal In ipaclient-install.log it should use the username that was entered earlier in the install process at the prompt. Related to : https://pagure.io/freeipa/issue/5406 """ client = self.clients[0] tasks.install_master(self.master) tasks.kinit_admin(self.master) username = 'testuser1' password = 'userSecretPassword123' password_confirmation = "%s\n%s\n" % (password, password) self.master.run_command(['ipa', 'user-add', username, '--first', username, '--last', username, '--password'], stdin_text=password_confirmation) role_add = ['ipa', 'role-add', 'useradmin'] self.master.run_command(role_add) self.master.run_command(['ipa', 'privilege-add', 'Add Hosts']) self.master.run_command(['ipa', 'privilege-add-permission', '--permissions', 'System: Add Hosts', 'Add Hosts']) self.master.run_command(['ipa', 'privilege-add-permission', '--permissions', 'System: Manage Host Keytab', 'Add Hosts']) self.master.run_command(['ipa', 'role-add-privilege', 'useradmin', '--privileges', 'Host Enrollment']) self.master.run_command(['ipa', 'role-add-privilege', 'useradmin', '--privileges', 'Add Hosts']) role_member_add = ['ipa', 'role-add-member', 'useradmin', '--users={}'.format(username)] self.master.run_command(role_member_add) user_kinit = "%s\n%s\n%s\n" % (password, password, password) self.master.run_command(['kinit', username], stdin_text=user_kinit) tasks.install_client( self.master, client, extra_args=['--request-cert'], user=username, password=password ) msg = "args=['/usr/bin/getent', 'passwd', '%s@%s']" % \ (username, client.domain.name) install_log = client.get_file_contents(paths.IPACLIENT_INSTALL_LOG, encoding='utf-8') assert msg in install_log # Make sure we do not fallback to an old keytab retrieval method anymore msg = "Retrying with pre-4.0 keytab retrieval method..." assert msg not in install_log # check that user is able to request a host cert, too result = tasks.run_certutil(client, ['-L'], paths.IPA_NSSDB_DIR) assert 'Local IPA host' in result.stdout_text result = tasks.run_certutil( client, ['-K', '-f', paths.IPA_NSSDB_PWDFILE_TXT], paths.IPA_NSSDB_DIR ) assert 'Local IPA host' in result.stdout_text
13,032
Python
.py
270
34.840741
80
0.562102
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,571
test_ca_custom_sdn.py
freeipa_freeipa/ipatests/test_integration/test_ca_custom_sdn.py
# # Copyright (C) 2019 FreeIPA Contributors see COPYING for license # import time from ipapython.dn import DN from ipatests.test_integration.base import IntegrationTest from ipatests.pytest_ipa.integration import tasks class TestCACustomSubjectDN(IntegrationTest): """ Test that everything works properly when IPA CA has a custom Subject DN. We will also choose a custom Subject Base, that does not have anything in common with the CA Subject DN. Generating a random DN might be interest, but for now we construct one that regression tests some previously encountered issues: * Comma in RDN value: https://pagure.io/freeipa/issue/7347 * KRA authentication failed for all custom subject DNs: https://pagure.io/freeipa/issue/8084 """ num_replicas = 0 @classmethod def install(cls, mh): """ Successful installation is sufficient to verify https://pagure.io/freeipa/issue/7347. """ tasks.install_master( cls.master, setup_kra=True, extra_args=[ '--subject-base', str(create_custom_subject_base()), '--ca-subject', str(create_custom_ca_subject()), ], ) def test_kra_authn(self): """ vault-add is sufficient to verify https://pagure.io/freeipa/issue/8084. """ self.master.run_command([ 'ipa', 'vault-add', "test1", '--password', 'Secret.123', '--type', 'symmetric', ]) def create_custom_ca_subject(): return DN( ('CN', 'IPA CA'), ('O', 'Corporation {}, Inc.'.format(int(time.time()))), ) def create_custom_subject_base(): return DN(('O', 'Red Hat, Inc.'))
1,755
Python
.py
49
28.612245
76
0.635664
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,572
test_fips.py
freeipa_freeipa/ipatests/test_integration/test_fips.py
# # Copyright (C) 2019 FreeIPA Contributors see COPYING for license # """Smoke tests for FreeIPA installation in (fake) userspace FIPS mode """ import pytest from ipaplatform.osinfo import osinfo from ipapython.dn import DN from ipapython.ipautil import ipa_generate_password, realm_to_suffix from ipatests.pytest_ipa.integration import tasks from ipatests.pytest_ipa.integration import fips from ipatests.test_integration.base import IntegrationTest from .test_dnssec import ( test_zone, dnssec_install_master, dnszone_add_dnssec, wait_until_record_is_signed, ) @pytest.mark.xfail( osinfo.id == 'fedora' and osinfo.version_number > (35,), reason='freeipa ticket 9002', strict=True) class TestInstallFIPS(IntegrationTest): num_replicas = 1 num_clients = 1 fips_mode = True @classmethod def install(cls, mh): super(TestInstallFIPS, cls).install(mh) # sanity check for host in cls.get_all_hosts(): assert host.is_fips_mode assert fips.is_fips_enabled(host) # patch named-pkcs11 crypto policy # see RHBZ#1772111 for host in [cls.master] + cls.replicas: host.run_command( [ "sed", "-i", "-E", "s/RSAMD5;//g", "/etc/crypto-policies/back-ends/bind.config", ] ) # master with CA, KRA, DNS+DNSSEC tasks.install_master(cls.master, setup_dns=True, setup_kra=True) # replica with CA, KRA, DNS tasks.install_replica( cls.master, cls.replicas[0], setup_dns=True, setup_ca=True, setup_kra=True, ) tasks.install_clients([cls.master] + cls.replicas, cls.clients) def test_basic(self): client = self.clients[0] tasks.kinit_admin(client) client.run_command(["ipa", "ping"]) def test_dnssec(self): dnssec_install_master(self.master) # DNSSEC zone dnszone_add_dnssec(self.master, test_zone) assert wait_until_record_is_signed( self.master.ip, test_zone, timeout=100 ), ("Zone %s is not signed (master)" % test_zone) # test replica assert wait_until_record_is_signed( self.replicas[0].ip, test_zone, timeout=200 ), ("DNS zone %s is not signed (replica)" % test_zone) def test_vault_basic(self): vault_name = "testvault" vault_password = ipa_generate_password() vault_data = "SSBsb3ZlIENJIHRlc3RzCg==" # create vault self.master.run_command( [ "ipa", "vault-add", vault_name, "--password", vault_password, "--type", "symmetric", ] ) # archive secret self.master.run_command( [ "ipa", "vault-archive", vault_name, "--password", vault_password, "--data", vault_data, ] ) self.master.run_command( [ "ipa", "vault-retrieve", vault_name, "--password", vault_password, ] ) def test_krb_enctypes(self): realm = self.master.domain.realm suffix = realm_to_suffix(realm) dn = DN(("cn", realm), ("cn", "kerberos")) + suffix args = ["krbSupportedEncSaltTypes", "krbDefaultEncSaltTypes"] for host in [self.master] + self.replicas: result = tasks.ldapsearch_dm(host, str(dn), args, scope="base") assert "camellia" not in result.stdout_text assert "aes256-cts" in result.stdout_text assert "aes128-cts" in result.stdout_text # test that update does not add camellia self.master.run_command(["ipa-server-upgrade"]) result = tasks.ldapsearch_dm(self.master, str(dn), args, scope="base") assert "camellia" not in result.stdout_text
4,197
Python
.py
121
24.561983
78
0.56373
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,573
test_krbtpolicy.py
freeipa_freeipa/ipatests/test_integration/test_krbtpolicy.py
# # Copyright (C) 2019,2020 FreeIPA Contributors see COPYING for license # """ Module provides tests for Kerberos ticket policy options """ from __future__ import absolute_import import pytest import time from datetime import datetime from ipalib.constants import IPAAPI_USER from ipaplatform.paths import paths from ipatests.test_integration.base import IntegrationTest from ipatests.test_integration.test_otp import add_otptoken, del_otptoken from ipatests.pytest_ipa.integration import tasks PASSWORD = "Secret123" USER1 = "testuser1" USER2 = "testuser2" MAXLIFE = 86400 LANG_PKG = ["langpacks-en"] def maxlife_within_policy(input, maxlife, slush=3600): """Given klist output of the TGT verify that it is within policy Ensure that the validity period is somewhere within the absolute maxlife and a slush value, maxlife - slush. Returns True if within policy. Input should be a string like: 11/19/2019 16:37:40 11/20/2019 16:37:39 krbtgt/... slush defaults to 1 * 60 * 60 matching the jitter window. """ data = input.split() start = datetime.strptime(data[0] + ' ' + data[1], '%m/%d/%Y %H:%M:%S') end = datetime.strptime(data[2] + ' ' + data[3], '%m/%d/%Y %H:%M:%S') diff = int((end - start).total_seconds()) return maxlife >= diff >= maxlife - slush @pytest.fixture def reset_to_default_policy(): """Reset default user authentication and user authentication type""" state = dict() def _reset_to_default_policy(host, user=None): state['host'] = host state['user'] = user yield _reset_to_default_policy host = state['host'] user = state['user'] tasks.kinit_admin(host) host.run_command(['ipa', 'krbtpolicy-reset']) if user: host.run_command(['ipa', 'user-mod', user, '--user-auth-type=']) host.run_command(['ipa', 'krbtpolicy-reset', user]) def kinit_check_life(master, user): """Acquire a TGT and check if it's within the lifetime window""" master.run_command(["kinit", user], stdin_text=f"{PASSWORD}\n") result = master.run_command("LANG=en_US.utf-8 klist | grep krbtgt") assert maxlife_within_policy(result.stdout_text, MAXLIFE) is True class TestPWPolicy(IntegrationTest): """Tests password custom and default password policies. """ num_replicas = 0 @classmethod def install(cls, mh): tasks.install_packages(cls.master, LANG_PKG) tasks.install_master(cls.master) tasks.create_active_user(cls.master, USER1, PASSWORD) tasks.create_active_user(cls.master, USER2, PASSWORD) @pytest.fixture(autouse=True, scope="function") def with_admin(self): tasks.kinit_admin(self.master) yield tasks.kdestroy_all(self.master) def test_krbtpolicy_default(self): """Test the default kerberos ticket policy 24-hr tickets""" master = self.master master.run_command(['ipa', 'krbtpolicy-mod', USER1, '--maxlife', str(MAXLIFE)]) tasks.kdestroy_all(master) master.run_command(['kinit', USER1], stdin_text=PASSWORD + '\n') result = master.run_command("LANG=en_US.utf-8 klist | grep krbtgt") assert maxlife_within_policy(result.stdout_text, MAXLIFE) is True def test_krbtpolicy_password_and_hardended(self): """Test a pwd and hardened kerberos ticket policy with 10min tickets""" if self.master.is_fips_mode: pytest.skip("SPAKE pre-auth is not compatible with FIPS mode") master = self.master master.run_command(['ipa', 'user-mod', USER1, '--user-auth-type', 'password', '--user-auth-type', 'hardened']) master.run_command(['ipa', 'config-mod', '--user-auth-type', 'password', '--user-auth-type', 'hardened']) master.run_command(['ipa', 'krbtpolicy-mod', USER1, '--hardened-maxlife', '600']) tasks.kdestroy_all(master) master.run_command(['kinit', USER1], stdin_text=PASSWORD + '\n') result = master.run_command('LANG=en_US.utf-8 klist | grep krbtgt') assert maxlife_within_policy(result.stdout_text, 600, slush=600) is True tasks.kdestroy_all(master) # Verify that the short policy only applies to USER1 master.run_command(['kinit', USER2], stdin_text=PASSWORD + '\n') result = master.run_command('LANG=en_US.utf-8 klist | grep krbtgt') assert maxlife_within_policy(result.stdout_text, MAXLIFE) is True def test_krbtpolicy_hardended(self): """Test a hardened kerberos ticket policy with 30min tickets""" if self.master.is_fips_mode: pytest.skip("SPAKE pre-auth is not compatible with FIPS mode") master = self.master master.run_command(['ipa', 'user-mod', USER1, '--user-auth-type', 'hardened']) master.run_command(['ipa', 'config-mod', '--user-auth-type', 'hardened']) master.run_command(['ipa', 'krbtpolicy-mod', USER1, '--hardened-maxlife', '1800']) tasks.kdestroy_all(master) master.run_command(['kinit', USER1], stdin_text=PASSWORD + '\n') result = master.run_command('LANG=en_US.utf-8 klist | grep krbtgt') assert maxlife_within_policy(result.stdout_text, 1800, slush=1800) is True tasks.kdestroy_all(master) # Verify that the short policy only applies to USER1 master.run_command(['kinit', USER2], stdin_text=PASSWORD + '\n') result = master.run_command('LANG=en_US.utf-8 klist | grep krbtgt') assert maxlife_within_policy(result.stdout_text, MAXLIFE) is True def test_krbtpolicy_password(self): """Test the kerberos ticket policy which issues 20 min tickets""" master = self.master master.run_command(['ipa', 'krbtpolicy-mod', USER2, '--maxlife', '1200']) tasks.kdestroy_all(master) master.run_command(['kinit', USER2], stdin_text=PASSWORD + '\n') result = master.run_command('LANG=en_US.utf-8 klist | grep krbtgt') assert maxlife_within_policy(result.stdout_text, 1200, slush=1200) is True def test_krbtpolicy_reset(self): """Test a hardened kerberos ticket policy reset""" master = self.master master.run_command(['ipa', 'krbtpolicy-reset', USER2]) master.run_command(['kinit', USER2], stdin_text=PASSWORD + '\n') result = master.run_command('LANG=en_US.utf-8 klist | grep krbtgt') assert maxlife_within_policy(result.stdout_text, MAXLIFE) is True def test_krbtpolicy_otp(self, reset_to_default_policy): """Test otp ticket policy""" master = self.master master.run_command(['ipa', 'user-mod', USER1, '--user-auth-type', 'otp']) master.run_command(['ipa', 'config-mod', '--user-auth-type', 'otp']) master.run_command(['ipa', 'krbtpolicy-mod', USER1, '--otp-maxrenew=90', '--otp-maxlife=60']) armor = tasks.create_temp_file(self.master, create_file=False) otpuid, totp = add_otptoken(master, USER1, otptype="totp") otpvalue = totp.generate(int(time.time())).decode("ascii") reset_to_default_policy(master, USER1) try: tasks.kdestroy_all(master) # create armor for FAST master.run_command(['kinit', '-n', '-c', armor]) # expect ticket expire in otp-maxlife=60 seconds master.run_command( ['kinit', '-T', armor, USER1, '-r', '90'], stdin_text='{0}{1}\n'.format(PASSWORD, otpvalue)) master.run_command(['ipa', 'user-find', USER1]) time.sleep(30) # when user kerberos ticket expired but still within renew time, # kinit -R should give user new life master.run_command(['kinit', '-R', USER1]) master.run_command(['ipa', 'user-find', USER1]) time.sleep(60) # when renew time expires, kinit -R should fail result1 = master.run_command(['kinit', '-R', USER1], raiseonerr=False) tasks.assert_error( result1, "kinit: Ticket expired while renewing credentials", 1) master.run_command(['ipa', 'user-find', USER1], ok_returncode=1) finally: del_otptoken(master, otpuid) self.master.run_command(['rm', '-f', armor]) master.run_command(['ipa', 'config-mod', '--user-auth-type=']) def test_krbtpolicy_jitter(self): """Test jitter lifetime with no auth indicators""" kinit_check_life(self.master, USER1) def test_krbtpolicy_jitter_otp(self, reset_to_default_policy): """Test jitter lifetime with OTP""" reset_to_default_policy(self.master, USER1) self.master.run_command(["ipa", "user-mod", USER1, "--user-auth-type", "otp"]) kinit_check_life(self.master, USER1) def test_ccache_sweep_expired(self, reset_to_default_policy): """Test that the ccache sweeper works on expired ccaches - Force wipe all existing ccaches - Set the ticket policy to a short value, 20 seconds. - Do a series of kinit, ipa command, kdestroy to generate ccaches - sleep() for expiration - Run the sweeper - Verify that all expired ccaches are gone """ MAXLIFE = 20 reset_to_default_policy(self.master) # this will reset at END of test tasks.kinit_admin(self.master) self.master.run_command( ['ipa', 'krbtpolicy-mod', '--maxlife', str(MAXLIFE)] ) tasks.kdestroy_all(self.master) self.master.run_command( ['find', paths.IPA_CCACHES, '-type', 'f', '-delete'] ) for _i in range(5): tasks.kinit_admin(self.master) self.master.run_command(['ipa', 'user-show', 'admin']) tasks.kdestroy_all(self.master) result = self.master.run_command( "ls -1 {0} | wc -l".format(paths.IPA_CCACHES) ) assert int(result.stdout_text.strip()) == 5 # let ccache expire time.sleep(MAXLIFE) ccache_sweep_cmd = ["/usr/libexec/ipa/ipa-ccache-sweeper", "-m", "0"] # should be run as ipaapi for GSSProxy self.master.run_command( ["runuser", "-u", IPAAPI_USER, "--"] + ccache_sweep_cmd ) result = self.master.run_command( "ls -1 {0} | wc -l".format(paths.IPA_CCACHES) ) assert int(result.stdout_text.strip()) == 0 def test_ccache_sweep_valid(self): """Test that the ccache sweeper doesn't remove valid ccaches - Force wipe all existing ccaches - Run the sweeper - Verify that all valid ccaches weren't removed Note: assumed that ccache expiration doesn't happen during test """ tasks.kdestroy_all(self.master) self.master.run_command( ["find", paths.IPA_CCACHES, "-type", "f", "-delete"] ) for _i in range(5): tasks.kinit_admin(self.master) self.master.run_command(["ipa", "user-show", "admin"]) tasks.kdestroy_all(self.master) result = self.master.run_command( "ls -1 {0} | wc -l".format(paths.IPA_CCACHES) ) assert int(result.stdout_text.strip()) == 5 ccache_sweep_cmd = ["/usr/libexec/ipa/ipa-ccache-sweeper", "-m", "0"] # should be run as ipaapi for GSSProxy self.master.run_command( ["runuser", "-u", IPAAPI_USER, "--"] + ccache_sweep_cmd ) result = self.master.run_command( "ls -1 {0} | wc -l".format(paths.IPA_CCACHES) ) assert int(result.stdout_text.strip()) == 5
12,444
Python
.py
261
36.885057
79
0.591689
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,574
test_idviews.py
freeipa_freeipa/ipatests/test_integration/test_idviews.py
# # Copyright (C) 2016 FreeIPA Contributors see COPYING for license # from __future__ import absolute_import import os import re import string from SSSDConfig import ServiceAlreadyExists from ipatests.pytest_ipa.integration import tasks from ipatests.test_integration.base import IntegrationTest from ipatests.pytest_ipa.integration.env_config import get_global_config from ipaplatform.paths import paths config = get_global_config() class TestCertsInIDOverrides(IntegrationTest): topology = "line" num_ad_domains = 1 adview = 'Default Trust View' cert_re = re.compile('Certificate: (?P<cert>.*?)\\s+.*') adcert1 = 'MyCert1' adcert2 = 'MyCert2' adcert1_file = adcert1 + '.crt' adcert2_file = adcert2 + '.crt' @classmethod def uninstall(cls, mh): super(TestCertsInIDOverrides, cls).uninstall(mh) cls.master.run_command(['rm', '-rf', cls.reqdir], raiseonerr=False) @classmethod def install(cls, mh): super(TestCertsInIDOverrides, cls).install(mh) cls.ad = config.ad_domains[0].ads[0] cls.ad_domain = cls.ad.domain.name cls.aduser = "testuser@%s" % cls.ad_domain master = cls.master # A setup for test_dbus_user_lookup master.run_command(['dnf', 'install', '-y', 'sssd-dbus'], raiseonerr=False) master.run_command( "sed -i 's/= 7/= 0xFFF0/' %s" % paths.SSSD_CONF, raiseonerr=False) with tasks.remote_sssd_config(master) as sssd_config: try: sssd_config.new_service('ifp') except ServiceAlreadyExists: pass sssd_config.activate_service('ifp') master.run_command(['systemctl', 'restart', 'sssd.service']) # End of setup for test_dbus_user_lookup # AD-related stuff tasks.install_adtrust(master) tasks.sync_time(master, cls.ad) tasks.configure_dns_for_trust(master, cls.ad) tasks.establish_trust_with_ad(cls.master, cls.ad_domain, extra_args=['--range-type', 'ipa-ad-trust']) cls.reqdir = os.path.join(master.config.test_dir, "certs") cls.reqfile1 = os.path.join(cls.reqdir, "test1.csr") cls.reqfile2 = os.path.join(cls.reqdir, "test2.csr") cls.pwname = os.path.join(cls.reqdir, "pwd") # Create a NSS database folder master.run_command(['mkdir', cls.reqdir], raiseonerr=False) # Create an empty password file master.run_command(["touch", cls.pwname], raiseonerr=False) # Initialize NSS database tasks.run_certutil(master, ["-N", "-f", cls.pwname], cls.reqdir) # Now generate self-signed certs for a windows user stdin_text = string.digits+string.ascii_letters[2:] + '\n' tasks.run_certutil(master, ['-S', '-s', "cn=%s,dc=ad,dc=test" % cls.adcert1, '-n', cls.adcert1, '-x', '-t', 'CT,C,C', '-v', '120', '-m', '1234'], cls.reqdir, stdin=stdin_text) tasks.run_certutil(master, ['-S', '-s', "cn=%s,dc=ad,dc=test" % cls.adcert2, '-n', cls.adcert2, '-x', '-t', 'CT,C,C', '-v', '120', '-m', '1234'], cls.reqdir, stdin=stdin_text) # Export the previously generated cert res = tasks.run_certutil(master, ['-L', '-n', cls.adcert1, '-a'], cls.reqdir) master.put_file_contents( os.path.join(master.config.test_dir, cls.adcert1_file), res.stdout_text) res = tasks.run_certutil(master, ['-L', '-n', cls.adcert2, '-a'], cls.reqdir) master.put_file_contents( os.path.join(master.config.test_dir, cls.adcert2_file), res.stdout_text) cls.cert1_base64 = cls.master.run_command( "openssl x509 -outform der -in %s | base64 -w 0" % cls.adcert1_file ).stdout_text cls.cert2_base64 = cls.master.run_command( "openssl x509 -outform der -in %s | base64 -w 0" % cls.adcert2_file ).stdout_text cls.cert1_pem = cls.master.run_command( "openssl x509 -in %s -outform pem" % cls.adcert1_file ).stdout_text cls.cert2_pem = cls.master.run_command( "openssl x509 -in %s -outform pem" % cls.adcert2_file ).stdout_text def test_certs_in_idoverrides_ad_users(self): """ http://www.freeipa.org/page/V4/Certs_in_ID_overrides/Test_Plan #Test_case:_Manipulate_certificate_in_ID_override_entry """ master = self.master master.run_command(['ipa', 'idoverrideuser-add', self.adview, self.aduser]) master.run_command(['ipa', 'idoverrideuser-add-cert', self.adview, self.aduser, "--certificate=%s" % self.cert1_base64]) master.run_command(['ipa', 'idoverrideuser-add-cert', self.adview, self.aduser, "--certificate=%s" % self.cert2_base64]) result = master.run_command(['ipa', 'idoverrideuser-show', self.adview, self.aduser]) assert(self.cert1_base64 in result.stdout_text and self.cert2_base64 in result.stdout_text), ( "idoverrideuser-show does not show all user certificates") master.run_command(['ipa', 'idoverrideuser-remove-cert', self.adview, self.aduser, "--certificate=%s" % self.cert2_base64]) def test_dbus_user_lookup(self): """ http://www.freeipa.org/page/V4/Certs_in_ID_overrides/Test_Plan #Test_case:_User_lookup_by_certificate """ master = self.master userpath_re = re.compile('.*object path "(.*?)".*') result0 = master.run_command([ 'dbus-send', '--system', '--print-reply', '--dest=org.freedesktop.sssd.infopipe', '/org/freedesktop/sssd/infopipe/Users', 'org.freedesktop.sssd.infopipe.Users.FindByCertificate', "string:%s" % self.cert1_pem]) assert("object path" in result0.stdout_text), ( "command output did not contain expected" "string:\n\n%s" % result0.stdout_text) userpath = userpath_re.findall(result0.stdout_text)[0] result1 = master.run_command( "dbus-send --system --print-reply" " --dest=org.freedesktop.sssd.infopipe" " %s org.freedesktop.DBus.Properties.Get" " string:\"org.freedesktop.sssd.infopipe.Users.User\"" " string:\"name\"" % userpath, raiseonerr=False) assert(self.aduser in result1.stdout_text) result2 = master.run_command( "dbus-send --system --print-reply" " --dest=org.freedesktop.sssd.infopipe" " %s org.freedesktop.DBus.Properties.GetAll" " string:\"org.freedesktop.sssd.infopipe.Users.User\"" % userpath ) assert('dict entry' in result2.stdout_text) class TestRulesWithServicePrincipals(IntegrationTest): """ https://fedorahosted.org/freeipa/ticket/6146 """ topology = 'star' num_replicas = 0 num_clients = 0 service_certprofile = 'caIPAserviceCert' caacl = 'test_caacl' keytab = "replica.keytab" csr = "my.csr" csr_conf = "replica.cnf" @classmethod def prepare_config(cls): template = """ req_extensions = v3_req distinguished_name = req_distinguished_name [req_distinguished_name] commonName = %s [ v3_req ] # Extensions to add to a certificate request basicConstraints = CA:FALSE keyUsage = nonRepudiation, digitalSignature, keyEncipherment subjectAltName = @alt_names [alt_names] DNS.1 = %s DNS.2 = %s EOF """ contents = template % (cls.replica, cls.replica, cls.master.hostname) cls.master.run_command("cat <<EOF > %s\n%s" % (cls.csr_conf, contents)) @classmethod def install(cls, mh): super(TestRulesWithServicePrincipals, cls).install(mh) master = cls.master tasks.kinit_admin(master) cls.replica = "replica.%s" % master.domain.name master.run_command(['ipa', 'host-add', cls.replica, '--force']) cls.service_name = "svc/%s" % master.hostname cls.replica_service_name = "svc/%s" % cls.replica master.run_command("ipa service-add %s" % cls.service_name) master.run_command("ipa service-add %s --force" % cls.replica_service_name) master.run_command("ipa service-add-host %s --hosts %s" % ( cls.service_name, cls.replica)) master.run_command("ipa caacl-add %s --desc \"test\"" % cls.caacl) master.run_command("ipa caacl-add-host %s --hosts %s" % (cls.caacl, cls.replica)) master.run_command("ipa caacl-add-service %s --services" " svc/`hostname`" % cls.caacl) master.run_command("ipa-getkeytab -p host/%s@%s -k %s" % ( cls.replica, master.domain.realm, cls.keytab)) master.run_command("kinit -kt %s host/%s" % (cls.keytab, cls.replica)) # Prepare a CSR cls.prepare_config() stdin_text = "qwerty\nqwerty\n%s\n" % cls.replica master.run_command(['openssl', 'req', '-config', cls.csr_conf, '-new', '-out', cls.csr], stdin_text=stdin_text) def test_rules_with_service_principals(self): result = self.master.run_command(['ipa', 'cert-request', self.csr, '--principal', "svc/%s@%s" % ( self.replica, self.master.domain.realm), '--profile-id', self.service_certprofile], raiseonerr=False) assert(result.returncode == 0), ( 'Failed to add a cert to custom certprofile') class TestIDViews(IntegrationTest): topology = 'star' num_replicas = 0 num_clients = 1 user1 = 'testuser1' user1_uid = 10001 user1_gid = 10001 user1_uid_override = 5001 user1_gid_override = 6001 user2 = 'testuser2' user2_uid = 10002 user2_gid = 10002 group1 = 'testgroup1' group1_gid = 11001 group1_gid_override = 7001 idview = 'testview' @classmethod def install(cls, mh): super(TestIDViews, cls).install(mh) master = cls.master client = cls.clients[0] tasks.kinit_admin(master) tasks.user_add( master, cls.user1, first='Test1', extra_args=[ '--uid', str(cls.user1_uid), '--gidnumber', str(cls.user1_gid), ] ) tasks.user_add( master, cls.user2, first='Test2', extra_args=[ '--uid', str(cls.user2_uid), '--gidnumber', str(cls.user2_gid), ] ) tasks.group_add( master, cls.group1, extra_args=['--gid', str(cls.group1_gid)] ) master.run_command(['ipa', 'idview-add', cls.idview]) # add overrides for user1 and its default user group master.run_command([ 'ipa', 'idoverrideuser-add', cls.idview, cls.user1, '--uid', str(cls.user1_uid_override), '--gid', str(cls.user1_gid_override), '--homedir', '/special-home/{}'.format(cls.user1), '--shell', '/bin/special' ]) master.run_command([ 'ipa', 'idoverridegroup-add', cls.idview, cls.group1, '--gid', str(cls.group1_gid_override), ]) # ID view overrides don't work on IPA masters master.run_command([ 'ipa', 'idview-apply', cls.idview, '--hosts', client.hostname ]) # finally restart SSSD to materialize idviews client.run_command(['systemctl', 'restart', 'sssd.service']) def test_useroverride(self): result = self.clients[0].run_command(['id', self.user1]) assert 'uid={}'.format(self.user1_uid_override) in result.stdout_text assert 'gid={}'.format(self.user1_gid_override) in result.stdout_text result = self.clients[0].run_command( ['getent', 'passwd', str(self.user1_uid_override)] ) expected = '{}:*:{}:{}'.format( self.user1, self.user1_uid_override, self.user1_gid_override ) assert expected in result.stdout_text result = self.master.run_command(['id', self.user1]) assert 'uid={}'.format(self.user1_uid) in result.stdout_text assert 'gid={}'.format(self.user1_gid) in result.stdout_text def test_useroverride_original_uid(self): # It's still possible to request the user with its original UID. In # this case the getent command returns the user with override uid. result = self.clients[0].run_command( ['getent', 'passwd', str(self.user1_uid)] ) expected = '{}:*:{}:{}'.format( self.user1, self.user1_uid_override, self.user1_gid_override ) assert expected in result.stdout_text def test_anchor_username(self): result = self.master.run_command([ 'ipa', 'idoverrideuser-find', self.idview, '--anchor', self.user1 ]) expected = "Anchor to override: {}".format(self.user1) assert expected in result.stdout_text def test_groupoverride(self): result = self.clients[0].run_command(['getent', 'group', self.group1]) assert ':{}:'.format(self.group1_gid_override) in result.stdout_text result = self.master.run_command(['getent', 'group', self.group1]) assert ':{}:'.format(self.group1_gid) in result.stdout_text def test_groupoverride_system_objects(self): # group override for user group should fail result = self.master.run_command( ['ipa', 'idoverridegroup-add', self.idview, self.user1, '--gid', str(self.user1_gid_override)], raiseonerr=False ) assert result.returncode == 1 assert "cannot be overridden" in result.stderr_text def test_anchor_groupname(self): result = self.master.run_command([ 'ipa', 'idoverridegroup-find', self.idview, '--anchor', self.group1 ]) expected = "Anchor to override: {}".format(self.group1) assert expected in result.stdout_text
14,968
Python
.py
329
34.191489
79
0.574004
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,575
test_legacy_clients.py
freeipa_freeipa/ipatests/test_integration/test_legacy_clients.py
# Authors: # Tomas Babej <tbabej@redhat.com> # # Copyright (C) 2013 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # FIXME: Pylint errors # pylint: disable=no-member from __future__ import absolute_import import os import re import pytest from ipaplatform.constants import constants as platformconstants from ipaplatform.paths import paths from ipatests.pytest_ipa.integration import tasks # importing test_trust under different name to avoid nose executing the test # base class imported from this module from ipatests.test_integration import test_trust as trust_tests class BaseTestLegacyClient: """ Tests legacy client support. """ advice_id = None backup_files = ['/etc/sysconfig/authconfig', '/etc/pam.d', '/etc/openldap/cacerts', '/etc/openldap/ldap.conf', '/etc/nsswitch.conf', paths.SSSD_CONF] homedir_template = "/home/{domain}/{username}" default_shell = platformconstants.DEFAULT_SHELL required_extra_roles = () optional_extra_roles = () # Actual test classes need to override these attributes to set the expected # values on the UID and GID results, since this varies with the usage of the # POSIX and non-POSIX ID ranges testuser_uid_regex = None testuser_gid_regex = None subdomain_testuser_uid_regex = None subdomain_testuser_gid_regex = None treedomain_testuser_uid_regex = None treedomain_testuser_gid_regex = None # To allow custom validation dependent on the trust type posix_trust = False def test_apply_advice(self): # Obtain the advice from the server tasks.kinit_admin(self.master) result = self.master.run_command(['ipa-advise', self.advice_id]) advice = result.stdout_text # Apply the advice on the legacy client advice_path = os.path.join(self.legacy_client.config.test_dir, 'advice.sh') self.legacy_client.put_file_contents(advice_path, advice) result = self.legacy_client.run_command(['bash', '-x', '-e', advice_path]) # Restart SSHD to load new PAM configuration self.legacy_client.run_command([paths.SBIN_SERVICE, 'sshd', 'restart']) def clear_sssd_caches(self): tasks.clear_sssd_cache(self.master) tasks.clear_sssd_cache(self.legacy_client) def test_getent_ipa_user(self): self.clear_sssd_caches() result = self.legacy_client.run_command(['getent', 'passwd', 'admin']) admin_regex = r"admin:\*:(\d+):(\d+):"\ r"Administrator:/home/admin:{}".format( platformconstants.DEFAULT_ADMIN_SHELL, ) assert re.search(admin_regex, result.stdout_text) def test_getent_ipa_group(self): self.clear_sssd_caches() result = self.legacy_client.run_command(['getent', 'group', 'admins']) admin_group_regex = r"admins:\*:(\d+):admin" assert re.search(admin_group_regex, result.stdout_text) def test_id_ipa_user(self): self.clear_sssd_caches() result = self.legacy_client.run_command(['id', 'admin']) uid_regex = r"uid=(\d+)\(admin\)" gid_regex = r"gid=(\d+)\(admins\)" groups_regex = r"groups=(\d+)\(admins\)" assert re.search(uid_regex, result.stdout_text) assert re.search(gid_regex, result.stdout_text) assert re.search(groups_regex, result.stdout_text) def test_getent_ad_user(self): self.clear_sssd_caches() testuser = 'testuser@%s' % self.ad.domain.name result = self.legacy_client.run_command(['getent', 'passwd', testuser]) testuser_regex = r"testuser@%s:\*:%s:%s:"\ r"Test User:%s:%s"\ % (re.escape(self.ad.domain.name), self.testuser_uid_regex, self.testuser_gid_regex, self.homedir_template.format( username='testuser', domain=re.escape(self.ad.domain.name)), self.default_shell, ) assert re.search(testuser_regex, result.stdout_text) def test_getent_ad_group(self): self.clear_sssd_caches() testgroup = 'testgroup@%s' % self.ad.domain.name result = self.legacy_client.run_command(['getent', 'group', testgroup]) testgroup_regex = r"%s:\*:%s:" % (testgroup, self.testuser_gid_regex) assert re.search(testgroup_regex, result.stdout_text) def test_id_ad_user(self): self.clear_sssd_caches() testuser = 'testuser@%s' % self.ad.domain.name testgroup = 'testgroup@%s' % self.ad.domain.name result = self.legacy_client.run_command(['id', testuser]) # Only for POSIX trust testing does the testuser belong to the # testgroup group_name = r'\(%s\)' % testgroup if self.posix_trust else '' uid_regex = r"uid=%s\(%s\)" % (self.testuser_uid_regex, testuser) gid_regex = "gid=%s%s" % (self.testuser_gid_regex, group_name) groups_regex = "groups=%s%s" % (self.testuser_gid_regex, group_name) assert re.search(uid_regex, result.stdout_text) assert re.search(gid_regex, result.stdout_text) assert re.search(groups_regex, result.stdout_text) def test_login_ipa_user(self): if not self.master.transport.file_exists('/usr/bin/sshpass'): pytest.skip('Package sshpass not available on %s' % self.master.hostname) result = self.master.run_command( 'sshpass -p %s ' 'ssh ' '-o StrictHostKeyChecking=no ' '-l admin ' '%s ' '"echo test"' % (self.legacy_client.config.admin_password, self.legacy_client.hostname)) assert "test" in result.stdout_text def test_login_ad_user(self): if not self.master.transport.file_exists('/usr/bin/sshpass'): pytest.skip('Package sshpass not available on %s' % self.master.hostname) testuser = 'testuser@%s' % self.ad.domain.name result = self.master.run_command( 'sshpass -p Secret123 ' 'ssh ' '-o StrictHostKeyChecking=no ' '-l %s ' '%s ' '"echo test"' % (testuser, self.legacy_client.hostname)) assert "test" in result.stdout_text def test_login_disabled_ipa_user(self): if not self.master.transport.file_exists('/usr/bin/sshpass'): pytest.skip('Package sshpass not available on %s' % self.master.hostname) self.clear_sssd_caches() result = self.master.run_command( 'sshpass -p %s ' 'ssh ' '-o StrictHostKeyChecking=no ' '-l disabledipauser ' '%s ' '"echo test"' % (self.legacy_client.config.admin_password, self.legacy_client.external_hostname), raiseonerr=False) assert result.returncode != 0 def test_login_disabled_ad_user(self): if not self.master.transport.file_exists('/usr/bin/sshpass'): pytest.skip('Package sshpass not available on %s' % self.master.hostname) testuser = 'disabledaduser@%s' % self.ad.domain.name result = self.master.run_command( 'sshpass -p Secret123 ' 'ssh ' '-o StrictHostKeyChecking=no ' '-l %s ' '%s ' '"echo test"' % (testuser, self.legacy_client.external_hostname), raiseonerr=False) assert result.returncode != 0 def test_getent_subdomain_ad_user(self): if not self.ad_subdomain: pytest.skip('AD for the subdomain is not available.') self.clear_sssd_caches() testuser = 'subdomaintestuser@%s' % self.ad_subdomain result = self.legacy_client.run_command(['getent', 'passwd', testuser]) testuser_regex = r"subdomaintestuser@%s:\*:%s:%s:"\ r"Subdomaintest User:%s:"\ r"%s"\ % (re.escape(self.ad_subdomain), self.subdomain_testuser_uid_regex, self.subdomain_testuser_gid_regex, self.homedir_template.format( username='subdomaintestuser', domain=re.escape(self.ad_subdomain)), self.default_shell, ) assert re.search(testuser_regex, result.stdout_text) def test_getent_subdomain_ad_group(self): if not self.ad_subdomain: pytest.skip('AD for the subdomain is not available.') self.clear_sssd_caches() testgroup = 'subdomaintestgroup@%s' % self.ad_subdomain result = self.legacy_client.run_command(['getent', 'group', testgroup]) testgroup_stdout = r"%s:\*:%s:" % (testgroup, self.subdomain_testuser_gid_regex) assert re.search(testgroup_stdout, result.stdout_text) def test_id_subdomain_ad_user(self): if not self.ad_subdomain: pytest.skip('AD for the subdomain is not available.') self.clear_sssd_caches() testuser = 'subdomaintestuser@%s' % self.ad_subdomain testgroup = 'subdomaintestgroup@%s' % self.ad_subdomain result = self.legacy_client.run_command(['id', testuser]) # Only for POSIX trust testing does the testuser belong to the # testgroup group_name = r'\(%s\)' % testgroup if self.posix_trust else '' uid_regex = r"uid=%s\(%s\)" % (self.subdomain_testuser_uid_regex, testuser) gid_regex = "gid=%s%s" % (self.subdomain_testuser_gid_regex, group_name) groups_regex = "groups=%s%s" % (self.subdomain_testuser_gid_regex, group_name) assert re.search(uid_regex, result.stdout_text) assert re.search(gid_regex, result.stdout_text) assert re.search(groups_regex, result.stdout_text) def test_login_subdomain_ad_user(self): if not self.ad_subdomain: pytest.skip('AD for the subdomain is not available.') if not self.master.transport.file_exists('/usr/bin/sshpass'): pytest.skip('Package sshpass not available on %s' % self.master.hostname) testuser = 'subdomaintestuser@%s' % self.ad_subdomain result = self.master.run_command( 'sshpass -p Secret123 ' 'ssh ' '-o StrictHostKeyChecking=no ' '-l %s ' '%s ' '"echo test"' % (testuser, self.legacy_client.external_hostname)) assert "test" in result.stdout_text def test_login_disabled_subdomain_ad_user(self): if not self.ad_subdomain: pytest.skip('AD for the subdomain is not available.') if not self.master.transport.file_exists('/usr/bin/sshpass'): pytest.skip('Package sshpass not available on %s' % self.master.hostname) testuser = 'subdomaindisabledaduser@%s' % self.ad_subdomain result = self.master.run_command( 'sshpass -p Secret123 ' 'ssh ' '-o StrictHostKeyChecking=no ' '-l %s ' '%s ' '"echo test"' % (testuser, self.legacy_client.external_hostname), raiseonerr=False) assert result.returncode != 0 def test_getent_treedomain_ad_user(self): if not self.ad_treedomain: pytest.skip('AD tree root domain is not available.') self.clear_sssd_caches() testuser = 'treetestuser@{0}'.format(self.ad_treedomain) result = self.legacy_client.run_command(['getent', 'passwd', testuser]) testuser_regex = (r"treetestuser@{0}:\*:{1}:{2}:TreeTest User:" r"/home/{0}/treetestuser:{3}".format( re.escape(self.ad_treedomain), self.treedomain_testuser_uid_regex, self.treedomain_testuser_gid_regex, self.default_shell, )) assert re.search(testuser_regex, result.stdout_text) def test_getent_treedomain_ad_group(self): if not self.ad_treedomain: pytest.skip('AD tree root domain is not available') self.clear_sssd_caches() testgroup = 'treetestgroup@{0}'.format(self.ad_treedomain) result = self.legacy_client.run_command(['getent', 'group', testgroup]) testgroup_stdout = r"{0}:\*:{1}:".format( testgroup, self.treedomain_testuser_gid_regex) assert re.search(testgroup_stdout, result.stdout_text) def test_id_treedomain_ad_user(self): if not self.ad_treedomain: pytest.skip('AD tree root domain is not available') self.clear_sssd_caches() testuser = 'treetestuser@{0}'.format(self.ad_treedomain) testgroup = 'treetestgroup@{0}'.format(self.ad_treedomain) result = self.legacy_client.run_command(['id', testuser]) # Only for POSIX trust testing does the testuser belong to the # testgroup group_name = r'\({}\)'.format(testgroup) if self.posix_trust else '' uid_regex = r"uid={0}\({1}\)".format( self.treedomain_testuser_uid_regex, testuser) gid_regex = "gid={0}{1}".format( self.treedomain_testuser_gid_regex, group_name) group_regex = "groups={0}{1}".format( self.treedomain_testuser_gid_regex, group_name) assert re.search(uid_regex, result.stdout_text) assert re.search(gid_regex, result.stdout_text) assert re.search(group_regex, result.stdout_text) def test_login_treedomain_ad_user(self): if not self.ad_treedomain: pytest.skip('AD tree root domain is not available.') if not self.master.transport.file_exists('/usr/bin/sshpass'): pytest.skip( 'Package sshpass not available on {}'.format( self.master.hostname) ) result = self.master.run_command( 'sshpass -p {0} ssh -o StrictHostKeyChecking=no ' '-l admin {1} "echo test"'.format( self.legacy_client.config.admin_password, self.legacy_client.external_hostname)) assert "test" in result.stdout_text @classmethod def install(cls, mh): super(BaseTestLegacyClient, cls).install(mh) tasks.kinit_admin(cls.master) password_confirmation = ( cls.master.config.admin_password + '\n' + cls.master.config.admin_password ) cls.master.run_command(['ipa', 'user-add', 'disabledipauser', '--first', 'disabled', '--last', 'ipauser', '--password'], stdin_text=password_confirmation) cls.master.run_command(['ipa', 'user-disable', 'disabledipauser']) cls.ad = cls.ad_domains[0].ads[0] cls.legacy_client = cls.host_by_role(cls.required_extra_roles[0]) # Determine whether the subdomain AD is available try: child_ad = cls.host_by_role(cls.optional_extra_roles[0]) cls.ad_subdomain = '.'.join( child_ad.hostname.split('.')[1:]) except LookupError: cls.ad_subdomain = None # Determine whether the tree domain AD is available try: cls.tree_ad = cls.host_by_role(cls.optional_extra_roles[1]) cls.ad_treedomain = '.'.join( cls.tree_ad.hostname.split('.')[1:]) except LookupError: cls.ad_treedomain = None tasks.apply_common_fixes(cls.legacy_client) for f in cls.backup_files: tasks.backup_file(cls.legacy_client, f) @classmethod def uninstall(cls, mh): cls.master.run_command(['ipa', 'user-del', 'disabledipauser'], raiseonerr=False) # Remove information about trust from AD, if domain was defined if hasattr(cls, 'ad_domain'): tasks.remove_trust_info_from_ad(cls.master, cls.ad_domain, cls.ad_domain.hostname) # Also unapply fixes on the legacy client, if defined if hasattr(cls, 'legacy_client'): tasks.unapply_fixes(cls.legacy_client) super(BaseTestLegacyClient, cls).uninstall(mh) # Base classes with attributes that are specific for each legacy client test class BaseTestLegacySSSDBefore19RedHat: advice_id = 'config-redhat-sssd-before-1-9' required_extra_roles = ['legacy_client_sssd_redhat'] optional_extra_roles = ['ad_subdomain', 'ad_treedomain'] class BaseTestLegacyNssPamLdapdRedHat: advice_id = 'config-redhat-nss-pam-ldapd' required_extra_roles = ['legacy_client_nss_pam_ldapd_redhat'] optional_extra_roles = ['ad_subdomain', 'ad_treedomain'] def clear_sssd_caches(self): tasks.clear_sssd_cache(self.master) class BaseTestLegacyNssLdapRedHat: advice_id = 'config-redhat-nss-ldap' required_extra_roles = ['legacy_client_nss_ldap_redhat'] optional_extra_roles = ['ad_subdomain', 'ad_treedomain'] def clear_sssd_caches(self): tasks.clear_sssd_cache(self.master) # Base classes that join legacy client specific steps with steps required # to setup IPA with trust (both with and without using the POSIX attributes) class BaseTestLegacyClientPosix(trust_tests.BaseTestTrust, BaseTestLegacyClient): testuser_uid_regex = '10042' testuser_gid_regex = '10047' subdomain_testuser_uid_regex = '10142' subdomain_testuser_gid_regex = '10147' treedomain_testuser_uid_regex = '10242' treedomain_testuser_gid_regex = '10247' posix_trust = True def test_remove_trust_with_posix_attributes(self): pass class BaseTestLegacyClientNonPosix(trust_tests.BaseTestTrust, BaseTestLegacyClient): testuser_uid_regex = r'(?!10042)(\d+)' testuser_gid_regex = r'(?!10047)(\d+)' subdomain_testuser_uid_regex = r'(?!10142)(\d+)' subdomain_testuser_gid_regex = r'(?!10147)(\d+)' treedomain_testuser_uid_regex = r'(?!10242)(\d+)' treedomain_testuser_gid_regex = r'(?!10247)(\d+)' def test_remove_nonposix_trust(self): pass class BaseTestSSSDMixin: def test_apply_advice(self): super(BaseTestSSSDMixin, self).test_apply_advice() tasks.setup_sssd_conf(self.legacy_client) # Tests definitions themselves. Beauty. Just pure beauty. class TestLegacySSSDBefore19RedHatNonPosix(BaseTestSSSDMixin, BaseTestLegacySSSDBefore19RedHat, BaseTestLegacyClientNonPosix): pass class TestLegacyNssPamLdapdRedHatNonPosix(BaseTestLegacyNssPamLdapdRedHat, BaseTestLegacyClientNonPosix): pass class TestLegacyNssLdapRedHatNonPosix(BaseTestLegacyNssLdapRedHat, BaseTestLegacyClientNonPosix): pass class TestLegacySSSDBefore19RedHatPosix(BaseTestSSSDMixin, BaseTestLegacySSSDBefore19RedHat, BaseTestLegacyClientPosix): pass class TestLegacyNssPamLdapdRedHatPosix(BaseTestLegacyNssPamLdapdRedHat, BaseTestLegacyClientPosix): pass class TestLegacyNssLdapRedHatPosix(BaseTestLegacyNssLdapRedHat, BaseTestLegacyClientPosix): pass
21,026
Python
.py
434
36.490783
80
0.601047
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,576
test_idp.py
freeipa_freeipa/ipatests/test_integration/test_idp.py
from __future__ import absolute_import import time import pytest import re import textwrap from ipaplatform.paths import paths from ipatests.test_integration.base import IntegrationTest from ipatests.pytest_ipa.integration import tasks, create_keycloak user_code_script = textwrap.dedent(""" from selenium import webdriver from datetime import datetime from pkg_resources import parse_version from selenium.webdriver.firefox.options import Options from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC options = Options() if parse_version(webdriver.__version__) < parse_version('4.10.0'): options.headless = True driver = webdriver.Firefox(executable_path="/opt/geckodriver", options=options) else: options.add_argument('-headless') service = webdriver.FirefoxService( executable_path="/opt/geckodriver") driver = webdriver.Firefox(options=options, service=service) verification_uri = "{uri}" driver.get(verification_uri) try: element = WebDriverWait(driver, 90).until( EC.presence_of_element_located((By.ID, "username"))) driver.find_element(By.ID, "username").send_keys("testuser1") driver.find_element(By.ID, "password").send_keys("{passwd}") driver.find_element(By.ID, "kc-login").click() element = WebDriverWait(driver, 90).until( EC.presence_of_element_located((By.ID, "kc-login"))) driver.find_element(By.ID, "kc-login").click() assert "Device Login Successful" in driver.page_source finally: now = datetime.now().strftime("%M-%S") driver.get_screenshot_as_file("/var/log/httpd/screenshot-%s.png" % now) driver.quit() """) def add_user_code(host, verification_uri): contents = user_code_script.format(uri=verification_uri, passwd=host.config.admin_password) try: host.put_file_contents("/tmp/add_user_code.py", contents) tasks.run_repeatedly( host, ['python3', '/tmp/add_user_code.py']) finally: host.run_command(["rm", "-f", "/tmp/add_user_code.py"]) def kinit_idp(host, user, keycloak_server): ARMOR = "/tmp/armor" tasks.kdestroy_all(host) # create armor for FAST host.run_command(["kinit", "-n", "-c", ARMOR]) cmd = ["kinit", "-T", ARMOR, user] with host.spawn_expect(cmd, default_timeout=100) as e: e.expect('Authenticate at (.+) and press ENTER.:') prompt = e.get_last_output() uri = re.search(r'Authenticate at (.*?) and press ENTER.:', prompt ).group(1) time.sleep(15) if uri: add_user_code(keycloak_server, uri) e.sendline('\n') e.expect_exit() test_idp = host.run_command(["klist", "-C"]) assert "152" in test_idp.stdout_text class TestIDPKeycloak(IntegrationTest): num_replicas = 2 topology = 'line' @classmethod def install(cls, mh): cls.client = cls.replicas[0] cls.replica = cls.replicas[1] tasks.install_master(cls.master, extra_args=['--no-dnssec-validation']) tasks.install_client(cls.master, cls.replicas[0], extra_args=["--mkhomedir"]) tasks.install_replica(cls.master, cls.replicas[1]) for host in [cls.master, cls.replicas[0], cls.replicas[1]]: content = host.get_file_contents(paths.IPA_DEFAULT_CONF, encoding='utf-8') new_content = content + "\noidc_child_debug_level = 10" host.put_file_contents(paths.IPA_DEFAULT_CONF, new_content) with tasks.remote_sssd_config(cls.master) as sssd_config: sssd_config.edit_domain( cls.master.domain, 'krb5_auth_timeout', 1100) tasks.clear_sssd_cache(cls.master) tasks.clear_sssd_cache(cls.replicas[0]) tasks.kinit_admin(cls.master) cls.master.run_command(["ipa", "config-mod", "--user-auth-type=idp", "--user-auth-type=password"]) xvfb = ("nohup /usr/bin/Xvfb :99 -ac -noreset -screen 0 1400x1200x8 " "</dev/null &>/dev/null &") cls.replicas[0].run_command(xvfb) def test_auth_keycloak_idp(self): """ Test case to check that OAuth 2.0 Device Authorization Grant is working as expected for user configured with external idp. """ create_keycloak.setup_keycloakserver(self.client) time.sleep(60) create_keycloak.setup_keycloak_client(self.client) tasks.kinit_admin(self.master) cmd = ["ipa", "idp-add", "keycloakidp", "--provider=keycloak", "--client-id=ipa_oidc_client", "--org=master", "--base-url={0}:8443/auth".format(self.client.hostname)] self.master.run_command(cmd, stdin_text="{0}\n{0}".format( self.client.config.admin_password)) tasks.user_add(self.master, 'keycloakuser', extra_args=["--user-auth-type=idp", "--idp-user-id=testuser1@ipa.test", "--idp=keycloakidp"] ) list_user = self.master.run_command( ["ipa", "user-find", "--idp-user-id=testuser1@ipa.test"] ) assert "keycloakuser" in list_user.stdout_text list_by_idp = self.master.run_command(["ipa", "user-find", "--idp=keycloakidp"] ) assert "keycloakuser" in list_by_idp.stdout_text list_by_user = self.master.run_command( ["ipa", "user-find", "--idp-user-id=testuser1@ipa.test", "--all"] ) assert "keycloakidp" in list_by_user.stdout_text tasks.clear_sssd_cache(self.master) kinit_idp(self.master, 'keycloakuser', keycloak_server=self.client) @pytest.fixture def hbac_setup_teardown(self): # allow sshd only on given host tasks.kinit_admin(self.master) self.master.run_command(["ipa", "hbacrule-disable", "allow_all"]) self.master.run_command(["ipa", "hbacrule-add", "rule1"]) self.master.run_command(["ipa", "hbacrule-add-user", "rule1", "--users=keycloakuser"] ) self.master.run_command(["ipa", "hbacrule-add-host", "rule1", "--hosts", self.replica.hostname]) self.master.run_command(["ipa", "hbacrule-add-service", "rule1", "--hbacsvcs=sshd"] ) tasks.clear_sssd_cache(self.master) tasks.clear_sssd_cache(self.replica) yield # cleanup tasks.kinit_admin(self.master) self.master.run_command(["ipa", "hbacrule-enable", "allow_all"]) self.master.run_command(["ipa", "hbacrule-del", "rule1"]) def test_auth_hbac(self, hbac_setup_teardown): """ Test case to check that hbacrule is working as expected for user configured with external idp. """ kinit_idp(self.master, 'keycloakuser', keycloak_server=self.client) ssh_cmd = "ssh -q -K -l keycloakuser {0} whoami" valid_ssh = self.master.run_command( ssh_cmd.format(self.replica.hostname)) assert "keycloakuser" in valid_ssh.stdout_text negative_ssh = self.master.run_command( ssh_cmd.format(self.master.hostname), raiseonerr=False ) assert negative_ssh.returncode == 255 def test_auth_sudo_idp(self): """ Test case to check that sudorule is working as expected for user configured with external idp. """ tasks.kdestroy_all(self.master) tasks.kinit_admin(self.master) # rule: keycloakuser are allowed to execute yum on # the client machine as root. cmdlist = [ ["ipa", "sudocmd-add", "/usr/bin/yum"], ["ipa", "sudorule-add", "sudorule"], ['ipa', 'sudorule-add-user', '--users=keycloakuser', 'sudorule'], ['ipa', 'sudorule-add-host', '--hosts', self.client.hostname, 'sudorule'], ['ipa', 'sudorule-add-runasuser', '--users=root', 'sudorule'], ['ipa', 'sudorule-add-allow-command', '--sudocmds=/usr/bin/yum', 'sudorule'], ['ipa', 'sudorule-show', 'sudorule', '--all'], ['ipa', 'sudorule-add-option', 'sudorule', '--sudooption', "!authenticate"] ] for cmd in cmdlist: self.master.run_command(cmd) tasks.clear_sssd_cache(self.master) tasks.clear_sssd_cache(self.client) try: cmd = 'sudo -ll -U keycloakuser' test = self.client.run_command(cmd).stdout_text assert "User keycloakuser may run the following commands" in test assert "/usr/bin/yum" in test kinit_idp(self.client, 'keycloakuser', self.client) test_sudo = 'su -c "sudo yum list yum" keycloakuser' self.client.run_command(test_sudo) list_fail = self.master.run_command(cmd).stdout_text assert "User keycloakuser is not allowed to run sudo" in list_fail finally: tasks.kinit_admin(self.master) self.master.run_command(['ipa', 'sudorule-del', 'sudorule']) self.master.run_command(["ipa", "sudocmd-del", "/usr/bin/yum"]) def test_auth_replica(self): """ Test case to check that OAuth 2.0 Device Authorization is working as expected on replica. """ tasks.clear_sssd_cache(self.master) tasks.clear_sssd_cache(self.replica) tasks.kinit_admin(self.replica) list_user = self.master.run_command( ["ipa", "user-find", "--idp-user-id=testuser1@ipa.test"] ) assert "keycloakuser" in list_user.stdout_text list_by_idp = self.replica.run_command(["ipa", "user-find", "--idp=keycloakidp"] ) assert "keycloakuser" in list_by_idp.stdout_text list_by_user = self.replica.run_command( ["ipa", "user-find", "--idp-user-id=testuser1@ipa.test", "--all"] ) assert "keycloakidp" in list_by_user.stdout_text kinit_idp(self.replica, 'keycloakuser', keycloak_server=self.client) def test_idp_with_services(self): """ Test case to check that services can be configured auth indicator as idp. """ tasks.clear_sssd_cache(self.master) tasks.kinit_admin(self.master) domain = self.master.domain.name.upper() services = [ "DNS/{0}@{1}".format(self.master.hostname, domain), "HTTP/{0}@{1}".format(self.client.hostname, domain), "dogtag/{0}@{1}".format(self.master.hostname, domain), "ipa-dnskeysyncd/{0}@{1}".format(self.master.hostname, domain) ] try: for service in services: test = self.master.run_command(["ipa", "service-mod", service, "--auth-ind=idp"] ) assert "Authentication Indicators: idp" in test.stdout_text finally: for service in services: self.master.run_command(["ipa", "service-mod", service, "--auth-ind="]) def test_idp_backup_restore(self): """ Test case to check that after restore data is retrieved with related idp configuration. """ tasks.kinit_admin(self.master) user = "backupuser" cmd = ["ipa", "idp-add", "testidp", "--provider=keycloak", "--client-id=ipa_oidc_client", "--org=master", "--base-url={0}:8443/auth".format(self.client.hostname)] self.master.run_command(cmd, stdin_text="{0}\n{0}".format( self.client.config.admin_password)) tasks.user_add(self.master, user, extra_args=["--user-auth-type=idp", "--idp-user-id=testuser1@ipa.test", "--idp=testidp"] ) backup_path = tasks.get_backup_dir(self.master) # change data after backup self.master.run_command(['ipa', 'user-del', user]) self.master.run_command(['ipa', 'idp-del', 'testidp']) dirman_password = self.master.config.dirman_password self.master.run_command(['ipa-restore', backup_path], stdin_text=dirman_password + '\nyes') try: list_user = self.master.run_command( ['ipa', 'user-show', 'backupuser', '--all'] ).stdout_text assert "External IdP configuration: testidp" in list_user assert "User authentication types: idp" in list_user assert ("External IdP user identifier: " "testuser1@ipa.test") in list_user list_idp = self.master.run_command(['ipa', 'idp-find', 'testidp']) assert "testidp" in list_idp.stdout_text kinit_idp(self.master, user, self.client) finally: tasks.kdestroy_all(self.master) tasks.kinit_admin(self.master) self.master.run_command(["rm", "-rf", backup_path]) self.master.run_command(["ipa", "idp-del", "testidp"])
13,706
Python
.py
293
35.334471
79
0.582194
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,577
test_http_kdc_proxy.py
freeipa_freeipa/ipatests/test_integration/test_http_kdc_proxy.py
# # Copyright (C) 2016 FreeIPA Contributors see COPYING for license # from __future__ import absolute_import import re from contextlib import contextmanager import pytest from ipatests.pytest_ipa.integration import tasks from ipatests.pytest_ipa.integration.firewall import Firewall from ipatests.test_integration.base import IntegrationTest from ipaplatform.paths import paths class TestHttpKdcProxy(IntegrationTest): topology = "line" num_clients = 1 num_ad_domains = 1 @classmethod def install(cls, mh): super().install(mh) cls.client = cls.clients[0] cls.ad = cls.ads[0] tasks.kinit_admin(cls.master) cls.master.run_command(['ipa', 'pwpolicy-mod', '--minlife=0']) tasks.install_adtrust(cls.master) tasks.configure_dns_for_trust(cls.master, cls.ad) tasks.establish_trust_with_ad(cls.master, cls.ad.domain.name) @classmethod def uninstall(cls, mh): tasks.remove_trust_info_from_ad( cls.master, cls.ad.domain.name, cls.ad.hostname) super().uninstall(mh) @pytest.fixture(autouse=True, scope='function') def cleanup_credentials(self): tasks.kdestroy_all(self.client) tasks.clear_sssd_cache(self.client) @pytest.fixture(scope='class') def users(self, mh): master = mh.master ad = mh.ads[0] users = { 'ipa': { 'name': 'ipa_test_user', 'password': 'SecretIpaTestUser', 'domain': mh.master.domain, 'test_service': 'HTTP/{}@{}' .format(master.hostname, master.domain.realm), }, 'ad': { 'name': 'testuser@{}'.format(ad.domain.realm), 'password': 'Secret123', 'domain': ad.domain, 'test_service': 'HTTP/{}@{}' .format(ad.hostname, ad.domain.realm), } } tasks.kinit_admin(mh.master) tasks.create_active_user( mh.master, users['ipa']['name'], users['ipa']['password']) yield users tasks.kinit_admin(mh.master) mh.master.run_command(['ipa', 'user-del', users['ipa']['name']]) @pytest.fixture() def restrict_network_for_client(self, mh): fw_rules_allow = [ ['OUTPUT', '-p', 'udp', '--dport', '53', '-j', 'ACCEPT'], ['OUTPUT', '-p', 'tcp', '--dport', '80', '-j', 'ACCEPT'], ['OUTPUT', '-p', 'tcp', '--dport', '443', '-j', 'ACCEPT'], ['OUTPUT', '-p', 'tcp', '--sport', '22', '-j', 'ACCEPT']] fw = Firewall(self.client) fw.prepend_passthrough_rules(fw_rules_allow) fw.passthrough_rule(['-P', 'OUTPUT', 'DROP']) yield fw.passthrough_rule(['-P', 'OUTPUT', 'ACCEPT']) fw.remove_passthrough_rules(fw_rules_allow) @pytest.fixture() def client_use_kdcproxy(self, mh): """Configure client for using kdcproxy for IPA and AD domains.""" def replace_regexp_once(pattern, repl, string): res, n = re.subn(pattern, repl, string) assert n == 1 return res krb5conf_backup = tasks.FileBackup(self.client, paths.KRB5_CONF) krb5conf = self.client.get_file_contents( paths.KRB5_CONF, encoding='utf-8') kdc_url = 'https://{}/KdcProxy'.format(self.master.hostname) # configure kdc proxy for IPA realm krb5conf = replace_regexp_once( r' kdc = .+', ' kdc = {}'.format(kdc_url), krb5conf) krb5conf = replace_regexp_once( r'kpasswd_server = .+', 'kpasswd_server = {}'.format(kdc_url), krb5conf) # configure kdc proxy for Windows AD realm ad_realm_config = ''' {realm} = {{ kdc = {kdc_url} kpasswd_server = {kdc_url} }} '''.format(realm=self.ad.domain.realm, kdc_url=kdc_url) krb5conf = replace_regexp_once( r'\[realms\]', '[realms]' + ad_realm_config, krb5conf ) self.client.put_file_contents(paths.KRB5_CONF, krb5conf) self.client.run_command(['systemctl', 'restart', 'sssd.service']) yield krb5conf_backup.restore() self.client.run_command(['systemctl', 'restart', 'sssd.service']) @contextmanager def configure_kdc_proxy_for_ad_trust(self, use_tcp): backup = tasks.FileBackup(self.master, paths.KDCPROXY_CONFIG) with tasks.remote_ini_file(self.master, paths.KDCPROXY_CONFIG) as conf: conf.set('global', 'use_dns', 'true') conf.set('global', 'configs', 'mit') if use_tcp: conf.add_section(self.ad.domain.realm) conf.set(self.ad.domain.realm, 'kerberos', 'kerberos+tcp://{}:88'.format(self.ad.hostname)) conf.set(self.ad.domain.realm, 'kpasswd', 'kpasswd+tcp://{}:464'.format(self.ad.hostname)) try: self.master.run_command(['ipactl', 'restart']) yield finally: backup.restore() self.master.run_command(['ipactl', 'restart']) def check_kerberos_requests(self, user, skip_kpasswd_check=False): # KDC AS request tasks.kinit_as_user(self.client, user['name'], user['password']) # KDC TGS requests self.client.run_command(['kvno', user['test_service']]) # KDC AS requests and kpasswd requests # Changing password on Windows AD can not be done now because # of default password policy mandating that minimal password lifetime # is one day. # Once we switch to dynamically creating test users in Windows AD # and create an utility for modifying Group Policy Objects then # we should update test setup and remove this condition. def set_password(old_pass, new_pass): with self.client.spawn_expect(['kpasswd', user['name']]) as e: e.expect('Password for .+:') e.sendline(old_pass) e.expect_exact('Enter new password:') e.sendline(new_pass) e.expect_exact('Enter it again:') e.sendline(new_pass) e.expect_exit(ignore_remaining_output=True) if not skip_kpasswd_check: test_password = 'Secret123456' set_password(user['password'], test_password) # Restore password: set_password(test_password, user['password']) @pytest.mark.parametrize('user_origin', ['ipa', 'ad']) def test_user_login_on_client_without_firewall(self, users, user_origin): """Basic check for test setup.""" self.check_kerberos_requests(users[user_origin], skip_kpasswd_check=user_origin == 'ad') @pytest.mark.usefixtures('restrict_network_for_client') @pytest.mark.parametrize('user_origin', ['ipa', 'ad']) def test_access_blocked_on_client_without_kdcproxy( self, users, user_origin): """Check for test firewall setup.""" user = users[user_origin] result = tasks.kinit_as_user( self.client, user['name'], user['password'], raiseonerr=False) expected_errors = [ ("Cannot contact any KDC for realm '{}' while getting initial " "credentials".format(user['domain'].realm)), ('Cannot find KDC for realm "{}" while getting initial ' "credentials".format(user['domain'].realm)), ] assert (result.returncode == 1 and any(s in result.stderr_text for s in expected_errors)) @pytest.mark.usefixtures('restrict_network_for_client', 'client_use_kdcproxy') def test_ipa_user_login_on_client_with_kdcproxy(self, users): self.check_kerberos_requests(users['ipa']) @pytest.mark.usefixtures('restrict_network_for_client', 'client_use_kdcproxy') @pytest.mark.parametrize('use_tcp', [True, False]) def test_ad_user_login_on_client_with_kdcproxy(self, users, use_tcp): with self.configure_kdc_proxy_for_ad_trust(use_tcp): self.check_kerberos_requests(users['ad'], skip_kpasswd_check=True) @pytest.fixture() def windows_small_mtu_size(self, mh): new_mtu = 70 def get_iface_name(): result = self.ad.run_command([ 'powershell', '-c', '(Get-NetIPAddress -IPAddress {}).InterfaceAlias'.format( self.ad.ip)]) return result.stdout_text.strip() def get_mtu(iface_name): result = self.ad.run_command([ 'netsh', 'interface', 'ipv4', 'show', 'subinterface', iface_name]) mtu = result.stdout_text.strip().splitlines()[-1].split()[0] return int(mtu) def set_mtu(iface_name, mtu): self.ad.run_command([ 'netsh', 'interface', 'ipv4', 'set', 'subinterface', iface_name, 'mtu={}'.format(mtu)]) iface_name = get_iface_name() original_mtu = get_mtu(iface_name) set_mtu(iface_name, new_mtu) # `netsh` does not report failures with return code so we check # it was successful by inspecting the actual value of MTU assert get_mtu(iface_name) == new_mtu yield set_mtu(iface_name, original_mtu) assert get_mtu(iface_name) == original_mtu @pytest.mark.usefixtures('restrict_network_for_client', 'client_use_kdcproxy', 'windows_small_mtu_size') def test_kdcproxy_handles_small_packets_from_ad(self, users): """Check that kdcproxy handles AD response split to several TCP packets This is a regression test for the bug in python-kdcproxy: https://github.com/latchset/kdcproxy/pull/44 When the reply from AD is split into several TCP packets the kdc proxy software cannot handle it and returns a false error message indicating it cannot contact the KDC server. """ with self.configure_kdc_proxy_for_ad_trust(use_tcp=True): self.check_kerberos_requests(users['ad'], skip_kpasswd_check=True)
10,331
Python
.py
223
35.591928
79
0.59025
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,578
test_crlgen_manage.py
freeipa_freeipa/ipatests/test_integration/test_crlgen_manage.py
# # Copyright (C) 2018 FreeIPA Contributors see COPYING for license # """ Module provides tests for the ipa-crlgen-manage command. """ from __future__ import absolute_import import os from cryptography.hazmat.backends import default_backend from cryptography import x509 from ipaplatform.paths import paths from ipatests.pytest_ipa.integration import tasks from ipatests.test_integration.base import IntegrationTest CRLGEN_STATUS_ENABLED = 'enabled' CRLGEN_STATUS_DISABLED = 'disabled' CRL_FILENAME = os.path.join(paths.PKI_CA_PUBLISH_DIR, 'MasterCRL.bin') def check_crlgen_status(host, rc=0, msg=None, enabled=True, check_crl=False): """Checks that CRLGen is configured as expected :param host: The host where ;ipa-crlgen-manage status' command is run :param rc: the expected result code :param msg: the expected msg in stderr :param enabled: the expected status :param check_crl: if True we expect a Master.bin CRL file If enabled: ipa-crlgen-manage status must return 'CRL generation: enabled' and print the last CRL update date and number if crl_present=True. If disabled: ipa-crlgen-manage status must return 'CRL generation: disabled' """ result = host.run_command(['ipa-crlgen-manage', 'status'], raiseonerr=False) assert result.returncode == rc if msg: assert msg in result.stderr_text if rc == 0: status = CRLGEN_STATUS_ENABLED if enabled else CRLGEN_STATUS_DISABLED assert 'CRL generation: {}'.format(status) in result.stdout_text if check_crl and enabled: # We expect CRL generation to be enabled and need to check for # MasterCRL.bin crl_content = host.get_file_contents(CRL_FILENAME) crl = x509.load_der_x509_crl(crl_content, default_backend()) last_update_msg = 'Last CRL update: {}'.format(crl.last_update) assert last_update_msg in result.stdout_text for ext in crl.extensions: if ext.oid == x509.oid.ExtensionOID.CRL_NUMBER: number_msg = "Last CRL Number: {}".format( ext.value.crl_number) assert number_msg in result.stdout_text try: value = get_CS_cfg_value(host, 'ca.certStatusUpdateInterval') except IOError: return if enabled: assert value is None else: assert value == '0' def check_crlgen_enable(host, rc=0, msg=None, check_crl=False): """Check ipa-crlgen-manage enable command Launch ipa-crlgen-manage command and check the result code and output """ result = host.run_command(['ipa-crlgen-manage', 'enable'], raiseonerr=False) assert result.returncode == rc if msg: assert msg in result.stderr_text if rc == 0: # check ipa-crlgen-manage status is consistent check_crlgen_status(host, enabled=True, check_crl=check_crl) def check_crlgen_disable(host, rc=0, msg=None): """Check ipa-crlgen-manage disable command Launch ipa-crlgen-manage command and check the result code and output """ result = host.run_command(['ipa-crlgen-manage', 'disable'], raiseonerr=False) assert result.returncode == rc if msg: assert msg in result.stderr_text if rc == 0: # check ipa-crlgen-manage status is consistent check_crlgen_status(host, enabled=False) def break_crlgen_with_rewriterule(host): """Create an inconsistent configuration on a CRL master In the file /etc/httpd/conf.d/ipa-pki-proxy.conf, add a RewriteRule that should be present only on non-CRL master""" content = host.get_file_contents(paths.HTTPD_IPA_PKI_PROXY_CONF, encoding='utf-8') new_content = content + "\nRewriteRule ^/ipa/crl/MasterCRL.bin " \ "https://{}/ca/ee/ca/getCRL?op=getCRL&crlIssuingPoint=MasterCRL " \ "[L,R=301,NC]".format(host.hostname) host.put_file_contents(paths.HTTPD_IPA_PKI_PROXY_CONF, new_content) check_crlgen_status(host, rc=1, msg="Configuration is inconsistent") def break_crlgen_with_CS_cfg(host): """Create an inconsistent configuration on a CRL master Add a enableCRLUpdates=false directive that should be present only on non-CRL master""" content = host.get_file_contents(paths.CA_CS_CFG_PATH, encoding='utf-8') new_lines = [] for line in content.split('\n'): if line.startswith('ca.crl.MasterCRL.enableCRLCache'): new_lines.append("ca.crl.MasterCRL.enableCRLCache=false") else: new_lines.append(line) host.put_file_contents(paths.CA_CS_CFG_PATH, '\n'.join(new_lines)) check_crlgen_status(host, rc=1, msg="Configuration is inconsistent") def get_CS_cfg_value(host, directive): """Retrieve and return the a directive from the CA CS.cfg This returns None if the directives is not found. """ content = host.get_file_contents(paths.CA_CS_CFG_PATH, encoding='utf-8') value = None for line in content.split('\n'): l = line.lower() if l.startswith(directive.lower()): value = line.split('=', 1)[1] return value class TestCRLGenManage(IntegrationTest): """Tests the ipa-crlgen-manage command. ipa-crlgen-manage can be used to enable, disable or check the status of CRL generation. """ num_replicas = 1 @classmethod def install(cls, mh): # Install a master and check CRL status (=enabled) tasks.install_master(cls.master) # We don't check for MasterCRL.bin presence because it may not # be generated right after the install check_crlgen_status(cls.master, enabled=True) def test_master_enable_crlgen_already_enabled(self): """Test ipa-crlgen-manage enable on an already enabled instance""" # We don't check for MasterCRL.bin presence because it may not # be generated right after the install check_crlgen_enable( self.master, rc=0, msg="Nothing to do, CRL generation already enabled") def test_master_disable_crlgen(self): """Test ipa-crlgen-manage disable on an enabled instance""" check_crlgen_disable( self.master, rc=0, msg="make sure to configure CRL generation on another master") def test_master_disable_crlgen_already_disabled(self): """Test ipa-crlgen-manage disable on an enabled instance""" check_crlgen_disable( self.master, rc=0, msg="Nothing to do, CRL generation already disabled") def test_master_enable_crlgen(self): """Test ipa-crlgen-manage enable on a disabled instance""" # This time we check that MasterCRL.bin is present check_crlgen_enable( self.master, rc=0, msg="make sure to have only a single CRL generation master", check_crl=True) def test_crlgen_status_on_replica(self): """Test crlgen status on a replica without CA Install a replica without CA then call ipa-crlgen-manage status. """ tasks.install_replica(self.master, self.replicas[0], setup_ca=False) check_crlgen_status(self.replicas[0], enabled=False) def test_crlgen_disable_on_caless_replica(self): """Test crlgen disable on a replica without CA""" check_crlgen_disable( self.replicas[0], rc=0, msg="Warning: Dogtag CA is not installed on this server") def test_crlgen_enable_on_caless_replica(self): """Test crlgen enable on a replica without CA""" check_crlgen_enable( self.replicas[0], rc=1, msg="Dogtag CA is not installed. Please install a CA first") def test_crlgen_enable_on_ca_replica(self): """Test crlgen enable on a replica with CA Install a CA clone and enable CRLgen""" tasks.install_ca(self.replicas[0]) value = get_CS_cfg_value(self.replicas[0], 'ca.certStatusUpdateInterval') assert value == '0' check_crlgen_enable( self.replicas[0], rc=0, msg="make sure to have only a single CRL generation master", check_crl=True) def test_crlgen_enable_on_broken_master(self): """Test crlgen enable on master with inconsistent config Break the (enabled) master config by setting the rewriterule and call enable""" # Make sure the config is enabled check_crlgen_enable(self.master) # Break the config with RewriteRule break_crlgen_with_rewriterule(self.master) # Call enable to repair check_crlgen_enable( self.master, rc=0, msg="CRL generation is partially enabled, repairing...", check_crl=True) def test_crlgen_disable_on_broken_master(self): """Test crlgen disable on master with inconsistent config Break the (enabled) master config by setting the rewriterule and call disable""" # Make sure the config is enabled check_crlgen_enable(self.master) # Break the config with RewriteRule break_crlgen_with_rewriterule(self.master) # Call disable to repair check_crlgen_disable( self.master, rc=0, msg="CRL generation is partially enabled, repairing...") def test_crlgen_enable_on_broken_replica(self): """Test crlgen enable on replica with inconsistent config Break the (enabled) replica config by setting enableCRLUpdates=false and call enable""" # Make sure the config is enabled check_crlgen_enable(self.replicas[0]) # Break the config with RewriteRule break_crlgen_with_CS_cfg(self.replicas[0]) # Call enable to repair check_crlgen_enable( self.replicas[0], rc=0, msg="CRL generation is partially enabled, repairing...", check_crl=True) def test_crlgen_disable_on_broken_replica(self): """Test crlgen disable on replica with inconsistent config Break the (enabled) replica config by setting enableCRLUpdates=false and call disable""" # Make sure the config is enabled check_crlgen_enable(self.replicas[0]) # Break the config with RewriteRule break_crlgen_with_CS_cfg(self.replicas[0]) # Call disable to repair check_crlgen_disable( self.replicas[0], rc=0, msg="CRL generation is partially enabled, repairing...") def test_uninstall_without_ignore_last_of_role(self): """Test uninstallation of the CRL generation master If --ignore-last-of-role is not provided, uninstall prints a msg and exits on error. """ # Make sure CRL gen is enabled on the master check_crlgen_enable(self.master) # call uninstall without --ignore-last-of-role, should be refused result = self.master.run_command( ['ipa-server-install', '--uninstall', '-U'], raiseonerr=False) assert result.returncode == 1 expected_msg = "Deleting this server will leave your installation " \ "without a CRL generation master" assert expected_msg in result.stdout_text def test_uninstall_with_ignore_last_of_role(self): """Test uninstallation of the CRL generation master When --ignore-last-of-role is provided, uninstall prints a msg but gets executed. """ # Make sure CRL gen is enabled on the master check_crlgen_enable(self.master) # call uninstall with --ignore-last-of-role, should be OK result = self.master.run_command( ['ipa-server-install', '--uninstall', '-U', '--ignore-last-of-role']) expected_msg = "Deleting this server will leave your installation " \ "without a CRL generation master" assert expected_msg in result.stdout_text tasks.run_server_del( self.replicas[0], self.master.hostname, force=True, ignore_topology_disconnect=True, ignore_last_of_role=True) def test_uninstall_last_master_does_not_require_ignore_last_of_role(self): """Test uninstallation of the last master Even if the host is CRL generation master, uninstall must proceed even without --ignore-last-of-role because we are removing the last master. """ # Make sure CRL gen is enabled on the replica check_crlgen_enable(self.replicas[0]) # call uninstall without --ignore-last-of-role, should be OK self.replicas[0].run_command( ['ipa-server-install', '--uninstall', '-U'])
12,950
Python
.py
276
37.807971
78
0.65205
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,579
test_dns_locations.py
freeipa_freeipa/ipatests/test_integration/test_dns_locations.py
# # Copyright (C) 2016 FreeIPA Contributors see COPYING for license # import logging import re import time import pytest import dns.resolver import dns.rrset import dns.rdatatype import dns.rdataclass from ipatests.test_integration.base import IntegrationTest from ipatests.pytest_ipa.integration import tasks from ipapython.dnsutil import DNSName, DNSResolver from ipalib.constants import IPA_CA_RECORD logger = logging.getLogger(__name__) IPA_DEFAULT_MASTER_SRV_REC = ( # srv record name, port (DNSName(u'_ldap._tcp'), 389), (DNSName(u'_kerberos._tcp'), 88), (DNSName(u'_kerberos._udp'), 88), (DNSName(u'_kerberos-master._tcp'), 88), (DNSName(u'_kerberos-master._udp'), 88), (DNSName(u'_kpasswd._tcp'), 464), (DNSName(u'_kpasswd._udp'), 464), ) IPA_DEFAULT_MASTER_URI_REC = ( ( DNSName('_kerberos'), ("krb5srv:m:tcp:{hostname}", "krb5srv:m:udp:{hostname}") ), ( DNSName('_kpasswd'), ("krb5srv:m:tcp:{hostname}", "krb5srv:m:udp:{hostname}") ), ) IPA_DEFAULT_ADTRUST_SRV_REC = ( # srv record name, port (DNSName(u'_ldap._tcp.Default-First-Site-Name._sites.dc._msdcs'), 389), (DNSName(u'_ldap._tcp.dc._msdcs'), 389), (DNSName(u'_kerberos._tcp.Default-First-Site-Name._sites.dc._msdcs'), 88), (DNSName(u'_kerberos._udp.Default-First-Site-Name._sites.dc._msdcs'), 88), (DNSName(u'_kerberos._tcp.dc._msdcs'), 88), (DNSName(u'_kerberos._udp.dc._msdcs'), 88), ) IPA_CA_A_REC = ( (DNSName(str(IPA_CA_RECORD))), ) def resolve_records_from_server(rname, rtype, nameserver): error = None res = DNSResolver() res.nameservers = [nameserver] res.lifetime = 30 logger.info("Query: %s %s, nameserver %s", rname, rtype, nameserver) # lets try to query 3x for _i in range(3): try: ans = res.resolve(rname, rtype) logger.info("Answer: %s", ans.rrset) return ans.rrset except (dns.resolver.NXDOMAIN, dns.resolver.Timeout) as e: error = e time.sleep(10) pytest.fail("Query: {} {}, nameserver {} failed due to {}".format( rname, rtype, nameserver, error)) return None def _gen_expected_srv_rrset(rname, port, servers, ttl=86400): rdata_list = [ "{prio} {weight} {port} {servername}".format( prio=prio, weight=weight, port=port, servername=servername.make_absolute() ) for prio, weight, servername in servers ] return dns.rrset.from_text_list( rname, ttl, dns.rdataclass.IN, dns.rdatatype.SRV, rdata_list ) def _gen_expected_uri_rrset(rname, uri_templates, servers, ttl=86400): rdata_list = [ "{prio} {weight} {uri}".format( prio=prio, weight=weight, uri=uri_template.format(hostname=servername.make_absolute()), ) for uri_template in uri_templates for prio, weight, servername in servers ] return dns.rrset.from_text_list( rname, ttl, dns.rdataclass.IN, dns.rdatatype.URI, rdata_list ) def _gen_expected_a_rrset(rname, servers, ttl=86400): return dns.rrset.from_text_list(rname, ttl, dns.rdataclass.IN, dns.rdatatype.A, servers) def _get_relative_weights(text): """Takes location-show output and returns a list of percentages""" return re.findall(r"\d+.\d%", text) class TestDNSLocations(IntegrationTest): """Simple test if SRV DNS records for IPA locations are generated properly Topology: * 3 servers (replica0 --- master --- replica1) replica0 with no CA, master with ADtrust installed later, replica1 with CA * 2 locations (prague, paris) """ num_replicas = 2 topology = 'star' LOC_PRAGUE = u'prague' LOC_PARIS = u'paris' PRIO_HIGH = 0 PRIO_LOW = 50 WEIGHT = 100 @classmethod def install(cls, mh): cls.domain = DNSName(cls.master.domain.name).make_absolute() tasks.install_master(cls.master, setup_dns=True) tasks.install_replica(cls.master, cls.replicas[0], setup_dns=True, setup_ca=False) tasks.install_replica(cls.master, cls.replicas[1], setup_dns=True, setup_ca=True) for host in (cls.master, cls.replicas[0], cls.replicas[1]): ldap = host.ldap_connect() tasks.wait_for_replication(ldap) # give time to named to retrieve new records time.sleep(20) @classmethod def delete_update_system_records(cls, rnames): filepath = '/tmp/ipa.nsupdate' cls.master.run_command([ 'ipa', 'dns-update-system-records', '--dry-run', '--out', filepath ]) for name in rnames: cls.master.run_command([ 'ipa', 'dnsrecord-del', str(cls.domain), str(name), '--del-all']) time.sleep(15) # allow unauthenticates nsupdate (no need to testing authentication) cls.master.run_command([ 'ipa', 'dnszone-mod', str(cls.domain), '--update-policy=grant * wildcard *;' ], raiseonerr=False) cls.master.run_command(['nsupdate', '-g', filepath]) time.sleep(15) def _test_A_rec_against_server(self, server_ip, domain, expected_servers, rec_list=IPA_CA_A_REC): for rname in rec_list: name_abs = rname.derelativize(domain) expected = _gen_expected_a_rrset(name_abs, expected_servers) query = resolve_records_from_server( name_abs, 'A', server_ip) assert expected == query, ( "Expected and received DNS data do not match on server " "with IP: '{}' for name '{}' (expected:\n{}\ngot:\n{})". format(server_ip, name_abs, expected, query)) def _test_SRV_rec_against_server(self, server_ip, domain, expected_servers, rec_list=IPA_DEFAULT_MASTER_SRV_REC): for rname, port in rec_list: name_abs = rname.derelativize(domain) expected = _gen_expected_srv_rrset( name_abs, port, expected_servers) query = resolve_records_from_server( name_abs, 'SRV', server_ip) assert expected == query, ( "Expected and received DNS data do not match on server " "with IP: '{}' for name '{}' (expected:\n{}\ngot:\n{})". format(server_ip, name_abs, expected, query)) def _test_URI_rec_against_server(self, server_ip, domain, expected_servers, rec_list=IPA_DEFAULT_MASTER_URI_REC): for rname, uri_templates in rec_list: name_abs = rname.derelativize(domain) expected = _gen_expected_uri_rrset( name_abs, uri_templates, expected_servers) query = resolve_records_from_server( name_abs, 'URI', server_ip) assert expected == query, ( "Expected and received DNS data do not match on server " "with IP: '{}' for name '{}' (expected:\n{}\ngot:\n{})". format(server_ip, name_abs, expected, query)) def test_without_locations(self): """Servers are not in locations, this tests if basic system records are generated properly""" expected_servers = ( (self.PRIO_HIGH, self.WEIGHT, DNSName(self.master.hostname)), (self.PRIO_HIGH, self.WEIGHT, DNSName(self.replicas[0].hostname)), (self.PRIO_HIGH, self.WEIGHT, DNSName(self.replicas[1].hostname)), ) for ip in (self.master.ip, self.replicas[0].ip, self.replicas[1].ip): self._test_SRV_rec_against_server(ip, self.domain, expected_servers) self._test_URI_rec_against_server( ip, self.domain, expected_servers ) def test_nsupdate_without_locations(self): """Test nsupdate file generated by dns-update-system-records Remove all records and the use nsupdate to restore state and test if all record are there as expected""" self.delete_update_system_records(rnames=(r[0] for r in IPA_DEFAULT_MASTER_SRV_REC)) self.test_without_locations() def test_one_replica_in_location(self): """Put one replica to location and test if records changed properly """ # create location prague, replica0 --> location prague self.master.run_command([ 'ipa', 'location-add', self.LOC_PRAGUE ]) self.master.run_command([ 'ipa', 'server-mod', self.replicas[0].hostname, '--location', self.LOC_PRAGUE ]) tasks.restart_named(self.replicas[0]) servers_without_loc = ( (self.PRIO_HIGH, self.WEIGHT, DNSName(self.master.hostname)), (self.PRIO_HIGH, self.WEIGHT, DNSName(self.replicas[0].hostname)), (self.PRIO_HIGH, self.WEIGHT, DNSName(self.replicas[1].hostname)), ) domain_without_loc = DNSName(self.master.domain.name).make_absolute() servers_prague_loc = ( (self.PRIO_LOW, self.WEIGHT, DNSName(self.master.hostname)), (self.PRIO_HIGH, self.WEIGHT, DNSName(self.replicas[0].hostname)), (self.PRIO_LOW, self.WEIGHT, DNSName(self.replicas[1].hostname)), ) domain_prague_loc = ( DNSName('{}._locations'.format(self.LOC_PRAGUE)) + DNSName(self.master.domain.name).make_absolute() ) self._test_SRV_rec_against_server( self.replicas[0].ip, domain_prague_loc, servers_prague_loc ) self._test_URI_rec_against_server( self.replicas[0].ip, domain_prague_loc, servers_prague_loc ) for ip in (self.master.ip, self.replicas[1].ip): self._test_SRV_rec_against_server( ip, domain_without_loc, servers_without_loc ) self._test_URI_rec_against_server( ip, domain_without_loc, servers_without_loc ) def test_two_replicas_in_location(self): """Put second replica to location and test if records changed properly """ # create location paris, replica1 --> location prague self.master.run_command(['ipa', 'location-add', self.LOC_PARIS]) self.master.run_command([ 'ipa', 'server-mod', self.replicas[1].hostname, '--location', self.LOC_PARIS]) tasks.restart_named(self.replicas[1]) servers_without_loc = ( (self.PRIO_HIGH, self.WEIGHT, DNSName(self.master.hostname)), (self.PRIO_HIGH, self.WEIGHT, DNSName(self.replicas[0].hostname)), (self.PRIO_HIGH, self.WEIGHT, DNSName(self.replicas[1].hostname)), ) domain_without_loc = DNSName(self.master.domain.name).make_absolute() servers_prague_loc = ( (self.PRIO_LOW, self.WEIGHT, DNSName(self.master.hostname)), (self.PRIO_HIGH, self.WEIGHT, DNSName(self.replicas[0].hostname)), (self.PRIO_LOW, self.WEIGHT, DNSName(self.replicas[1].hostname)), ) domain_prague_loc = ( DNSName('{}._locations'.format(self.LOC_PRAGUE)) + DNSName( self.master.domain.name).make_absolute()) servers_paris_loc = ( (self.PRIO_LOW, self.WEIGHT, DNSName(self.master.hostname)), (self.PRIO_LOW, self.WEIGHT, DNSName(self.replicas[0].hostname)), (self.PRIO_HIGH, self.WEIGHT, DNSName(self.replicas[1].hostname)), ) domain_paris_loc = ( DNSName('{}._locations'.format(self.LOC_PARIS)) + DNSName( self.master.domain.name).make_absolute()) self._test_SRV_rec_against_server( self.replicas[0].ip, domain_prague_loc, servers_prague_loc ) self._test_URI_rec_against_server( self.replicas[0].ip, domain_prague_loc, servers_prague_loc ) self._test_SRV_rec_against_server( self.replicas[1].ip, domain_paris_loc, servers_paris_loc ) self._test_URI_rec_against_server( self.replicas[1].ip, domain_paris_loc, servers_paris_loc ) self._test_SRV_rec_against_server( self.master.ip, domain_without_loc, servers_without_loc ) self._test_URI_rec_against_server( self.master.ip, domain_without_loc, servers_without_loc ) def test_all_servers_in_location(self): """Put master (as second server) to location and test if records changed properly """ # master --> location paris self.master.run_command([ 'ipa', 'server-mod', self.master.hostname, '--location', self.LOC_PARIS]) tasks.restart_named(self.master) servers_prague_loc = ( (self.PRIO_LOW, self.WEIGHT, DNSName(self.master.hostname)), (self.PRIO_HIGH, self.WEIGHT, DNSName(self.replicas[0].hostname)), (self.PRIO_LOW, self.WEIGHT, DNSName(self.replicas[1].hostname)), ) domain_prague_loc = ( DNSName('{}._locations'.format(self.LOC_PRAGUE)) + DNSName( self.master.domain.name).make_absolute()) servers_paris_loc = ( (self.PRIO_HIGH, self.WEIGHT, DNSName(self.master.hostname)), (self.PRIO_LOW, self.WEIGHT, DNSName(self.replicas[0].hostname)), (self.PRIO_HIGH, self.WEIGHT, DNSName(self.replicas[1].hostname)), ) domain_paris_loc = ( DNSName('{}._locations'.format(self.LOC_PARIS)) + DNSName( self.master.domain.name).make_absolute()) self._test_SRV_rec_against_server( self.replicas[0].ip, domain_prague_loc, servers_prague_loc ) self._test_URI_rec_against_server( self.replicas[0].ip, domain_prague_loc, servers_prague_loc ) for ip in (self.replicas[1].ip, self.master.ip): self._test_SRV_rec_against_server( ip, domain_paris_loc, servers_paris_loc ) self._test_URI_rec_against_server( ip, domain_paris_loc, servers_paris_loc ) def test_change_weight(self): """Change weight of master and test if records changed properly """ new_weight = 2000 self.master.run_command([ 'ipa', 'server-mod', self.master.hostname, '--service-weight', str(new_weight) ]) # all servers must be restarted tasks.restart_named(self.master, self.replicas[0], self.replicas[1]) servers_prague_loc = ( (self.PRIO_LOW, new_weight, DNSName(self.master.hostname)), (self.PRIO_HIGH, self.WEIGHT, DNSName(self.replicas[0].hostname)), (self.PRIO_LOW, self.WEIGHT, DNSName(self.replicas[1].hostname)), ) domain_prague_loc = ( DNSName('{}._locations'.format(self.LOC_PRAGUE)) + DNSName( self.master.domain.name).make_absolute()) servers_paris_loc = ( (self.PRIO_HIGH, new_weight, DNSName(self.master.hostname)), (self.PRIO_LOW, self.WEIGHT, DNSName(self.replicas[0].hostname)), (self.PRIO_HIGH, self.WEIGHT, DNSName(self.replicas[1].hostname)), ) domain_paris_loc = ( DNSName('{}._locations'.format(self.LOC_PARIS)) + DNSName( self.master.domain.name).make_absolute()) self._test_SRV_rec_against_server( self.replicas[0].ip, domain_prague_loc, servers_prague_loc ) self._test_URI_rec_against_server( self.replicas[0].ip, domain_prague_loc, servers_prague_loc ) for ip in (self.replicas[1].ip, self.master.ip): self._test_SRV_rec_against_server( ip, domain_paris_loc, servers_paris_loc ) self._test_URI_rec_against_server( ip, domain_paris_loc, servers_paris_loc ) def test_change_weight_relative_zero_0(self): """Change weight of one master and check on relative weight % """ new_weight = 0 # Put all servers into one location self.master.run_command([ 'ipa', 'server-mod', self.replicas[0].hostname, '--location', self.LOC_PARIS]) # Modify one to have a weight of 0 result = self.master.run_command([ 'ipa', 'server-mod', self.master.hostname, '--service-weight', str(new_weight) ]) result = self.master.run_command([ 'ipa', 'location-show', self.LOC_PARIS ]) weights = _get_relative_weights(result.stdout_text) assert weights.count('0.1%') == 1 assert weights.count('50.0%') == 2 # The following three tests are name-sensitive so they run in # a specific order. They use the paris location and depend on # the existing values of the server location and weight to work # properly def test_change_weight_relative_zero_1(self): """Change all weights to zero and ensure no div by zero """ new_weight = 0 # Depends on order of test execution but all masters are now # in LOC_PARIS and self.master has a weight of 0. # Modify all replicas to have a weight of 0 for hostname in (self.replicas[0].hostname, self.replicas[1].hostname): self.master.run_command([ 'ipa', 'server-mod', hostname, '--service-weight', str(new_weight) ]) result = self.master.run_command([ 'ipa', 'location-show', self.LOC_PARIS ]) weights = _get_relative_weights(result.stdout_text) assert weights.count('33.3%') == 3 def test_change_weight_relative_zero_2(self): """Change to mixed weight values and check percentages """ new_weight = 100 # Change master to be primary, replicas secondary self.master.run_command([ 'ipa', 'server-mod', self.master.hostname, '--service-weight', '200' ]) for hostname in (self.replicas[0].hostname, self.replicas[1].hostname): self.master.run_command([ 'ipa', 'server-mod', hostname, '--service-weight', str(new_weight) ]) result = self.master.run_command([ 'ipa', 'location-show', self.LOC_PARIS ]) weights = _get_relative_weights(result.stdout_text) assert weights.count('50.0%') == 1 assert weights.count('25.0%') == 2 def test_restore_locations_and_weight(self): """Restore locations and weight. Not just for test purposes but also for the following tests""" for hostname in (self.master.hostname, self.replicas[0].hostname, self.replicas[1].hostname): self.master.run_command(['ipa', 'server-mod', hostname, '--location=''']) self.master.run_command(['ipa', 'location-del', self.LOC_PRAGUE]) self.master.run_command(['ipa', 'location-del', self.LOC_PARIS]) self.master.run_command([ 'ipa', 'server-mod', self.master.hostname, '--service-weight', str(self.WEIGHT) ]) tasks.restart_named(self.master, self.replicas[0], self.replicas[1]) time.sleep(5) def test_ipa_ca_records(self): """ Test ipa-ca dns records with firstly removing the records and then using the nsupdate generated by dns-update-system-records""" self.delete_update_system_records(rnames=IPA_CA_A_REC) expected_servers = (self.master.ip, self.replicas[1].ip) ldap = self.master.ldap_connect() tasks.wait_for_replication(ldap) for ip in (self.master.ip, self.replicas[0].ip, self.replicas[1].ip): self._test_A_rec_against_server(ip, self.domain, expected_servers) def test_adtrust_system_records(self): """ Test ADTrust dns records with firstly installing a trust then removing the records and using the nsupdate generated by dns-update-system-records.""" self.master.run_command(['ipa-adtrust-install', '-U', '--enable-compat', '--netbios-name', 'IPA', '-a', self.master.config.admin_password, '--add-sids']) # lets re-kinit after adtrust-install and restart named tasks.kinit_admin(self.master) tasks.restart_named(self.master) time.sleep(5) self.delete_update_system_records(rnames=(r[0] for r in IPA_DEFAULT_ADTRUST_SRV_REC)) expected_servers = ( (self.PRIO_HIGH, self.WEIGHT, DNSName(self.master.hostname)), ) ldap = self.master.ldap_connect() tasks.wait_for_replication(ldap) for ip in (self.master.ip, self.replicas[0].ip, self.replicas[1].ip): self._test_SRV_rec_against_server( ip, self.domain, expected_servers, rec_list=IPA_DEFAULT_ADTRUST_SRV_REC) def test_remove_replica_with_ca(self): """Test ipa-ca dns records after removing the replica with CA""" tasks.uninstall_replica(self.master, self.replicas[1]) self.delete_update_system_records(rnames=IPA_CA_A_REC) expected_servers = (self.master.ip,) self._test_A_rec_against_server(self.master.ip, self.domain, expected_servers)
21,923
Python
.py
481
34.948025
79
0.595699
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,580
__init__.py
freeipa_freeipa/ipatests/test_integration/__init__.py
# Authors: # Petr Viktorin <pviktori@redhat.com> # # Copyright (C) 2013 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import ipatests.util ipatests.util.check_ipaclient_unittests() ipatests.util.check_no_ipaapi()
870
Python
.py
21
40.333333
71
0.781582
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,581
test_ipa_cert_fix.py
freeipa_freeipa/ipatests/test_integration/test_ipa_cert_fix.py
# # Copyright (C) 2020 FreeIPA Contributors see COPYING for license # """ Module provides tests for ipa-cert-fix CLI. """ from datetime import datetime, date import pytest import time import logging from ipalib import x509 from ipaplatform.paths import paths from ipapython.ipaldap import realm_to_serverid from ipatests.pytest_ipa.integration import tasks from ipatests.test_integration.base import IntegrationTest from ipatests.test_integration.test_caless import CALessBase, ipa_certs_cleanup from ipatests.test_integration.test_cert import get_certmonger_fs_id logger = logging.getLogger(__name__) def server_install_teardown(func): def wrapped(*args): master = args[0].master try: func(*args) finally: ipa_certs_cleanup(master) return wrapped def check_status(host, cert_count, state, timeout=600): """Helper method to check that if all the certs are in given state :param host: the host :param cert_count: no of cert to look for :param state: state to check for :param timeout: max time in seconds to wait for the state """ for _i in range(0, timeout, 10): result = host.run_command(['getcert', 'list']) count = result.stdout_text.count(f"status: {state}") logger.info("cert count in %s state : %s", state, count) if int(count) == cert_count: break time.sleep(10) else: raise RuntimeError("request timed out") return count def needs_resubmit(host, req_id): """Helper method to identify if cert request needs to be resubmitted :param host: the host :param req_id: request id to perform operation for Returns True if resubmit needed else False """ # check if cert is in monitoring state tasks.wait_for_certmonger_status( host, ('MONITORING'), req_id, timeout=600 ) # check if cert is valid and not expired cmd = host.run_command( 'getcert list -i {} | grep expires'.format(req_id) ) cert_expiry = cmd.stdout_text.split(' ') cert_expiry = datetime.strptime(cert_expiry[1], '%Y-%m-%d').date() if cert_expiry > date.today(): return False else: return True def get_cert_expiry(host, nssdb_path, cert_nick): """Method to get cert expiry date of given certificate :param host: the host :param nssdb_path: nssdb path of certificate :param cert_nick: certificate nick name for extracting cert from nssdb """ # get initial expiry date to compare later with renewed cert host.run_command([ 'certutil', '-L', '-a', '-d', nssdb_path, '-n', cert_nick, '-o', '/root/cert.pem' ]) data = host.get_file_contents('/root/cert.pem') cert = x509.load_pem_x509_certificate(data) return cert.not_valid_after_utc @pytest.fixture def expire_cert_critical(): """ Fixture to expire the certs by moving the system date using date -s command and revert it back """ hosts = dict() def _expire_cert_critical(host, setup_kra=False): hosts['host'] = host # Do not install NTP as the test plays with the date tasks.install_master(host, setup_dns=False, extra_args=['--no-ntp']) if setup_kra: tasks.install_kra(host) # move date to expire certs tasks.move_date(host, 'stop', '+3Years+1day') yield _expire_cert_critical host = hosts.pop('host') # Prior to uninstall remove all the cert tracking to prevent # errors from certmonger trying to check the status of certs # that don't matter because we are uninstalling. host.run_command(['systemctl', 'stop', 'certmonger']) # Important: run_command with a str argument is able to # perform shell expansion but run_command with a list of # arguments is not host.run_command('rm -fv ' + paths.CERTMONGER_REQUESTS_DIR + '*') tasks.uninstall_master(host) tasks.move_date(host, 'start', '-3Years-1day') class TestIpaCertFix(IntegrationTest): @classmethod def uninstall(cls, mh): # Uninstall method is empty as the uninstallation is done in # the fixture pass @pytest.fixture def expire_ca_cert(self): tasks.install_master(self.master, setup_dns=False, extra_args=['--no-ntp']) tasks.move_date(self.master, 'stop', '+20Years+1day') yield tasks.uninstall_master(self.master) tasks.move_date(self.master, 'start', '-20Years-1day') def test_missing_csr(self, expire_cert_critical): """ Test that ipa-cert-fix succeeds when CSR is missing from CS.cfg Test case for https://pagure.io/freeipa/issue/8618 Scenario: - move the date so that ServerCert cert-pki-ca is expired - remove the ca.sslserver.certreq directive from CS.cfg - call getcert resubmit in order to create the CSR in certmonger file - use ipa-cert-fix, no issue should be seen """ expire_cert_critical(self.master) # pki must be stopped in order to edit CS.cfg self.master.run_command(['ipactl', 'stop']) self.master.run_command(['sed', '-i', r'/ca\.sslserver\.certreq=/d', paths.CA_CS_CFG_PATH]) # dirsrv needs to be up in order to run ipa-cert-fix self.master.run_command(['ipactl', 'start', '--ignore-service-failures']) # It's the call to getcert resubmit that creates the CSR in certmonger. # In normal operations it would be launched automatically when the # expiration date is near but in the test we force the CSR creation. self.master.run_command(['getcert', 'resubmit', '-n', 'Server-Cert cert-pki-ca', '-d', paths.PKI_TOMCAT_ALIAS_DIR]) # Wait a few secs time.sleep(3) # Now the real test, call ipa-cert-fix and ensure it doesn't # complain about missing sslserver.crt result = self.master.run_command(['ipa-cert-fix', '-v'], stdin_text='yes\n', raiseonerr=False) msg = ("No such file or directory: " "'/etc/pki/pki-tomcat/certs/sslserver.crt'") assert msg not in result.stderr_text # Because of BZ 1897120, pki-cert-fix fails on pki-core 10.10.0 # https://bugzilla.redhat.com/show_bug.cgi?id=1897120 if (tasks.get_pki_version(self.master) != tasks.parse_version('10.10.0')): assert result.returncode == 0 # get the number of certs track by certmonger cmd = self.master.run_command(['getcert', 'list']) certs = cmd.stdout_text.count('Request ID') timeout = 600 renewed = 0 start = time.time() # wait up to 10 min for all certs to renew while time.time() - start < timeout: cmd = self.master.run_command(['getcert', 'list']) renewed = cmd.stdout_text.count('status: MONITORING') if renewed == certs: break time.sleep(100) else: # timeout raise AssertionError('Timeout: Failed to renew all the certs') def test_renew_expired_cert_on_master(self, expire_cert_critical): """Test if ipa-cert-fix renews expired certs Test moves system date to expire certs. Then calls ipa-cert-fix to renew them. This certs include subsystem, audit-signing, OCSP signing, Dogtag HTTPS, IPA RA agent, LDAP and KDC certs. related: https://pagure.io/freeipa/issue/7885 """ expire_cert_critical(self.master) # wait for cert expiry check_status(self.master, 8, "CA_UNREACHABLE") self.master.run_command(['ipa-cert-fix', '-v'], stdin_text='yes\n') check_status(self.master, 9, "MONITORING") # second iteration of ipa-cert-fix result = self.master.run_command( ['ipa-cert-fix', '-v'], stdin_text='yes\n' ) assert "Nothing to do" in result.stdout_text check_status(self.master, 9, "MONITORING") def test_ipa_cert_fix_non_ipa(self): """Test ipa-cert-fix doesn't work on non ipa system ipa-cert-fix tool should not work on non ipa system. related: https://pagure.io/freeipa/issue/7885 """ result = self.master.run_command(['ipa-cert-fix', '-v'], stdin_text='yes\n', raiseonerr=False) assert result.returncode == 2 def test_missing_startup(self, expire_cert_critical): """ Test ipa-cert-fix fails/warns when startup directive is missing This test checks that if 'selftests.container.order.startup' directive is missing from CS.cfg, ipa-cert-fix fails and throw proper error message. It also checks that underlying command 'pki-server cert-fix' should fail to renew the cert. related: https://pagure.io/freeipa/issue/8721 With https://github.com/dogtagpki/pki/pull/3466, it changed to display a warning than failing. This test also checks that if 'selftests.container.order.startup' directive is missing from CS.cfg, ipa-cert-fix dsplay proper warning (depending on pki version) related: https://pagure.io/freeipa/issue/8890 """ expire_cert_critical(self.master) # pki must be stopped in order to edit CS.cfg self.master.run_command(['ipactl', 'stop']) self.master.run_command([ 'sed', '-i', r'/selftests\.container\.order\.startup/d', paths.CA_CS_CFG_PATH ]) # dirsrv needs to be up in order to run ipa-cert-fix self.master.run_command(['ipactl', 'start', '--ignore-service-failures']) result = self.master.run_command(['ipa-cert-fix', '-v'], stdin_text='yes\n', raiseonerr=False) err_msg1 = "ERROR: 'selftests.container.order.startup'" # check that pki-server cert-fix command fails err_msg2 = ("ERROR: CalledProcessError(Command " "['pki-server', 'cert-fix'") warn_msg = "WARNING: No selftests configured in" if (tasks.get_pki_version(self.master) < tasks.parse_version('10.11.0')): assert (err_msg1 in result.stderr_text and err_msg2 in result.stderr_text) else: assert warn_msg in result.stderr_text def test_expired_CA_cert(self, expire_ca_cert): """Test to check ipa-cert-fix when CA certificate is expired In order to fix expired certs using ipa-cert-fix, CA cert should be valid. If CA cert expired, ipa-cert-fix won't work. related: https://pagure.io/freeipa/issue/8721 """ result = self.master.run_command(['ipa-cert-fix', '-v'], stdin_text='yes\n', raiseonerr=False) # check that pki-server cert-fix command fails err_msg = ("ERROR: CalledProcessError(Command " "['pki-server', 'cert-fix'") assert err_msg in result.stderr_text class TestIpaCertFixThirdParty(CALessBase): """ Test that ipa-cert-fix works with an installation with custom certs. """ @classmethod def install(cls, mh): cls.nickname = 'ca1/server' super(TestIpaCertFixThirdParty, cls).install(mh) tasks.install_master(cls.master, setup_dns=True) @server_install_teardown def test_third_party_certs(self): self.create_pkcs12(self.nickname, password=self.cert_password, filename='server.p12') self.prepare_cacert('ca1') # We have a chain length of one. If this is extended then the # additional cert names will need to be calculated. nick_chain = self.nickname.split('/') ca_cert = '%s.crt' % nick_chain[0] # Add the CA to the IPA store self.copy_cert(self.master, ca_cert) self.master.run_command(['ipa-cacert-manage', 'install', ca_cert]) # Apply the new cert chain otherwise ipa-server-certinstall will fail self.master.run_command(['ipa-certupdate']) # Install the updated certs and restart the world self.copy_cert(self.master, 'server.p12') args = ['ipa-server-certinstall', '-p', self.master.config.dirman_password, '--pin', self.master.config.admin_password, '-d', 'server.p12'] self.master.run_command(args) self.master.run_command(['ipactl', 'restart']) # Run ipa-cert-fix. This is basically a no-op but tests that # the DS nickname is used and not a hardcoded value. result = self.master.run_command(['ipa-cert-fix', '-v'],) assert self.nickname in result.stderr_text class TestCertFixKRA(IntegrationTest): @classmethod def uninstall(cls, mh): # Uninstall method is empty as the uninstallation is done in # the fixture pass def test_renew_expired_cert_with_kra(self, expire_cert_critical): """Test if ipa-cert-fix renews expired certs with kra installed This test check if ipa-cert-fix renews certs with kra certificate installed. related: https://pagure.io/freeipa/issue/7885 """ expire_cert_critical(self.master, setup_kra=True) # check if all subsystem cert expired check_status(self.master, 11, "CA_UNREACHABLE") self.master.run_command(['ipa-cert-fix', '-v'], stdin_text='yes\n') check_status(self.master, 12, "MONITORING") class TestCertFixReplica(IntegrationTest): num_replicas = 1 @classmethod def install(cls, mh): tasks.install_master( mh.master, setup_dns=False, extra_args=['--no-ntp'] ) # Important: this test is date-sensitive and may fail if executed # around Feb 28 or Feb 29 on a leap year. # The previous tests are playing with the date by jumping in the # future and back to the (expected) current date but calling # date -s +3Years+1day and then date -s -3Years-1day doesn't # bring the date back to the original value if called around Feb 29. # As a consequence, client and server are not synchronized any more # and client installation may fail with the following error: # Joining realm failed: JSON-RPC call failed: # SSL peer certificate or SSH remote key was not OK # If you see this failure, just ignore and relaunch on March 1. tasks.install_replica( mh.master, mh.replicas[0], setup_dns=False, extra_args=['--no-ntp'] ) @classmethod def uninstall(cls, mh): # Uninstall method is empty as the uninstallation is done in # the fixture pass @pytest.fixture def expire_certs(self): # move system date to expire certs for host in self.master, self.replicas[0]: tasks.move_date(host, 'stop', '+3years+1days') host.run_command( ['ipactl', 'restart', '--ignore-service-failures'] ) yield # move date back on replica and master for host in self.replicas[0], self.master: tasks.uninstall_master(host) tasks.move_date(host, 'start', '-3years-1days') def test_renew_expired_cert_replica(self, expire_certs): """Test renewal of certificates on replica with ipa-cert-fix This is to check that ipa-cert-fix renews the certificates on replica related: https://pagure.io/freeipa/issue/7885 """ # wait for cert expiry check_status(self.master, 8, "CA_UNREACHABLE") self.master.run_command(['ipa-cert-fix', '-v'], stdin_text='yes\n') check_status(self.master, 9, "MONITORING") # replica operations # 'Server-Cert cert-pki-ca' cert will be in CA_UNREACHABLE state cmd = self.replicas[0].run_command( ['getcert', 'list', '-d', paths.PKI_TOMCAT_ALIAS_DIR, '-n', 'Server-Cert cert-pki-ca'] ) req_id = get_certmonger_fs_id(cmd.stdout_text) tasks.wait_for_certmonger_status( self.replicas[0], ('CA_UNREACHABLE'), req_id, timeout=600 ) # get initial expiry date to compare later with renewed cert initial_expiry = get_cert_expiry( self.replicas[0], paths.PKI_TOMCAT_ALIAS_DIR, 'Server-Cert cert-pki-ca' ) # check that HTTP,LDAP,PKINIT are renewed and in MONITORING state instance = realm_to_serverid(self.master.domain.realm) dirsrv_cert = paths.ETC_DIRSRV_SLAPD_INSTANCE_TEMPLATE % instance for cert in (paths.KDC_CERT, paths.HTTPD_CERT_FILE): cmd = self.replicas[0].run_command( ['getcert', 'list', '-f', cert] ) req_id = get_certmonger_fs_id(cmd.stdout_text) tasks.wait_for_certmonger_status( self.replicas[0], ('MONITORING'), req_id, timeout=600 ) cmd = self.replicas[0].run_command( ['getcert', 'list', '-d', dirsrv_cert] ) req_id = get_certmonger_fs_id(cmd.stdout_text) tasks.wait_for_certmonger_status( self.replicas[0], ('MONITORING'), req_id, timeout=600 ) # check if replication working fine testuser = 'testuser1' password = 'Secret@123' stdin = (f"{self.master.config.admin_password}\n" f"{self.master.config.admin_password}\n" f"{self.master.config.admin_password}\n") self.master.run_command(['kinit', 'admin'], stdin_text=stdin) tasks.user_add(self.master, testuser, password=password) self.replicas[0].run_command(['kinit', 'admin'], stdin_text=stdin) self.replicas[0].run_command(['ipa', 'user-show', testuser]) # renew shared certificates by resubmitting to certmonger cmd = self.replicas[0].run_command( ['getcert', 'list', '-f', paths.RA_AGENT_PEM] ) req_id = get_certmonger_fs_id(cmd.stdout_text) if needs_resubmit(self.replicas[0], req_id): self.replicas[0].run_command( ['getcert', 'resubmit', '-i', req_id] ) tasks.wait_for_certmonger_status( self.replicas[0], ('MONITORING'), req_id, timeout=600 ) for cert_nick in ('auditSigningCert cert-pki-ca', 'ocspSigningCert cert-pki-ca', 'subsystemCert cert-pki-ca'): cmd = self.replicas[0].run_command( ['getcert', 'list', '-d', paths.PKI_TOMCAT_ALIAS_DIR, '-n', cert_nick] ) req_id = get_certmonger_fs_id(cmd.stdout_text) if needs_resubmit(self.replicas[0], req_id): self.replicas[0].run_command( ['getcert', 'resubmit', '-i', req_id] ) tasks.wait_for_certmonger_status( self.replicas[0], ('MONITORING'), req_id, timeout=600 ) self.replicas[0].run_command( ['ipa-cert-fix', '-v'], stdin_text='yes\n' ) check_status(self.replicas[0], 9, "MONITORING") # Sometimes certmonger takes time to update the cert status # So check in nssdb instead of relying on getcert command renewed_expiry = get_cert_expiry( self.replicas[0], paths.PKI_TOMCAT_ALIAS_DIR, 'Server-Cert cert-pki-ca' ) assert renewed_expiry > initial_expiry
20,207
Python
.py
444
35.292793
79
0.608775
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,582
test_backup_and_restore.py
freeipa_freeipa/ipatests/test_integration/test_backup_and_restore.py
# Authors: # Petr Viktorin <pviktori@redhat.com> # # Copyright (C) 2014 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from __future__ import print_function, absolute_import import logging import os import re import contextlib import pytest from ipaplatform.constants import constants from ipaplatform.paths import paths from ipaplatform.tasks import tasks as platformtasks from ipapython.ipaldap import realm_to_serverid from ipapython.dn import DN from ipapython import ipautil from ipatests.test_integration.base import IntegrationTest from ipatests.pytest_ipa.integration import tasks from ipatests.test_integration.test_dnssec import wait_until_record_is_signed from ipatests.test_integration.test_simple_replication import check_replication from ipatests.test_integration.test_topology import find_segment from ipatests.util import assert_deepequal from ldap.dn import escape_dn_chars logger = logging.getLogger(__name__) def assert_entries_equal(a, b): assert_deepequal(a.dn, b.dn) assert_deepequal(dict(a), dict(b)) def assert_results_equal(a, b): def to_dict(r): return { 'stdout': r.stdout_text, 'stderr': r.stderr_text, 'returncode': r.returncode, } assert_deepequal(to_dict(a), to_dict(b)) def check_admin_in_ldap(host): ldap = host.ldap_connect() basedn = host.domain.basedn user_dn = DN(('uid', 'admin'), ('cn', 'users'), ('cn', 'accounts'), basedn) entry = ldap.get_entry(user_dn) print(entry) assert entry.dn == user_dn assert entry['uid'] == ['admin'] entry.pop('krbLastSuccessfulAuth', None) return entry def check_admin_in_cli(host): result = host.run_command(['ipa', 'user-show', 'admin']) assert 'User login: admin' in result.stdout_text, result.stdout_text # LDAP do not guarantee any order, so the test cannot assume it. Based on # that, the code bellow order the 'Member of groups' field to able to # assert it latter. data = dict(re.findall(r"\W*(.+):\W*(.+)\W*", result.stdout_text)) data["Member of groups"] = ', '.join(sorted(data["Member of groups"] .split(", "))) result.stdout_text = ''.join([' {}: {}\n'.format(k, v) for k, v in data.items()]) return result def check_admin_in_id(host): result = host.run_command(['id', 'admin']) assert 'admin' in result.stdout_text, result.stdout_text return result def check_certs(host): result = host.run_command(['ipa', 'cert-find']) assert re.search(r'^Number of entries returned [1-9]\d*$', result.stdout_text, re.MULTILINE), result.stdout_text return result def check_dns(host): result = host.run_command(['host', host.hostname, 'localhost']) return result def check_kinit(host): result = host.run_command(['kinit', 'admin'], stdin_text=host.config.admin_password) return result def check_custodia_files(host): """regression test for https://pagure.io/freeipa/issue/7247""" assert host.transport.file_exists(paths.IPA_CUSTODIA_KEYS) assert host.transport.file_exists(paths.IPA_CUSTODIA_CONF) return True def check_pkcs11_modules(host): """regression test for https://pagure.io/freeipa/issue/8073""" # Return a dictionary with key = filename, value = file content # containing all the PKCS11 modules modified by the installer result = dict() for filename in platformtasks.get_pkcs11_modules(): assert host.transport.file_exists(filename) result[filename] = host.get_file_contents(filename) return result CHECKS = [ (check_admin_in_ldap, assert_entries_equal), (check_admin_in_cli, assert_results_equal), (check_admin_in_id, assert_results_equal), (check_certs, assert_results_equal), (check_dns, assert_results_equal), (check_kinit, assert_results_equal), (check_custodia_files, assert_deepequal), (check_pkcs11_modules, assert_deepequal) ] @contextlib.contextmanager def restore_checker(host): """Check that the IPA at host works the same at context enter and exit""" tasks.kinit_admin(host) results = [] for check, assert_func in CHECKS: logger.info('Storing result for %s', check.__name__) results.append(check(host)) yield # Wait for SSSD to become online before doing any other check tasks.wait_for_sssd_domain_status_online(host) tasks.kinit_admin(host) for (check, assert_func), expected in zip(CHECKS, results): logger.info('Checking result for %s', check.__name__) got = check(host) assert_func(expected, got) @pytest.fixture def cert_sign_request(request): master = request.instance.master hosts = [master] + request.instance.replicas csrs = {} for host in hosts: request_path = host.run_command(['mktemp']).stdout_text.strip() openssl_command = [ 'openssl', 'req', '-new', '-nodes', '-out', request_path, '-subj', '/CN=' + master.hostname ] host.run_command(openssl_command) csrs[host.hostname] = request_path yield csrs for host in hosts: host.run_command(['rm', csrs[host.hostname]]) class TestBackupAndRestore(IntegrationTest): topology = 'star' def test_full_backup_and_restore(self): """backup, uninstall, restore""" with restore_checker(self.master): backup_path = tasks.get_backup_dir(self.master) self.master.run_command(['ipa-server-install', '--uninstall', '-U']) assert not self.master.transport.file_exists( paths.IPA_CUSTODIA_KEYS) assert not self.master.transport.file_exists( paths.IPA_CUSTODIA_CONF) dirman_password = self.master.config.dirman_password self.master.run_command(['ipa-restore', backup_path], stdin_text=dirman_password + '\nyes') # check the file permssion and ownership is set to 770 and # dirsrv:dirsrv after restore on /var/log/dirsrv/slapd-<instance> # related ticket : https://pagure.io/freeipa/issue/7725 instance = realm_to_serverid(self.master.domain.realm) log_path = paths.VAR_LOG_DIRSRV_INSTANCE_TEMPLATE % instance cmd = self.master.run_command(['stat', '-c', '"%a %G:%U"', log_path]) assert "770 dirsrv:dirsrv" in cmd.stdout_text def test_data_backup_and_restore(self): """backup data only then restore""" with restore_checker(self.master): backup_path = tasks.get_backup_dir(self.master, data_only=True) self.master.run_command(['ipa', 'user-add', 'testuser', '--first', 'test', '--last', 'user']) tasks.ipa_restore(self.master, backup_path) # the user added in the interim should now be gone result = self.master.run_command( ['ipa', 'user-show', 'test-user'], raiseonerr=False ) assert 'user not found' in result.stderr_text def test_data_backup_and_restore_backend(self): """backup data only then restore""" with restore_checker(self.master): backup_path = tasks.get_backup_dir(self.master, data_only=True) self.master.run_command(['ipa', 'user-add', 'testuser', '--first', 'test', '--last', 'user']) tasks.ipa_restore(self.master, backup_path, backend='userRoot') # the user added in the interim should now be gone result = self.master.run_command( ['ipa', 'user-show', 'test-user'], raiseonerr=False ) assert 'user not found' in result.stderr_text def test_full_backup_and_restore_with_removed_users(self): """regression test for https://fedorahosted.org/freeipa/ticket/3866""" with restore_checker(self.master): backup_path = tasks.get_backup_dir(self.master) logger.info('Backup path for %s is %s', self.master, backup_path) self.master.run_command(['ipa-server-install', '--uninstall', '-U']) homedir = os.path.join(self.master.config.test_dir, 'testuser_homedir') self.master.run_command(['useradd', 'ipatest_user1', '--system', '-d', homedir]) try: dirman_password = self.master.config.dirman_password self.master.run_command(['ipa-restore', backup_path], stdin_text=dirman_password + '\nyes') finally: self.master.run_command(['userdel', 'ipatest_user1']) @pytest.mark.skipif( not platformtasks.is_selinux_enabled(), reason="Test needs SELinux enabled") def test_full_backup_and_restore_with_selinux_booleans_off(self): """regression test for https://fedorahosted.org/freeipa/ticket/4157""" with restore_checker(self.master): backup_path = tasks.get_backup_dir(self.master) logger.info('Backup path for %s is %s', self.master, backup_path) self.master.run_command(['ipa-server-install', '--uninstall', '-U']) self.master.run_command([ 'setsebool', '-P', 'httpd_can_network_connect=off', 'httpd_manage_ipa=off', ]) dirman_password = self.master.config.dirman_password self.master.run_command(['ipa-restore', backup_path], stdin_text=dirman_password + '\nyes') result = self.master.run_command([ 'getsebool', 'httpd_can_network_connect', 'httpd_manage_ipa', ]) assert 'httpd_can_network_connect --> on' in result.stdout_text assert 'httpd_manage_ipa --> on' in result.stdout_text class BaseBackupAndRestoreWithDNS(IntegrationTest): """ Abstract class for DNS restore tests """ topology = 'star' example_test_zone = "example.test." example2_test_zone = "example2.test." @classmethod def install(cls, mh): tasks.install_master(cls.master, setup_dns=True) def _full_backup_restore_with_DNS_zone(self, reinstall=False): """backup, uninstall, restore. Test for bug https://pagure.io/freeipa/issue/7630. """ with restore_checker(self.master): self.master.run_command([ 'ipa', 'dnszone-add', self.example_test_zone, ]) tasks.resolve_record(self.master.ip, self.example_test_zone) backup_path = tasks.get_backup_dir(self.master) self.master.run_command(['ipa-server-install', '--uninstall', '-U']) tasks.uninstall_packages(self.master, ['*ipa-server-dns']) dirman_password = self.master.config.dirman_password result = self.master.run_command( ['ipa-restore', backup_path], stdin_text=dirman_password + '\nyes', raiseonerr=False) assert 'Please install the package' in result.stderr_text tasks.install_packages(self.master, ['*ipa-server-dns']) if reinstall: tasks.install_master(self.master, setup_dns=True) self.master.run_command(['ipa-restore', backup_path], stdin_text=dirman_password + '\nyes') if reinstall: # If the server was reinstalled, reinstall may have changed # the uid and restore reverts to the original value. # clear the cache to make sure we get up-to-date values tasks.clear_sssd_cache(self.master) tasks.resolve_record(self.master.ip, self.example_test_zone) tasks.kinit_admin(self.master) self.master.run_command([ 'ipa', 'dnszone-add', self.example2_test_zone, ]) tasks.resolve_record(self.master.ip, self.example2_test_zone) class TestBackupAndRestoreWithDNS(BaseBackupAndRestoreWithDNS): def test_full_backup_and_restore_with_DNS_zone(self): """backup, uninstall, restore""" self._full_backup_restore_with_DNS_zone(reinstall=False) class TestBackupReinstallRestoreWithDNS(BaseBackupAndRestoreWithDNS): def test_full_backup_reinstall_restore_with_DNS_zone(self): """backup, uninstall, reinstall, restore""" self._full_backup_restore_with_DNS_zone(reinstall=True) class BaseBackupAndRestoreWithDNSSEC(IntegrationTest): """ Abstract class for DNSSEC restore tests """ topology = 'star' example_test_zone = "example.test." example2_test_zone = "example2.test." @classmethod def install(cls, mh): tasks.install_master(cls.master, setup_dns=True) args = [ "ipa-dns-install", "--dnssec-master", "--forwarder", cls.master.config.dns_forwarder, "-U", ] cls.master.run_command(args) def _full_backup_and_restore_with_DNSSEC_zone(self, reinstall=False): with restore_checker(self.master): self.master.run_command([ 'ipa', 'dnszone-add', self.example_test_zone, '--dnssec', 'true', ]) assert ( wait_until_record_is_signed( self.master.ip, self.example_test_zone) ), "Zone is not signed" backup_path = tasks.get_backup_dir(self.master) self.master.run_command(['ipa-server-install', '--uninstall', '-U']) if reinstall: tasks.install_master(self.master, setup_dns=True) dirman_password = self.master.config.dirman_password self.master.run_command(['ipa-restore', backup_path], stdin_text=dirman_password + '\nyes') if reinstall: # If the server was reinstalled, reinstall may have changed # the uid and restore reverts to the original value. # clear the cache to make sure we get up-to-date values tasks.clear_sssd_cache(self.master) assert ( wait_until_record_is_signed( self.master.ip, self.example_test_zone) ), "Zone is not signed after restore" tasks.kinit_admin(self.master) self.master.run_command([ 'ipa', 'dnszone-add', self.example2_test_zone, '--dnssec', 'true', ]) assert ( wait_until_record_is_signed( self.master.ip, self.example2_test_zone) ), "A new zone is not signed" class TestBackupAndRestoreWithDNSSEC(BaseBackupAndRestoreWithDNSSEC): def test_full_backup_and_restore_with_DNSSEC_zone(self): """backup, uninstall, restore""" self._full_backup_and_restore_with_DNSSEC_zone(reinstall=False) class TestBackupReinstallRestoreWithDNSSEC(BaseBackupAndRestoreWithDNSSEC): def test_full_backup_reinstall_restore_with_DNSSEC_zone(self): """backup, uninstall, install, restore""" self._full_backup_and_restore_with_DNSSEC_zone(reinstall=True) class BaseBackupAndRestoreWithKRA(IntegrationTest): """ Abstract class for KRA restore tests """ topology = 'star' vault_name = "ci_test_vault" vault_password = "password" vault_data = "SSBsb3ZlIENJIHRlc3RzCg==" @classmethod def install(cls, mh): tasks.install_master(cls.master, setup_dns=True, setup_kra=True) def _full_backup_restore_with_vault(self, reinstall=False): with restore_checker(self.master): # create vault self.master.run_command([ "ipa", "vault-add", self.vault_name, "--password", self.vault_password, "--type", "symmetric", ]) # archive secret self.master.run_command([ "ipa", "vault-archive", self.vault_name, "--password", self.vault_password, "--data", self.vault_data, ]) # retrieve secret self.master.run_command([ "ipa", "vault-retrieve", self.vault_name, "--password", self.vault_password, ]) backup_path = tasks.get_backup_dir(self.master) # check that no error message in uninstall log for KRA instance cmd = self.master.run_command(['ipa-server-install', '--uninstall', '-U']) assert "failed to uninstall KRA" not in cmd.stderr_text if reinstall: tasks.install_master(self.master, setup_dns=True) dirman_password = self.master.config.dirman_password self.master.run_command(['ipa-restore', backup_path], stdin_text=dirman_password + '\nyes') if reinstall: # If the server was reinstalled, reinstall may have changed # the uid and restore reverts to the original value. # clear the cache to make sure we get up-to-date values tasks.clear_sssd_cache(self.master) tasks.kinit_admin(self.master) # retrieve secret after restore self.master.run_command([ "ipa", "vault-retrieve", self.vault_name, "--password", self.vault_password, ]) class TestBackupAndRestoreWithKRA(BaseBackupAndRestoreWithKRA): def test_full_backup_restore_with_vault(self): """backup, uninstall, restore""" self._full_backup_restore_with_vault(reinstall=False) class TestBackupReinstallRestoreWithKRA(BaseBackupAndRestoreWithKRA): def test_full_backup_reinstall_restore_with_vault(self): """backup, uninstall, reinstall, restore""" self._full_backup_restore_with_vault(reinstall=True) def test_no_error_message_with_uninstall_ipa_with_kra(self): """Test there is no error message in uninstall log for KRA instance There was error message in uninstall log when IPA with KRA was uninstalled. This test check that there is no error message in uninstall log for kra instance. related: https://pagure.io/freeipa/issue/8550 """ cmd = self.master.run_command(['ipa-server-install', '--uninstall', '-U']) assert "failed to uninstall KRA" not in cmd.stderr_text class TestBackupAndRestoreWithReplica(IntegrationTest): """Regression tests for issues 7234 and 7455 https://pagure.io/freeipa/issue/7234 - check that oddjobd service is started after restore - check new replica setup after restore https://pagure.io/freeipa/issue/7455 check that after restore and replication reinitialization - users and CA data are at state before backup - CA can be installed on existing replica - new replica with CA can be setup """ num_replicas = 2 topology = "star" @classmethod def install(cls, mh): cls.replica1 = cls.replicas[0] cls.replica2 = cls.replicas[1] if cls.domain_level is None: domain_level = cls.master.config.domain_level else: domain_level = cls.domain_level # Configure only master and one replica. # Replica is configured without CA tasks.install_topo( cls.topology, cls.master, [cls.replica1], cls.clients, domain_level, setup_replica_cas=False ) def get_users(self, host): res = host.run_command(['ipa', 'user-find']) users = set() for line in res.stdout_text.splitlines(): k, _unused, v = line.strip().partition(': ') if k == 'User login': users.add(v) return users def check_replication_error(self, host): status = r'Error \(19\) Replication error acquiring replica: ' \ 'Replica has different database generation ID' tasks.wait_for_replication( host.ldap_connect(), target_status_re=status, raise_on_timeout=True) def check_replication_success(self, host): status = r'Error \(0\) Replica acquired successfully: ' \ 'Incremental update succeeded' tasks.wait_for_replication( host.ldap_connect(), target_status_re=status, raise_on_timeout=True) def request_test_service_cert(self, host, request_path, expect_connection_error=False): res = host.run_command([ 'ipa', 'cert-request', '--principal=TEST/' + self.master.hostname, request_path ], raiseonerr=not expect_connection_error) if expect_connection_error: assert (1 == res.returncode and '[Errno 111] Connection refused' in res.stderr_text) def test_full_backup_and_restore_with_replica(self, cert_sign_request): # check prerequisites self.check_replication_success(self.master) self.check_replication_success(self.replica1) self.master.run_command( ['ipa', 'service-add', 'TEST/' + self.master.hostname]) tasks.user_add(self.master, 'test1_master') tasks.user_add(self.replica1, 'test1_replica') with restore_checker(self.master): backup_path = tasks.get_backup_dir(self.master) # change data after backup self.master.run_command(['ipa', 'user-del', 'test1_master']) self.replica1.run_command(['ipa', 'user-del', 'test1_replica']) tasks.user_add(self.master, 'test2_master') tasks.user_add(self.replica1, 'test2_replica') # simulate master crash # the replica is stopped to make sure master uninstallation # does not delete any entry on the replica. In case of a # real master crash there would not be any communication between # master and replica self.replica1.run_command(['ipactl', 'stop']) self.master.run_command(['ipactl', 'stop']) tasks.uninstall_master(self.master, clean=False) logger.info("Stopping and disabling oddjobd service") self.master.run_command([ "systemctl", "stop", "oddjobd" ]) self.master.run_command([ "systemctl", "disable", "oddjobd" ]) self.replica1.run_command(['ipactl', 'start']) self.master.run_command(['ipa-restore', '-U', backup_path]) status = self.master.run_command([ "systemctl", "status", "oddjobd" ]) assert "active (running)" in status.stdout_text # replication should not work after restoration # create users to force master and replica to try to replicate tasks.user_add(self.master, 'test3_master') tasks.user_add(self.replica1, 'test3_replica') self.check_replication_error(self.master) self.check_replication_error(self.replica1) assert {'admin', 'test1_master', 'test1_replica', 'test3_master'} == \ self.get_users(self.master) assert {'admin', 'test2_master', 'test2_replica', 'test3_replica'} == \ self.get_users(self.replica1) # reestablish and check replication self.replica1.run_command(['ipa-replica-manage', 're-initialize', '--from', self.master.hostname]) # create users to force master and replica to try to replicate tasks.user_add(self.master, 'test4_master') tasks.user_add(self.replica1, 'test4_replica') self.check_replication_success(self.master) self.check_replication_success(self.replica1) assert {'admin', 'test1_master', 'test1_replica', 'test3_master', 'test4_master', 'test4_replica'} == \ self.get_users(self.master) assert {'admin', 'test1_master', 'test1_replica', 'test3_master', 'test4_master', 'test4_replica'} == \ self.get_users(self.replica1) # CA on master should be accesible from master and replica self.request_test_service_cert( self.master, cert_sign_request[self.master.hostname]) self.request_test_service_cert( self.replica1, cert_sign_request[self.replica1.hostname]) # replica should not be able to sign certificates without CA on master self.master.run_command(['ipactl', 'stop']) try: self.request_test_service_cert( self.replica1, cert_sign_request[self.replica1.hostname], expect_connection_error=True) finally: self.master.run_command(['ipactl', 'start']) tasks.install_ca(self.replica1) # now replica should be able to sign certificates without CA on master self.master.run_command(['ipactl', 'stop']) self.request_test_service_cert( self.replica1, cert_sign_request[self.replica1.hostname]) self.master.run_command(['ipactl', 'start']) # check installation of new replica tasks.install_replica(self.master, self.replica2, setup_ca=True) check_replication(self.master, self.replica2, "testuser") # new replica should be able to sign certificates without CA on master # and old replica self.master.run_command(['ipactl', 'stop']) self.replica1.run_command(['ipactl', 'stop']) try: self.request_test_service_cert( self.replica2, cert_sign_request[self.replica2.hostname]) finally: self.replica1.run_command(['ipactl', 'start']) self.master.run_command(['ipactl', 'start']) class TestUserRootFilesOwnershipPermission(IntegrationTest): """Test to check if userroot.ldif have proper ownership. Before the fix, when ipa-backup was called for the first time, the LDAP database exported to /var/lib/dirsrv/slapd-<instance>/ldif/<instance>-userRoot.ldif. db2ldif is called for this and it runs under root, hence files were owned by root. When ipa-backup called the next time, the db2ldif fails, because the tool does not have permissions to write to the ldif file which was owned by root (instead of dirsrv). This test check if files are owned by dirsrv and db2ldif doesn't fail related ticket: https://pagure.io/freeipa/issue/7010 This test also checks if the access rights for user/group are set and umask 0022 set while restoring. related ticket: https://pagure.io/freeipa/issue/6844 """ @classmethod def install(cls, mh): super(TestUserRootFilesOwnershipPermission, cls).install(mh) cls.bashrc_file = cls.master.get_file_contents('/root/.bashrc') def test_userroot_ldif_files_ownership_and_permission(self): """backup, uninstall, restore, backup""" tasks.install_master(self.master) backup_path = tasks.get_backup_dir(self.master) self.master.run_command(['ipa-server-install', '--uninstall', '-U']) # set umask to 077 just to check if restore success. self.master.run_command('echo "umask 0077" >> /root/.bashrc') result = self.master.run_command(['umask']) assert '0077' in result.stdout_text dirman_password = self.master.config.dirman_password result = self.master.run_command(['ipa-restore', backup_path], stdin_text=dirman_password + '\nyes') assert 'Temporary setting umask to 022' in result.stderr_text # check if umask reset to 077 after restore. result = self.master.run_command(['umask']) assert '0077' in result.stdout_text # check if files have proper owner and group. dashed_domain = self.master.domain.realm.replace(".", '-') arg = ['stat', '-c', '%U:%G', '{}/ldif/'.format( paths.VAR_LIB_SLAPD_INSTANCE_DIR_TEMPLATE % dashed_domain)] cmd = self.master.run_command(arg) expected = '{}:{}'.format(constants.DS_USER, constants.DS_GROUP) assert expected in cmd.stdout_text # also check of access rights are set to 644. arg = ['stat', '-c', '%U:%G:%a', '{}/ldif/{}-ipaca.ldif'.format( paths.VAR_LIB_SLAPD_INSTANCE_DIR_TEMPLATE % dashed_domain, dashed_domain)] cmd = self.master.run_command(arg) assert '{}:644'.format(expected) in cmd.stdout_text arg = ['stat', '-c', '%U:%G:%a', '{}/ldif/{}-userRoot.ldif'.format( paths.VAR_LIB_SLAPD_INSTANCE_DIR_TEMPLATE % dashed_domain, dashed_domain)] cmd = self.master.run_command(arg) assert '{}:644'.format(expected) in cmd.stdout_text cmd = self.master.run_command(['ipa-backup', '-d']) unexp_str = "CRITICAL: db2ldif failed:" assert cmd.returncode == 0 assert unexp_str not in cmd.stdout_text def test_files_ownership_and_permission_teardown(self): """ Method to restore the default bashrc contents""" if self.bashrc_file is not None: self.master.put_file_contents('/root/.bashrc', self.bashrc_file) class TestBackupAndRestoreDMPassword(IntegrationTest): """Negative tests for incorrect DM password""" topology = 'star' def test_restore_bad_dm_password(self): """backup, uninstall, restore, wrong DM password (expect failure)""" with restore_checker(self.master): backup_path = tasks.get_backup_dir(self.master) # No uninstall, just pure restore, the only case where # prompting for the DM password matters. result = self.master.run_command(['ipa-restore', backup_path], stdin_text='badpass\nyes', raiseonerr=False) assert result.returncode == 1 def test_restore_dirsrv_not_running(self): """backup, restore, dirsrv not running (expect failure)""" # Flying blind without the restore_checker so we can have # an error thrown when dirsrv is down. backup_path = tasks.get_backup_dir(self.master) self.master.run_command(['ipactl', 'stop']) dirman_password = self.master.config.dirman_password result = self.master.run_command( ['ipa-restore', backup_path], stdin_text=dirman_password + '\nyes', raiseonerr=False) assert result.returncode == 1 class TestReplicaInstallAfterRestore(IntegrationTest): """Test to check second replica installation after master restore When master is restored from backup and replica1 is re-initialize, second replica installation was failing. The issue was with ipa-backup tool which was not backing up the /etc/ipa/custodia/custodia.conf and /etc/ipa/custodia/server.keys. related ticket: https://pagure.io/freeipa/issue/7247 """ num_replicas = 2 def test_replica_install_after_restore(self): master = self.master replica1 = self.replicas[0] replica2 = self.replicas[1] tasks.install_master(master) tasks.install_replica(master, replica1) check_replication(master, replica1, "testuser1") # backup master. backup_path = tasks.get_backup_dir(self.master) suffix = ipautil.realm_to_suffix(master.domain.realm) suffix = escape_dn_chars(str(suffix)) entry_ldif = ( "dn: cn=meTo{hostname},cn=replica," "cn={suffix}," "cn=mapping tree,cn=config\n" "changetype: modify\n" "replace: nsds5ReplicaEnabled\n" "nsds5ReplicaEnabled: off\n\n" "dn: cn=caTo{hostname},cn=replica," "cn=o\\3Dipaca,cn=mapping tree,cn=config\n" "changetype: modify\n" "replace: nsds5ReplicaEnabled\n" "nsds5ReplicaEnabled: off").format( hostname=replica1.hostname, suffix=suffix) # disable replication agreement tasks.ldapmodify_dm(master, entry_ldif) # uninstall master. tasks.uninstall_master(master, clean=False) # master restore. dirman_password = master.config.dirman_password master.run_command(['ipa-restore', backup_path], stdin_text=dirman_password + '\nyes') tasks.kinit_admin(master) # re-initialize topology after restore. for topo_suffix in 'domain', 'ca': topo_name = find_segment(master, replica1, topo_suffix) arg = ['ipa', 'topologysegment-reinitialize', topo_suffix, topo_name] if topo_name.split('-to-', maxsplit=1)[0] != master.hostname: arg.append('--left') else: arg.append('--right') replica1.run_command(arg) # wait sometime for re-initialization tasks.wait_for_replication(replica1.ldap_connect()) # install second replica after restore tasks.install_replica(master, replica2) check_replication(master, replica2, "testuser2") class TestBackupAndRestoreTrust(IntegrationTest): """Test for Backup and Restore for Trust scenario""" topology = 'star' def test_restore_trust_pkg_before_restore(self): """Test restore with adtrust when trust-ad pkg is missing. Test for bug https://pagure.io/freeipa/issue/7630. """ tasks.install_packages(self.master, ['*ipa-server-trust-ad']) self.master.run_command(['ipa-adtrust-install', '-U', '--enable-compat', '--netbios-name', 'IPA', '-a', self.master.config.admin_password, '--add-sids']) with restore_checker(self.master): backup_path = tasks.get_backup_dir(self.master) self.master.run_command(['ipa-server-install', '--uninstall', '-U']) tasks.uninstall_packages(self.master, ['*ipa-server-trust-ad']) dirman_password = self.master.config.dirman_password result = self.master.run_command( ['ipa-restore', backup_path], stdin_text=dirman_password + '\nyes', raiseonerr=False) assert 'Please install the package' in result.stderr_text tasks.install_packages(self.master, ['*ipa-server-trust-ad']) self.master.run_command(['ipa-restore', backup_path], stdin_text=dirman_password + '\nyes') class TestBackupRoles(IntegrationTest): """ipa-backup should only run on replicas with all the in-use roles https://pagure.io/freeipa/issue/8217 """ num_replicas = 1 topology = 'star' serverroles = { 'ADTA': u'AD trust agent', 'ADTC': u'AD trust controller', 'CA': u'CA server', 'DNS': u'DNS server', 'KRA': u'KRA server' } @classmethod def install(cls, mh): tasks.install_master(cls.master, setup_dns=True) def _check_rolecheck_backup_failure(self, host): result = tasks.ipa_backup(host, raiseonerr=False) assert result.returncode == 1 assert "Error: Local roles" in result.stderr_text assert "do not match globally used roles" in result.stderr_text result = tasks.ipa_backup(host, disable_role_check=True) assert result.returncode == 0 assert "Warning: Local roles" in result.stderr_text assert "do not match globally used roles" in result.stderr_text def _check_rolecheck_backup_success(self, host): result = tasks.ipa_backup(host) assert result.returncode == 0 assert "Local roles match globally used roles, proceeding." \ in result.stderr_text def _ipa_replica_role_check(self, replica, role): return "enabled" in self.master.run_command([ 'ipa', 'server-role-find', '--server', replica, '--role', role ]).stdout_text def test_rolecheck_DNS_CA(self): """ipa-backup rolecheck: start with a master with DNS and CA then gradually upgrade a replica to the DNS and CA roles. """ # single master: check that backup works. assert self._ipa_replica_role_check( self.master.hostname, self.serverroles['DNS'] ) assert self._ipa_replica_role_check( self.master.hostname, self.serverroles['CA'] ) assert not self._ipa_replica_role_check( self.master.hostname, self.serverroles['KRA'] ) self._check_rolecheck_backup_success(self.master) # install CA-less, DNS-less replica tasks.install_replica(self.master, self.replicas[0], setup_ca=False) assert not self._ipa_replica_role_check( self.replicas[0].hostname, self.serverroles['DNS'] ) assert not self._ipa_replica_role_check( self.replicas[0].hostname, self.serverroles['CA'] ) assert not self._ipa_replica_role_check( self.replicas[0].hostname, self.serverroles['KRA'] ) self._check_rolecheck_backup_success(self.master) self._check_rolecheck_backup_failure(self.replicas[0]) # install DNS on replica tasks.install_dns(self.replicas[0]) assert self._ipa_replica_role_check( self.replicas[0].hostname, self.serverroles['DNS'] ) self._check_rolecheck_backup_failure(self.replicas[0]) def test_rolecheck_KRA(self): """ipa-backup rolecheck: add a KRA. """ # install CA on replica. tasks.install_ca(self.replicas[0]) # master and replicas[0] have matching roles now. assert self._ipa_replica_role_check( self.replicas[0].hostname, self.serverroles['CA'] ) self._check_rolecheck_backup_success(self.master) self._check_rolecheck_backup_success(self.replicas[0]) # install KRA on replica tasks.install_kra(self.replicas[0], first_instance=True) assert self._ipa_replica_role_check( self.replicas[0].hostname, self.serverroles['KRA'] ) self._check_rolecheck_backup_success(self.replicas[0]) self._check_rolecheck_backup_failure(self.master) # install KRA on master tasks.install_kra(self.master) # master and replicas[0] have matching roles now. assert self._ipa_replica_role_check( self.master.hostname, self.serverroles['KRA'] ) self._check_rolecheck_backup_success(self.replicas[0]) self._check_rolecheck_backup_success(self.master) def test_rolecheck_Trust(self): """ipa-backup rolecheck: add Trust controllers/agents. """ # install AD Trust packages on replica first tasks.install_packages(self.replicas[0], ['*ipa-server-trust-ad']) self._check_rolecheck_backup_success(self.replicas[0]) self._check_rolecheck_backup_success(self.master) tasks.install_packages(self.master, ['*ipa-server-trust-ad']) # make replicas[0] become Trust Controller self.replicas[0].run_command([ 'ipa-adtrust-install', '-U', '--netbios-name', 'IPA', '-a', self.master.config.admin_password, '--add-sids' ]) # wait for replication to propagate the change on # cn=adtrust agents,cn=sysaccounts,cn=etc,dc=ipa,dc=test # as the ipa server-role-find call is using this entry to # build its output tasks.wait_for_replication(self.replicas[0].ldap_connect()) # double-check assert self._ipa_replica_role_check( self.replicas[0].hostname, self.serverroles['ADTC'] ) # check that master has no AD Trust-related role assert not self._ipa_replica_role_check( self.master.hostname, self.serverroles['ADTA'] ) self._check_rolecheck_backup_success(self.replicas[0]) self._check_rolecheck_backup_failure(self.master) # make master become Trust Agent cmd_input = ( # admin password: self.master.config.admin_password + '\n' + # WARNING: The smb.conf already exists. Running ipa-adtrust-install # will break your existing samba configuration. # Do you wish to continue? [no]: 'yes\n' # Enable trusted domains support in slapi-nis? [no]: '\n' + # WARNING: 1 IPA masters are not yet able to serve information # about users from trusted forests. # Installer can add them to the list of IPA masters allowed to # access information about trusts. # If you choose to do so, you also need to restart LDAP service on # those masters. # Refer to ipa-adtrust-install(1) man page for details. # IPA master[replica1.testrelm.test]?[no]: 'yes\n' ) self.replicas[0].run_command([ 'ipa-adtrust-install', '--add-agents'], stdin_text=cmd_input ) # wait for replication to propagate the change on # cn=adtrust agents,cn=sysaccounts,cn=etc,dc=ipa,dc=test # as the ipa server-role-find call is using this entry to # build its output tasks.wait_for_replication(self.replicas[0].ldap_connect()) # check that master is now an AD Trust agent assert self._ipa_replica_role_check( self.master.hostname, self.serverroles['ADTA'] ) # but not an AD Trust controller assert not self._ipa_replica_role_check( self.master.hostname, self.serverroles['ADTC'] ) self._check_rolecheck_backup_success(self.replicas[0]) self._check_rolecheck_backup_failure(self.master) # make master become Trust Controller self.master.run_command([ 'ipa-adtrust-install', '-U', '--netbios-name', 'IPA', '-a', self.master.config.admin_password, '--add-sids' ]) # wait for replication to propagate the change on # cn=adtrust agents,cn=sysaccounts,cn=etc,dc=ipa,dc=test # as the ipa server-role-find call is using this entry to # build its output tasks.wait_for_replication(self.master.ldap_connect()) # master and replicas[0] are both AD Trust Controllers now. for hostname in [self.master.hostname, self.replicas[0].hostname]: assert self._ipa_replica_role_check( hostname, self.serverroles['ADTC'] ) self._check_rolecheck_backup_success(self.master) self._check_rolecheck_backup_success(self.replicas[0]) # switch replicas[0] to hidden self.replicas[0].run_command([ 'ipa', 'server-state', self.replicas[0].hostname, '--state=hidden' ]) self._check_rolecheck_backup_success(self.master) self._check_rolecheck_backup_success(self.replicas[0])
45,316
Python
.py
954
36.399371
79
0.61054
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,583
test_sso.py
freeipa_freeipa/ipatests/test_integration/test_sso.py
from __future__ import absolute_import import pytest import textwrap from ipaplatform.osinfo import osinfo from ipatests.test_integration.base import IntegrationTest from ipatests.pytest_ipa.integration import tasks, create_keycloak from ipatests.pytest_ipa.integration import create_bridge user_code_script = textwrap.dedent(""" from selenium import webdriver from datetime import datetime from selenium.webdriver.firefox.options import Options from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC options = Options() options.headless = True driver = webdriver.Firefox(executable_path="/opt/geckodriver", options=options) verification_uri = "https://{hostname}:8443/auth/realms/master/account/#/" driver.get(verification_uri) try: element = WebDriverWait(driver, 90).until( EC.element_to_be_clickable((By.ID, "landingSignInButton"))) driver.find_element(By.ID, "landingSignInButton").click() element = WebDriverWait(driver, 90).until( EC.presence_of_element_located((By.ID, "kc-login"))) driver.find_element(By.ID, "username").send_keys("{username}") driver.find_element(By.ID, "password").send_keys("{password}") driver.find_element(By.ID, "kc-login").click() element = WebDriverWait(driver, 900).until( EC.text_to_be_present_in_element((By.ID, "landingLoggedInUser"), "{username_fl}")) assert driver.find_element(By.ID, "landingLoggedInUser").text \ == "{username_fl}" finally: now = datetime.now().strftime("%M-%S") driver.get_screenshot_as_file("/var/log/httpd/screenshot-%s.png" % now) driver.quit() """) def keycloak_login(host, username, password, username_fl=None): if username_fl is None: username_fl = username contents = user_code_script.format(hostname=host.hostname, username=username, password=password, username_fl=username_fl) try: host.put_file_contents("/tmp/keycloak_login.py", contents) tasks.run_repeatedly(host, ['python3', '/tmp/keycloak_login.py']) finally: host.run_command(["rm", "-f", "/tmp/keycloak_login.py"]) def keycloak_add_user(host, kcadm_pass, username, password=None): domain = host.domain.name kcadmin_sh = "/opt/keycloak/bin/kcadm.sh" kcadmin = [kcadmin_sh, "config", "credentials", "--server", f"https://{host.hostname}:8443/auth/", "--realm", "master", "--user", "admin", "--password", kcadm_pass] host.run_command(kcadmin) host.run_command([kcadmin_sh, "create", "users", "-r", "master", "-s", f"username={username}", "-s", f"email={username}@{domain}", "-s", "enabled=true"]) if password is not None: host.run_command([kcadmin_sh, "set-password", "-r", "master", "--username", "testuser1", "--new-password", password]) class TestSsoBridge(IntegrationTest): # Replicas used instead of clients due to memory requirements # for running Keycloak and Bridge servers num_replicas = 2 @classmethod def install(cls, mh): cls.keycloak = cls.replicas[0] cls.bridge = cls.replicas[1] tasks.install_master(cls.master, extra_args=['--no-dnssec-validation']) tasks.install_client(cls.master, cls.replicas[0], extra_args=["--mkhomedir"]) tasks.install_client(cls.master, cls.replicas[1], extra_args=["--mkhomedir"]) tasks.clear_sssd_cache(cls.master) tasks.clear_sssd_cache(cls.keycloak) tasks.clear_sssd_cache(cls.bridge) tasks.kinit_admin(cls.master) username = 'ipauser1' password = cls.keycloak.config.admin_password tasks.create_active_user(cls.master, username, password) create_keycloak.setup_keycloakserver(cls.keycloak) create_keycloak.setup_keycloak_client(cls.keycloak) create_bridge.setup_scim_server(cls.bridge) create_bridge.setup_keycloak_scim_plugin(cls.keycloak, cls.bridge.hostname) @classmethod def uninstall(cls, mh): tasks.uninstall_client(cls.keycloak) tasks.uninstall_client(cls.bridge) tasks.uninstall_master(cls.master) create_keycloak.uninstall_keycloak(cls.keycloak) create_bridge.uninstall_scim_server(cls.bridge) create_bridge.uninstall_scim_plugin(cls.keycloak) def test_sso_login_with_ipa_user(self): """ Test case to check authenticating to Keycloak as an IPA user """ username = 'ipauser1' username_fl = 'test user' password = self.keycloak.config.admin_password keycloak_login(self.keycloak, username, password, username_fl) @pytest.mark.xfail( osinfo.id == 'fedora', reason='freeipa ticket 9264', strict=True) def test_ipa_login_with_sso_user(self): """ Test case to authenticate via ssh to IPA client as Keycloak user with password set in IPA without using external IdP related: https://pagure.io/freeipa/issue/9250 """ username = "kcuser1" password = self.keycloak.config.admin_password keycloak_add_user(self.keycloak, password, username) tasks.set_user_password(self.master, username, password) tasks.run_ssh_cmd(to_host=self.master.external_hostname, username=username, auth_method="password", password=password)
5,817
Python
.py
123
37.96748
79
0.646634
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,584
base.py
freeipa_freeipa/ipatests/test_integration/base.py
# Authors: # Petr Viktorin <pviktori@redhat.com> # # Copyright (C) 2013 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """Base class for FreeIPA integration tests""" import pytest import subprocess from ipatests.pytest_ipa.integration import tasks from pytest_sourceorder import ordered @ordered @pytest.mark.usefixtures('mh') @pytest.mark.usefixtures('integration_logs') class IntegrationTest: num_replicas = 0 num_clients = 0 num_ad_domains = 0 num_ad_subdomains = 0 num_ad_treedomains = 0 required_extra_roles = [] topology = None domain_level = None fips_mode = None random_serial = False token_password = None @classmethod def host_by_role(cls, role): for domain in cls.get_domains(): try: return domain.host_by_role(role) except LookupError: pass raise LookupError(role) @classmethod def get_all_hosts(cls): return ([cls.master] + cls.replicas + cls.clients + [cls.host_by_role(r) for r in cls.required_extra_roles]) @classmethod def get_domains(cls): return [cls.domain] + cls.ad_domains @classmethod def enable_fips_mode(cls): for host in cls.get_all_hosts(): if not host.is_fips_mode: host.enable_userspace_fips() @classmethod def disable_fips_mode(cls): for host in cls.get_all_hosts(): if host.is_userspace_fips: host.disable_userspace_fips() @classmethod def install(cls, mh): extra_args = [] if cls.domain_level is not None: domain_level = cls.domain_level else: domain_level = cls.master.config.domain_level if cls.master.config.fips_mode: cls.fips_mode = True if cls.fips_mode: cls.enable_fips_mode() if cls.topology is None: return else: if cls.token_password: extra_args.extend(('--token-password', cls.token_password,)) tasks.install_topo(cls.topology, cls.master, cls.replicas, cls.clients, domain_level, random_serial=cls.random_serial, extra_args=extra_args,) @classmethod def uninstall(cls, mh): for replica in cls.replicas: try: tasks.run_server_del( cls.master, replica.hostname, force=True, ignore_topology_disconnect=True, ignore_last_of_role=True) except subprocess.CalledProcessError: # If the master has already been uninstalled, # this call may fail pass tasks.uninstall_master(replica) tasks.uninstall_master(cls.master) for client in cls.clients: tasks.uninstall_client(client) if cls.fips_mode: cls.disable_fips_mode()
3,671
Python
.py
101
27.772277
78
0.625527
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,585
test_vault.py
freeipa_freeipa/ipatests/test_integration/test_vault.py
# # Copyright (C) 2015 FreeIPA Contributors see COPYING for license # import time from ipatests.test_integration.base import IntegrationTest from ipatests.pytest_ipa.integration import tasks WAIT_AFTER_ARCHIVE = 45 # give some time to replication class TestInstallKRA(IntegrationTest): """ Test if vault feature behaves as expected, when KRA is installed or not installed on replica """ num_replicas = 1 topology = 'star' vault_password = "password" vault_data = "SSBsb3ZlIENJIHRlc3RzCg==" vault_user = "vault_user" vault_user_password = "vault_user_password" vault_name_master = "ci_test_vault_master" vault_name_master2 = "ci_test_vault_master2" vault_name_master3 = "ci_test_vault_master3" vault_name_replica_without_KRA = "ci_test_vault_replica_without_kra" shared_vault_name_replica_without_KRA = ("ci_test_shared" "_vault_replica_without_kra") vault_name_replica_with_KRA = "ci_test_vault_replica_with_kra" vault_name_replica_KRA_uninstalled = "ci_test_vault_replica_KRA_uninstalled" @classmethod def install(cls, mh): tasks.install_master(cls.master, setup_kra=True, random_serial=cls.random_serial) # do not install KRA on replica, it is part of test tasks.install_replica(cls.master, cls.replicas[0], setup_kra=False) def _retrieve_secret(self, vault_names=[]): # try to retrieve secret from vault on both master and replica for vault_name in vault_names: self.master.run_command([ "ipa", "vault-retrieve", vault_name, "--password", self.vault_password, ]) self.replicas[0].run_command([ "ipa", "vault-retrieve", vault_name, "--password", self.vault_password, ]) def test_create_and_retrieve_vault_master(self): # create vault self.master.run_command([ "ipa", "vault-add", self.vault_name_master, "--password", self.vault_password, "--type", "symmetric", ]) # archive secret self.master.run_command([ "ipa", "vault-archive", self.vault_name_master, "--password", self.vault_password, "--data", self.vault_data, ]) time.sleep(WAIT_AFTER_ARCHIVE) self._retrieve_secret([self.vault_name_master]) def test_create_and_retrieve_vault_replica_without_kra(self): # create vault self.replicas[0].run_command([ "ipa", "vault-add", self.vault_name_replica_without_KRA, "--password", self.vault_password, "--type", "symmetric", ]) # archive secret self.replicas[0].run_command([ "ipa", "vault-archive", self.vault_name_replica_without_KRA, "--password", self.vault_password, "--data", self.vault_data, ]) time.sleep(WAIT_AFTER_ARCHIVE) self._retrieve_secret([self.vault_name_replica_without_KRA]) def test_create_and_retrieve_shared_vault_replica_without_kra(self): # create vault self.replicas[0].run_command([ "ipa", "vault-add", self.shared_vault_name_replica_without_KRA, "--shared", "--type", "standard", ]) # archive secret self.replicas[0].run_command([ "ipa", "vault-archive", self.shared_vault_name_replica_without_KRA, "--shared", "--data", self.vault_data, ]) time.sleep(WAIT_AFTER_ARCHIVE) # add non-admin user self.replicas[0].run_command([ 'ipa', 'user-add', self.vault_user, '--first', self.vault_user, '--last', self.vault_user, '--password'], stdin_text=self.vault_user_password) # add it to vault self.replicas[0].run_command([ "ipa", "vault-add-member", self.shared_vault_name_replica_without_KRA, "--shared", "--users", self.vault_user, ]) self.replicas[0].run_command([ 'kdestroy', '-A']) user_kinit = "%s\n%s\n%s\n" % (self.vault_user_password, self.vault_user_password, self.vault_user_password) self.replicas[0].run_command([ 'kinit', self.vault_user], stdin_text=user_kinit) # TODO: possibly refactor with: # self._retrieve_secret([self.vault_name_replica_without_KRA]) self.replicas[0].run_command([ "ipa", "vault-retrieve", "--shared", self.shared_vault_name_replica_without_KRA, "--out=test.txt"]) self.replicas[0].run_command([ 'kdestroy', '-A']) tasks.kinit_admin(self.replicas[0]) def test_create_and_retrieve_vault_replica_with_kra(self): # install KRA on replica tasks.install_kra(self.replicas[0], first_instance=False) # create vault self.replicas[0].run_command([ "ipa", "vault-add", self.vault_name_replica_with_KRA, "--password", self.vault_password, "--type", "symmetric", ]) # archive secret self.replicas[0].run_command([ "ipa", "vault-archive", self.vault_name_replica_with_KRA, "--password", self.vault_password, "--data", self.vault_data, ]) time.sleep(WAIT_AFTER_ARCHIVE) self._retrieve_secret([self.vault_name_replica_with_KRA]) # ################ master ################# # test master again after KRA was installed on replica # create vault self.master.run_command([ "ipa", "vault-add", self.vault_name_master2, "--password", self.vault_password, "--type", "symmetric", ]) # archive secret self.master.run_command([ "ipa", "vault-archive", self.vault_name_master2, "--password", self.vault_password, "--data", self.vault_data, ]) time.sleep(WAIT_AFTER_ARCHIVE) self._retrieve_secret([self.vault_name_master2]) # ############### old vaults ############### # test if old vaults are still accessible self._retrieve_secret([ self.vault_name_master, self.vault_name_replica_without_KRA, ])
6,717
Python
.py
171
28.426901
80
0.55914
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,586
test_dnssec.py
freeipa_freeipa/ipatests/test_integration/test_dnssec.py
# # Copyright (C) 2015 FreeIPA Contributors see COPYING for license # from __future__ import absolute_import import base64 import logging import re import subprocess import time import textwrap import dns.dnssec import dns.name import pytest import yaml from ipatests.test_integration.base import IntegrationTest from ipatests.pytest_ipa.integration import tasks from ipatests.pytest_ipa.integration.firewall import Firewall from ipaplatform.tasks import tasks as platform_tasks from ipaplatform.paths import paths from ipapython.dnsutil import DNSResolver logger = logging.getLogger(__name__) # Sleep 5 seconds at most when waiting for LDAP updates # for DNSSEC changes. Test zones should be updated with 1 second TTL DNSSEC_SLEEP = 5 test_zone = "dnssec.test." test_zone_repl = "dnssec-replica.test." root_zone = "." example_test_zone = "example.test." example2_test_zone = "example2.test." example3_test_zone = "example3.test." def resolve_with_dnssec(nameserver, query, rtype="SOA"): res = DNSResolver() res.nameservers = [nameserver] res.lifetime = 10 # wait max 10 seconds for reply # enable Authenticated Data + Checking Disabled flags res.set_flags(dns.flags.AD | dns.flags.CD) # enable EDNS v0 + enable DNSSEC-Ok flag res.use_edns(0, dns.flags.DO, 0) ans = res.resolve(query, rtype) return ans def get_RRSIG_record(nameserver, query, rtype="SOA"): ans = resolve_with_dnssec(nameserver, query, rtype=rtype) return ans.response.find_rrset( ans.response.answer, dns.name.from_text(query), dns.rdataclass.IN, dns.rdatatype.RRSIG, dns.rdatatype.from_text(rtype)) def is_record_signed(nameserver, query, rtype="SOA"): try: get_RRSIG_record(nameserver, query, rtype=rtype) except KeyError: return False except dns.exception.DNSException: return False return True def wait_until_record_is_signed(nameserver, record, rtype="SOA", timeout=100): """ Returns True if record is signed, or False on timeout :param nameserver: nameserver to query :param record: query :param rtype: record type :param timeout: :return: True if records is signed, False if timeout """ logger.info("Waiting for signed %s record of %s from server %s (timeout " "%s sec)", rtype, record, nameserver, timeout) wait_until = time.time() + timeout while time.time() < wait_until: if is_record_signed(nameserver, record, rtype=rtype): return True time.sleep(1) return False def dnskey_rec_with_ksk_and_zsk(nameserver, query): """ Returns true if the DNSKEY record contains 2 types of keys, KSK and ZSK :param nameserver: nameserver to query :param record: query :return: True if the DNSKEY records contains a ZSK and a KSK """ ksk = False zsk = False ans = resolve_with_dnssec(nameserver, query, rtype="DNSKEY") dnskey_rrset = ans.response.get_rrset( ans.response.answer, dns.name.from_text(query), dns.rdataclass.IN, dns.rdatatype.DNSKEY) assert dnskey_rrset, "No DNSKEY records received" for key_rdata in dnskey_rrset: if key_rdata.flags == 257: ksk = True elif key_rdata.flags == 256: zsk = True return (ksk and zsk) def dnszone_add_dnssec(host, test_zone): """Add dnszone with dnssec and short TTL """ args = [ "ipa", "dnszone-add", test_zone, "--skip-overlap-check", "--dnssec", "true", "--ttl", "1", "--default-ttl", "1", ] return host.run_command(args) def dnssec_install_master(host): args = [ "ipa-dns-install", "--dnssec-master", "--forwarder", host.config.dns_forwarder, "-U", ] return host.run_command(args) class TestInstallDNSSECLast(IntegrationTest): """Simple DNSSEC test Install a server and a replica with DNS, then reinstall server as DNSSEC master """ num_replicas = 1 topology = 'star' @classmethod def install(cls, mh): tasks.install_master(cls.master, setup_dns=True) tasks.install_replica(cls.master, cls.replicas[0], setup_dns=True) def test_install_dnssec_master(self): """Both master and replica have DNS installed""" dnssec_install_master(self.master) def test_if_zone_is_signed_master(self): # add zone with enabled DNSSEC signing on master dnszone_add_dnssec(self.master, test_zone) # test master assert wait_until_record_is_signed( self.master.ip, test_zone, timeout=100 ), "Zone %s is not signed (master)" % test_zone # test replica assert wait_until_record_is_signed( self.replicas[0].ip, test_zone, timeout=200 ), "DNS zone %s is not signed (replica)" % test_zone def test_if_zone_is_signed_replica(self): # add zone with enabled DNSSEC signing on replica dnszone_add_dnssec(self.replicas[0], test_zone_repl) # test replica assert wait_until_record_is_signed( self.replicas[0].ip, test_zone_repl, timeout=300 ), "Zone %s is not signed (replica)" % test_zone_repl # we do not need to wait, on master zones should be singed faster # than on replicas assert wait_until_record_is_signed( self.master.ip, test_zone_repl, timeout=5 ), "DNS zone %s is not signed (master)" % test_zone def test_key_types(self): assert dnskey_rec_with_ksk_and_zsk(self.master.ip, test_zone) assert dnskey_rec_with_ksk_and_zsk(self.replicas[0].ip, test_zone) assert dnskey_rec_with_ksk_and_zsk(self.master.ip, test_zone_repl) assert dnskey_rec_with_ksk_and_zsk(self.replicas[0].ip, test_zone_repl) def test_disable_reenable_signing_master(self): dnskey_old = resolve_with_dnssec(self.master.ip, test_zone, rtype="DNSKEY").rrset # disable DNSSEC signing of zone on master args = [ "ipa", "dnszone-mod", test_zone, "--dnssec", "false", ] self.master.run_command(args) time.sleep(DNSSEC_SLEEP) # test master assert not is_record_signed( self.master.ip, test_zone ), "Zone %s is still signed (master)" % test_zone # test replica assert not is_record_signed( self.replicas[0].ip, test_zone ), "DNS zone %s is still signed (replica)" % test_zone # reenable DNSSEC signing args = [ "ipa", "dnszone-mod", test_zone, "--dnssec", "true", ] self.master.run_command(args) # TODO: test require restart tasks.restart_named(self.master, self.replicas[0]) # test master assert wait_until_record_is_signed( self.master.ip, test_zone, timeout=100 ), "Zone %s is not signed (master)" % test_zone # test replica assert wait_until_record_is_signed( self.replicas[0].ip, test_zone, timeout=200 ), "DNS zone %s is not signed (replica)" % test_zone dnskey_new = resolve_with_dnssec(self.master.ip, test_zone, rtype="DNSKEY").rrset assert dnskey_old != dnskey_new, "DNSKEY should be different" def test_disable_reenable_signing_replica(self): dnskey_old = resolve_with_dnssec(self.replicas[0].ip, test_zone_repl, rtype="DNSKEY").rrset # disable DNSSEC signing of zone on replica args = [ "ipa", "dnszone-mod", test_zone_repl, "--dnssec", "false", ] self.master.run_command(args) time.sleep(DNSSEC_SLEEP) # test master assert not is_record_signed( self.master.ip, test_zone_repl ), "Zone %s is still signed (master)" % test_zone_repl # test replica assert not is_record_signed( self.replicas[0].ip, test_zone_repl ), "DNS zone %s is still signed (replica)" % test_zone_repl # reenable DNSSEC signing args = [ "ipa", "dnszone-mod", test_zone_repl, "--dnssec", "true", ] self.master.run_command(args) # TODO: test require restart tasks.restart_named(self.master, self.replicas[0]) # test master assert wait_until_record_is_signed( self.master.ip, test_zone_repl, timeout=100 ), "Zone %s is not signed (master)" % test_zone_repl # test replica assert wait_until_record_is_signed( self.replicas[0].ip, test_zone_repl, timeout=200 ), "DNS zone %s is not signed (replica)" % test_zone_repl dnskey_new = resolve_with_dnssec(self.replicas[0].ip, test_zone_repl, rtype="DNSKEY").rrset assert dnskey_old != dnskey_new, "DNSKEY should be different" class TestInstallDNSSECFirst(IntegrationTest): """Simple DNSSEC test Install the server with DNSSEC and then install the replica with DNS """ num_replicas = 1 topology = 'star' @classmethod def install(cls, mh): tasks.install_master(cls.master, setup_dns=False) args = [ "ipa-dns-install", "--dnssec-master", "--forwarder", cls.master.config.dns_forwarder, "-U", ] cls.master.run_command(args) # Enable dns service on master as it has been installed without dns # support before Firewall(cls.master).enable_services(["dns"]) tasks.install_replica(cls.master, cls.replicas[0], setup_dns=True, nameservers=None) # backup trusted key tasks.backup_file(cls.master, paths.DNSSEC_TRUSTED_KEY) tasks.backup_file(cls.replicas[0], paths.DNSSEC_TRUSTED_KEY) @classmethod def uninstall(cls, mh): # restore trusted key tasks.restore_files(cls.master) tasks.restore_files(cls.replicas[0]) super(TestInstallDNSSECFirst, cls).uninstall(mh) def test_sign_root_zone(self): dnszone_add_dnssec(self.master, root_zone) # make BIND happy: add the glue record and delegate zone args = [ "ipa", "dnsrecord-add", root_zone, self.master.hostname, "--a-rec=" + self.master.ip ] self.master.run_command(args) args = [ "ipa", "dnsrecord-add", root_zone, self.replicas[0].hostname, "--a-rec=" + self.replicas[0].ip ] self.master.run_command(args) time.sleep(DNSSEC_SLEEP) args = [ "ipa", "dnsrecord-add", root_zone, self.master.domain.name, "--ns-rec=" + self.master.hostname ] self.master.run_command(args) # test master assert wait_until_record_is_signed( self.master.ip, root_zone, timeout=100 ), "Zone %s is not signed (master)" % root_zone # test replica assert wait_until_record_is_signed( self.replicas[0].ip, root_zone, timeout=300 ), "Zone %s is not signed (replica)" % root_zone def test_delegation(self): dnszone_add_dnssec(self.master, example_test_zone) # delegation args = [ "ipa", "dnsrecord-add", root_zone, example_test_zone, "--ns-rec=" + self.master.hostname ] self.master.run_command(args) # TODO: test require restart tasks.restart_named(self.master, self.replicas[0]) # wait until zone is signed assert wait_until_record_is_signed( self.master.ip, example_test_zone, timeout=100 ), "Zone %s is not signed (master)" % example_test_zone # wait until zone is signed assert wait_until_record_is_signed( self.replicas[0].ip, example_test_zone, timeout=200 ), "Zone %s is not signed (replica)" % example_test_zone # GET DNSKEY records from zone ans = resolve_with_dnssec(self.master.ip, example_test_zone, rtype="DNSKEY") dnskey_rrset = ans.response.get_rrset( ans.response.answer, dns.name.from_text(example_test_zone), dns.rdataclass.IN, dns.rdatatype.DNSKEY) assert dnskey_rrset, "No DNSKEY records received" logger.debug("DNSKEY records returned: %s", dnskey_rrset.to_text()) # generate DS records ds_records = [] for key_rdata in dnskey_rrset: if key_rdata.flags != 257: continue # it is not KSK ds_records.append(dns.dnssec.make_ds(example_test_zone, key_rdata, 'sha256')) assert ds_records, ("No KSK returned from the %s zone" % example_test_zone) logger.debug("DS records for %s created: %r", example_test_zone, ds_records) # add DS records to root zone args = [ "ipa", "dnsrecord-add", root_zone, example_test_zone, # DS record requires to coexists with NS "--ns-rec", self.master.hostname, ] for ds in ds_records: args.append("--ds-rec") args.append(ds.to_text()) self.master.run_command(args) # wait until DS records it replicated assert wait_until_record_is_signed( self.replicas[0].ip, example_test_zone, timeout=100, rtype="DS" ), "No DS record of '%s' returned from replica" % example_test_zone def test_chain_of_trust_drill(self): """ Validate signed DNS records, using our own signed root zone """ # extract DSKEY from root zone ans = resolve_with_dnssec(self.master.ip, root_zone, rtype="DNSKEY") dnskey_rrset = ans.response.get_rrset(ans.response.answer, dns.name.from_text(root_zone), dns.rdataclass.IN, dns.rdatatype.DNSKEY) assert dnskey_rrset, "No DNSKEY records received" logger.debug("DNSKEY records returned: %s", dnskey_rrset.to_text()) # export trust keys for root zone root_key_rdatas = [] for key_rdata in dnskey_rrset: if key_rdata.flags != 257: continue # it is not KSK root_key_rdatas.append(key_rdata) assert root_key_rdatas, "No KSK returned from the root zone" root_keys_rrset = dns.rrset.from_rdata_list(dnskey_rrset.name, dnskey_rrset.ttl, root_key_rdatas) logger.debug("Root zone trusted key: %s", root_keys_rrset.to_text()) # set trusted key for our root zone self.master.put_file_contents(paths.DNSSEC_TRUSTED_KEY, root_keys_rrset.to_text() + '\n') self.replicas[0].put_file_contents(paths.DNSSEC_TRUSTED_KEY, root_keys_rrset.to_text() + '\n') # verify signatures time.sleep(DNSSEC_SLEEP) args = [ "drill", "@localhost", "-k", paths.DNSSEC_TRUSTED_KEY, "-S", example_test_zone, "SOA" ] # test if signature chains are valid self.master.run_command(args) self.replicas[0].run_command(args) def test_chain_of_trust_delv(self): """ Validate signed DNS records, using our own signed root zone """ INITIAL_KEY_FMT = '%s initial-key %d %d %d "%s";' # delv reports its version on stderr delv_version = self.master.run_command( ["delv", "-v"] ).stderr_text.rstrip().replace("delv ", "") assert delv_version delv_version_parsed = platform_tasks.parse_ipa_version(delv_version) if delv_version_parsed < platform_tasks.parse_ipa_version("9.16"): pytest.skip( f"Requires delv >= 9.16(+yaml), installed: '{delv_version}'" ) # extract DSKEY from root zone ans = resolve_with_dnssec( self.master.ip, root_zone, rtype="DNSKEY" ) dnskey_rrset = ans.response.get_rrset( ans.response.answer, dns.name.from_text(root_zone), dns.rdataclass.IN, dns.rdatatype.DNSKEY, ) assert dnskey_rrset, "No DNSKEY records received" # export trust keys for root zone initial_keys = [] for key_rdata in dnskey_rrset: if key_rdata.flags != 257: continue # it is not KSK initial_keys.append( INITIAL_KEY_FMT % ( root_zone, key_rdata.flags, key_rdata.protocol, key_rdata.algorithm, base64.b64encode(key_rdata.key).decode("utf-8"), ) ) assert initial_keys, "No KSK returned from the root zone" trust_anchors = textwrap.dedent( """\ trust-anchors {{ {initial_key} }}; """ ).format(initial_key="\n".join(initial_keys)) logger.debug("Root zone trust-anchors: %s", trust_anchors) # set trusted anchor for our root zone for host in [self.master, self.replicas[0]]: host.put_file_contents(paths.DNSSEC_TRUSTED_KEY, trust_anchors) # verify signatures args = [ "delv", "+yaml", "+nosplit", "+vtrace", "@127.0.0.1", example_test_zone, "-a", paths.DNSSEC_TRUSTED_KEY, "SOA", ] # delv puts trace info on stderr for host in [self.master, self.replicas[0]]: result = host.run_command(args) yaml_data = yaml.safe_load(result.stdout_text) query_name_abs = dns.name.from_text(example_test_zone) root_zone_name = dns.name.from_text(root_zone) query_name_rel = query_name_abs.relativize( root_zone_name ).to_text() assert yaml_data["query_name"] == query_name_rel assert yaml_data["status"] == "success" assert len(yaml_data["records"]) == 1 fully_validated = yaml_data["records"][0]["fully_validated"] fully_validated.sort() assert len(fully_validated) == 2 assert f"{example_test_zone} 1 IN RRSIG SOA" in fully_validated[0] assert f"{example_test_zone} 1 IN SOA" in fully_validated[1] def test_servers_use_localhost_as_dns(self): # check that localhost is set as DNS server for host in [self.master, self.replicas[0]]: assert host.resolver.uses_localhost_as_dns() class TestMigrateDNSSECMaster(IntegrationTest): """test DNSSEC master migration Install a server and a replica with DNS, then reinstall server as DNSSEC master Test: * migrate dnssec master to replica * create new zone * verify if zone is signed on all replicas * add new replica * add new zone * test if new zone is signed on all replicas """ num_replicas = 2 topology = 'star' @classmethod def install(cls, mh): tasks.install_master(cls.master, setup_dns=True) args = [ "ipa-dns-install", "--dnssec-master", "--forwarder", cls.master.config.dns_forwarder, "-U", ] cls.master.run_command(args) # No need to enable dns service in the firewall as master has been # installed with dns support enabled # Firewall(cls.master).enable_services(["dns"]) tasks.install_replica(cls.master, cls.replicas[0], setup_dns=True) @classmethod def uninstall(cls, mh): # For this test, we need to uninstall DNSSEC master last # Find which server is DNSSec master result = cls.master.run_command(["ipa", "config-show"]).stdout_text matches = list(re.finditer('IPA DNSSec key master: (.*)', result)) if len(matches) == 1: # Found the DNSSec master dnssec_master_hostname = matches[0].group(1) for replica in cls.replicas + [cls.master]: if replica.hostname == dnssec_master_hostname: dnssec_master = replica else: # By default consider that the master is DNSSEC dnssec_master = cls.master for replica in cls.replicas + [cls.master]: if replica == dnssec_master: # Skip this one continue try: tasks.run_server_del( dnssec_master, replica.hostname, force=True, ignore_topology_disconnect=True, ignore_last_of_role=True) except subprocess.CalledProcessError: # If the master has already been uninstalled, # this call may fail pass tasks.uninstall_master(replica) tasks.uninstall_master(dnssec_master) def test_migrate_dnssec_master(self): """Both master and replica have DNS installed""" backup_filename = "/var/lib/ipa/ipa-kasp.db.backup" replica_backup_filename = "/tmp/ipa-kasp.db.backup" # add test zone dnszone_add_dnssec(self.master, example_test_zone) # wait until zone is signed assert wait_until_record_is_signed( self.master.ip, example_test_zone, timeout=100 ), "Zone %s is not signed (master)" % example_test_zone # wait until zone is signed assert wait_until_record_is_signed( self.replicas[0].ip, example_test_zone, timeout=200 ), "Zone %s is not signed (replica)" % example_test_zone dnskey_old = resolve_with_dnssec(self.master.ip, example_test_zone, rtype="DNSKEY").rrset # migrate dnssec master to replica args = [ "ipa-dns-install", "--disable-dnssec-master", "--forwarder", self.master.config.dns_forwarder, "--force", "-U", ] self.master.run_command(args) # move content of "ipa-kasp.db.backup" to replica kasp_db_backup = self.master.get_file_contents(backup_filename) self.replicas[0].put_file_contents(replica_backup_filename, kasp_db_backup) args = [ "ipa-dns-install", "--dnssec-master", "--kasp-db", replica_backup_filename, "--forwarder", self.master.config.dns_forwarder, "-U", ] self.replicas[0].run_command(args) # Enable the dns service in the firewall on the replica Firewall(self.replicas[0]).enable_services(["dns"]) # wait until zone is signed assert wait_until_record_is_signed( self.master.ip, example_test_zone, timeout=100 ), "Zone %s is not signed after migration (master)" % example_test_zone # wait until zone is signed assert wait_until_record_is_signed( self.replicas[0].ip, example_test_zone, timeout=200 ), "Zone %s is not signed after migration (replica)" % example_test_zone # test if dnskey are the same dnskey_new = resolve_with_dnssec(self.master.ip, example_test_zone, rtype="DNSKEY").rrset assert dnskey_old == dnskey_new, "DNSKEY should be the same" # add test zone dnszone_add_dnssec(self.replicas[0], example2_test_zone) # wait until zone is signed assert wait_until_record_is_signed( self.replicas[0].ip, example2_test_zone, timeout=100 ), ("Zone %s is not signed after migration (replica - dnssec master)" % example2_test_zone) # wait until zone is signed assert wait_until_record_is_signed( self.master.ip, example2_test_zone, timeout=200 ), ("Zone %s is not signed after migration (master)" % example2_test_zone) # add new replica tasks.install_replica(self.master, self.replicas[1], setup_dns=True) # test if originial zones are signed on new replica # wait until zone is signed assert wait_until_record_is_signed( self.replicas[1].ip, example_test_zone, timeout=200 ), ("Zone %s is not signed (new replica)" % example_test_zone) # wait until zone is signed assert wait_until_record_is_signed( self.replicas[1].ip, example2_test_zone, timeout=200 ), ("Zone %s is not signed (new replica)" % example2_test_zone) # add new zone to new replica dnszone_add_dnssec(self.replicas[0], example3_test_zone) # wait until zone is signed assert wait_until_record_is_signed( self.replicas[1].ip, example3_test_zone, timeout=200 ), ("Zone %s is not signed (new replica)" % example3_test_zone) assert wait_until_record_is_signed( self.replicas[0].ip, example3_test_zone, timeout=200 ), ("Zone %s is not signed (replica)" % example3_test_zone) # wait until zone is signed assert wait_until_record_is_signed( self.master.ip, example3_test_zone, timeout=200 ), ("Zone %s is not signed (master)" % example3_test_zone) class TestInstallNoDnssecValidation(IntegrationTest): """test installation of the master with --no-dnssec-validation Test for issue 7666: ipa-server-install --setup-dns is failing if using --no-dnssec-validation and --forwarder, when the specified forwarder does not support DNSSEC. The forwarder should not be checked for DNSSEC support when --no-dnssec-validation argument is specified. In order to reproduce the conditions, the test is using a dummy IP address for the forwarder (i.e. there is no BIND service available at this IP address). To make sure of that, the test is using the IP of a replica (that is not yet setup). """ num_replicas = 1 @classmethod def install(cls, mh): cls.install_args = [ 'ipa-server-install', '-n', cls.master.domain.name, '-r', cls.master.domain.realm, '-p', cls.master.config.dirman_password, '-a', cls.master.config.admin_password, '-U', '--setup-dns', '--forwarder', cls.replicas[0].ip, '--auto-reverse' ] def test_install_withDnssecValidation(self): cmd = self.master.run_command(self.install_args, raiseonerr=False) # The installer checks that the forwarder supports DNSSEC # but the forwarder does not answer => expect failure assert cmd.returncode != 0 def test_install_noDnssecValidation(self): # With the --no-dnssec-validation, the installer does not check # whether the forwarder supports DNSSEC => success even if the # forwarder is not reachable self.master.run_command( self.install_args + ['--no-dnssec-validation'])
27,737
Python
.py
656
31.977134
80
0.597352
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,587
test_replica_promotion.py
freeipa_freeipa/ipatests/test_integration/test_replica_promotion.py
# # Copyright (C) 2016 FreeIPA Contributors see COPYING for license # from __future__ import absolute_import import os import time import re import textwrap import pytest from ipatests.test_integration.base import IntegrationTest from ipatests.test_integration.test_ipahealthcheck import ( run_healthcheck, set_excludes, HEALTHCHECK_PKG ) from ipatests.pytest_ipa.integration import tasks from ipatests.pytest_ipa.integration.tasks import ( assert_error, replicas_cleanup ) from ipatests.pytest_ipa.integration.firewall import Firewall from ipatests.pytest_ipa.integration.env_config import get_global_config from ipalib.constants import ( DOMAIN_LEVEL_1, IPA_CA_NICKNAME, CA_SUFFIX_NAME ) from ipaplatform.paths import paths from ipapython import certdb from ipatests.test_integration.test_cert import get_certmonger_fs_id from ipatests.test_integration.test_dns_locations import ( resolve_records_from_server, IPA_DEFAULT_MASTER_SRV_REC ) from ipapython.dnsutil import DNSName from ipalib.constants import IPA_CA_RECORD from ipatests.util import xfail_context config = get_global_config() class ReplicaPromotionBase(IntegrationTest): @classmethod def install(cls, mh): tasks.install_master(cls.master, domain_level=cls.domain_level) def test_kra_install_master(self): result1 = tasks.install_kra(self.master, first_instance=True, raiseonerr=False) assert result1.returncode == 0, result1.stderr_text tasks.kinit_admin(self.master) result2 = self.master.run_command(["ipa", "vault-find"], raiseonerr=False) found = result2.stdout_text.find("0 vaults matched") assert(found > 0), result2.stdout_text def sssd_config_allows_ipaapi_access_to_ifp(host): """Checks that the sssd configuration allows the ipaapi user to access ifp :param host the machine on which to check that sssd allows ipaapi access to ifp """ with tasks.remote_sssd_config(host) as sssd_conf: ifp = sssd_conf.get_service('ifp') uids = [ uid.strip() for uid in ifp.get_option('allowed_uids').split(',') ] assert 'ipaapi' in uids class TestReplicaPromotionLevel1(ReplicaPromotionBase): """ TestCase: http://www.freeipa.org/page/V4/Replica_Promotion/Test_plan# Test_case:_Make_sure_the_old_workflow_is_disabled_at_domain_level_1 """ topology = 'star' num_replicas = 1 domain_level = DOMAIN_LEVEL_1 @replicas_cleanup def test_one_step_install_pwd_and_admin_pwd(self): """--password and --admin-password options are mutually exclusive Test for ticket 6353 """ # Configure firewall first Firewall(self.replicas[0]).enable_services(["freeipa-ldap", "freeipa-ldaps"]) expected_err = "--password and --admin-password options are " \ "mutually exclusive" result = self.replicas[0].run_command([ 'ipa-replica-install', '-w', self.master.config.admin_password, '-p', 'OTPpwd', '-n', self.master.domain.name, '-r', self.master.domain.realm, '--server', self.master.hostname, '-U'], raiseonerr=False) assert result.returncode == 1 assert expected_err in result.stderr_text @replicas_cleanup def test_install_with_host_auth_ind_set(self): """ A client shouldn't be able to be promoted if it has any auth indicator set in the host principal. https://pagure.io/freeipa/issue/8206 """ client = self.replicas[0] # Configure firewall first Firewall(client).enable_services(["freeipa-ldap", "freeipa-ldaps"]) client.run_command(['ipa-client-install', '-U', '--domain', self.master.domain.name, '--realm', self.master.domain.realm, '-p', 'admin', '-w', self.master.config.admin_password, '--server', self.master.hostname, '--force-join']) tasks.kinit_admin(client) client.run_command(['ipa', 'host-mod', '--auth-ind=otp', client.hostname]) res = client.run_command(['ipa-replica-install', '-U', '-w', self.master.config.dirman_password], raiseonerr=False) client.run_command(['ipa', 'host-mod', '--auth-ind=', client.hostname]) expected_err = ("Client cannot be promoted to a replica if the host " "principal has an authentication indicator set.") assert res.returncode == 1 assert expected_err in res.stderr_text @replicas_cleanup def test_one_command_installation(self): """ TestCase: http://www.freeipa.org/page/V4/Replica_Promotion/Test_plan #Test_case:_Replica_can_be_installed_using_one_command """ # Configure firewall first Firewall(self.replicas[0]).enable_services(["freeipa-ldap", "freeipa-ldaps"]) self.replicas[0].run_command(['ipa-replica-install', '-w', self.master.config.admin_password, '-n', self.master.domain.name, '-r', self.master.domain.realm, '--server', self.master.hostname, '-U']) # Ensure that pkinit is properly configured, test for 7566 result = self.replicas[0].run_command(['ipa-pkinit-manage', 'status']) assert "PKINIT is enabled" in result.stdout_text # Verify that the sssd configuration allows the ipaapi user to # access ifp sssd_config_allows_ipaapi_access_to_ifp(self.replicas[0]) class TestUnprivilegedUserPermissions(IntegrationTest): """ TestCase: http://www.freeipa.org/page/V4/Replica_Promotion/Test_plan #Test_case:_Unprivileged_users_are_not_allowed_to_enroll _and_promote_clients """ num_replicas = 1 domain_level = DOMAIN_LEVEL_1 @classmethod def install(cls, mh): cls.username = 'testuser' tasks.install_master(cls.master, domain_level=cls.domain_level) password = cls.master.config.dirman_password cls.new_password = '$ome0therPaaS' adduser_stdin_text = "%s\n%s\n" % (cls.master.config.admin_password, cls.master.config.admin_password) user_kinit_stdin_text = "%s\n%s\n%s\n" % (password, cls.new_password, cls.new_password) tasks.kinit_admin(cls.master) cls.master.run_command(['ipa', 'user-add', cls.username, '--password', '--first', 'John', '--last', 'Donn'], stdin_text=adduser_stdin_text) # Now we need to change the password for the user cls.master.run_command(['kinit', cls.username], stdin_text=user_kinit_stdin_text) # And again kinit admin tasks.kinit_admin(cls.master) def test_client_enrollment_by_unprivileged_user(self): replica = self.replicas[0] result1 = replica.run_command(['ipa-client-install', '-p', self.username, '-w', self.new_password, '--domain', replica.domain.name, '--realm', replica.domain.realm, '-U', '--server', self.master.hostname], raiseonerr=False) assert_error(result1, "No permission to join this host", 1) def test_replica_promotion_by_unprivileged_user(self): replica = self.replicas[0] tasks.install_client(self.master, replica) # Configure firewall first Firewall(replica).enable_services(["freeipa-ldap", "freeipa-ldaps"]) result2 = replica.run_command(['ipa-replica-install', '-P', self.username, '-p', self.new_password, '-n', self.master.domain.name, '-r', self.master.domain.realm], raiseonerr=False) assert_error(result2, "Insufficient privileges to promote the server", 1) def test_replica_promotion_after_adding_to_admin_group(self): self.master.run_command(['ipa', 'group-add-member', 'admins', '--users=%s' % self.username]) # Configure firewall first Firewall(self.replicas[0]).enable_services(["freeipa-ldap", "freeipa-ldaps"]) self.replicas[0].run_command(['ipa-replica-install', '-P', self.username, '-p', self.new_password, '-n', self.master.domain.name, '-r', self.master.domain.realm, '-U']) def test_sssd_config_allows_ipaapi_access_to_ifp(self): sssd_config_allows_ipaapi_access_to_ifp(self.replicas[0]) class TestProhibitReplicaUninstallation(IntegrationTest): topology = 'line' num_replicas = 2 domain_level = DOMAIN_LEVEL_1 def test_replica_uninstallation_prohibited(self): """ http://www.freeipa.org/page/V4/Replica_Promotion/Test_plan #Test_case:_Prohibit_ipa_server_uninstallation_from_disconnecting _topology_segment """ result = self.replicas[0].run_command(['ipa-server-install', '--uninstall', '-U'], raiseonerr=False) assert_error(result, "Removal of '%s' leads to disconnected" " topology" % self.replicas[0].hostname, 1) self.replicas[0].run_command(['ipa-server-install', '--uninstall', '-U', '--ignore-topology-disconnect']) Firewall(self.replicas[0]).disable_services(["freeipa-ldap", "freeipa-ldaps"]) class TestWrongClientDomain(IntegrationTest): topology = "star" num_replicas = 1 domain_name = 'exxample.test' domain_level = DOMAIN_LEVEL_1 @classmethod def install(cls, mh): tasks.install_master(cls.master, domain_level=cls.domain_level) @pytest.fixture(autouse=True) def wrong_client_dom_setup(self, request): def fin(): if len(config.domains) == 0: # No YAML config was set return self.replicas[0].run_command(['ipa-client-install', '--uninstall', '-U'], raiseonerr=False) tasks.kinit_admin(self.master) self.master.run_command(['ipa', 'host-del', self.replicas[0].hostname], raiseonerr=False) request.addfinalizer(fin) def test_wrong_client_domain(self): client = self.replicas[0] client.run_command(['ipa-client-install', '-U', '--domain', self.domain_name, '--realm', self.master.domain.realm, '-p', 'admin', '-w', self.master.config.admin_password, '--server', self.master.hostname, '--force-join']) # Configure firewall first Firewall(client).enable_services(["freeipa-ldap", "freeipa-ldaps"]) result = client.run_command(['ipa-replica-install', '-U', '-w', self.master.config.dirman_password], raiseonerr=False) assert_error(result, "Cannot promote this client to a replica. Local domain " "'%s' does not match IPA domain " "'%s'" % (self.domain_name, self.master.domain.name)) def test_upcase_client_domain(self): client = self.replicas[0] result = client.run_command(['ipa-client-install', '-U', '--domain', self.master.domain.name.upper(), '-w', self.master.config.admin_password, '-p', 'admin', '--server', self.master.hostname, '--force-join'], raiseonerr=False) assert(result.returncode == 0), ( 'Failed to setup client with the upcase domain name') # Configure firewall first Firewall(self.replicas[0]).enable_services(["freeipa-ldap", "freeipa-ldaps"]) result1 = client.run_command(['ipa-replica-install', '-U', '-w', self.master.config.dirman_password], raiseonerr=False) assert (result1.returncode == 0), ( 'Failed to promote the client installed with the upcase domain name') def test_client_rollback(self): """Test that bogus error msgs are not in output on rollback. FIXME: including in this suite to avoid setting up a master just to test a client install failure. If a pure client install suite is added this can be moved. Ticket https://pagure.io/freeipa/issue/7729 """ client = self.replicas[0] # Cleanup previous run client.run_command(['ipa-server-install', '--uninstall', '-U'], raiseonerr=False) result = client.run_command(['ipa-client-install', '-U', '--server', self.master.hostname, '--domain', client.domain.name, '-w', 'foo'], raiseonerr=False) assert(result.returncode == 1) assert("Unconfigured automount client failed" not in result.stdout_text) assert("WARNING: Unable to revert" not in result.stdout_text) assert("An error occurred while removing SSSD" not in result.stdout_text) def test_hostname_domain_matching(self): client = self.replicas[0] client.run_command(['ipa-client-install', '-U', '--domain', self.master.domain.name, '-w', self.master.config.admin_password, '-p', 'admin', '--server', self.master.hostname, '--hostname', self.master.domain.name]) Firewall(self.replicas[0]).enable_services(["freeipa-ldap", "freeipa-ldaps"]) result = client.run_command(['ipa-replica-install', '-U', '-w', self.master.config.dirman_password], raiseonerr=False) assert result.returncode == 1 assert 'hostname cannot be the same as the domain name' \ in result.stderr_text class TestRenewalMaster(IntegrationTest): topology = 'star' num_replicas = 1 def assertCARenewalMaster(self, host, expected): """ Ensure there is only one CA renewal master set """ result = host.run_command(["ipa", "config-show"]).stdout_text matches = list(re.finditer('IPA CA renewal master: (.*)', result)) assert len(matches), 1 assert matches[0].group(1) == expected def test_replica_not_marked_as_renewal_master(self): """ https://fedorahosted.org/freeipa/ticket/5902 """ master = self.master replica = self.replicas[0] result = master.run_command(["ipa", "config-show"]).stdout_text assert("IPA CA renewal master: %s" % master.hostname in result), ( "Master hostname not found among CA renewal masters" ) assert("IPA CA renewal master: %s" % replica.hostname not in result), ( "Replica hostname found among CA renewal masters" ) def test_renewal_replica_with_ipa_ca_cert_manage(self): """Make replica as IPA CA renewal master using ipa-cacert-manage --renew""" master = self.master replica = self.replicas[0] self.assertCARenewalMaster(master, master.hostname) replica.run_command([paths.IPA_CACERT_MANAGE, 'renew']) self.assertCARenewalMaster(replica, replica.hostname) # set master back to ca-renewal-master master.run_command([paths.IPA_CACERT_MANAGE, 'renew']) self.assertCARenewalMaster(master, master.hostname) self.assertCARenewalMaster(replica, master.hostname) def test_manual_renewal_master_transfer(self): replica = self.replicas[0] replica.run_command(['ipa', 'config-mod', '--ca-renewal-master-server', replica.hostname]) result = self.master.run_command(["ipa", "config-show"]).stdout_text assert("IPA CA renewal master: %s" % replica.hostname in result), ( "Replica hostname not found among CA renewal masters" ) # additional check e.g. to see if there is only one renewal master self.assertCARenewalMaster(replica, replica.hostname) def test_renewal_master_with_csreplica_manage(self): master = self.master replica = self.replicas[0] self.assertCARenewalMaster(master, replica.hostname) self.assertCARenewalMaster(replica, replica.hostname) master.run_command(['ipa-csreplica-manage', 'set-renewal-master', '-p', master.config.dirman_password]) result = master.run_command(["ipa", "config-show"]).stdout_text assert("IPA CA renewal master: %s" % master.hostname in result), ( "Master hostname not found among CA renewal masters" ) # lets give replication some time time.sleep(60) self.assertCARenewalMaster(master, master.hostname) self.assertCARenewalMaster(replica, master.hostname) replica.run_command(['ipa-csreplica-manage', 'set-renewal-master', '-p', replica.config.dirman_password]) result = replica.run_command(["ipa", "config-show"]).stdout_text assert("IPA CA renewal master: %s" % replica.hostname in result), ( "Replica hostname not found among CA renewal masters" ) self.assertCARenewalMaster(master, replica.hostname) self.assertCARenewalMaster(replica, replica.hostname) def test_replica_concheck(self): """Test cases for ipa-replica-conncheck command Following test cases would be checked: - when called with --principal (it should then prompt for a password) - when called with --principal / --password - when called without principal and password but with a kerberos TGT, kinit admin done before calling ipa-replica-conncheck - when called without principal and password, and without any kerberos TGT (it should default to principal=admin and prompt for a password) related: https://pagure.io/freeipa/issue/9047 """ exp_str1 = "Connection from replica to master is OK." exp_str2 = "Connection from master to replica is OK" tasks.kdestroy_all(self.replicas[0]) # when called with --principal (it should then prompt for a password) result = self.replicas[0].run_command( ['ipa-replica-conncheck', '--auto-master-check', '--master', self.master.hostname, '-r', self.replicas[0].domain.realm, '-p', self.replicas[0].config.admin_name], stdin_text=self.master.config.admin_password ) assert result.returncode == 0 assert ( exp_str1 in result.stderr_text and exp_str2 in result.stderr_text ) # when called with --principal / --password result = self.replicas[0].run_command([ 'ipa-replica-conncheck', '--auto-master-check', '--master', self.master.hostname, '-r', self.replicas[0].domain.realm, '-p', self.replicas[0].config.admin_name, '-w', self.master.config.admin_password ]) assert result.returncode == 0 assert ( exp_str1 in result.stderr_text and exp_str2 in result.stderr_text ) # when called without principal and password, and without # any kerberos TGT, it should default to principal=admin # and prompt for a password result = self.replicas[0].run_command( ['ipa-replica-conncheck', '--auto-master-check', '--master', self.master.hostname, '-r', self.replicas[0].domain.realm], stdin_text=self.master.config.admin_password ) assert result.returncode == 0 assert ( exp_str1 in result.stderr_text and exp_str2 in result.stderr_text ) # when called without principal and password but with a kerberos TGT, # kinit admin done before calling ipa-replica-conncheck tasks.kinit_admin(self.replicas[0]) result = self.replicas[0].run_command( ['ipa-replica-conncheck', '--auto-master-check', '--master', self.master.hostname, '-r', self.replicas[0].domain.realm] ) assert result.returncode == 0 assert ( exp_str1 in result.stderr_text and exp_str2 in result.stderr_text ) tasks.kdestroy_all(self.replicas[0]) def test_automatic_renewal_master_transfer_ondelete(self): # Test that after replica uninstallation, master overtakes the cert # renewal master role from replica (which was previously set there) tasks.uninstall_replica(self.master, self.replicas[0]) result = self.master.run_command(['ipa', 'config-show']).stdout_text assert("IPA CA renewal master: %s" % self.master.hostname in result), ( "Master hostname not found among CA renewal masters" ) class TestReplicaInstallWithExistingEntry(IntegrationTest): """replica install might fail because of existing entry for replica like `cn=ipa-http-delegation,cn=s4u2proxy,cn=etc,$SUFFIX` etc. The situation may arise due to incorrect uninstall of replica. https://pagure.io/freeipa/issue/7174""" num_replicas = 1 def test_replica_install_with_existing_entry(self): master = self.master tasks.install_master(master) replica = self.replicas[0] base_dn = "dc=%s" % (",dc=".join(replica.domain.name.split("."))) # adding entry for replica on master so that master will have it before # replica installtion begins and creates a situation for pagure-7174 entry_ldif = textwrap.dedent(""" dn: cn=ipa-http-delegation,cn=s4u2proxy,cn=etc,{base_dn} changetype: modify add: memberPrincipal memberPrincipal: HTTP/{hostname}@{realm} dn: cn=ipa-ldap-delegation-targets,cn=s4u2proxy,cn=etc,{base_dn} changetype: modify add: memberPrincipal memberPrincipal: ldap/{hostname}@{realm}""").format( base_dn=base_dn, hostname=replica.hostname, realm=replica.domain.name.upper()) tasks.ldapmodify_dm(master, entry_ldif) tasks.install_replica(master, replica) AUTH_ID_RE = re.compile( 'Authority ID: ' '([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})' ) class TestSubCAkeyReplication(IntegrationTest): """ Test if subca key replication is not failing. """ topology = 'line' num_replicas = 1 SUBCA_DESC = 'subca' SUBCA_MASTER = 'test_subca_master' SUBCA_MASTER_CN = 'cn=' + SUBCA_MASTER SUBCA_REPLICA = 'test_subca_replica' SUBCA_REPLICA_CN = 'cn=' + SUBCA_REPLICA PKI_DEBUG_PATH = '/var/log/pki/pki-tomcat/ca/debug' ERR_MESS = 'Caught exception during cert/key import' SERVER_CERT_NICK = 'Server-Cert cert-pki-ca' SERVER_KEY_NICK = 'NSS Certificate DB:Server-Cert cert-pki-ca' SERVER_KEY_NICK_FIPS = ( 'NSS FIPS 140-2 Certificate DB:Server-Cert cert-pki-ca' ) EXPECTED_CERTS = { IPA_CA_NICKNAME: 'CTu,Cu,Cu', 'ocspSigningCert cert-pki-ca': 'u,u,u', 'subsystemCert cert-pki-ca': 'u,u,u', 'auditSigningCert cert-pki-ca': 'u,u,Pu', SERVER_CERT_NICK: 'u,u,u', } def add_subca(self, host, name, subject, raiseonerr=True): result = host.run_command([ 'ipa', 'ca-add', name, '--subject', subject, '--desc', self.SUBCA_DESC], raiseonerr=raiseonerr ) if raiseonerr: assert "ipa: ERROR:" not in result.stderr_text auth_id = "".join(re.findall(AUTH_ID_RE, result.stdout_text)) return '{} {}'.format(IPA_CA_NICKNAME, auth_id) else: assert "ipa: ERROR:" in result.stderr_text assert result.returncode != 0 return result def del_subca(self, host, name): host.run_command([ 'ipa', 'ca-disable', name ]) result = host.run_command([ 'ipa', 'ca-del', name ]) assert "Deleted CA \"{}\"".format(name) in result.stdout_text def check_subca(self, host, name, cert_nick): result = host.run_command(['ipa', 'ca-show', name]) # ipa ca-show returns 0 even if the cert cannot be found locally. if "ipa: ERROR:" in result.stderr_text: return False tasks.run_certutil( host, ['-L', '-n', cert_nick], paths.PKI_TOMCAT_ALIAS_DIR ) host.run_command([ paths.CERTUTIL, '-d', paths.PKI_TOMCAT_ALIAS_DIR, '-f', paths.PKI_TOMCAT_ALIAS_PWDFILE_TXT, '-K', '-n', cert_nick ]) return True def get_certinfo(self, host): result = tasks.run_certutil( host, ['-L', '-f', paths.PKI_TOMCAT_ALIAS_PWDFILE_TXT], paths.PKI_TOMCAT_ALIAS_DIR ) certs = {} for line in result.stdout_text.splitlines(): mo = certdb.CERT_RE.match(line) if mo: # Strip out any token nick = mo.group('nick') if ':' in nick: nick = nick.split(':', maxsplit=1)[1] certs[nick] = mo.group('flags') result = tasks.run_certutil( host, ['-K', '-f', paths.PKI_TOMCAT_ALIAS_PWDFILE_TXT], paths.PKI_TOMCAT_ALIAS_DIR ) keys = {} for line in result.stdout_text.splitlines(): mo = certdb.KEY_RE.match(line) if mo: # Strip out any token nick = mo.group('nick') if ':' in nick: nick = nick.split(':', maxsplit=1)[1] keys[nick] = mo.group('keyid') return certs, keys def check_certdb(self, master, replica): expected_certs = self.EXPECTED_CERTS.copy() # find and add sub CAs to expected certs result = master.run_command( ['ipa', 'ca-find', '--desc', self.SUBCA_DESC] ) for auth_id in re.findall(AUTH_ID_RE, result.stdout_text): nick = '{} {}'.format(IPA_CA_NICKNAME, auth_id) expected_certs[nick] = 'u,u,u' if master.is_fips_mode: # Mixed FIPS/non-FIPS installations are not supported assert replica.is_fips_mode expected_keys = set(expected_certs) # get certs and keys from Dogtag's NSSDB master_certs, master_keys = self.get_certinfo(master) replica_certs, replica_keys = self.get_certinfo(replica) assert master_certs == expected_certs assert replica_certs == expected_certs assert set(master_keys) == expected_keys assert set(replica_keys) == expected_keys # The Server-Cert keys are unique per-machine master_server_key = master_keys.pop('Server-Cert cert-pki-ca') replica_server_key = replica_keys.pop('Server-Cert cert-pki-ca') assert master_server_key != replica_server_key # but key ids of other keys are equal assert master_keys == replica_keys def check_pki_error(self, host): pki_log_filename = "{0}.{1}.log".format( self.PKI_DEBUG_PATH, time.strftime("%Y-%m-%d") ) pki_debug_log = host.get_file_contents( pki_log_filename, encoding='utf-8' ) # check for cert/key import error message assert self.ERR_MESS not in pki_debug_log def test_subca_master(self): master = self.master replica = self.replicas[0] master_nick = self.add_subca( master, self.SUBCA_MASTER, self.SUBCA_MASTER_CN ) # give replication some time, up to 60 seconds for _i in range(0,6): time.sleep(10) m = self.check_subca(master, self.SUBCA_MASTER, master_nick) r = self.check_subca(replica, self.SUBCA_MASTER, master_nick) if m and r: break else: assert m, "master doesn't have the subCA" assert r, "replica doesn't have the subCA" self.check_pki_error(replica) self.check_certdb(master, replica) def test_subca_replica(self): master = self.master replica = self.replicas[0] replica_nick = self.add_subca( replica, self.SUBCA_REPLICA, self.SUBCA_REPLICA_CN ) # give replication some time, up to 60 seconds for _i in range(0,6): time.sleep(10) r = self.check_subca(replica, self.SUBCA_REPLICA, replica_nick) m = self.check_subca(master, self.SUBCA_REPLICA, replica_nick) if m and r: break else: assert m, "master doesn't have the subCA" assert r, "replica doesn't have the subCA" # replica.run_command(['ipa-certupdate']) self.check_pki_error(master) self.check_certdb(master, replica) def test_sign_with_subca_on_replica(self): master = self.master replica = self.replicas[0] TEST_KEY_FILE = os.path.join( paths.OPENSSL_PRIVATE_DIR, 'test_subca.key' ) TEST_CRT_FILE = os.path.join( paths.OPENSSL_PRIVATE_DIR, 'test_subca.crt' ) caacl_cmd = [ 'ipa', 'caacl-add-ca', 'hosts_services_caIPAserviceCert', '--cas', self.SUBCA_MASTER ] master.run_command(caacl_cmd) request_cmd = [ paths.IPA_GETCERT, 'request', '-w', '-k', TEST_KEY_FILE, '-f', TEST_CRT_FILE, '-X', self.SUBCA_MASTER ] replica.run_command(request_cmd) status_cmd = [paths.IPA_GETCERT, 'status', '-v', '-f', TEST_CRT_FILE] status = replica.run_command(status_cmd) assert 'State MONITORING, stuck: no' in status.stdout_text ssl_cmd = ['openssl', 'x509', '-text', '-in', TEST_CRT_FILE, '-nameopt', 'space_eq'] ssl = replica.run_command(ssl_cmd) assert 'Issuer: CN = {}'.format(self.SUBCA_MASTER) in ssl.stdout_text def test_del_subca_master_on_replica(self): self.del_subca(self.replicas[0], self.SUBCA_MASTER) def test_del_subca_replica(self): self.del_subca(self.replicas[0], self.SUBCA_REPLICA) def test_scale_add_subca(self): master = self.master replica = self.replicas[0] subcas = {} for i in range(0, 16): name = "_".join((self.SUBCA_MASTER, str(i))) cn = "_".join((self.SUBCA_MASTER_CN, str(i))) subcas[name] = self.add_subca(master, name, cn) self.add_subca(master, name, cn, raiseonerr=False) # give replication some time time.sleep(15) for name, cert_nick in subcas.items(): self.check_subca(replica, name, cert_nick) self.del_subca(replica, name) class TestReplicaInstallCustodia(IntegrationTest): """ Pagure Reference: https://pagure.io/freeipa/issue/7518 """ topology = 'line' num_replicas = 2 domain_level = DOMAIN_LEVEL_1 @classmethod def install(cls, mh): tasks.install_master(cls.master, domain_level=cls.domain_level) def test_replica_install_for_custodia(self): master = self.master replica1 = self.replicas[0] replica2 = self.replicas[1] # Install Replica1 without CA and stop ipa-custodia tasks.install_replica(master, replica1, setup_ca=False) replica1.run_command(['ipactl', 'status']) replica1.run_command(['systemctl', 'stop', 'ipa-custodia']) replica1.run_command(['ipactl', 'status'], raiseonerr=False) # Install Replica2 with CA with source as Replica1. tasks.install_replica(replica1, replica2, setup_ca=True, nameservers='master') result = replica2.run_command(['ipactl', 'status']) assert 'ipa-custodia Service: RUNNING' in result.stdout_text def update_etc_hosts(host, ip, old_hostname, new_hostname): '''Adds or update /etc/hosts If /etc/hosts contains an entry for old_hostname, replace it with new_hostname. If /etc/hosts did not contain the entry, create one for new_hostname with the provided ip. The function makes a backup in /etc/hosts.sav :param host the machine on which /etc/hosts needs to be update_dns_records :param ip the ip address for the new record :param old_hostname the hostname to replace :param new_hostname the new hostname to put in /etc/hosts ''' # Make a backup host.run_command(['/bin/cp', paths.HOSTS, '%s.sav' % paths.HOSTS]) contents = host.get_file_contents(paths.HOSTS, encoding='utf-8') # If /etc/hosts already contains old_hostname, simply replace pattern = r'^(.*\s){}(\s)'.format(old_hostname) new_contents, mods = re.subn(pattern, r'\1{}\2'.format(new_hostname), contents, flags=re.MULTILINE) # If it didn't contain any entry for old_hostname, just add new_hostname if mods == 0: short = new_hostname.split(".", 1)[0] new_contents = new_contents + "\n{}\t{} {}\n".format(ip, new_hostname, short) host.put_file_contents(paths.HOSTS, new_contents) def restore_etc_hosts(host): '''Restores /etc/hosts.sav into /etc/hosts ''' host.run_command(['/bin/mv', '%s.sav' % paths.HOSTS, paths.HOSTS], raiseonerr=False) class TestReplicaInForwardZone(IntegrationTest): """ Pagure Reference: https://pagure.io/freeipa/issue/7369 Scenario: install a replica whose name is in a forwarded zone """ forwardzone = 'forward.test' num_replicas = 1 @classmethod def install(cls, mh): tasks.install_master(cls.master, setup_dns=True) def test_replica_install_in_forward_zone(self): master = self.master replica = self.replicas[0] # Create a forward zone on the master master.run_command(['ipa', 'dnsforwardzone-add', self.forwardzone, '--skip-overlap-check', '--forwarder', master.config.dns_forwarder]) # Configure the client with a name in the forwardzone r_shortname = replica.hostname.split(".", 1)[0] r_new_hostname = '{}.{}'.format(r_shortname, self.forwardzone) # Update /etc/hosts on the master with an entry for the replica # otherwise replica conncheck would fail update_etc_hosts(master, replica.ip, replica.hostname, r_new_hostname) # Remove the replica previous hostname from /etc/hosts # and add the replica new hostname # otherwise replica install will complain because # hostname does not match update_etc_hosts(replica, replica.ip, replica.hostname, r_new_hostname) try: # install client with a hostname in the forward zone tasks.install_client(self.master, replica, extra_args=['--hostname', r_new_hostname]) # Configure firewall first Firewall(replica).enable_services(["freeipa-ldap", "freeipa-ldaps"]) replica.run_command(['ipa-replica-install', '--principal', replica.config.admin_name, '--admin-password', replica.config.admin_password, '--setup-dns', '--forwarder', master.config.dns_forwarder, '-U']) finally: # Restore /etc/hosts on master and replica restore_etc_hosts(master) restore_etc_hosts(replica) class TestHiddenReplicaPromotion(IntegrationTest): """Test hidden replica features """ topology = None num_replicas = 2 @classmethod def install(cls, mh): for srv in (cls.master, cls.replicas[0]): tasks.install_packages(srv, HEALTHCHECK_PKG) # master with DNSSEC master tasks.install_master(cls.master, setup_dns=True, setup_kra=True) cls.master.run_command([ "ipa-dns-install", "--dnssec-master", "--forwarder", cls.master.config.dns_forwarder, "-U", ]) # hidden replica with CA and DNS tasks.install_replica( cls.master, cls.replicas[0], setup_dns=True, setup_kra=False, extra_args=('--hidden-replica',) ) # manually install KRA to verify that hidden state is synced tasks.install_kra(cls.replicas[0]) set_excludes(cls.master, "key", "DSCLE0004") set_excludes(cls.replicas[0], "key", "DSCLE0004") def _check_dnsrecords(self, hosts_expected, hosts_unexpected=()): domain = DNSName(self.master.domain.name).make_absolute() rset = [ (rname, 'SRV') for rname, _port in IPA_DEFAULT_MASTER_SRV_REC ] rset.append((DNSName(IPA_CA_RECORD), 'A')) for rname, rtype in rset: name_abs = rname.derelativize(domain) query = resolve_records_from_server( name_abs, rtype, self.master.ip ) if rtype == 'SRV': records = [q.target.to_text() for q in query] else: records = [q.address for q in query] for host in hosts_expected: value = host.hostname + "." if rtype == 'SRV' else host.ip assert value in records for host in hosts_unexpected: value = host.hostname + "." if rtype == 'SRV' else host.ip assert value not in records def _check_server_role(self, host, status, kra=True, dns=True): roles = [u'IPA master', u'CA server'] if kra: roles.append(u'KRA server') if dns: roles.append(u'DNS server') for role in roles: result = self.replicas[0].run_command([ 'ipa', 'server-role-find', '--server', host.hostname, '--role', role ]) expected = 'Role status: {}'.format(status) assert expected in result.stdout_text def _check_config(self, enabled=(), hidden=()): enabled = {host.hostname for host in enabled} hidden = {host.hostname for host in hidden} services = [ 'IPA masters', 'IPA CA servers', 'IPA KRA servers', 'IPA DNS servers' ] result = self.replicas[0].run_command(['ipa', 'config-show']) values = {} for line in result.stdout_text.split('\n'): if ':' not in line: continue k, v = line.split(':', 1) values[k.strip()] = {item.strip() for item in v.split(',')} for service in services: hservice = 'Hidden {}'.format(service) assert values.get(service, set()) == enabled assert values.get(hservice, set()) == hidden def test_hidden_replica_install(self): self._check_server_role(self.master, 'enabled') self._check_server_role(self.replicas[0], 'hidden') self._check_dnsrecords([self.master], [self.replicas[0]]) self._check_config([self.master], [self.replicas[0]]) def test_ipahealthcheck_hidden_replica(self): """Ensure that ipa-healthcheck runs successfully on all members of an IPA cluster that includes a hidden replica. """ os_version = (tasks.get_platform(self.master), tasks.get_platform_version(self.master)) pki_version = tasks.get_pki_version(self.master) # verify state self._check_config([self.master], [self.replicas[0]]) # A DNA range is needed on the replica for ipa-healthcheck to work. # Create a user so that the replica gets a range. tasks.user_add(self.replicas[0], 'testuser') tasks.user_del(self.replicas[0], 'testuser') for srv in (self.master, self.replicas[0]): returncode, _unused = run_healthcheck( srv, failures_only=True ) pki_too_old = \ (os_version[0] == 'fedora' and pki_version < tasks.parse_version('11.1.0'))\ or (os_version[0] == 'rhel' and os_version[1][0] == 8 and pki_version < tasks.parse_version('10.12.0'))\ or (os_version[0] == 'rhel' and os_version[1][0] == 9 and pki_version < tasks.parse_version('11.0.4')) with xfail_context(pki_too_old, 'https://pagure.io/freeipa/issue/8582'): assert returncode == 0 def test_hide_last_visible_server_fails(self): # verify state self._check_config([self.master], [self.replicas[0]]) # nothing to do result = self.master.run_command([ 'ipa', 'server-state', self.master.hostname, '--state=enabled' ], raiseonerr=False) assert result.returncode == 1 assert "no modifications to be performed" in result.stderr_text # hiding the last master fails result = self.master.run_command([ 'ipa', 'server-state', self.master.hostname, '--state=hidden' ], raiseonerr=False) assert result.returncode == 1 keys = [ "CA renewal master", "DNSSec key master", "CA server", "KRA server", "DNS server", "IPA server" ] for key in keys: assert key in result.stderr_text def test_hidden_replica_promote(self): self.replicas[0].run_command([ 'ipa', 'server-state', self.replicas[0].hostname, '--state=enabled' ]) self._check_server_role(self.replicas[0], 'enabled') tasks.wait_for_replication( self.replicas[0].ldap_connect() ) tasks.dns_update_system_records(self.master) tasks.wait_for_replication( self.master.ldap_connect() ) self._check_config([self.master, self.replicas[0]]) self._check_dnsrecords([self.master, self.replicas[0]]) def test_promote_twice_fails(self): result = self.replicas[0].run_command([ 'ipa', 'server-state', self.replicas[0].hostname, '--state=enabled' ], raiseonerr=False) assert result.returncode == 1 assert 'no modifications to be performed' in result.stderr_text def test_hidden_replica_demote(self): self.replicas[0].run_command([ 'ipa', 'server-state', self.replicas[0].hostname, '--state=hidden' ]) self._check_server_role(self.replicas[0], 'hidden') tasks.wait_for_replication( self.replicas[0].ldap_connect() ) tasks.dns_update_system_records(self.master) tasks.wait_for_replication( self.master.ldap_connect() ) self._check_config([self.master], [self.replicas[0]]) self._check_dnsrecords([self.master], [self.replicas[0]]) def test_replica_from_hidden(self): # install a replica from a hidden replica self._check_server_role(self.replicas[0], 'hidden') tasks.install_replica( master=self.replicas[0], replica=self.replicas[1], setup_dns=True ) self._check_server_role(self.replicas[0], 'hidden') self._check_server_role( self.replicas[1], 'enabled', kra=False, dns=False ) self._check_dnsrecords( [self.master, self.replicas[1]], [self.replicas[0]] ) # hide the new replica self.replicas[0].run_command([ 'ipa', 'server-state', self.replicas[1].hostname, '--state=hidden' ]) # and establish replication agreements from master tasks.connect_replica( master=self.master, replica=self.replicas[1], ) tasks.connect_replica( master=self.master, replica=self.replicas[1], database=CA_SUFFIX_NAME, ) # remove replication agreements again tasks.disconnect_replica( master=self.master, replica=self.replicas[1], ) tasks.disconnect_replica( master=self.master, replica=self.replicas[1], database=CA_SUFFIX_NAME, ) # and uninstall tasks.uninstall_replica( master=self.replicas[0], replica=self.replicas[1], ) def test_hidden_replica_backup_and_restore(self): """Exercises backup+restore and hidden replica uninstall """ self._check_server_role(self.replicas[0], 'hidden') # backup backup_path = tasks.get_backup_dir(self.replicas[0]) # uninstall tasks.uninstall_master(self.replicas[0]) # restore dirman_password = self.master.config.dirman_password self.replicas[0].run_command( ['ipa-restore', backup_path], stdin_text=dirman_password + '\nyes' ) tasks.kinit_admin(self.master) tasks.kinit_admin(self.replicas[0]) # restore turns a hidden replica into an enabled replica # https://pagure.io/freeipa/issue/7894 self._check_config([self.master, self.replicas[0]]) self._check_server_role(self.replicas[0], 'enabled') def test_hidden_replica_automatic_crl(self): """Exercises if automatic CRL configuration works with hidden replica. """ # Demoting Replica to be hidden. self.replicas[0].run_command([ 'ipa', 'server-state', self.replicas[0].hostname, '--state=hidden' ]) self._check_server_role(self.replicas[0], 'hidden') # check CRL status result = self.replicas[0].run_command([ 'ipa-crlgen-manage', 'status']) assert "CRL generation: disabled" in result.stdout_text # Enbable CRL status on hidden replica self.replicas[0].run_command([ 'ipa-crlgen-manage', 'enable']) # check CRL status result = self.replicas[0].run_command([ 'ipa-crlgen-manage', 'status']) assert "CRL generation: enabled" in result.stdout_text def test_hidden_replica_renew_pkinit_cert(self): """Renew the PKINIT cert on a hidden replica. Test for https://pagure.io/freeipa/issue/9611 """ # Get Request ID cmd = ['getcert', 'list', '-f', paths.KDC_CERT] result = self.replicas[0].run_command(cmd) req_id = get_certmonger_fs_id(result.stdout_text) self.replicas[0].run_command([ 'getcert', 'resubmit', '-f', paths.KDC_CERT ]) tasks.wait_for_certmonger_status( self.replicas[0], ('MONITORING'), req_id, timeout=600 ) class TestHiddenReplicaKRA(IntegrationTest): """Test KRA & hidden replica features. """ topology = 'star' num_replicas = 2 @classmethod def install(cls, mh): tasks.install_master(cls.master, setup_dns=True, setup_kra=False) # hidden replica with CA and DNS tasks.install_replica( cls.master, cls.replicas[0], setup_dns=True, setup_kra=False, extra_args=('--hidden-replica',) ) # normal replica with CA and DNS tasks.install_replica( cls.replicas[0], cls.replicas[1], setup_dns=True, setup_kra=False ) def test_install_kra_on_hidden_replica(self): # manually install KRA on hidden replica. tasks.install_kra(self.replicas[0]) @pytest.mark.xfail(reason='freeipa ticket 8240', strict=True) def test_kra_hidden_no_preconfig(self): """Test installing KRA on a replica when all KRAs are hidden. https://pagure.io/freeipa/issue/8240 """ result = tasks.install_kra(self.replicas[1], raiseonerr=False) if result.returncode == 0: # If KRA installation was successful, the only clean-up possible is # uninstalling the whole replica as hiding the last visible KRA # member is inhibited by design. # This step is necessary so that the next test runs with all KRA # members hidden too. tasks.uninstall_replica(self.master, self.replicas[1]) assert "Failed to find an active KRA server!" not in result.stderr_text assert result.returncode == 0 def test_kra_hidden_temp(self): """Test for workaround: temporarily un-hide the hidden replica. https://pagure.io/freeipa/issue/8240 """ self.replicas[0].run_command([ 'ipa', 'server-state', self.replicas[0].hostname, '--state=enabled' ]) result = tasks.install_kra(self.master, raiseonerr=False) self.replicas[0].run_command([ 'ipa', 'server-state', self.replicas[0].hostname, '--state=hidden' ]) assert result.returncode == 0 class TestReplicaConn(IntegrationTest): num_replicas = 1 num_ad_domains = 1 @classmethod def install(cls, mh): cls.replica = cls.replicas[0] cls.ad = cls.ads[0] ad_domain = cls.ad.domain.name cls.ad_admin = 'Administrator@{}'.format(ad_domain.upper()) cls.adview = 'Default Trust View' tasks.install_master(cls.master, setup_adtrust=True) tasks.configure_dns_for_trust(cls.master, cls.ad) tasks.establish_trust_with_ad(cls.master, cls.ad.domain.name) tasks.install_client(cls.master, cls.replica) def test_replica_conncheck_ad_admin(self): """ Test to verify that replica installation is not failing for replica connection check when AD administrator Administrator@AD.EXAMPLE.COM is used for the deployment or promotion of a replica. Related : https://pagure.io/freeipa/issue/9542 """ self.master.run_command( ['ipa', 'idoverrideuser-add', self.adview, self.ad_admin] ) self.master.run_command( ["ipa", "group-add-member", "admins", "--idoverrideusers", self.ad_admin] ) tasks.clear_sssd_cache(self.master) self.replica.run_command( ["ipa-replica-install", "--setup-ca", "-U", "--ip-address", self.replica.ip, "--realm", self.replica.domain.realm, "--domain", self.replica.domain.name, "--principal={0}".format(self.ad_admin), "--password", self.master.config.ad_admin_password] ) logs = self.replica.get_file_contents(paths.IPAREPLICA_CONNCHECK_LOG) error = "not allowed to perform server connection check" assert error.encode() not in logs
53,660
Python
.py
1,172
33.783276
81
0.578881
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,588
test_advise.py
freeipa_freeipa/ipatests/test_integration/test_advise.py
# Authors: # Gabe Alford <redhatrises@gmail.com> # # Copyright (C) 2013 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import re from ipalib.constants import IPAAPI_USER from ipaplatform.paths import paths from ipaplatform.constants import constants from ipatests.create_external_ca import ExternalCA from ipatests.pytest_ipa.integration import tasks from ipatests.test_integration.base import IntegrationTest def run_advice(master, advice_id, advice_regex, raiseerr=True): # Obtain the advice from the server tasks.kinit_admin(master) result = master.run_command(['ipa-advise', advice_id], raiseonerr=raiseerr) if not result.stdout_text: advice = result.stderr_text else: advice = result.stdout_text assert re.search(advice_regex, advice, re.S) class TestAdvice(IntegrationTest): """ Tests ipa-advise output. """ topology = 'line' num_replicas = 0 num_clients = 1 @classmethod def install(cls, mh): # Install without dnssec validation because the test is # calling dnf install on the client and mirrors.fedoraproject.org # has a broken trust chain tasks.install_master( cls.master, setup_dns=True, extra_args=['--no-dnssec-validation'] ) tasks.install_client(cls.master, cls.clients[0]) def execute_advise(self, host, advice_id, *args): # ipa-advise script is only available on a server tasks.kinit_admin(self.master) advice = self.master.run_command(['ipa-advise', advice_id]) # execute script on host (client or master) if host is not self.master: tasks.kinit_admin(host) filename = tasks.upload_temp_contents(host, advice.stdout_text) cmd = ['sh', filename] cmd.extend(args) try: result = host.run_command(cmd) finally: host.run_command(['rm', '-f', filename]) return advice, result def test_invalid_advice(self): advice_id = r'invalid-advise-param' advice_regex = r"invalid[\s]+\'advice\'.*" run_advice(self.master, advice_id, advice_regex, raiseerr=False) def test_advice_FreeBSDNSSPAM(self): advice_id = 'config-freebsd-nss-pam-ldapd' advice_regex = r"\#\!\/bin\/sh.*" \ r"pkg_add[\s]+\-r[\s]+nss\-pam\-ldapd[\s]+curl.*" \ r"\/usr\/local\/etc\/rc\.d\/nslcd[\s]+restart" run_advice(self.master, advice_id, advice_regex) def test_advice_GenericNSSPAM(self): advice_id = 'config-generic-linux-nss-pam-ldapd' advice_regex = ( r"\#\!\/bin\/sh.*" r"apt\-get[\s]+\-y[\s]+install[\s]+curl[\s]+openssl[\s]+" r"libnss\-ldapd[\s]+libpam\-ldapd[\s]+nslcd.*" r"service[\s]+nscd[\s]+stop[\s]+\&\&[\s]+service[\s]+" r"nslcd[\s]+restart" ) run_advice(self.master, advice_id, advice_regex) def test_advice_GenericSSSDBefore19(self): advice_id = r'config-generic-linux-sssd-before-1-9' advice_regex = r"\#\!\/bin\/sh.*" \ r"apt\-get[\s]+\-y[\s]+install sssd curl openssl.*" \ r"service[\s]+sssd[\s]+start" run_advice(self.master, advice_id, advice_regex) def test_advice_RedHatNSS(self): advice_id = 'config-redhat-nss-ldap' advice_regex = ( r"\#\!\/bin\/sh.*" r"yum[\s]+install[\s]+\-y[\s]+curl[\s]+openssl[\s]+nss_ldap" r"[\s]+authconfig.*authconfig[\s]+\-\-updateall" r"[\s]+\-\-enableldap[\s]+\-\-enableldaptls" r"[\s]+\-\-enableldapauth[\s]+" r"\-\-ldapserver=.*[\s]+\-\-ldapbasedn=.*" ) run_advice(self.master, advice_id, advice_regex) def test_advice_RedHatNSSPAM(self): advice_id = 'config-redhat-nss-pam-ldapd' advice_regex = r"\#\!\/bin\/sh.*" \ r"yum[\s]+install[\s]+\-y[\s]+curl[\s]+openssl[\s]+" \ r"nss\-pam\-ldapd[\s]+pam_ldap[\s]+authconfig.*" \ r"authconfig[\s]+\-\-updateall[\s]+\-\-enableldap"\ r"[\s]+\-\-enableldaptls[\s]+\-\-enableldapauth[\s]+" \ r"\-\-ldapserver=.*[\s]+\-\-ldapbasedn=.*" run_advice(self.master, advice_id, advice_regex) def test_advice_RedHatSSSDBefore19(self): advice_id = 'config-redhat-sssd-before-1-9' advice_regex = ( r"\#\!\/bin\/sh.*" r"yum[\s]+install[\s]+\-y[\s]+sssd[\s]+authconfig[\s]+" r"curl[\s]+openssl.*service[\s]+sssd[\s]+start" ) run_advice(self.master, advice_id, advice_regex) # trivial checks def test_advice_enable_admins_sudo(self): advice_id = 'enable_admins_sudo' advice_regex = r"\#\!\/bin\/sh.*" run_advice(self.master, advice_id, advice_regex) def test_advice_config_server_for_smart_card_auth(self): advice_id = 'config_server_for_smart_card_auth' advice_regex = r"\#\!\/bin\/sh.*" run_advice(self.master, advice_id, advice_regex) ca_pem = ExternalCA().create_ca() ca_file = tasks.upload_temp_contents(self.master, ca_pem) try: self.execute_advise(self.master, advice_id, ca_file) except Exception: # debug: sometimes ipa-certupdate times out in # "Resubmitting certmonger request" self.master.run_command(['getcert', 'list']) raise finally: self.master.run_command(['rm', '-f', ca_file]) sssd_conf = self.master.get_file_contents( paths.SSSD_CONF, encoding='utf-8' ) assert constants.HTTPD_USER in sssd_conf assert IPAAPI_USER in sssd_conf def test_advice_config_client_for_smart_card_auth(self): advice_id = 'config_client_for_smart_card_auth' advice_regex = r"\#\!\/bin\/sh.*" run_advice(self.master, advice_id, advice_regex) client = self.clients[0] ca_pem = ExternalCA().create_ca() ca_file = tasks.upload_temp_contents(client, ca_pem) try: self.execute_advise(client, advice_id, ca_file) finally: client.run_command(['rm', '-f', ca_file]) def test_ipa_advise(self): """Test ipa-advise is not failing with error. The command should not fail with error in command. Related: https://pagure.io/freeipa/issue/6044 """ test = self.master.run_command(["ipa-advise"], raiseonerr=False) error = "object of type 'type' has no len()" assert error not in (test.stdout_text + test.stderr_text)
7,394
Python
.py
164
36.20122
78
0.607197
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,589
test_ipahealthcheck.py
freeipa_freeipa/ipatests/test_integration/test_ipahealthcheck.py
# Copyright (C) 2020 FreeIPA Contributors see COPYING for license # """ Tests to verify that the ipa-healthcheck scenarios """ from __future__ import absolute_import from configparser import RawConfigParser, NoOptionError from datetime import datetime, timedelta, timezone UTC = timezone.utc import io import json import os import re import uuid import pytest from ipalib import x509 from ipapython.dn import DN from ipapython.ipaldap import realm_to_serverid from ipapython.certdb import NSS_SQL_FILES from ipatests.pytest_ipa.integration import tasks from ipaplatform.paths import paths from ipaplatform.osinfo import osinfo from ipaserver.install.installutils import resolve_ip_addresses_nss from ipatests.test_integration.base import IntegrationTest from pkg_resources import parse_version from ipatests.test_integration.test_cert import get_certmonger_fs_id from ipatests.test_integration.test_external_ca import ( install_server_external_ca_step1, install_server_external_ca_step2, ISSUER_CN, ) HEALTHCHECK_LOG = "/var/log/ipa/healthcheck/healthcheck.log" HEALTHCHECK_SYSTEMD_FILE = ( "/etc/systemd/system/multi-user.target.wants/ipa-healthcheck.timer" ) HEALTHCHECK_LOG_ROTATE_CONF = "/etc/logrotate.d/ipahealthcheck" HEALTHCHECK_LOG_DIR = "/var/log/ipa/healthcheck" HEALTHCHECK_OUTPUT_FILE = "/tmp/output.json" HEALTHCHECK_PKG = ["*ipa-healthcheck"] SOS_CMD = "/usr/sbin/sos" SOS_PKG = ["sos"] IPA_CA = "ipa_ca.crt" ROOT_CA = "root_ca.crt" sources = [ "ipahealthcheck.dogtag.ca", "ipahealthcheck.ds.replication", "ipahealthcheck.ipa.certs", "ipahealthcheck.ipa.dna", "ipahealthcheck.ipa.idns", "ipahealthcheck.ipa.files", "ipahealthcheck.ipa.host", "ipahealthcheck.ipa.roles", "ipahealthcheck.ipa.topology", "ipahealthcheck.ipa.trust", "ipahealthcheck.ipa.meta", "ipahealthcheck.meta.core", "ipahealthcheck.meta.services", "ipahealthcheck.system.filesystemspace", ] sources_0_4 = [ "ipahealthcheck.ds.replication", "ipahealthcheck.dogtag.ca", "ipahealthcheck.ipa.certs", "ipahealthcheck.ipa.dna", "ipahealthcheck.ipa.idns", "ipahealthcheck.ipa.files", "ipahealthcheck.ipa.host", "ipahealthcheck.ipa.roles", "ipahealthcheck.ipa.topology", "ipahealthcheck.ipa.trust", "ipahealthcheck.meta.services", "ipahealthcheck.meta.core", "ipahealthcheck.system.filesystemspace", ] ipa_cert_checks = [ "IPACertmongerExpirationCheck", "IPACertfileExpirationCheck", "IPACertTracking", "IPACertNSSTrust", "IPANSSChainValidation", "IPAOpenSSLChainValidation", "IPARAAgent", "IPACertRevocation", "IPACertmongerCA", "IPACAChainExpirationCheck", ] ipatrust_checks = [ "IPATrustAgentCheck", "IPATrustDomainsCheck", "IPADomainCheck", "IPATrustCatalogCheck", "IPAsidgenpluginCheck", "IPATrustAgentMemberCheck", "IPATrustControllerPrincipalCheck", "IPATrustControllerServiceCheck", "IPATrustControllerConfCheck", "IPATrustControllerGroupSIDCheck", "IPATrustPackageCheck", ] metaservices_checks = [ "certmonger", "dirsrv", "gssproxy", "httpd", "ipa_custodia", "ipa_dnskeysyncd", "ipa_otpd", "kadmin", "krb5kdc", "named", "pki_tomcatd", "sssd", ] ipafiles_checks = ["IPAFileNSSDBCheck", "IPAFileCheck", "TomcatFileCheck"] dogtag_checks = ["DogtagCertsConfigCheck", "DogtagCertsConnectivityCheck"] pki_clone_checks = ["ClonesConnectivyAndDataCheck"] iparoles_checks = ["IPACRLManagerCheck", "IPARenewalMasterCheck"] replication_checks = ["ReplicationCheck"] replication_checks_0_4 = ["ReplicationConflictCheck"] ruv_checks = ["RUVCheck"] dna_checks = ["IPADNARangeCheck"] idns_checks = ["IPADNSSystemRecordsCheck"] ipahost_checks = ["IPAHostKeytab"] ipatopology_checks = ["IPATopologyDomainCheck"] filesystem_checks = ["FileSystemSpaceCheck"] metacore_checks = ["MetaCheck"] DEFAULT_PKI_CA_CERTS = [ "caSigningCert cert-pki-ca", "ocspSigningCert cert-pki-ca", "subsystemCert cert-pki-ca", "auditSigningCert cert-pki-ca", "Server-Cert cert-pki-ca", ] DEFAULT_PKI_KRA_CERTS = [ "transportCert cert-pki-kra", "storageCert cert-pki-kra", "auditSigningCert cert-pki-kra", ] TOMCAT_CONFIG_FILES = ( paths.PKI_TOMCAT_PASSWORD_CONF, paths.PKI_TOMCAT_SERVER_XML, paths.CA_CS_CFG_PATH, ) def run_healthcheck(host, source=None, check=None, output_type="json", failures_only=False, config=None): """ Run ipa-healthcheck on the remote host and return the result Returns: the tuple returncode, output output is: json data if output_type == "json" stdout if output_type == "human" """ data = None cmd = ["ipa-healthcheck"] if source: cmd.append("--source") cmd.append(source) if check: cmd.append("--check") cmd.append(check) cmd.append("--output-type") cmd.append(output_type) if failures_only: cmd.append("--failures-only") if config: config_data = host.get_file_contents(config, encoding='utf-8') cfg = RawConfigParser() cfg.read_string(config_data) # The config file value overrides the CLI so if human or # some other option is overridden, don't import as json. try: output_type = cfg.get('default', 'output_type') except NoOptionError: pass cmd.append("--config") cmd.append(config) result = host.run_command(cmd, raiseonerr=False) if result.stdout_text: if output_type == "json": data = json.loads(result.stdout_text) else: data = result.stdout_text.strip() return result.returncode, data def set_excludes(host, option, value, config_file='/etc/ipahealthcheck/ipahealthcheck.conf'): """Mark checks that should be excluded from the results This will set in the [excludes] section on host: option=value """ EXCLUDES = "excludes" conf = host.get_file_contents(config_file, encoding='utf-8') cfg = RawConfigParser() cfg.read_string(conf) if not cfg.has_section(EXCLUDES): cfg.add_section(EXCLUDES) if not cfg.has_option(EXCLUDES, option): cfg.set(EXCLUDES, option, value) out = io.StringIO() cfg.write(out) out.seek(0) host.put_file_contents(config_file, out.read()) @pytest.fixture def restart_service(): """Shut down and restart a service as a fixture""" service = dict() def _stop_service(host, service_name): service_name = service_name.replace('_', '-') if service_name == 'pki-tomcatd': service_name = 'pki-tomcatd@pki-tomcat' elif service_name == 'dirsrv': serverid = (realm_to_serverid(host.domain.realm)).upper() service_name = 'dirsrv@%s.service' % serverid elif service_name == 'named': # The service name may differ depending on the host OS script = ("from ipaplatform.services import knownservices; " "print(knownservices.named.systemd_name)") result = host.run_command(['python3', '-c', script]) service_name = result.stdout_text.strip() if 'host' not in service: service['host'] = host service['name'] = [service_name] else: service['name'].append(service_name) host.run_command(["systemctl", "stop", service_name]) yield _stop_service if service.get('name'): service.get('name', []).reverse() for name in service.get('name', []): service.get('host').run_command(["systemctl", "start", name]) class TestIpaHealthCheck(IntegrationTest): """ Tier-1 test for ipa-healthcheck tool with IPA Master setup with dns and IPA Replica with dns enabled """ num_replicas = 1 num_clients = 1 @classmethod def install(cls, mh): if not cls.master.transport.file_exists(SOS_CMD): tasks.install_packages(cls.master, SOS_PKG) tasks.install_master( cls.master, setup_dns=True, extra_args=['--no-dnssec-validation'] ) tasks.install_client(cls.master, cls.clients[0]) tasks.install_replica( cls.master, cls.replicas[0], setup_dns=True, extra_args=['--no-dnssec-validation'] ) set_excludes(cls.master, "key", "DSCLE0004") def test_ipa_healthcheck_install_on_master(self): """ Testcase to check healthcheck package is installed succesfully on IPA master. """ tasks.install_packages(self.master, HEALTHCHECK_PKG) def test_ipa_healthcheck_install_on_replica(self): """ Testcase to check healthcheck package is installed succesfully on IPA replica. """ tasks.install_packages(self.replicas[0], HEALTHCHECK_PKG) def test_running_ipahealthcheck_ipaclient(self): """ Testcase checks that when ipa-healthcheck command is run on ipaclient it displays "IPA is not configured" """ valid_msg = ( 'IPA is not configured\n', 'IPA server is not configured\n' ) tasks.install_packages(self.clients[0], HEALTHCHECK_PKG) cmd = self.clients[0].run_command( ["ipa-healthcheck"], raiseonerr=False ) assert cmd.returncode == 1 assert cmd.stdout_text in valid_msg def test_run_ipahealthcheck_list_source(self): """ Testcase to verify sources available in healthcheck tool. """ version = tasks.get_healthcheck_version(self.master) result = self.master.run_command(["ipa-healthcheck", "--list-sources"]) if parse_version(version) >= parse_version("0.6"): sources_avail = sources else: sources_avail = sources_0_4 for source in sources_avail: assert source in result.stdout_text def test_human_severity(self, restart_service): """ Test that in human output the severity value is correct Only the SUCCESS (0) value was being translated, otherwise the numeric value was being shown (BZ 1752849) """ restart_service(self.master, "sssd") returncode, output = run_healthcheck( self.master, "ipahealthcheck.meta.services", "sssd", "human", ) assert returncode == 1 assert output == \ "ERROR: ipahealthcheck.meta.services.sssd: sssd: not running" def test_human_output(self): """ Test if in case no failures were found, informative string is printed in human output. https://pagure.io/freeipa/issue/8892 """ returncode, output = run_healthcheck(self.master, output_type="human", failures_only=True) assert returncode == 0 assert output == "No issues found." def test_ipa_healthcheck_fips_enabled(self): """ Test if FIPS is enabled and the check exists. https://pagure.io/freeipa/issue/8951 """ returncode, check = run_healthcheck(self.master, source="ipahealthcheck.meta.core", check="MetaCheck", output_type="json", failures_only=False) assert returncode == 0 cmd = self.master.run_command( [paths.FIPS_MODE_SETUP, "--is-enabled"], raiseonerr=False ) returncode = cmd.returncode assert "fips" in check[0]["kw"] if check[0]["kw"]["fips"] == "disabled": assert returncode == 2 elif check[0]["kw"]["fips"] == "enabled": assert returncode == 0 elif check[0]["kw"]["fips"] == f"missing {paths.FIPS_MODE_SETUP}": assert returncode == 127 else: assert returncode == 1 def test_ipa_healthcheck_after_certupdate(self): """ Verify that ipa-certupdate hasn't messed up tracking ipa-certupdate was dropping the profile value from the CA signing cert tracking. ipa-healthcheck discovered this. Run ipa-healthcheck after ipa-certupdate to ensure that no problems are discovered. """ self.master.run_command([paths.IPA_CERTUPDATE]) returncode, _data = run_healthcheck(self.master) assert returncode == 0 def test_dogtag_ca_check_exists(self): """ Testcase to verify checks available in ipahealthcheck.dogtag.ca source """ result = self.master.run_command( ["ipa-healthcheck", "--source", "ipahealthcheck.dogtag.ca"] ) for check in dogtag_checks: assert check in result.stdout_text def test_replication_check_exists(self): """ Testcase to verify checks available in ipahealthcheck.ds.replication source """ version = tasks.get_healthcheck_version(self.master) result = self.master.run_command( ["ipa-healthcheck", "--source", "ipahealthcheck.ds.replication"] ) if parse_version(version) >= parse_version("0.6"): checks = replication_checks else: checks = replication_checks_0_4 for check in checks: assert check in result.stdout_text def test_ipa_cert_check_exists(self): """ Testcase to verify checks available in ipahealthcheck.ipa.certs source """ result = self.master.run_command( ["ipa-healthcheck", "--source", "ipahealthcheck.ipa.certs"] ) for check in ipa_cert_checks: assert check in result.stdout_text def test_ipa_trust_check_exists(self): """ Testcase to verify checks available in ipahealthcheck.ipa.trust source """ result = self.master.run_command( ["ipa-healthcheck", "--source", "ipahealthcheck.ipa.trust"] ) for check in ipatrust_checks: assert check in result.stdout_text def test_source_ipahealthcheck_meta_services_check(self, restart_service): """ Testcase checks behaviour of check configured services in ipahealthcheck.meta.services when service is stopped and started respectively """ svc_list = ('certmonger', 'gssproxy', 'httpd', 'ipa_custodia', 'ipa_dnskeysyncd', 'kadmin', 'krb5kdc', 'named', 'pki_tomcatd', 'sssd', 'dirsrv') for service in svc_list: returncode, data = run_healthcheck( self.master, "ipahealthcheck.meta.services", service, ) assert returncode == 0 assert data[0]["check"] == service assert data[0]["result"] == "SUCCESS" assert data[0]["kw"]["status"] is True version = tasks.get_healthcheck_version(self.master) # With healthcheck newer versions, the error msg for PKI tomcat # contains the string pki-tomcatd instead of pki_tomcatd always_replace = parse_version(version) >= parse_version("0.13") for service in svc_list: restart_service(self.master, service) returncode, data = run_healthcheck( self.master, "ipahealthcheck.meta.services", service, ) assert returncode == 1 service_found = False for check in data: if check["check"] != service: continue if service != 'pki_tomcatd' or always_replace: service = service.replace('_', '-') assert check["result"] == "ERROR" assert check["kw"]["msg"] == "%s: not running" % service assert check["kw"]["status"] is False service_found = True assert service_found def test_source_ipahealthcheck_dogtag_ca_dogtagcertsconfigcheck(self): """ Testcase checks behaviour of check DogtagCertsConfigCheck in ipahealthcheck.dogtag.ca when tomcat config file is removed """ version = tasks.get_pki_version(self.master) if version >= parse_version("11.5"): pytest.skip("Skipping test for 11.5 pki version, since the " "check CADogtagCertsConfigCheck itself is skipped " "See ipa-healthcheck ticket 317") returncode, data = run_healthcheck( self.master, "ipahealthcheck.dogtag.ca", "DogtagCertsConfigCheck", ) assert returncode == 0 for check in data: assert check["result"] == "SUCCESS" assert check["kw"]["configfile"] == paths.CA_CS_CFG_PATH assert check["kw"]["key"] in DEFAULT_PKI_CA_CERTS self.master.run_command(["mv", paths.CA_CS_CFG_PATH, "%s.old" % paths.CA_CS_CFG_PATH]) returncode, data = run_healthcheck( self.master, "ipahealthcheck.dogtag.ca", "DogtagCertsConfigCheck", ) assert returncode == 1 assert data[0]["result"] == "CRITICAL" self.master.run_command(["mv", "%s.old" % paths.CA_CS_CFG_PATH, paths.CA_CS_CFG_PATH]) self.master.run_command(["ipactl", "restart"]) @pytest.fixture def restart_tomcat(self): """Fixture to Stop and then start tomcat instance during test""" self.master.run_command( ["systemctl", "stop", "pki-tomcatd@pki-tomcat"] ) yield self.master.run_command( ["systemctl", "start", "pki-tomcatd@pki-tomcat"] ) def test_ipahealthcheck_dogtag_ca_connectivity_check(self, restart_tomcat): """ This testcase checks that when the pki-tomcat service is stopped, DogtagCertsConnectivityCheck displays the result as ERROR. """ error_msg = "Request for certificate failed" additional_msg = ( "Certificate operation cannot be completed: " "Request failed with status 503: " "Non-2xx response from CA REST API: 503. (503)" ) returncode, data = run_healthcheck( self.master, "ipahealthcheck.dogtag.ca", "DogtagCertsConnectivityCheck", ) assert returncode == 1 for check in data: assert check["result"] == "ERROR" assert error_msg in check["kw"]["msg"] # pre ipa-healthcheck 0.11, the additional msg was in msg # but moved to "error" with 0.11+ assert additional_msg in check["kw"]["msg"] or \ additional_msg == check["kw"]["error"] def test_ipahealthcheck_ca_not_configured(self): """ Test if the healthcheck ignores pki-tomcat errors when CA is not configured on the machine Related: https://github.com/freeipa/freeipa-healthcheck/issues/201 """ # uninstall replica installed by class' install method tasks.uninstall_replica(self.master, self.replicas[0]) # install it again without CA tasks.install_replica(self.master, self.replicas[0], setup_ca=False, setup_dns=True, extra_args=['--no-dnssec-validation'] ) set_excludes(self.replicas[0], "key", "DSCLE0004") # Init a user on replica to assign a DNA range tasks.kinit_admin(self.replicas[0]) tasks.user_add( self.replicas[0], 'ipauser1', first='Test', last='User', ) returncode, data = run_healthcheck(self.replicas[0], failures_only=True) assert returncode == 0 assert len(data) == 0 # restore the replica original configuration tasks.user_del(self.replicas[0], 'ipauser1') tasks.uninstall_replica(self.master, self.replicas[0]) tasks.install_replica( self.master, self.replicas[0], setup_dns=True, extra_args=['--no-dnssec-validation'] ) def test_source_ipahealthcheck_meta_core_metacheck(self): """ Testcase checks behaviour of check MetaCheck in source ipahealthcheck.meta.core when run on IPA master """ returncode, data = run_healthcheck( self.master, "ipahealthcheck.meta.core", "MetaCheck", ) assert returncode == 0 assert data[0]["result"] == "SUCCESS" result = self.master.run_command( [ "python3", "-c", 'from ipapython import version; ' 'print("%s\t%s" % (version.VERSION, version.API_VERSION))', ] ) assert data[0]["kw"]["ipa_version"] in result.stdout_text assert data[0]["kw"]["ipa_api_version"] in result.stdout_text def test_source_ipahealthcheck_ipa_host_check_ipahostkeytab(self): """ Testcase checks behaviour of check IPAHostKeytab in source ipahealthcheck.ipa.host when GSSAPI credentials cannot be obtained from host's keytab. """ version = tasks.get_healthcheck_version(self.master) if parse_version(version) >= parse_version("0.15"): msg = ( "Service {service} keytab {path} does not exist." ) else: msg = ( "Minor (2529639107): No credentials cache found" ) with tasks.FileBackup(self.master, paths.KRB5_KEYTAB): self.master.run_command(["rm", "-f", paths.KRB5_KEYTAB]) returncode, data = run_healthcheck( self.master, source="ipahealthcheck.ipa.host", check="IPAHostKeytab", ) assert returncode == 1 assert data[0]["result"] == "ERROR" assert msg in data[0]["kw"]["msg"] def test_source_ipahealthcheck_topology_IPATopologyDomainCheck(self): """ Testcase checks default behaviour of check IPATopologyDomainCheck in source ipahealthcheck.ipa.topology on IPA Master """ returncode, data = run_healthcheck( self.master, "ipahealthcheck.ipa.topology", "IPATopologyDomainCheck", ) assert returncode == 0 for check in data: assert check["result"] == "SUCCESS" assert ( check["kw"]["suffix"] == "domain" or check["kw"]["suffix"] == "ca" ) @pytest.fixture def disable_crlgen(self): """Fixture to disable crlgen then enable it once test is done""" self.master.run_command(["ipa-crlgen-manage", "disable"]) yield self.master.run_command(["ipa-crlgen-manage", "enable"]) def test_source_ipa_roles_check_crlmanager(self, disable_crlgen): """ This testcase checks the status of healthcheck tool reflects correct information when crlgen is disabled using ipa-crl-manage disable """ returncode, data = run_healthcheck( self.master, "ipahealthcheck.ipa.roles", "IPACRLManagerCheck", ) assert returncode == 0 for check in data: assert check["result"] == "SUCCESS" assert check["kw"]["key"] == "crl_manager" assert check["kw"]["crlgen_enabled"] is False def test_ipa_healthcheck_no_errors(self): """ Ensure that on a default installation with KRA and DNS installed ipa-healthcheck runs with no errors. """ cmd = tasks.install_kra(self.master) assert cmd.returncode == 0 returncode, _unused = run_healthcheck( self.master, failures_only=True ) assert returncode == 0 def test_ipa_healthcheck_no_errors_with_overrides(self): """ Test overriding command-line options in a configuration file. """ version = tasks.get_healthcheck_version(self.master) if parse_version(version) < parse_version("0.10"): pytest.skip("Skipping test for 0.10 healthcheck version") tmpcmd = self.master.run_command(['mktemp']) config_file = tmpcmd.stdout_text.strip() HC_LOG = "/tmp/hc.log" self.master.put_file_contents( config_file, '\n'.join([ '[default]', 'output_type=human' ]) ) set_excludes(self.master, "key", "DSCLE0004", config_file) returncode, output = run_healthcheck( self.master, failures_only=True, config=config_file ) assert returncode == 0 assert output == "No issues found." # Setting an output file automatically enables all=True self.master.put_file_contents( config_file, '\n'.join([ '[default]', 'output_type=human', 'output_file=%s' % HC_LOG, ]) ) set_excludes(self.master, "key", "DSCLE0004") returncode, _unused = run_healthcheck( self.master, config=config_file ) logsize = len(self.master.get_file_contents(HC_LOG, encoding='utf-8')) self.master.run_command(['rm', '-f', HC_LOG]) self.master.run_command(['rm', '-f', config_file]) assert logsize > 0 # run afterward to ensure cleanup def test_ipa_healthcheck_dna_plugin_returns_warning_pagure_issue_60(self): """ This testcase checks that the status for IPADNARangeCheck on replica changes from WARNING to SUCCESS when user is added on the replica as the DNA range is set. Issue: freeipa/freeipa-healthcheck#60 """ returncode, data = run_healthcheck( self.master, "ipahealthcheck.ipa.dna", "IPADNARangeCheck", ) assert returncode == 0 for check in data: assert check["result"] == "SUCCESS" # Install ipa-healthcheck rpm on replica tasks.install_packages(self.replicas[0], HEALTHCHECK_PKG) returncode, data = run_healthcheck( self.replicas[0], "ipahealthcheck.ipa.dna", "IPADNARangeCheck", ) assert returncode == 1 for check in data: assert check["result"] == "WARNING" assert ( check["kw"]["msg"] == "No DNA range defined. If no masters " "define a range then users and groups cannot be created." ) # Now kinit as admin and add a user on replica which will create a # DNA configuration. tasks.kinit_admin(self.replicas[0]) tasks.user_add( self.replicas[0], 'ipauser1', first='Test', last='User', ) # Now run the ipa-healthcheck command again returncode, data = run_healthcheck( self.replicas[0], "ipahealthcheck.ipa.dna", "IPADNARangeCheck", ) assert returncode == 0 for check in data: assert check["result"] == "SUCCESS" def test_ipa_healthcheck_log_rotate_file_exist_issue35(self): """ This test checks if log rotation has been added for ipa-healthcheck tool so that logs are rotated in /var/log/ipa/healthcheck folder. The test also checks that the logrotate configuration file is syntactically correct by calling logrotate --debug This is a testcase for below pagure issue https://github.com/freeipa/freeipa-healthcheck/issues/35 """ msg = "error: {}:".format(HEALTHCHECK_LOG_ROTATE_CONF) tasks.uninstall_packages(self.master, HEALTHCHECK_PKG) assert not self.master.transport.file_exists( HEALTHCHECK_LOG_ROTATE_CONF ) tasks.install_packages(self.master, HEALTHCHECK_PKG) assert self.master.transport.file_exists(HEALTHCHECK_LOG_ROTATE_CONF) cmd = self.master.run_command( ['logrotate', '--debug', HEALTHCHECK_LOG_ROTATE_CONF] ) assert msg not in cmd.stdout_text def test_ipa_dns_systemrecords_check(self): """ This test ensures that the ipahealthcheck.ipa.idns check displays the correct result when master and replica is setup with integrated DNS. """ SYSTEM_RECORDS = [ rr for h in [self.master, self.replicas[0]] for rr in [ # SRV rrs f"_ldap._tcp.{h.domain.name}.:{h.hostname}.", f"_kerberos._tcp.{h.domain.name}.:{h.hostname}.", f"_kerberos._udp.{h.domain.name}.:{h.hostname}.", f"_kerberos-master._tcp.{h.domain.name}.:{h.hostname}.", f"_kerberos-master._udp.{h.domain.name}.:{h.hostname}.", f"_kpasswd._tcp.{h.domain.name}.:{h.hostname}.", f"_kpasswd._udp.{h.domain.name}.:{h.hostname}.", # URI rrs f"_kerberos.{h.domain.name}.:krb5srv:m:tcp:{h.hostname}.", f"_kerberos.{h.domain.name}.:krb5srv:m:udp:{h.hostname}.", f"_kpasswd.{h.domain.name}.:krb5srv:m:tcp:{h.hostname}.", f"_kpasswd.{h.domain.name}.:krb5srv:m:udp:{h.hostname}.", ] + [str(ip) for ip in resolve_ip_addresses_nss(h.external_hostname)] ] SYSTEM_RECORDS.append(f'"{self.master.domain.realm.upper()}"') version = tasks.get_healthcheck_version(self.master) if parse_version(version) >= parse_version("0.12"): SYSTEM_RECORDS.append('ipa_ca_check') returncode, data = run_healthcheck( self.master, "ipahealthcheck.ipa.idns", "IPADNSSystemRecordsCheck" ) assert returncode == 0 for check in data: assert check["result"] == "SUCCESS" assert check["kw"]["key"] in SYSTEM_RECORDS def test_ipa_healthcheck_ds_ruv_check(self): """ This testcase checks that ipa-healthcheck tool with RUVCheck discovers the same RUV entries as the ipa-replica-manage list-ruv command """ result = self.master.run_command( [ "ipa-replica-manage", "list-ruv", "-p", self.master.config.dirman_password, ] ) output = re.findall( r"\w+.+.\w+.\w:\d+", result.stdout_text.replace("389: ", "") ) ruvs = [] for r in output: (host, r) = r.split(":") if host == self.master.hostname: ruvs.append(r) returncode, data = run_healthcheck( self.master, "ipahealthcheck.ds.ruv", "RUVCheck" ) assert returncode == 0 for check in data: assert check["result"] == "SUCCESS" assert check["kw"]["key"] in (self.master.domain.basedn, "o=ipaca") assert check["kw"]["ruv"] in ruvs ruvs.remove(check["kw"]["ruv"]) assert not ruvs def test_ipa_healthcheck_revocation(self): """ Ensure that healthcheck reports when IPA certs are revoked. """ error_msg = ( "Certificate tracked by {key} is revoked {revocation_reason}" ) error_msg_0_4 = ( "Certificate is revoked, unspecified" ) result = self.master.run_command( ["getcert", "list", "-f", paths.HTTPD_CERT_FILE] ) request_id = get_certmonger_fs_id(result.stdout_text) # Revoke the web cert certfile = self.master.get_file_contents(paths.HTTPD_CERT_FILE) cert = x509.load_certificate_list(certfile) serial = cert[0].serial_number self.master.run_command(["ipa", "cert-revoke", str(serial)]) # re-run to confirm returncode, data = run_healthcheck( self.master, "ipahealthcheck.ipa.certs", "IPACertRevocation" ) assert returncode == 1 assert len(data) == 12 version = tasks.get_healthcheck_version(self.master) for check in data: if check["kw"]["key"] == request_id: assert check["result"] == "ERROR" assert check["kw"]["revocation_reason"] == "unspecified" if (parse_version(version) >= parse_version('0.6')): assert check["kw"]["msg"] == error_msg else: assert ( check["kw"]["msg"] == error_msg_0_4 ) else: assert check["result"] == "SUCCESS" def test_ipa_healthcheck_without_trust_setup(self): """ This testcase checks that when trust isn't setup between IPA server and Windows AD, IPADomainCheck displays key value as domain-check and result is SUCCESS """ returncode, data = run_healthcheck( self.master, "ipahealthcheck.ipa.trust", "IPADomainCheck" ) assert returncode == 0 for check in data: assert check["result"] == "SUCCESS" assert check["kw"]["key"] == "domain-check" def test_ipa_healthcheck_output_indent(self): """ This test case checks whether default (2) indentation is applied to output without it being implicitly stated """ cmd = self.master.run_command(["ipa-healthcheck", "--source", "ipahealthcheck.meta.services"], raiseonerr=False) output_str = cmd.stdout_text output_json = json.loads(output_str) assert output_str == "{}\n".format(json.dumps(output_json, indent=2)) @pytest.fixture def ipactl(self): """Stop and start IPA during test""" self.master.run_command(["ipactl", "stop"]) yield self.master.run_command(["ipactl", "start"]) def test_run_with_stopped_master(self, ipactl): """ Test output of healthcheck where master IPA services are stopped contains only errors regarding master being stopped and no other false positives. """ version = tasks.get_healthcheck_version(self.master) if (parse_version(version) >= parse_version('0.6')): returncode, output = run_healthcheck( self.master, "ipahealthcheck.meta", output_type="human", failures_only=True, ) else: returncode, output = run_healthcheck( self.master, "ipahealthcheck.meta.services", output_type="human", failures_only=True, ) assert returncode == 1 errors = re.findall("ERROR: .*: not running", output) assert len(errors) == len(output.split("\n")) def test_ipahealthcheck_topology_with_ipactl_stop(self, ipactl): """ This testcase checks that ipahealthcheck.ipa.topology check doesnot display 'source not found' on a system when ipactl stop is run """ error_msg = "Source 'ipahealthcheck.ipa.topology' not found" msg = ( "Source 'ipahealthcheck.ipa.topology' is missing " "one or more requirements 'dirsrv'" ) result = self.master.run_command( [ "ipa-healthcheck", "--source", "ipahealthcheck.ipa.topology", "--debug", ], raiseonerr=False, ) assert result.returncode == 1 assert msg in result.stdout_text assert error_msg not in result.stdout_text @pytest.fixture def move_ipa_ca_crt(self): """ Fixture to move ipa_ca_crt and revert """ self.master.run_command( ["mv", paths.IPA_CA_CRT, "%s.old" % paths.CA_CRT] ) yield self.master.run_command( ["mv", "%s.old" % paths.CA_CRT, paths.IPA_CA_CRT] ) def test_chainexpiration_check_without_cert(self, move_ipa_ca_crt): """ Testcase checks that ERROR message is displayed when ipa ca crt file is not renamed """ version = tasks.get_healthcheck_version(self.master) error_text = ( "[Errno 2] No such file or directory: '{}'" .format(paths.IPA_CA_CRT) ) msg_text = ( "Error opening IPA CA chain at {key}: {error}" ) error_4_0_text = ( "[Errno 2] No such file or directory: '{}'" .format(paths.IPA_CA_CRT) ) returncode, data = run_healthcheck( self.master, "ipahealthcheck.ipa.certs", "IPACAChainExpirationCheck", ) assert returncode == 1 for check in data: assert check["result"] == "ERROR" assert check["kw"]["key"] == paths.IPA_CA_CRT if parse_version(version) >= parse_version("0.6"): assert check["kw"]["error"] == error_text assert check["kw"]["msg"] == msg_text else: assert error_4_0_text in check["kw"]["msg"] @pytest.fixture def modify_cert_trust_attr(self): """ Fixture to modify trust attribute for Server-cert and revert the change. """ self.master.run_command( [ "certutil", "-M", "-d", paths.PKI_TOMCAT_ALIAS_DIR, "-n", "Server-Cert cert-pki-ca", "-t", "CTu,u,u", "-f", paths.PKI_TOMCAT_ALIAS_PWDFILE_TXT, ] ) yield self.master.run_command( [ "certutil", "-M", "-d", paths.PKI_TOMCAT_ALIAS_DIR, "-n", "Server-Cert cert-pki-ca", "-t", "u,u,u", "-f", paths.PKI_TOMCAT_ALIAS_PWDFILE_TXT, ] ) def test_ipacertnsstrust_check(self, modify_cert_trust_attr): """ Test for IPACertNSSTrust when trust attribute is modified for Server-Cert """ version = tasks.get_healthcheck_version(self.master) error_msg = ( "Incorrect NSS trust for {nickname} in {dbdir}. " "Got {got} expected {expected}." ) error_msg_4_0 = ( "Incorrect NSS trust for Server-Cert cert-pki-ca. " "Got CTu,u,u expected u,u,u" ) returncode, data = run_healthcheck( self.master, "ipahealthcheck.ipa.certs", "IPACertNSSTrust", ) assert returncode == 1 for check in data: if check["kw"]["key"] == "Server-Cert cert-pki-ca": assert check["result"] == "ERROR" assert check["kw"]["expected"] == "u,u,u" assert check["kw"]["got"] == "CTu,u,u" assert check["kw"]["dbdir"] == paths.PKI_TOMCAT_ALIAS_DIR if (parse_version(version) >= parse_version('0.6')): assert check["kw"]["msg"] == error_msg else: assert check["kw"]["msg"] == error_msg_4_0 @pytest.fixture def update_logging(self): """ Fixture disables nsslapd-logging-hr-timestamps-enabled parameter and reverts it back """ ldap = self.master.ldap_connect() dn = DN( ("cn", "config"), ) entry = ldap.get_entry(dn) entry.single_value["nsslapd-logging-hr-timestamps-enabled"] = 'off' ldap.update_entry(entry) yield entry = ldap.get_entry(dn) entry.single_value["nsslapd-logging-hr-timestamps-enabled"] = 'on' ldap.update_entry(entry) def test_ipahealthcheck_ds_configcheck(self, update_logging): """ This testcase ensures that ConfigCheck displays warning when high resolution timestamp is disabled. """ warn_msg = ( "nsslapd-logging-hr-timestamps-enabled changes the " "log format in directory server " ) returncode, data = run_healthcheck( self.master, "ipahealthcheck.ds.config", "ConfigCheck", ) assert returncode == 1 for check in data: if check["kw"]["key"] == "DSCLE0001": assert check["result"] == "WARNING" assert 'cn=config' in check["kw"]["items"] assert warn_msg in check["kw"]["msg"] @pytest.fixture def rename_ldif(self): """Fixture to rename dse.ldif file and revert after test""" instance = realm_to_serverid(self.master.domain.realm) self.master.run_command( [ "mv", "-v", paths.ETC_DIRSRV_SLAPD_INSTANCE_TEMPLATE % instance + "/dse.ldif", paths.ETC_DIRSRV_SLAPD_INSTANCE_TEMPLATE % instance + "/dse.ldif.renamed", ] ) yield self.master.run_command( [ "mv", "-v", paths.ETC_DIRSRV_SLAPD_INSTANCE_TEMPLATE % instance + "/dse.ldif.renamed", paths.ETC_DIRSRV_SLAPD_INSTANCE_TEMPLATE % instance + "/dse.ldif", ] ) def test_source_ipahealthcheck_ds_backends(self, rename_ldif): """ This test ensures that BackendsCheck check displays the correct status when the dse.ldif file is renamed in the DS instance directory """ exception_msg = "Could not find configuration for instance:" returncode, data = run_healthcheck( self.master, "ipahealthcheck.ds.backends", "BackendsCheck" ) assert returncode == 1 for check in data: assert check["result"] == "CRITICAL" assert exception_msg in check["kw"]["exception"] def test_source_pki_server_clones_connectivity_and_data(self): """ This testcase checks that when ClonesConnectivyAndDataCheck is run it doesn't display source not found error """ if (tasks.get_pki_version( self.master) >= tasks.parse_version('11.5.5')): raise pytest.skip("PKI dropped ClonesConnectivyAndDataCheck") error_msg = ( "Source 'pki.server.healthcheck.clones.connectivity_and_data' " "not found" ) result = self.master.run_command( ["ipa-healthcheck", "--source", "pki.server.healthcheck.clones.connectivity_and_data"] ) assert error_msg not in result.stdout_text for check in pki_clone_checks: assert check in result.stdout_text @pytest.fixture def modify_tls(self, restart_service): """ Fixture to modify DS tls version to TLS1.0 using dsconf tool and revert back to the default TLS1.2 """ instance = realm_to_serverid(self.master.domain.realm) cmd = ["systemctl", "restart", "dirsrv@{}".format(instance)] # The crypto policy must be set to LEGACY otherwise 389ds # combines crypto policy amd minSSLVersion and removes # TLS1.0 on fedora>=33 as the DEFAULT policy forbids TLS1.0 self.master.run_command(['update-crypto-policies', '--set', 'LEGACY']) self.master.run_command( [ "dsconf", "slapd-{}".format(instance), "security", "set", "--tls-protocol-min=TLS1.0", ] ) self.master.run_command(cmd) yield self.master.run_command(['update-crypto-policies', '--set', 'DEFAULT']) self.master.run_command( [ "dsconf", "slapd-{}".format(instance), "security", "set", "--tls-protocol-min=TLS1.2", ] ) self.master.run_command(cmd) @pytest.mark.skipif((osinfo.id == 'rhel' and osinfo.version_number >= (9,0)), reason=" TLS versions below 1.2 are not " "supported anymore in RHEL9.0 and above.") def test_ipahealthcheck_ds_encryption(self, modify_tls): """ This testcase modifies the default TLS version of DS instance to 1.0 and ensures that EncryptionCheck reports ERROR """ enc_msg = ( "This Directory Server may not be using strong TLS protocol " "versions. TLS1.0 is known to\nhave a number of issues with " "the protocol. " "Please see:\n\nhttps://tools.ietf.org/html/rfc7457\n\n" "It is advised you set this value to the maximum possible." ) returncode, data = run_healthcheck( self.master, "ipahealthcheck.ds.encryption", "EncryptionCheck", ) assert returncode == 1 for check in data: assert check["result"] == "ERROR" assert check["kw"]["key"] == "DSELE0001" assert "cn=encryption,cn=config" in check["kw"]["items"] assert check["kw"]["msg"] == enc_msg @pytest.fixture def update_riplugin(self): """ Fixture modifies the value of update delay for RI plugin to -1 and reverts it back """ ldap = self.master.ldap_connect() dn = DN( ("cn", "referential integrity postoperation"), ("cn", "plugins"), ("cn", "config"), ) entry = ldap.get_entry(dn) entry.single_value["referint-update-delay"] = -1 ldap.update_entry(entry) yield entry = ldap.get_entry(dn) entry.single_value["referint-update-delay"] = 0 ldap.update_entry(entry) def test_ipahealthcheck_ds_riplugincheck(self, update_riplugin): """ This testcase ensures that RIPluginCheck displays warning when update value is set. """ warn_msg = ( "We advise that you set this value to 0, and enable referint " ) returncode, data = run_healthcheck( self.master, "ipahealthcheck.ds.ds_plugins", "RIPluginCheck", ) assert returncode == 1 for check in data: assert check["result"] == "WARNING" assert warn_msg in check["kw"]["msg"] @pytest.fixture def modify_pwdstoragescheme(self): """ Fixture modifies the nsslapd-rootpwstoragescheme to MD5 and reverts it back """ ldap = self.master.ldap_connect() dn = DN(("cn", "config"),) entry = ldap.get_entry(dn) entry.single_value["nsslapd-rootpwstoragescheme"] = "MD5" ldap.update_entry(entry) yield entry = ldap.get_entry(dn) entry.single_value["nsslapd-rootpwstoragescheme"] = "PBKDF2_SHA256" ldap.update_entry(entry) def test_ds_configcheck_passwordstorage(self, modify_pwdstoragescheme): """ This testcase ensures that ConfigCheck reports CRITICAL status when nsslapd-rootpwstoragescheme is set to MD5 from the required PBKDF2_SHA256 """ error_msg = ( "\n\nIn Directory Server, we offer one hash suitable for this " ) returncode, data = run_healthcheck( self.master, "ipahealthcheck.ds.config", "ConfigCheck", ) assert returncode == 1 for check in data: if check["kw"]["key"] == "DSCLE0002": assert check["result"] == "CRITICAL" assert "cn=config" in check["kw"]["items"] assert error_msg in check["kw"]["msg"] @pytest.fixture def create_logfile(self): """ The fixture calls ipa-healthcheck command in order to create /var/log/ipa/healthcheck/healthcheck.log if file doesn't already exist. File is deleted once the test is finished. """ if not self.master.transport.file_exists(HEALTHCHECK_LOG): self.master.run_command( ["ipa-healthcheck", "--output-file", HEALTHCHECK_LOG], raiseonerr=False, ) yield self.master.run_command(["rm", "-f", HEALTHCHECK_LOG]) def test_sosreport_includes_healthcheck(self, create_logfile): """ This testcase checks that sosreport command when run on IPA system with healthcheck installed collects healthcheck.log file """ caseid = "123456" msg = "[plugin:ipa] collecting path '{}'".format(HEALTHCHECK_LOG) cmd = self.master.run_command( [ "sosreport", "-o", "ipa", "--case-id", caseid, "--batch", "-vv", "--build", ] ) assert msg in cmd.stdout_text def modify_perms_run_healthcheck(self, filename, modify_permissions, expected_permissions): """ Modify the ipa logfile permissions and run healthcheck command to check the status. """ modify_permissions(self.master, path=filename, mode="0644") returncode, data = run_healthcheck( self.master, "ipahealthcheck.ipa.files", failures_only=True ) assert returncode == 1 assert len(data) == 1 assert data[0]["result"] == "WARNING" assert data[0]["kw"]["path"] == filename assert data[0]["kw"]["type"] == "mode" assert data[0]["kw"]["expected"] == expected_permissions def test_ipahealthcheck_verify_perms_for_source_files(self, modify_permissions): """ This tests checks if files in /var/log are checked with ipa.files source. The test modifies permissions of ipainstall log file and checks the response from healthcheck. https://pagure.io/freeipa/issue/8949 """ self.modify_perms_run_healthcheck( paths.IPASERVER_INSTALL_LOG, modify_permissions, expected_permissions="0600" ) def test_ipahealthcheck_verify_perms_upgrade_log_file(self, modify_permissions): """ This testcase creates /var/log/ipaupgrade.log file. Once the file is generated the permissions are modified to check that correct status message is displayed by healthcheck tool """ self.master.run_command(["touch", paths.IPAUPGRADE_LOG]) self.modify_perms_run_healthcheck( paths.IPAUPGRADE_LOG, modify_permissions, expected_permissions="0600" ) def test_ipa_healthcheck_renew_internal_cert(self): """ This testcase checks that CADogtagCertsConfigCheck can handle cert renewal, when there can be two certs with the same nickname """ if (tasks.get_pki_version( self.master) < tasks.parse_version('11.4.0')): raise pytest.skip("PKI known issue #2022561") elif (tasks.get_pki_version( self.master) >= tasks.parse_version('11.5.0')): raise pytest.skip("Skipping test for 11.5 pki version, since " "check CADogtagCertsConfigCheck is " "not present in source " "pki.server.healthcheck.meta.csconfig") self.master.run_command( ['ipa-cacert-manage', 'renew', '--self-signed'] ) returncode, data = run_healthcheck( self.master, "pki.server.healthcheck.meta.csconfig", "CADogtagCertsConfigCheck" ) assert returncode == 0 for check in data: assert check["result"] == "SUCCESS" @pytest.fixture def remove_healthcheck(self): """ This fixture uninstalls healthcheck package on IPA and deletes /var/log/ipa/healthcheck/healthcheck.log file and reinstalls healthcheck package once test is finished """ tasks.uninstall_packages(self.master, HEALTHCHECK_PKG) self.master.run_command(["rm", "-f", HEALTHCHECK_LOG]) yield tasks.install_packages(self.master, HEALTHCHECK_PKG) def test_sosreport_without_healthcheck_installed(self, remove_healthcheck): """ This testcase checks that sosreport completes successfully even if there is no healthcheck log file to collect """ caseid = "123456" self.master.run_command( [ "sosreport", "-o", "ipa", "--case-id", caseid, "--batch", "-v", "--build", ] ) @pytest.fixture def expire_cert_critical(self): """ Fixture to expire the cert by moving the system date using date -s command and revert it back """ self.master.run_command(['date','-s', '+3Years']) yield self.master.run_command(['date','-s', '-3Years']) self.master.run_command(['ipactl', 'restart']) def test_nsscheck_cert_expired(self, expire_cert_critical): """ This test checks that critical message is displayed for NssCheck when Server-Cert has expired """ msg = "The certificate (Server-Cert) has expired" returncode, data = run_healthcheck( self.master, "ipahealthcheck.ds.nss_ssl", "NssCheck", ) assert returncode == 1 for check in data: assert check["result"] == "CRITICAL" assert check["kw"]["key"] == "DSCERTLE0002" assert "Expired Certificate" in check["kw"]["items"] assert check["kw"]["msg"] == msg def test_ipa_healthcheck_expiring(self, restart_service): """ There are two overlapping tests for expiring certs, check both. """ def execute_nsscheck_cert_expiring(check): """ This test checks that error message is displayed for NssCheck when 'Server-Cert' is about to expire """ msg = ( "The certificate (Server-Cert) will " "expire in less than 30 days" ) returncode, data = run_healthcheck( self.master, "ipahealthcheck.ds.nss_ssl", "NssCheck", ) assert returncode == 1 for check in data: assert check["result"] == "ERROR" assert check["kw"]["key"] == "DSCERTLE0001" assert "Expiring Certificate" in check["kw"]["items"] assert check["kw"]["msg"] == msg def execute_expiring_check(check): """ Test that certmonger will report warnings if expiration is near """ returncode, data = run_healthcheck( self.master, "ipahealthcheck.ipa.certs", check, ) assert returncode == 1 assert len(data) == 12 # KRA is 12 tracked certs for check in data: if check["result"] == "SUCCESS": # The CA is not expired request = self.master.run_command( ["getcert", "list", "-i", check["kw"]["key"]] ) assert "caSigningCert cert-pki-ca" in request.stdout_text else: assert check["result"] == "WARNING" if check["kw"]["days"] == 21: # the httpd, 389-ds and KDC renewal dates are later certs = (paths.HTTPD_CERT_FILE, paths.KDC_CERT, '/etc/dirsrv/slapd-',) request = self.master.run_command( ["getcert", "list", "-i", check["kw"]["key"]] ) assert any(cert in request.stdout_text for cert in certs) else: assert check["kw"]["days"] == 10 # Remove the replica now since it will be out of sync with the # updated certificates and replication will break. tasks.uninstall_replica(self.master, self.replicas[0]) # Store the current date to restore at the end of the test now = datetime.now(tz=UTC) now_str = datetime.strftime(now, "%Y-%m-%d %H:%M:%S Z") # Pick a cert to find the upcoming expiration certfile = self.master.get_file_contents(paths.RA_AGENT_PEM) cert = x509.load_certificate_list(certfile) cert_expiry = cert[0].not_valid_after_utc # Stop chronyd so it doesn't freak out with time so off restart_service(self.master, 'chronyd') # Stop pki_tomcatd so certs are not renewable. Don't restart # it because by the time the test is done the server is gone. self.master.run_command( ["systemctl", "stop", "pki-tomcatd@pki-tomcat"] ) try: # move date to the grace period grace_date = cert_expiry - timedelta(days=10) grace_date = datetime.strftime(grace_date, "%Y-%m-%d 00:00:01 Z") self.master.run_command(['date', '-s', grace_date]) for check in ("IPACertmongerExpirationCheck", "IPACertfileExpirationCheck",): execute_expiring_check(check) execute_nsscheck_cert_expiring(check) finally: # Prior to uninstall remove all the cert tracking to prevent # errors from certmonger trying to check the status of certs # that don't matter because we are uninstalling. self.master.run_command(['systemctl', 'stop', 'certmonger']) # Important: run_command with a str argument is able to # perform shell expansion but run_command with a list of # arguments is not self.master.run_command( "rm -fv " + paths.CERTMONGER_REQUESTS_DIR + "*" ) # Delete the renewal lock file to make sure the helpers don't block self.master.run_command("rm -fv " + paths.IPA_RENEWAL_LOCK) self.master.run_command(['systemctl', 'start', 'certmonger']) # Uninstall the master here so that the certs don't try # to renew after the CA is running again. tasks.uninstall_master(self.master) # After restarting chronyd, the date may need some time to get # synced. Help chrony by resetting the date self.master.run_command(['date', '-s', now_str]) """ IMPORTANT: Do not add tests after test_ipa_healthcheck_expiring as the system may be unstable after the date modification. """ def test_ipa_healthcheck_remove(self): """ This testcase checks the removal of of healthcheck tool on replica and master """ tasks.uninstall_packages(self.master, HEALTHCHECK_PKG) tasks.uninstall_packages(self.replicas[0], HEALTHCHECK_PKG) class TestIpaHealthCheckWithoutDNS(IntegrationTest): """ Test for ipa-healthcheck tool with IPA Master without DNS installed """ num_replicas = 1 @classmethod def install(cls, mh): tasks.uninstall_replica(cls.master, cls.replicas[0]) tasks.uninstall_master(cls.master) tasks.install_master( cls.master, setup_dns=False) def test_ipa_dns_systemrecords_check(self): """ Test checks the result of IPADNSSystemRecordsCheck when ipa-server is configured without DNS. """ version = tasks.get_healthcheck_version(self.master) if (parse_version(version) < parse_version('0.12')): expected_msgs = { "Expected SRV record missing", "Got {count} ipa-ca A records, expected {expected}", "Got {count} ipa-ca AAAA records, expected {expected}", "Expected URI record missing", } elif (parse_version(version) < parse_version('0.13')): expected_msgs = { "Expected SRV record missing", "Unexpected ipa-ca address {ipaddr}", "expected ipa-ca to contain {ipaddr} for {server}", "Expected URI record missing", } else: expected_msgs = { "Expected SRV record missing", "Expected URI record missing", "missing IP address for ipa-ca server {server}", } tasks.install_packages(self.master, HEALTHCHECK_PKG) returncode, data = run_healthcheck( self.master, "ipahealthcheck.ipa.idns", "IPADNSSystemRecordsCheck", ) assert returncode == 1 for check in data: assert check["result"] == "WARNING" assert check["kw"]["msg"] in expected_msgs def test_ipa_certs_check_ipacertnsstrust(self): """ Test checks the output for IPACertNSSTrust when kra is installed on the IPA system using ipa-kra-install """ cmd = tasks.install_kra(self.master) assert cmd.returncode == 0 tasks.install_packages(self.master, HEALTHCHECK_PKG) returncode, data = run_healthcheck( self.master, "ipahealthcheck.ipa.certs", "IPACertNSSTrust", ) assert returncode == 0 for check in data: assert check["result"] == "SUCCESS" assert ( check["kw"]["key"] in DEFAULT_PKI_CA_CERTS or check["kw"]["key"] in DEFAULT_PKI_KRA_CERTS ) tasks.uninstall_master(self.master) class TestIpaHealthCheckWithADtrust(IntegrationTest): """ Test for ipa-healthcheck tool with IPA Master with trust setup with Windows AD. """ topology = "line" num_ad_domains = 1 num_ad_treedomains = 1 num_ad_subdomains = 1 @classmethod def install(cls, mh): tasks.install_master( cls.master, setup_dns=True, extra_args=['--no-dnssec-validation'] ) cls.ad = cls.ads[0] cls.child_ad = cls.ad_subdomains[0] cls.tree_ad = cls.ad_treedomains[0] cls.ad_domain = cls.ad.domain.name cls.ad_subdomain = cls.child_ad.domain.name cls.ad_treedomain = cls.tree_ad.domain.name tasks.install_adtrust(cls.master) tasks.configure_dns_for_trust(cls.master, cls.ad) tasks.establish_trust_with_ad(cls.master, cls.ad.domain.name) tasks.install_packages(cls.master, HEALTHCHECK_PKG) def test_ipahealthcheck_trust_domainscheck(self): """ This testcase checks when trust between IPA-AD is established, IPATrustDomainsCheck displays result as SUCCESS and also displays ADREALM as sssd/trust domains """ returncode, data = run_healthcheck( self.master, "ipahealthcheck.ipa.trust", "IPATrustDomainsCheck" ) assert returncode == 0 trust_domains = ', '.join((self.ad_domain, self.ad_subdomain,)) for check in data: if check["kw"]["key"] == "domain-list": assert check["result"] == "SUCCESS" assert ( check["kw"]["sssd_domains"] == trust_domains and check["kw"]["trust_domains"] == trust_domains ) elif check["kw"]["key"] == "domain-status": assert check["result"] == "SUCCESS" assert check["kw"]["domain"] in trust_domains def test_ipahealthcheck_trust_catalogcheck(self): """ This testcase checks when trust between IPA-AD is established, IPATrustCatalogCheck displays result as SUCCESS and also domain value is displayed as ADREALM """ returncode, data = run_healthcheck( self.master, "ipahealthcheck.ipa.trust", "IPATrustCatalogCheck" ) assert returncode == 0 trust_domains = ', '.join((self.ad_domain, self.ad_subdomain,)) for check in data: if check["kw"]["key"] == "AD Global Catalog": assert check["result"] == "SUCCESS" assert check["kw"]["domain"] in trust_domains elif check["kw"]["key"] == "AD Domain Controller": assert check["result"] == "SUCCESS" assert check["kw"]["domain"] in trust_domains def test_ipahealthcheck_trustcontoller_conf_check(self): """ This testcase checks when trust between IPA-AD is established, IPATrustControllerConfCheck displays result as SUCCESS and also displays key as 'net conf list' """ returncode, data = run_healthcheck( self.master, "ipahealthcheck.ipa.trust", "IPATrustControllerConfCheck", ) assert returncode == 0 for check in data: assert check["result"] == "SUCCESS" assert check["kw"]["key"] == "net conf list" @pytest.fixture def modify_cifs_princ(self): """ This fixture removes the cifs principal from the cn=adtrust agents and adds it back """ ldap = self.master.ldap_connect() basedn = self.master.domain.basedn dn = DN( ("cn", "adtrust agents"), ("cn", "sysaccounts"), ("cn", "etc"), basedn, ) entry = ldap.get_entry(dn) krbprinc = entry['member'] entry['member'] = '' ldap.update_entry(entry) yield # Add the entry back entry['member'] = krbprinc ldap.update_entry(entry) def test_trustcontroller_principalcheck(self, modify_cifs_princ): """ This testcase checks when trust between IPA-AD is established without any errors, IPATrustControllerPrincipalCheck displays result as ERROR and when cifs principal is removed """ error_msg = "{key} is not a member of {group}" keyname = "cifs/{}@{}".format( self.master.hostname, self.master.domain.realm ) returncode, data = run_healthcheck( self.master, "ipahealthcheck.ipa.trust", "IPATrustControllerPrincipalCheck", ) assert returncode == 1 for check in data: assert check["result"] == "ERROR" assert check["kw"]["key"] == keyname assert check["kw"]["group"] == "adtrust agents" assert check["kw"]["msg"] == error_msg def test_principalcheck_with_cifs_entry(self): """ This testcase checks IPATrustControllerPrincipalCheck displays result as SUCCESS when cifs principal is present in cn=adtrust agents group """ keyname = "cifs/{}@{}".format( self.master.hostname, self.master.domain.realm ) returncode, data = run_healthcheck( self.master, "ipahealthcheck.ipa.trust", "IPATrustControllerPrincipalCheck", ) assert returncode == 0 for check in data: assert check["result"] == "SUCCESS" assert check["kw"]["key"] == keyname def test_ipahealthcheck_sidgenpluginCheck(self): """ This testcase checks when trust between IPA-AD is established, IPAsidgenpluginCheck displays result as SUCCESS and also displays key value as 'ipa-sidgen-task' """ returncode, data = run_healthcheck( self.master, "ipahealthcheck.ipa.trust", "IPAsidgenpluginCheck" ) assert returncode == 0 for check in data: assert check["result"] == "SUCCESS" assert ( check["kw"]["key"] == "IPA SIDGEN" or check["kw"]["key"] == "ipa-sidgen-task" ) def test_ipahealthcheck_controller_service_check(self): """ This testcase checks when trust between IPA-AD is established, IPATrustControllerServiceCheck displays result as SUCCESS and also displays key value as 'ADTRUST' """ returncode, data = run_healthcheck( self.master, "ipahealthcheck.ipa.trust", "IPATrustControllerServiceCheck" ) assert returncode == 0 for check in data: assert check["result"] == "SUCCESS" assert check["kw"]["key"] == "ADTRUST" def test_ipahealthcheck_trust_agent_member_check(self): """ This testcase checks when trust between IPA-AD is established, IPATrustAgentMemberCheck displays result as SUCCESS. """ returncode, data = run_healthcheck( self.master, "ipahealthcheck.ipa.trust", "IPATrustAgentMemberCheck" ) assert returncode == 0 for check in data: assert check["result"] == "SUCCESS" assert check["kw"]["key"] == self.master.hostname def test_ipahealthcheck_with_external_ad_trust(self): """ This testcase checks that when external trust is configured between IPA and AD tree domain, IPATrustDomainsCheck doesnot display ERROR """ tasks.configure_dns_for_trust(self.master, self.tree_ad) tasks.establish_trust_with_ad( self.master, self.ad_treedomain, extra_args=['--range-type', 'ipa-ad-trust', '--external=True']) trust_domains = ', '.join((self.ad_domain, self.ad_subdomain, self.ad_treedomain,)) returncode, data = run_healthcheck( self.master, "ipahealthcheck.ipa.trust", "IPATrustDomainsCheck", ) assert returncode == 0 for check in data: assert check["kw"]["key"] in ('domain-list', 'domain-status',) assert check["result"] == "SUCCESS" assert check["kw"].get("msg") is None if check["kw"]["key"] == 'domain-list': assert check["kw"]["sssd_domains"] == trust_domains assert check["kw"]["trust_domains"] == trust_domains else: assert check["kw"]["domain"] in trust_domains @pytest.fixture def modify_permissions(): """Fixture to change owner, group and/or mode This can run against multiple files at once but only one host. """ state = dict() def _modify_permission(host, path, owner=None, group=None, mode=None): """Change the ownership or mode of a path""" if 'host' not in state: state['host'] = host if path not in state: cmd = ["/usr/bin/stat", "-L", "-c", "%U:%G:%a", path] result = host.run_command(cmd) state[path] = result.stdout_text.strip() if owner is not None: host.run_command(["chown", owner, path]) if group is not None: host.run_command(["chgrp", group, path]) if mode is not None: host.run_command(["chmod", mode, path]) yield _modify_permission # Restore the previous state host = state.pop('host') for path, path_state in state.items(): (owner, group, mode) = path_state.split(":", maxsplit=2) host.run_command(["chown", "%s:%s" % (owner, group), path]) host.run_command(["chmod", mode, path]) class TestIpaHealthCheckFileCheck(IntegrationTest): """ Test for the ipa-healthcheck IPAFileCheck source """ num_replicas = 1 nssdb_testfiles = [] for filename in NSS_SQL_FILES: testfile = os.path.join(paths.PKI_TOMCAT_ALIAS_DIR, filename) nssdb_testfiles.append(testfile) @classmethod def install(cls, mh): tasks.install_master( cls.master, setup_dns=True, extra_args=['--no-dnssec-validation'] ) tasks.install_replica( cls.master, cls.replicas[0], setup_dns=True, extra_args=['--no-dnssec-validation'] ) tasks.install_packages(cls.master, HEALTHCHECK_PKG) def test_ipa_filecheck_bad_owner(self, modify_permissions): version = tasks.get_healthcheck_version(self.master) if parse_version(version) < parse_version("0.6"): pytest.skip("Skipping test for 0.4 healthcheck version") # ipa-healthcheck 0.8 returns a list of possible owners instead # of a single value if parse_version(version) >= parse_version("0.8"): expected_owner = 'root,systemd-resolve' expected_msg = ("Ownership of %s is admin " "and should be one of root,systemd-resolve" % paths.RESOLV_CONF) else: expected_owner = 'root' expected_msg = ("Ownership of %s is admin and should be root" % paths.RESOLV_CONF) modify_permissions(self.master, path=paths.RESOLV_CONF, owner="admin") returncode, data = run_healthcheck( self.master, "ipahealthcheck.ipa.files", "IPAFileCheck", failures_only=True, ) assert returncode == 1 for check in data: assert check["result"] == "WARNING" assert check["kw"]["key"] == '_etc_resolv.conf_owner' assert check["kw"]["type"] == 'owner' assert check["kw"]["expected"] == expected_owner assert check["kw"]["got"] == 'admin' assert check["kw"]["msg"] == expected_msg def test_ipa_filecheck_bad_group(self, modify_permissions): version = tasks.get_healthcheck_version(self.master) if parse_version(version) < parse_version("0.6"): pytest.skip("Skipping test for 0.4 healthcheck version") # ipa-healthcheck 0.8 returns a list of possible groups instead # of a single value if parse_version(version) >= parse_version("0.8"): expected_group = 'root,systemd-resolve' expected_msg = ("Group of %s is admins and should be one of " "root,systemd-resolve" % paths.RESOLV_CONF) else: expected_group = 'root' expected_msg = ("Group of %s is admins and should be root" % paths.RESOLV_CONF) modify_permissions(self.master, path=paths.RESOLV_CONF, group="admins") returncode, data = run_healthcheck( self.master, "ipahealthcheck.ipa.files", "IPAFileCheck", failures_only=True, ) assert returncode == 1 for check in data: assert check["result"] == "WARNING" assert check["kw"]["key"] == '_etc_resolv.conf_group' assert check["kw"]["type"] == 'group' assert check["kw"]["expected"] == expected_group assert check["kw"]["got"] == 'admins' assert check["kw"]["msg"] == expected_msg def test_ipa_filecheck_bad_too_restrictive(self, modify_permissions): version = tasks.get_healthcheck_version(self.master) if parse_version(version) < parse_version("0.6"): pytest.skip("Skipping test for 0.4 healthcheck version") modify_permissions(self.master, path=paths.RESOLV_CONF, mode="0400") returncode, data = run_healthcheck( self.master, "ipahealthcheck.ipa.files", "IPAFileCheck", failures_only=True, ) assert returncode == 1 for check in data: assert check["result"] == "ERROR" assert check["kw"]["key"] == '_etc_resolv.conf_mode' assert check["kw"]["type"] == 'mode' assert check["kw"]["expected"] == '0644' assert check["kw"]["got"] == '0400' assert ( check["kw"]["msg"] == "Permissions of %s are too restrictive: " "0400 and should be 0644" % paths.RESOLV_CONF ) def test_ipa_filecheck_too_permissive(self, modify_permissions): version = tasks.get_healthcheck_version(self.master) if parse_version(version) < parse_version("0.6"): pytest.skip("Skipping test for 0.4 healthcheck version") modify_permissions(self.master, path=paths.RESOLV_CONF, mode="0666") returncode, data = run_healthcheck( self.master, "ipahealthcheck.ipa.files", "IPAFileCheck", failures_only=True, ) assert returncode == 1 for check in data: assert check["result"] == "WARNING" assert check["kw"]["key"] == '_etc_resolv.conf_mode' assert check["kw"]["type"] == 'mode' assert check["kw"]["expected"] == '0644' assert check["kw"]["got"] == '0666' assert ( check["kw"]["msg"] == "Permissions of %s are too permissive: " "0666 and should be 0644" % paths.RESOLV_CONF ) def test_nssdb_filecheck_bad_owner(self, modify_permissions): for testfile in self.nssdb_testfiles: modify_permissions(self.master, path=testfile, owner='root') returncode, data = run_healthcheck( self.master, "ipahealthcheck.ipa.files", "IPAFileNSSDBCheck", failures_only=True, ) assert returncode == 1 for check in data: assert check["result"] == "WARNING" assert check["kw"]["path"] in self.nssdb_testfiles assert check["kw"]["type"] == 'owner' assert check["kw"]["expected"] == 'pkiuser' assert check["kw"]["got"] == 'root' assert ( check["kw"]["msg"] == "Ownership of %s is root and should be pkiuser" % check["kw"]["path"] ) def test_nssdb_filecheck_bad_group(self, modify_permissions): for testfile in self.nssdb_testfiles: modify_permissions(self.master, testfile, group='root') returncode, data = run_healthcheck( self.master, "ipahealthcheck.ipa.files", "IPAFileNSSDBCheck", failures_only=True, ) assert returncode == 1 for check in data: assert check["result"] == "WARNING" assert check["kw"]["path"] in self.nssdb_testfiles assert check["kw"]["type"] == 'group' assert check["kw"]["expected"] == 'pkiuser' assert check["kw"]["got"] == 'root' assert ( check["kw"]["msg"] == "Group of %s is root and should be pkiuser" % check["kw"]["path"] ) def test_nssdb_filecheck_too_restrictive(self, modify_permissions): for testfile in self.nssdb_testfiles: modify_permissions(self.master, path=testfile, mode="0400") returncode, data = run_healthcheck( self.master, "ipahealthcheck.ipa.files", "IPAFileNSSDBCheck", failures_only=True, ) assert returncode == 1 for check in data: assert check["result"] == "ERROR" assert check["kw"]["path"] in self.nssdb_testfiles assert check["kw"]["type"] == 'mode' assert check["kw"]["expected"] == '0600' assert check["kw"]["got"] == '0400' assert ( check["kw"]["msg"] == "Permissions of %s are too restrictive: " "0400 and should be 0600" % check["kw"]["path"] ) def test_nssdb_filecheck_too_permissive(self, modify_permissions): for testfile in self.nssdb_testfiles: modify_permissions(self.master, path=testfile, mode="0640") returncode, data = run_healthcheck( self.master, "ipahealthcheck.ipa.files", "IPAFileNSSDBCheck", failures_only=True, ) assert returncode == 1 for check in data: assert check["result"] == "WARNING" assert check["kw"]["path"] in self.nssdb_testfiles assert check["kw"]["type"] == 'mode' assert check["kw"]["expected"] == '0600' assert check["kw"]["got"] == '0640' assert ( check["kw"]["msg"] == "Permissions of %s are too permissive: " "0640 and should be 0600" % check["kw"]["path"] ) def test_tomcat_filecheck_bad_owner(self, modify_permissions): modify_permissions(self.master, path=paths.CA_CS_CFG_PATH, owner='root') returncode, data = run_healthcheck( self.master, "ipahealthcheck.ipa.files", "TomcatFileCheck", failures_only=True, ) assert returncode == 1 for check in data: assert check["result"] == "WARNING" assert check["kw"]["key"] == \ '_var_lib_pki_pki-tomcat_conf_ca_CS.cfg_owner' assert check["kw"]["type"] == 'owner' assert check["kw"]["expected"] == 'pkiuser' assert check["kw"]["got"] == 'root' assert ( check["kw"]["msg"] == "Ownership of %s is root and should be pkiuser" % check["kw"]["path"] ) def test_tomcat_filecheck_bad_group(self, modify_permissions): modify_permissions(self.master, path=paths.CA_CS_CFG_PATH, group='root') returncode, data = run_healthcheck( self.master, "ipahealthcheck.ipa.files", "TomcatFileCheck", failures_only=True, ) assert returncode == 1 for check in data: assert check["result"] == "WARNING" assert check["kw"]["key"] == \ '_var_lib_pki_pki-tomcat_conf_ca_CS.cfg_group' assert check["kw"]["type"] == 'group' assert check["kw"]["expected"] == 'pkiuser' assert check["kw"]["got"] == 'root' assert ( check["kw"]["msg"] == "Group of %s is root and should be pkiuser" % check["kw"]["path"] ) def test_tomcat_filecheck_too_restrictive(self, modify_permissions): modify_permissions(self.master, path=paths.CA_CS_CFG_PATH, mode="0600") returncode, data = run_healthcheck( self.master, "ipahealthcheck.ipa.files", "TomcatFileCheck", failures_only=True, ) assert returncode == 1 for check in data: assert check["result"] == "ERROR" assert check["kw"]["key"] == \ '_var_lib_pki_pki-tomcat_conf_ca_CS.cfg_mode' assert check["kw"]["type"] == 'mode' assert check["kw"]["expected"] == '0660' assert check["kw"]["got"] == '0600' assert ( check["kw"]["msg"] == "Permissions of %s are too restrictive: " "0600 and should be 0660" % check["kw"]["path"] ) def test_tomcat_filecheck_too_permissive(self, modify_permissions): version = tasks.get_healthcheck_version(self.master) modify_permissions(self.master, path=paths.CA_CS_CFG_PATH, mode="0666") returncode, data = run_healthcheck( self.master, "ipahealthcheck.ipa.files", "TomcatFileCheck", failures_only=True, ) assert returncode == 1 for check in data: assert check["result"] == "WARNING" assert check["kw"]["key"] == \ '_var_lib_pki_pki-tomcat_conf_ca_CS.cfg_mode' assert check["kw"]["type"] == 'mode' assert check["kw"]["expected"] == '0660' assert check["kw"]["got"] == '0666' if (parse_version(version) >= parse_version('0.5')): assert ( check["kw"]["msg"] == "Permissions of %s are too permissive: " "0666 and should be 0660" % check["kw"]["path"] ) else: assert ( check["kw"]["msg"] == "Permissions of %s are 0666 and should " "be 0660" % check["kw"]["path"] ) def test_ipahealthcheck_ds_fschecks(self, modify_permissions): """ This testcase ensures that FSCheck displays CRITICAL status when permission of pin.txt is modified. """ instance = realm_to_serverid(self.master.domain.realm) error_msg = ( "does not have the expected permissions (400). " "The\nsecurity database pin/password files should only " "be readable by Directory Server user." ) modify_permissions( self.master, path=paths.ETC_DIRSRV_SLAPD_INSTANCE_TEMPLATE % instance + "/pin.txt", mode="0000", ) returncode, data = run_healthcheck( self.master, "ipahealthcheck.ds.fs_checks", "FSCheck", ) assert returncode == 1 for check in data: assert check["result"] == "CRITICAL" assert check["kw"]["key"] == "DSPERMLE0002" assert error_msg in check["kw"]["msg"] class TestIpaHealthCheckFilesystemSpace(IntegrationTest): """ ipa-healthcheck tool test for running low on disk space. """ @classmethod def install(cls, mh): tasks.install_master( cls.master, setup_dns=True, extra_args=['--no-dnssec-validation'] ) tasks.install_packages(cls.master, HEALTHCHECK_PKG) @pytest.fixture def create_jumbo_file(self): """Calculate the free space and create a humongous file to fill it within the threshold without using all available space.""" path = os.path.join('/tmp', str(uuid.uuid4())) # CI has a single big disk so we may end up allocating most of it. result = self.master.run_command( ['df', '--block-size=1024', '--output=avail', '/tmp'] ) free = (int(result.stdout_text.split('\n')[1]) // 1024) - 50 self.master.run_command(['fallocate', '-l', '%dMiB' % free, path]) yield self.master.run_command(['rm', path]) def test_ipa_filesystemspace_check(self, create_jumbo_file): """ Create a large file in /tmp and verify that it reports low space This should raise 2 errors. One that the available space is below a size threshold and another that it is below a percentage threshold. """ returncode, data = run_healthcheck( self.master, "ipahealthcheck.system.filesystemspace", "FileSystemSpaceCheck", failures_only=True, ) assert returncode == 1 errors_found = 0 # Because PR-CI has a single filesystem more filesystems will # report as full. Let's only consider /tmp since this will work # with discrete /tmp as well. for check in data: if check["kw"]["store"] != "/tmp": continue assert check["result"] == "ERROR" assert check["kw"]["store"] == "/tmp" if "percent_free" in check["kw"]: assert "/tmp: free space percentage under threshold" in \ check["kw"]["msg"] assert check["kw"]["threshold"] == 20 else: assert "/tmp: free space under threshold" in \ check["kw"]["msg"] assert check["kw"]["threshold"] == 512 errors_found += 1 # Make sure we found the two errors we expected assert errors_found == 2 class TestIpaHealthCLI(IntegrationTest): """ Validate the command-line options An attempt is made to not overlap tests done in other classes. Run as a separate class so there is a "clean" system to test against. """ # In freeipa-healtcheck >= 0.6 the default tty output is # --failures-only. To show all output use --all. This will # tell us whether --all is available. all_option = osinfo.id in ['fedora',] if all_option: base_cmd = ["ipa-healthcheck", "--all"] else: base_cmd = ["ipa-healthcheck"] @classmethod def install(cls, mh): tasks.install_master( cls.master, setup_dns=True, extra_args=['--no-dnssec-validation'] ) tasks.install_packages(cls.master, HEALTHCHECK_PKG) set_excludes(cls.master, "key", "DSCLE0004") def test_indent(self): """ Use illegal values for indent """ for option in ('a', '9.0'): cmd = self.base_cmd + ["--indent", option] result = self.master.run_command(cmd, raiseonerr=False) assert result.returncode == 2 assert ('invalid int value' in result.stderr_text or 'is not an integer' in result.stderr_text) version = tasks.get_healthcheck_version(self.master) for option in ('-1', '5000'): cmd = self.base_cmd + ["--indent", option] result = self.master.run_command(cmd, raiseonerr=False) if parse_version(version) >= parse_version('0.13'): assert result.returncode == 2 assert 'is not in the range 0-32' in result.stderr_text else: # Older versions did not check for a given allowed range assert result.returncode == 0 def test_severity(self): """ Valid and invalid --severity """ # Baseline, there should be no errors cmd = ["ipa-healthcheck", "--severity", "SUCCESS"] result = self.master.run_command(cmd) data = json.loads(result.stdout_text) for check in data: assert check["result"] == "SUCCESS" # All the other's should return nothing for severity in ('WARNING', 'ERROR', 'CRITICAL'): cmd = ["ipa-healthcheck", "--severity", severity] result = self.master.run_command(cmd) data = json.loads(result.stdout_text) assert len(data) == 0 # An unknown severity cmd = ["ipa-healthcheck", "--severity", "BAD"] result = self.master.run_command(cmd, raiseonerr=False) assert result.returncode == 2 assert 'invalid choice' in result.stderr_text def test_input_file(self): """ Verify the --input-file option """ # ipa-healthcheck overwrites output file, no need to generate # a randomized name. outfile = "/tmp/healthcheck.out" # create our output file cmd = ["ipa-healthcheck", "--output-file", outfile] result = self.master.run_command(cmd) # load the file cmd = ["ipa-healthcheck", "--failures-only", "--input-file", outfile] result = self.master.run_command(cmd) data = json.loads(result.stdout_text) for check in data: assert check["result"] == "SUCCESS" # input file doesn't exist cmd = self.base_cmd + ["--input-file", "/tmp/enoent"] result = self.master.run_command(cmd, raiseonerr=False) assert result.returncode == 1 assert 'No such file or directory' in result.stdout_text # Invalid input file cmd = ["ipa-healthcheck", "--input-file", paths.IPA_CA_CRT] result = self.master.run_command(cmd, raiseonerr=False) assert result.returncode == 1 assert 'Expecting value' in result.stdout_text def test_output_type(self): """ Check invalid output types. The supported json and human types are checked in other classes. """ cmd = self.base_cmd + ["--output-type", "hooman"] result = self.master.run_command(cmd, raiseonerr=False) assert result.returncode == 2 assert 'invalid choice' in result.stderr_text def test_source_and_check(self): """ Verify that invalid --source and/or --check are handled. """ cmd = self.base_cmd + ["--source", "nonexist"] result = self.master.run_command(cmd, raiseonerr=False) assert result.returncode == 1 assert "Source 'nonexist' not found" in result.stdout_text cmd = self.base_cmd + ["--source", "ipahealthcheck.ipa.certs", "--check", "nonexist"] result = self.master.run_command(cmd, raiseonerr=False) assert result.returncode == 1 assert "Check 'nonexist' not found in Source" in result.stdout_text def test_pki_healthcheck(self): """ Ensure compatibility with pki-healthcheck Running on a clean system should produce no errors. This will ensure ABI compatibility. """ self.master.run_command(["pki-healthcheck"]) def test_append_arguments_to_list_sources(self): """ Verify that when arguments are specified to --list-sources option, error is displayed on the console. """ cmd = self.base_cmd + ["--list-sources", "source"] result = self.master.run_command(cmd, raiseonerr=False) assert result.returncode == 2 assert ( "ipa-healthcheck: error: unrecognized arguments: source" in result.stderr_text ) class TestIpaHealthCheckWithExternalCA(IntegrationTest): """ Tests to run and check whether ipa-healthcheck tool reports correct status when IPA server is configured with external CA. """ num_replicas = 1 @classmethod def install(cls, mh): result = install_server_external_ca_step1(cls.master) assert result.returncode == 0 root_ca_fname, ipa_ca_fname = tasks.sign_ca_and_transport( cls.master, paths.ROOT_IPA_CSR, ROOT_CA, IPA_CA ) install_server_external_ca_step2( cls.master, ipa_ca_fname, root_ca_fname ) tasks.kinit_admin(cls.master) tasks.install_packages(cls.master, HEALTHCHECK_PKG) tasks.install_packages(cls.replicas[0], HEALTHCHECK_PKG) tasks.install_replica(cls.master, cls.replicas[0], nameservers=None) def test_ipahealthcheck_crlmanagercheck(self): """ Test for IPACRLManagerCheck """ returncode, data = run_healthcheck( self.master, "ipahealthcheck.ipa.roles", "IPACRLManagerCheck" ) assert returncode == 0 for check in data: assert check["result"] == "SUCCESS" assert check["kw"]["key"] == "crl_manager" assert check["kw"]["crlgen_enabled"] is True # Run again on another server to verify it is False returncode, data = run_healthcheck( self.replicas[0], "ipahealthcheck.ipa.roles", "IPACRLManagerCheck" ) assert returncode == 0 for check in data: assert check["result"] == "SUCCESS" assert check["kw"]["key"] == "crl_manager" assert check["kw"]["crlgen_enabled"] is False @pytest.fixture() def getcert_ca(self): """ Fixture to remove and add ca using getcert command. """ self.master.run_command( ["getcert", "remove-ca", "-c", "dogtag-ipa-ca-renew-agent"] ) yield self.master.run_command( [ "getcert", "add-ca", "-c", "dogtag-ipa-ca-renew-agent", "-e", paths.DOGTAG_IPA_CA_RENEW_AGENT_SUBMIT, ] ) def test_ipahealthcheck_certmongerca(self, getcert_ca): """ Test that healthcheck detects that a certmonger-defined CA is missing """ returncode, data = run_healthcheck( self.master, "ipahealthcheck.ipa.certs", "IPACertmongerCA", ) assert returncode == 1 version = tasks.get_healthcheck_version(self.master) for check in data: if check["kw"]["key"] == "dogtag-ipa-ca-renew-agent": assert check["result"] == "ERROR" if (parse_version(version) >= parse_version('0.6')): assert ( check["kw"]["msg"] == "Certmonger CA '{key}' missing" ) else: assert ( check["kw"]["msg"] == "Certmonger CA 'dogtag-ipa-ca-renew-agent' missing" ) @pytest.fixture() def rename_httpd_cert(self): """ Fixture to rename http cert and revert the change. """ self.master.run_command( ["mv", paths.HTTPD_CERT_FILE, "%s.old" % paths.HTTPD_CERT_FILE] ) yield self.master.run_command( ["mv", "%s.old" % paths.HTTPD_CERT_FILE, paths.HTTPD_CERT_FILE] ) def test_ipahealthcheck_ipaopensslchainvalidation(self, rename_httpd_cert): """ Test for IPAOpenSSLChainValidation when httpd cert is moved. """ error_msg1 = "Can't open {} for reading".format(paths.HTTPD_CERT_FILE) # OpenSSL3 has a different error message error_msg3 = "Could not open file or uri for loading certificate " \ "file from {}".format(paths.HTTPD_CERT_FILE) returncode, data = run_healthcheck( self.master, "ipahealthcheck.ipa.certs", "IPAOpenSSLChainValidation", ) assert returncode == 1 for check in data: if check["kw"]["key"] == paths.HTTPD_CERT_FILE: assert check["result"] == "ERROR" assert (error_msg1 in check["kw"]["reason"] or error_msg3 in check["kw"]["reason"]) @pytest.fixture() def replace_ipa_chain(self): """ Fixture to drop the external CA from the IPA chain """ self.master.run_command( ["cp", paths.IPA_CA_CRT, "%s.old" % paths.IPA_CA_CRT] ) self.master.run_command( [paths.CERTUTIL, "-d", paths.PKI_TOMCAT_ALIAS_DIR, "-L", "-a", "-n", "caSigningCert cert-pki-ca", "-o", paths.IPA_CA_CRT] ) yield self.master.run_command( ["mv", "%s.old" % paths.IPA_CA_CRT, paths.IPA_CA_CRT] ) def test_opensslchainvalidation_ipa_ca_cert(self, replace_ipa_chain): """ Test for IPAOpenSSLChainValidation when /etc/ipa/ca.crt contains IPA CA cert but not the external CA """ version = tasks.get_healthcheck_version(self.master) error_msg = "Certificate validation for {key} failed: {reason}" error_reason = ( "CN = Certificate Authority\nerror 2 at 1 depth " "lookup: unable to get issuer certificate\n" ) returncode, data = run_healthcheck( self.master, "ipahealthcheck.ipa.certs", "IPAOpenSSLChainValidation", ) assert returncode == 1 for check in data: assert check["result"] == "ERROR" if parse_version(version) >= parse_version("0.6"): if check["kw"]["key"] in ( paths.HTTPD_CERT_FILE, paths.RA_AGENT_PEM, ): assert error_msg in check["kw"]["msg"] assert error_reason.replace(" ", "") in check["kw"][ "reason" ].replace(" ", "") else: assert error_reason in check["kw"]["reason"] assert error_reason in check["kw"]["msg"] @pytest.fixture def remove_server_cert(self): """ Fixture to remove Server cert and revert the change. """ instance = realm_to_serverid(self.master.domain.realm) instance_dir = paths.ETC_DIRSRV_SLAPD_INSTANCE_TEMPLATE % instance self.master.run_command( [ "certutil", "-L", "-d", instance_dir, "-n", "Server-Cert", "-a", "-o", instance_dir + "/Server-Cert.pem", ] ) self.master.run_command( [ "certutil", "-d", paths.ETC_DIRSRV_SLAPD_INSTANCE_TEMPLATE % instance, "-D", "-n", "Server-Cert", ] ) yield self.master.run_command( [ "certutil", "-d", instance_dir, "-A", "-i", instance_dir + "/Server-Cert.pem", "-t", "u,u,u", "-f", "%s/pwdfile.txt" % instance_dir, "-n", "Server-Cert", ] ) def test_ipahealthcheck_ipansschainvalidation(self, remove_server_cert): """ Test for IPANSSChainValidation check """ error_msg = ( ': certutil: could not find certificate named "Server-Cert": ' "PR_FILE_NOT_FOUND_ERROR: File not found\n" ) returncode, data = run_healthcheck( self.master, "ipahealthcheck.ipa.certs", "IPANSSChainValidation", ) assert returncode == 1 for check in data: if check["kw"]["nickname"] == "Server-Cert": assert check["result"] == "ERROR" assert check["kw"]["reason"] == error_msg @pytest.fixture() def modify_nssdb_chain_trust(self): """ Fixture to modify trust in the dirsrv NSS database """ instance = realm_to_serverid(self.master.domain.realm) for nickname in ('CN={}'.format(ISSUER_CN), '%s IPA CA' % self.master.domain.realm): cmd = [ paths.CERTUTIL, "-M", "-d", paths.ETC_DIRSRV_SLAPD_INSTANCE_TEMPLATE % instance, "-n", nickname, "-t", ",,", "-f", "%s/pwdfile.txt" % paths.ETC_DIRSRV_SLAPD_INSTANCE_TEMPLATE % instance, ] self.master.run_command(cmd) yield for nickname in ('CN={}'.format(ISSUER_CN), '%s IPA CA' % self.master.domain.realm): cmd = [ paths.CERTUTIL, "-M", "-d", paths.ETC_DIRSRV_SLAPD_INSTANCE_TEMPLATE % instance, "-n", nickname, "-t", "CT,C,C", "-f", "%s/pwdfile.txt" % paths.ETC_DIRSRV_SLAPD_INSTANCE_TEMPLATE % instance, ] self.master.run_command(cmd) def test_nsschainvalidation_ipa_invalid_chain(self, modify_nssdb_chain_trust): """ Test for IPANSSChainValidation when external CA is not trusted """ version = tasks.get_healthcheck_version(self.master) instance = realm_to_serverid(self.master.domain.realm) instance_dir = paths.ETC_DIRSRV_SLAPD_INSTANCE_TEMPLATE % instance error_msg = "Validation of {nickname} in {dbdir} failed: {reason}" error_msg_40_txt = ( "certificate is invalid: Peer's certificate issuer " "has been marked as not trusted by the user" ) returncode, data = run_healthcheck( self.master, "ipahealthcheck.ipa.certs", "IPANSSChainValidation", ) assert returncode == 1 for check in data: if check["kw"]["nickname"] != "Server-Cert": assert check["result"] == "SUCCESS" continue assert check["result"] == "ERROR" assert check["kw"]["dbdir"] == "%s/" % instance_dir assert "marked as not trusted" in check["kw"]["reason"] assert check["kw"]["key"] == "%s:Server-Cert" % instance_dir if parse_version(version) >= parse_version("0.6"): assert check["kw"]["msg"] == error_msg else: assert error_msg_40_txt in check["kw"]["msg"] @pytest.fixture def rename_raagent_cert(self): """ Fixture to rename IPA RA CRT and revert """ self.master.run_command( ["mv", paths.RA_AGENT_PEM, "%s.old" % paths.RA_AGENT_PEM] ) yield self.master.run_command( ["mv", "%s.old" % paths.RA_AGENT_PEM, paths.RA_AGENT_PEM] ) def test_ipahealthcheck_iparaagent(self, rename_raagent_cert): """ Testcase checks that ERROR message is displayed when IPA RA crt file is renamed """ version = tasks.get_healthcheck_version(self.master) error_msg = ( "[Errno 2] No such file or directory: '{}'" .format(paths.RA_AGENT_PEM) ) error_msg_40_txt = ( "Unable to load RA cert: [Errno 2] " "No such file or directory: '{}'".format(paths.RA_AGENT_PEM) ) returncode, data = run_healthcheck( self.master, "ipahealthcheck.ipa.certs", "IPARAAgent" ) assert returncode == 1 for check in data: assert check["result"] == "ERROR" if parse_version(version) >= parse_version("0.6"): assert check["kw"]["error"] == error_msg else: assert check["kw"]["msg"] == error_msg_40_txt @pytest.fixture def update_ra_cert_desc(self): """ Fixture to modify description of RA cert in ldap and revert """ ldap = self.master.ldap_connect() dn = DN(("uid", "ipara"), ("ou", "People"), ("o", "ipaca")) entry = ldap.get_entry(dn) ldap_cert_desc = entry.single_value.get("description") def _update_entry(description): entry = ldap.get_entry(dn) entry.single_value['description'] = description ldap.update_entry(entry) yield _update_entry entry = ldap.get_entry(dn) entry.single_value['description'] = ldap_cert_desc ldap.update_entry(entry) def test_ipahealthcheck_iparaagent_ldap(self, update_ra_cert_desc): """ Test to check that when description of RA cert in ldap is modified, healthcheck tool reports the correct message """ error_msg = 'RA agent not found in LDAP' update_ra_cert_desc('200,12,CN=abc,CN=test') returncode, data = run_healthcheck( self.master, "ipahealthcheck.ipa.certs", "IPARAAgent", ) assert returncode == 1 for check in data: assert check["result"] == "ERROR" assert check["kw"]["msg"] == error_msg def test_ipahealthcheck_iparaagent_bad_serial(self, update_ra_cert_desc): """ Test to check cert description doesnt match the expected """ version = tasks.get_healthcheck_version(self.master) error_msg = 'RA agent description does not match. Found {got} ' \ 'in LDAP and expected {expected}' error_reason = ( "RA agent description does not match" ) ldap = self.master.ldap_connect() dn = DN(("uid", "ipara"), ("ou", "People"), ("o", "ipaca")) entry = ldap.get_entry(dn) ldap_cert_desc = entry.single_value.get("description") update_ra_cert_desc( '2;16;CN=Certificate Authority,O=%s;CN=IPA RA,O=%s' % (self.master.domain.realm, self.master.domain.realm) ) returncode, data = run_healthcheck( self.master, "ipahealthcheck.ipa.certs", "IPARAAgent", ) assert returncode == 1 for check in data: assert check["result"] == "ERROR" assert ( check["kw"]["expected"] == ldap_cert_desc ) assert ( check["kw"]["got"] == "2;16;" "CN=Certificate Authority,O=%s;CN=IPA RA," "O=%s" % (self.master.domain.realm, self.master.domain.realm) ) if parse_version(version) >= parse_version("0.6"): assert check["kw"]["msg"] == error_msg else: assert error_reason in check["kw"]["msg"] class TestIpaHealthCheckSingleMaster(IntegrationTest): @classmethod def install(cls, mh): # Nota Bene: The ipa server is not installed tasks.install_packages(cls.master, HEALTHCHECK_PKG) def test_ipahealthcheck_mismatching_certificates_subject(self): """ Test if healthcheck uses cert subject base from IPA and not from REALM. This prevents false-positive errors when the subject base is customized. Related: https://github.com/freeipa/freeipa-healthcheck/issues/253 """ # install master with custom cert subject base tasks.install_master( self.master, setup_dns=True, extra_args=[ '--no-dnssec-validation', '--subject-base=O=LINUX.IS.GREAT,C=EU' ] ) try: returncode, data = run_healthcheck( self.master, source="ipahealthcheck.ipa.certs", check="IPADogtagCertsMatchCheck", failures_only=True) assert returncode == 0 assert len(data) == 0 finally: # uninstall server for the next step tasks.uninstall_master(self.master) # install master with custom CA certificate subject DN tasks.install_master( self.master, setup_dns=True, extra_args=[ '--no-dnssec-validation', '--ca-subject=CN=Healthcheck test,O=LINUX.IS.GREAT' ] ) try: returncode, data = run_healthcheck( self.master, source="ipahealthcheck.ipa.certs", check="IPADogtagCertsMatchCheck", failures_only=True) assert returncode == 0 assert len(data) == 0 finally: # cleanup tasks.uninstall_master(self.master)
112,489
Python
.py
2,802
29.160243
79
0.56689
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,590
test_pki_config_override.py
freeipa_freeipa/ipatests/test_integration/test_pki_config_override.py
# # Copyright (C) 2019 FreeIPA Contributors see COPYING for license # """Test cases for PKI config overrides """ from __future__ import absolute_import from cryptography.hazmat.primitives import hashes from ipalib.x509 import load_pem_x509_certificate from ipaplatform.paths import paths from ipatests.test_integration.base import IntegrationTest from ipatests.pytest_ipa.integration import tasks KEY_OVERRIDE = """ [DEFAULT] ipa_ca_key_size=4096 ipa_ca_key_algorithm=SHA512withRSA ipa_ca_signing_algorithm=SHA512withRSA """ class TestPKIConfigOverride(IntegrationTest): @classmethod def install(cls, mh): pki_ini = tasks.upload_temp_contents(cls.master, KEY_OVERRIDE) extra_args = [ '--pki-config-override', pki_ini, ] tasks.install_master( cls.master, setup_dns=False, extra_args=extra_args ) cls.master.run_command(['rm', '-f', pki_ini]) def test_cert_rsa4096(self): ca_pem = self.master.get_file_contents( paths.IPA_CA_CRT, encoding=None ) cert = load_pem_x509_certificate(ca_pem) assert cert.public_key().key_size == 4096 assert cert.signature_hash_algorithm.name == hashes.SHA512.name
1,235
Python
.py
35
30.2
71
0.709975
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,591
test_otp.py
freeipa_freeipa/ipatests/test_integration/test_otp.py
# # Copyright (C) 2019 FreeIPA Contributors see COPYING for license # """OTP token tests """ import base64 import logging import re import tempfile import textwrap import time from urllib.parse import parse_qs, urlparse import pytest from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.twofactor.hotp import HOTP from cryptography.hazmat.primitives.twofactor.totp import TOTP from ldap.controls.simple import BooleanControl from paramiko import AuthenticationException from ipalib import errors from ipaplatform.osinfo import osinfo from ipaplatform.paths import paths from ipapython.dn import DN from ipatests.pytest_ipa.integration import tasks from ipatests.test_integration.base import IntegrationTest from ipatests.util import xfail_context PASSWORD = "DummyPassword123" USER = "opttestuser" ARMOR = "/tmp/armor" logger = logging.getLogger(__name__) def add_otptoken(host, owner, *, otptype="hotp", digits=6, algo="sha1"): args = [ "ipa", "otptoken-add", "--owner", owner, "--type", otptype, "--digits", str(digits), "--algo", algo, "--no-qrcode", ] result = host.run_command(args) otpuid = re.search( r"Unique ID:\s*([a-z0-9-]*)\s+", result.stdout_text ).group(1) otpuristr = re.search(r"URI:\s*(.*)\s+", result.stdout_text).group(1) otpuri = urlparse(otpuristr) assert otpuri.netloc == otptype query = parse_qs(otpuri.query) assert query["algorithm"][0] == algo.upper() assert query["digits"][0] == str(digits) key = base64.b32decode(query["secret"][0]) assert len(key) == 35 hashcls = getattr(hashes, algo.upper()) if otptype == "hotp": return otpuid, HOTP(key, digits, hashcls(), default_backend()) else: period = int(query["period"][0]) return otpuid, TOTP(key, digits, hashcls(), period, default_backend()) def del_otptoken(host, otpuid): tasks.kinit_admin(host) host.run_command(["ipa", "otptoken-del", otpuid]) def kinit_otp(host, user, *, password, otp, success=True): tasks.kdestroy_all(host) # create armor for FAST host.run_command(["kinit", "-n", "-c", ARMOR]) host.run_command( ["kinit", "-T", ARMOR, user], stdin_text=f"{password}{otp}\n", ok_returncode=0 if success else 1, ) def ssh_2fa_with_cmd(host, hostname, username, password, otpvalue, command="exit 0"): """ ssh to user and in same session pass the command to check tgt of user :param host: host to ssh :param hostname: hostname to ssh :param str username: The name of user :param str password: password, usually the first factor :param str otpvalue: generated pin of user :param str command: command to execute in same session, by deafult set to "exit 0" :return: object class of expect command run """ temp_conf = tempfile.NamedTemporaryFile(suffix='.exp', delete=False) with open(temp_conf.name, 'w') as tfile: tfile.write('proc exitmsg { msg code } {\n') tfile.write('\t# Close spawned program, if we are in the prompt\n') tfile.write('\tcatch close\n\n') tfile.write('\t# Wait for the exit code\n') tfile.write('\tlassign [wait] pid spawnid os_error_flag rc\n\n') tfile.write('\tputs ""\n') tfile.write('\tputs "expect result: $msg"\n') tfile.write('\tputs "expect exit code: $code"\n') tfile.write('\tputs "expect spawn exit code: $rc"\n') tfile.write('\texit $code\n') tfile.write('}\n') tfile.write('set timeout 60\n') tfile.write('set prompt ".*\\[#\\$>\\] $"\n') tfile.write(f'set password "{password}"\n') tfile.write(f'set otpvalue "{otpvalue}"\n') tfile.write(f'spawn ssh -o NumberOfPasswordPrompts=1 -o ' f'StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null' f' -l {username} {hostname} {command}\n') tfile.write('expect {\n') tfile.write('"Enter first factor:*" {send -- "$password\r"}\n') tfile.write('timeout {exitmsg "Unexpected output" 201}\n') tfile.write('eof {exitmsg "Unexpected end of file" 202}\n') tfile.write('}\n') tfile.write('expect {\n') tfile.write('"Enter second factor:*" {send -- "$otpvalue\r"}\n') tfile.write('timeout {exitmsg "Unexpected output" 201}\n') tfile.write('eof {exitmsg "Unexpected end of file" 202}\n') tfile.write('}\n') tfile.write('expect {\n') tfile.write('"Authentication failure" ' '{exitmsg "Authentication failure" 1}\n') tfile.write('eof {exitmsg "Authentication successful" 0}\n') tfile.write('timeout {exitmsg "Unexpected output" 201}\n') tfile.write('}\n') tfile.write('expect {\n') tfile.write('exitmsg "Unexpected code path" 203\n') tfile.write('EOF\n') tfile.write('}') host.transport.put_file(temp_conf.name, '/tmp/ssh.exp') tasks.clear_sssd_cache(host) expect_cmd = 'expect -f /tmp/ssh.exp' cmd = host.run_command(expect_cmd, raiseonerr=False) return cmd def ssh_2f(hostname, username, answers_dict, port=22, unwanted_prompt=""): """ :param hostname: hostname :param username: username :param answers_dict: dictionary of options with prompt_message and value. :param port: port for ssh """ # Handler for server questions def answer_handler(title, instructions, prompt_list): resp = [] if title: print(title.strip()) if instructions: print(instructions.strip()) for prmpt in prompt_list: prmpt_str = prmpt[0].strip() resp.append(answers_dict[prmpt_str]) logger.info("Prompt is: '%s'", prmpt_str) logger.info( "Answer to ssh prompt is: '%s'", answers_dict[prmpt_str]) if unwanted_prompt and prmpt_str == unwanted_prompt: # We should not see this prompt raise ValueError("We got an unwanted prompt: " + answers_dict[prmpt_str]) return resp import paramiko trans = paramiko.Transport((hostname, port)) trans.connect() trans.auth_interactive(username, answer_handler) def set_sssd_conf(host, add_contents): contents = host.get_file_contents(paths.SSSD_CONF, encoding="utf-8") file_contents = contents + add_contents host.put_file_contents(paths.SSSD_CONF, file_contents) tasks.clear_sssd_cache(host) class TestOTPToken(IntegrationTest): """Tests for member manager feature for groups and hostgroups """ topology = "line" @classmethod def install(cls, mh): master = cls.master tasks.install_packages(master, ['expect']) super(TestOTPToken, cls).install(mh) tasks.kinit_admin(master) # create service with OTP auth indicator cls.service_name = f"otponly/{master.hostname}" master.run_command( ["ipa", "service-add", cls.service_name, "--auth-ind=otp"] ) # service needs a keytab before user can acquire a ticket for it keytab = "/tmp/otponly.keytab" master.run_command( ["ipa-getkeytab", "-p", cls.service_name, "-k", keytab] ) master.run_command(["rm", "-f", keytab]) tasks.create_active_user(master, USER, PASSWORD) tasks.kinit_admin(master) master.run_command(["ipa", "user-mod", USER, "--user-auth-type=otp"]) @classmethod def uninstall(cls, mh): cls.master.run_command(["rm", "-f", ARMOR]) super(TestOTPToken, cls).uninstall(mh) def test_otp_auth_ind(self): tasks.kinit_admin(self.master) result = self.master.run_command( ["kvno", self.service_name], ok_returncode=1 ) assert "KDC policy rejects request" in result.stderr_text def test_hopt(self): master = self.master tasks.kinit_admin(self.master) otpuid, hotp = add_otptoken(master, USER, otptype="hotp") master.run_command(["ipa", "otptoken-show", otpuid]) # normal password login fails master.run_command( ["kinit", USER], stdin_text=f"{PASSWORD}\n", ok_returncode=1 ) # OTP login works otpvalue = hotp.generate(0).decode("ascii") kinit_otp(master, USER, password=PASSWORD, otp=otpvalue) # repeating OTP fails kinit_otp( master, USER, password=PASSWORD, otp=otpvalue, success=False ) # skipping an OTP is ok otpvalue = hotp.generate(2).decode("ascii") kinit_otp(master, USER, password=PASSWORD, otp=otpvalue) # TGT with OTP auth indicator can get a ticket for OTP-only service master.run_command(["kvno", self.service_name]) result = master.run_command(["klist"]) assert self.service_name in result.stdout_text del_otptoken(master, otpuid) @pytest.fixture def desynchronized_hotp(self): """ Create an hotp token for user """ tasks.kinit_admin(self.master) otpuid, hotp = add_otptoken(self.master, USER, otptype="hotp") # skipping too many OTP fails otp1 = hotp.generate(10).decode("ascii") kinit_otp(self.master, USER, password=PASSWORD, otp=otp1, success=False) # Now the token is desynchronized yield (otpuid, hotp) del_otptoken(self.master, otpuid) def test_otptoken_sync_incorrect_password(self, desynchronized_hotp): """ Test if sync fails when incorrect password is provided """ otpuid, hotp = desynchronized_hotp otp2 = hotp.generate(20).decode("ascii") otp3 = hotp.generate(21).decode("ascii") # Try to sync with a wrong password result = self.master.run_command( ["ipa", "otptoken-sync", "--user", USER, otpuid], stdin_text=f"invalidpwd\n{otp2}\n{otp3}\n", raiseonerr=False ) assert result.returncode == 1 assert "Invalid Credentials!" in result.stderr_text # Now sync with the right values self.master.run_command( ["ipa", "otptoken-sync", "--user", USER, otpuid], stdin_text=f"{PASSWORD}\n{otp2}\n{otp3}\n" ) def test_otptoken_sync_incorrect_first_value(self, desynchronized_hotp): """ Test if sync fails when incorrect 1st token value is provided """ otpuid, hotp = desynchronized_hotp otp2 = "12345a" otp3 = hotp.generate(20).decode("ascii") otp4 = hotp.generate(21).decode("ascii") # Try to sync with a wrong first value (contains non-digit) result = self.master.run_command( ["ipa", "otptoken-sync", "--user", USER, otpuid], stdin_text=f"{PASSWORD}\n{otp2}\n{otp3}\n", raiseonerr=False ) assert result.returncode == 1 assert "Invalid Credentials!" in result.stderr_text # Now sync with the right values self.master.run_command( ["ipa", "otptoken-sync", "--user", USER, otpuid], stdin_text=f"{PASSWORD}\n{otp3}\n{otp4}\n" ) def test_otptoken_sync_incorrect_second_value(self, desynchronized_hotp): """ Test if sync fails when incorrect 2nd token value is provided """ otpuid, hotp = desynchronized_hotp otp2 = hotp.generate(20).decode("ascii") otp3 = hotp.generate(21).decode("ascii") # Try to sync with wrong order result = self.master.run_command( ["ipa", "otptoken-sync", "--user", USER, otpuid], stdin_text=f"{PASSWORD}\n{otp3}\n{otp2}\n", raiseonerr=False ) assert result.returncode == 1 assert "Invalid Credentials!" in result.stderr_text # Now sync with the right order self.master.run_command( ["ipa", "otptoken-sync", "--user", USER, otpuid], stdin_text=f"{PASSWORD}\n{otp2}\n{otp3}\n" ) def test_totp(self): master = self.master tasks.kinit_admin(self.master) otpuid, totp = add_otptoken(master, USER, otptype="totp") otpvalue = totp.generate(int(time.time())).decode("ascii") kinit_otp(master, USER, password=PASSWORD, otp=otpvalue) # TGT with OTP auth indicator can get a ticket for OTP-only service master.run_command(["kvno", self.service_name]) result = master.run_command(["klist"]) assert self.service_name in result.stdout_text del_otptoken(master, otpuid) def test_otptoken_sync(self): master = self.master tasks.kinit_admin(self.master) otpuid, hotp = add_otptoken(master, USER, otptype="hotp") otp1 = hotp.generate(10).decode("ascii") otp2 = hotp.generate(11).decode("ascii") master.run_command( ["ipa", "otptoken-sync", "--user", USER], stdin_text=f"{PASSWORD}\n{otp1}\n{otp2}\n", ) otpvalue = hotp.generate(12).decode("ascii") kinit_otp(master, USER, password=PASSWORD, otp=otpvalue) otp1 = hotp.generate(20).decode("ascii") otp2 = hotp.generate(21).decode("ascii") master.run_command( ["ipa", "otptoken-sync", otpuid, "--user", USER], stdin_text=f"{PASSWORD}\n{otp1}\n{otp2}\n", ) otpvalue = hotp.generate(22).decode("ascii") kinit_otp(master, USER, password=PASSWORD, otp=otpvalue) del_otptoken(master, otpuid) def test_2fa_enable_single_prompt(self): """Test ssh with 2FA when single prompt is enabled. Test for : https://pagure.io/SSSD/sssd/issue/3264 When [prompting/2fa/sshd] with single_prompt = True is set then during ssh it should be prompted with given message for first and second factor at once. """ master = self.master USER1 = 'sshuser1' sssd_conf_backup = tasks.FileBackup(master, paths.SSSD_CONF) first_prompt = 'Please enter password + OTP token value:' add_contents = textwrap.dedent(''' [prompting/2fa/sshd] single_prompt = True first_prompt = {0} ''').format(first_prompt) set_sssd_conf(master, add_contents) tasks.create_active_user(master, USER1, PASSWORD) tasks.kinit_admin(master) master.run_command(['ipa', 'user-mod', USER1, '--user-auth-type=otp']) try: otpuid, totp = add_otptoken(master, USER1, otptype='totp') master.run_command(['ipa', 'otptoken-show', otpuid]) otpvalue = totp.generate(int(time.time())).decode('ascii') password = '{0}{1}'.format(PASSWORD, otpvalue) tasks.run_ssh_cmd( to_host=self.master.external_hostname, username=USER1, auth_method="password", password=password ) # check if user listed in output cmd = self.master.run_command(['semanage', 'login', '-l']) assert USER1 in cmd.stdout_text finally: master.run_command(['ipa', 'user-del', USER1]) self.master.run_command(['semanage', 'login', '-D']) sssd_conf_backup.restore() def test_2fa_disable_single_prompt(self): """Test ssh with 2FA when single prompt is disabled. Test for : https://pagure.io/SSSD/sssd/issue/3264 When [prompting/2fa/sshd] with single_prompt = False is set then during ssh it should be prompted with given message for first factor and then for second factor. This requires paramiko until the 2-prompt sshpass RFE is fulfilled: https://sourceforge.net/p/sshpass/feature-requests/5/ """ if self.master.is_fips_mode: pytest.skip("paramiko is not compatible with FIPS mode") master = self.master USER2 = 'sshuser2' sssd_conf_backup = tasks.FileBackup(master, paths.SSSD_CONF) first_prompt = 'Enter first factor:' second_prompt = 'Enter second factor:' add_contents = textwrap.dedent(''' [prompting/2fa/sshd] single_prompt = False first_prompt = {0} second_prompt = {1} ''').format(first_prompt, second_prompt) set_sssd_conf(master, add_contents) tasks.create_active_user(master, USER2, PASSWORD) tasks.kinit_admin(master) master.run_command(['ipa', 'user-mod', USER2, '--user-auth-type=otp']) try: otpuid, totp = add_otptoken(master, USER2, otptype='totp') master.run_command(['ipa', 'otptoken-show', otpuid]) otpvalue = totp.generate(int(time.time())).decode('ascii') answers = { first_prompt: PASSWORD, second_prompt: otpvalue } ssh_2f(master.hostname, USER2, answers) # check if user listed in output cmd = self.master.run_command(['semanage', 'login', '-l']) assert USER2 in cmd.stdout_text finally: master.run_command(['ipa', 'user-del', USER2]) self.master.run_command(['semanage', 'login', '-D']) sssd_conf_backup.restore() def test_2fa_only_with_password(self): """Test ssh with 2FA only with the password(first factor) when user-auth-type is opt and password. Test for : https://github.com/SSSD/sssd/pull/7500 Add the IPA user and user-auth-type set to opt and password. Authenticate the user only with password, just press enter at `Second factor` """ master = self.master USER3 = 'sshuser3' sssd_conf_backup = tasks.FileBackup(master, paths.SSSD_CONF) first_prompt = 'Enter first factor:' second_prompt = 'Enter second factor:' add_contents = textwrap.dedent(''' [prompting/2fa/sshd] single_prompt = False first_prompt = {0} second_prompt = {1} ''').format(first_prompt, second_prompt) set_sssd_conf(master, add_contents) tasks.create_active_user(master, USER3, PASSWORD) tasks.kinit_admin(master) master.run_command(['ipa', 'user-mod', USER3, '--user-auth-type=otp', '--user-auth-type=password']) try: otpuid, totp = add_otptoken(master, USER3, otptype='totp') master.run_command(['ipa', 'otptoken-show', otpuid]) totp.generate(int(time.time())).decode('ascii') otpvalue = "\n" tasks.clear_sssd_cache(self.master) github_ticket = "https://github.com/SSSD/sssd/pull/7500" sssd_version = tasks.get_sssd_version(master) rhel_fail = ( osinfo.id == 'rhel' and sssd_version < tasks.parse_version("2.9.5") ) fedora_fail = ( osinfo.id == 'fedora' and sssd_version == tasks.parse_version("2.9.5") ) with xfail_context(rhel_fail or fedora_fail, reason=github_ticket): result = ssh_2fa_with_cmd(master, self.master.external_hostname, USER3, PASSWORD, otpvalue=otpvalue, command="klist") print(result.stdout_text) assert ('Authentication successful') in result.stdout_text assert USER3 in result.stdout_text assert (f'Default principal: ' f'{USER3}@{self.master.domain.realm}' in result.stdout_text) cmd = self.master.run_command(['semanage', 'login', '-l']) assert USER3 in cmd.stdout_text finally: master.run_command(['ipa', 'user-del', USER3]) self.master.run_command(['semanage', 'login', '-D']) sssd_conf_backup.restore() def test_2fa_with_otp_password(self): """Test ssh with 2FA only with password and otpvalue when user-auth-type is opt and password. Test for : https://github.com/SSSD/sssd/pull/7500 Add the IPA user and user-auth-type set to opt and password. Authenticate the user only with password and otpvalue. """ master = self.master USER4 = 'sshuser4' sssd_conf_backup = tasks.FileBackup(master, paths.SSSD_CONF) first_prompt = 'Enter first factor:' second_prompt = 'Enter second factor:' add_contents = textwrap.dedent(''' [prompting/2fa/sshd] single_prompt = False first_prompt = {0} second_prompt = {1} ''').format(first_prompt, second_prompt) set_sssd_conf(master, add_contents) tasks.create_active_user(master, USER4, PASSWORD) tasks.kinit_admin(master) master.run_command(['ipa', 'user-mod', USER4, '--user-auth-type=otp', '--user-auth-type=password']) try: otpuid, totp = add_otptoken(master, USER4, otptype='totp') master.run_command(['ipa', 'otptoken-show', otpuid]) otpvalue = totp.generate(int(time.time())).decode('ascii') tasks.clear_sssd_cache(self.master) result = ssh_2fa_with_cmd(master, self.master.external_hostname, USER4, PASSWORD, otpvalue=otpvalue, command="klist") print(result.stdout_text) cmd = self.master.run_command(['semanage', 'login', '-l']) # check the output assert ('Authentication successful') in result.stdout_text assert USER4 in result.stdout_text assert (f'Default principal: {USER4}@' f'{self.master.domain.realm}' in result.stdout_text) assert USER4 in cmd.stdout_text finally: master.run_command(['ipa', 'user-del', USER4]) self.master.run_command(['semanage', 'login', '-D']) sssd_conf_backup.restore() @pytest.fixture def setup_otp_nsslapd(self): check_services = self.master.run_command( ['systemctl', 'list-units', '--state=failed'] ) assert "ipa-otpd" not in check_services.stdout_text # Be sure no services are running and failed units self.master.run_command(['killall', 'ipa-otpd'], raiseonerr=False) # setting nsslapd-idletimeout new_limit = 30 conn = self.master.ldap_connect() dn = DN(('cn', 'config')) entry = conn.get_entry(dn) orig_limit = entry.single_value.get('nsslapd-idletimeout') ldap_query = textwrap.dedent(""" dn: cn=config changetype: modify replace: nsslapd-idletimeout nsslapd-idletimeout: {limit} """) tasks.ldapmodify_dm(self.master, ldap_query.format(limit=new_limit)) yield # cleanup tasks.ldapmodify_dm(self.master, ldap_query.format(limit=orig_limit)) def test_check_otpd_after_idle_timeout(self, setup_otp_nsslapd): """Test for OTP when the LDAP connection timed out. Test for : https://pagure.io/freeipa/issue/6587 ipa-otpd was exiting with failure when LDAP connection timed out. Test to verify that when the nsslapd-idletimeout is exceeded (30s idle, 60s sleep) then the ipa-otpd process should exit without error. """ since = time.strftime('%Y-%m-%d %H:%M:%S') tasks.kinit_admin(self.master) otpuid, totp = add_otptoken(self.master, USER, otptype="totp") try: # kinit with OTP auth otpvalue = totp.generate(int(time.time())).decode("ascii") kinit_otp(self.master, USER, password=PASSWORD, otp=otpvalue) time.sleep(60) # ldapsearch will wake up slapd and force walking through # the connection list, in order to spot the idle connections tasks.ldapsearch_dm(self.master, "", ldap_args=[], scope="base") def test_cb(cmd_jornalctl): # check if LDAP connection is timed out expected_msg = "Can't contact LDAP server" return expected_msg in cmd_jornalctl # ipa-otpd don't flush its logs to syslog immediately cmd = ['journalctl', '--since={}'.format(since)] tasks.run_repeatedly( self.master, command=cmd, test=test_cb, timeout=90) failed_services = self.master.run_command( ['systemctl', 'list-units', '--state=failed'] ) assert "ipa-otpd" not in failed_services.stdout_text finally: del_otptoken(self.master, otpuid) def test_totp_ldap(self): master = self.master basedn = master.domain.basedn USER1 = 'user-forced-otp' TMP_PASSWORD = 'Secret1234509' binddn = DN(f"uid={USER1},cn=users,cn=accounts,{basedn}") tasks.kinit_admin(master) master.run_command(['ipa', 'pwpolicy-mod', '--minlife', '0']) tasks.user_add(master, USER1, password=TMP_PASSWORD) # Enforce use of OTP token for this user master.run_command(['ipa', 'user-mod', USER1, '--user-auth-type=otp']) try: # Change initial password through the IPA endpoint url = f'https://{master.hostname}/ipa/session/change_password' master.run_command(['curl', '-d', f'user={USER1}', '-d', f'old_password={TMP_PASSWORD}', '-d', f'new_password={PASSWORD}', '--referer', f'https://{master.hostname}/ipa', url]) conn = master.ldap_connect() # First, attempt authenticating with a password but without LDAP # control to enforce OTP presence and without server-side # enforcement of the OTP presence check. conn.simple_bind(binddn, f"{PASSWORD}") # Next, enforce Password+OTP for a user with OTP token master.run_command(['ipa', 'config-mod', '--addattr', 'ipaconfigstring=EnforceLDAPOTP']) # Try to bind without OTP because there is no OTP token yet, # the operation should succeed because OTP enforcement is implicit # and there is no token yet, so it is allowed. conn.simple_bind(binddn, f"{PASSWORD}") conn.unbind() # Add an OTP token now otpuid, totp = add_otptoken(master, USER1, otptype="totp") # Next, authenticate with Password+OTP and with the LDAP control # this operation should succeed otpvalue = totp.generate(int(time.time())).decode("ascii") conn = master.ldap_connect() conn.simple_bind(binddn, f"{PASSWORD}{otpvalue}", client_controls=[ BooleanControl( controlType="2.16.840.1.113730.3.8.10.7", booleanValue=True)]) conn.unbind() # Sleep to make sure we are going to use a different token value time.sleep(45) # Use OTP token again, without LDAP control, should succeed # because OTP enforcement is implicit otpvalue = totp.generate(int(time.time())).decode("ascii") conn = master.ldap_connect() conn.simple_bind(binddn, f"{PASSWORD}{otpvalue}") conn.unbind() # Now, try to authenticate without otp and without control # this operation should fail because we have OTP token associated # with the user account try: conn = master.ldap_connect() conn.simple_bind(binddn, f"{PASSWORD}") conn.unbind() except errors.ACIError: pass # Sleep to make sure we are going to use a different token value time.sleep(45) # Use OTP token again, without LDAP control, should succeed # because OTP enforcement is implicit otpvalue = totp.generate(int(time.time())).decode("ascii") # Finally, change password again, now that otp is present master.run_command(['curl', '-d', f'user={USER1}', '-d', f'old_password={PASSWORD}', '-d', f'new_password={TMP_PASSWORD}0', '-d', f'otp={otpvalue}', '--referer', f'https://{master.hostname}/ipa', url]) # Remove token del_otptoken(self.master, otpuid) master.run_command(['ipa', 'config-mod', '--delattr', 'ipaconfigstring=EnforceLDAPOTP']) finally: master.run_command(['ipa', 'pwpolicy-mod', '--minlife', '1']) master.run_command(['ipa', 'user-del', USER1]) def test_totp_expired_ldap(self): master = self.master basedn = master.domain.basedn USER1 = 'user-expired-otp' TMP_PASSWORD = 'Secret1234509' binddn = DN(f"uid={USER1},cn=users,cn=accounts,{basedn}") controls = [ BooleanControl( controlType="2.16.840.1.113730.3.8.10.7", booleanValue=True) ] tasks.kinit_admin(master) master.run_command(['ipa', 'pwpolicy-mod', '--minlife', '0']) tasks.user_add(master, USER1, password=TMP_PASSWORD) # Enforce use of OTP token for this user master.run_command(['ipa', 'user-mod', USER1, '--user-auth-type=otp']) try: # Change initial password through the IPA endpoint url = f'https://{master.hostname}/ipa/session/change_password' master.run_command(['curl', '-d', f'user={USER1}', '-d', f'old_password={TMP_PASSWORD}', '-d', f'new_password={PASSWORD}', '--referer', f'https://{master.hostname}/ipa', url]) conn = master.ldap_connect() # First, attempt authenticating with a password but without LDAP # control to enforce OTP presence and without server-side # enforcement of the OTP presence check. conn.simple_bind(binddn, f"{PASSWORD}") # Add an OTP token and then modify it to be expired otpuid, totp = add_otptoken(master, USER1, otptype="totp") # Make sure OTP auth is working otpvalue = totp.generate(int(time.time())).decode("ascii") conn = master.ldap_connect() conn.simple_bind(binddn, f"{PASSWORD}{otpvalue}", client_controls=controls) conn.unbind() # Modfy token so that is now expired args = [ "ipa", "otptoken-mod", otpuid, "--not-after", "20241001010000Z", ] master.run_command(args) # Next, authenticate with Password+OTP again and with the LDAP # control this operation should now fail time.sleep(45) otpvalue = totp.generate(int(time.time())).decode("ascii") conn = master.ldap_connect() with pytest.raises(errors.ACIError): conn.simple_bind(binddn, f"{PASSWORD}{otpvalue}", client_controls=controls) # Sleep to make sure we are going to use a different token value time.sleep(45) # Use OTP token again but authenticate over ssh and make sure it # doesn't fallthrough to asking for a password otpvalue = totp.generate(int(time.time())).decode("ascii") answers = { 'Enter first factor:': PASSWORD, 'Enter second factor:': otpvalue } with pytest.raises(AuthenticationException): # ssh should fail and NOT ask for a password ssh_2f(master.hostname, USER1, answers, unwanted_prompt="Password:") # Remove token del_otptoken(self.master, otpuid) finally: master.run_command(['ipa', 'pwpolicy-mod', '--minlife', '1']) master.run_command(['ipa', 'user-del', USER1])
33,007
Python
.py
708
35.444915
79
0.588966
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,592
test_cockpit.py
freeipa_freeipa/ipatests/test_integration/test_cockpit.py
# # Copyright (C) 2024 FreeIPA Contributors see COPYING for license # from __future__ import absolute_import import time from ipatests.pytest_ipa.integration import tasks from ipatests.test_integration.base import IntegrationTest from ipaplatform.paths import paths class TestCockpitIntegration(IntegrationTest): topology = "line" reqcert = '/etc/cockpit/ws-certs.d/99-cockpit.cert' reqkey = '/etc/cockpit/ws-certs.d/99-cockpit.key' symlink = '/etc/cockpit/krb5.keytab' @classmethod def uninstall(cls, mh): cls.master.run_command(['ipa-getcert', 'stop-tracking', '-f', cls.reqcert], raiseonerr=False) cls.master.run_command(['rm', '-f', cls.symlink], raiseonerr=False) cls.master.run_command(['systemctl', 'disable', '--now', 'cockpit.socket']) super(TestCockpitIntegration, cls).uninstall(mh) @classmethod def install(cls, mh): master = cls.master # Install Cockpit and configure it to use IPA certificate and keytab master.run_command(['dnf', 'install', '-y', 'cockpit', 'curl'], raiseonerr=False) super(TestCockpitIntegration, cls).install(mh) master.run_command(['ipa-getcert', 'request', '-f', cls.reqcert, '-k', cls.reqkey, '-D', cls.master.hostname, '-K', 'host/' + cls.master.hostname, '-m', '0640', '-o', 'root:cockpit-ws', '-O', 'root:root', '-M', '0644'], raiseonerr=False) master.run_command(['ln', '-s', paths.HTTP_KEYTAB, cls.symlink], raiseonerr=False) time.sleep(5) master.run_command(['systemctl', 'enable', '--now', 'cockpit.socket']) def test_login_with_kerberos(self): """ Login to Cockpit using GSSAPI authentication """ master = self.master tasks.kinit_admin(master) cockpit_login = f'https://{master.hostname}:9090/cockpit/login' result = master.run_command([paths.BIN_CURL, '-u:', '--negotiate', '--cacert', paths.IPA_CA_CRT, cockpit_login]) assert ("csrf-token" in result.stdout_text)
2,324
Python
.py
48
36.729167
78
0.581087
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,593
test_simple_replication.py
freeipa_freeipa/ipatests/test_integration/test_simple_replication.py
# Authors: # Petr Viktorin <pviktori@redhat.com> # # Copyright (C) 2013 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from __future__ import print_function import pytest from ipaplatform.paths import paths from ipapython.dn import DN from ipaserver.install.replication import EXCLUDES from ipatests.pytest_ipa.integration import tasks from ipatests.test_integration.base import IntegrationTest from ipatests.test_integration.test_topology import find_segment def check_replication(source_host, dest_host, login): source_host.run_command([ "ipa", "user-add", login, "--first", "test", "--last", "user" ]) source_ldap = source_host.ldap_connect() tasks.wait_for_replication(source_ldap) ldap = dest_host.ldap_connect() tasks.wait_for_replication(ldap) # Check using LDAP basedn = dest_host.domain.basedn user_dn = DN( ("uid", login), ("cn", "users"), ("cn", "accounts"), basedn ) entry = ldap.get_entry(user_dn) assert entry.dn == user_dn assert entry["uid"] == [login] # Check using CLI result = dest_host.run_command(['ipa', 'user-show', login]) assert "User login: {}".format(login) in result.stdout_text @pytest.mark.ds_acceptance class TestSimpleReplication(IntegrationTest): """Simple replication test Install a server and a replica, then add an user on one host and ensure it is also present on the other one. """ num_replicas = 1 topology = 'star' def test_user_replication_to_replica(self): """Test user replication master -> replica""" check_replication(self.master, self.replicas[0], 'testuser1') def test_user_replication_to_master(self): """Test user replication replica -> master""" check_replication(self.replicas[0], self.master, 'testuser2') def test_replica_manage(self): """Test ipa-replica-manage list Ensure that ipa-replica-manage list -v <node> does not print last init status: None last init ended: 1970-01-01 00:00:00+00:00 when the node never had any total update. Test for ticket 7716. """ msg1 = "last init ended: 1970-01-01 00:00:00+00:00" msg2 = "last init status: None" result = self.master.run_command( ["ipa-replica-manage", "list", "-v", self.replicas[0].hostname]) assert msg1 not in result.stdout_text assert msg2 not in result.stdout_text result = self.master.run_command( ["ipa-replica-manage", "list", "-v", self.replicas[0].hostname], stdin_text=self.master.config.dirman_password) assert msg1 not in result.stdout_text assert msg2 not in result.stdout_text def test_ipa_custodia_check(self): replica = self.replicas[0] self.master.run_command( [paths.IPA_CUSTODIA_CHECK, replica.hostname] ) replica.run_command( [paths.IPA_CUSTODIA_CHECK, self.master.hostname] ) def test_fix_agreements(self): """Test that upgrade fixes the list of attributes excluded from repl Test for ticket 9385 """ # Prepare the server by removing some values from # from the nsDS5ReplicatedAttributeList segment = find_segment(self.master, self.replicas[0], "domain") self.master.run_command([ "ipa", "topologysegment-mod", "domain", segment, "--replattrs", "(objectclass=*) $ EXCLUDE memberof idnssoaserial entryusn"]) # Run the upgrade result = self.master.run_command(["ipa-server-upgrade"]) # Ensure that the upgrade updated the attribute without error errmsg = "Error caught updating nsDS5ReplicatedAttributeList" assert errmsg not in result.stdout_text # Check the updated value suffix = DN(self.master.domain.basedn) dn = DN(('cn', str(suffix)), ('cn', 'mapping tree'), ('cn', 'config')) result = tasks.ldapsearch_dm(self.master, str(dn), ["nsDS5ReplicatedAttributeList"]) output = result.stdout_text.lower() template = 'nsDS5ReplicatedAttributeList: (objectclass=*) $ EXCLUDE %s' expected_value = template % " ".join(EXCLUDES) assert expected_value.lower() in output def test_replica_removal(self): """Test replica removal""" result = self.master.run_command(['ipa-replica-manage', 'list']) assert self.replicas[0].hostname in result.stdout_text # has to be run with --force, there is no --unattended self.master.run_command(['ipa-replica-manage', 'del', self.replicas[0].hostname, '--force']) result = self.master.run_command( ['ipa-replica-manage', 'list', '-v', self.master.hostname]) assert self.replicas[0].hostname not in result.stdout_text
5,583
Python
.py
124
37.895161
79
0.665624
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,594
test_acme.py
freeipa_freeipa/ipatests/test_integration/test_acme.py
# # Copyright (C) 2020 FreeIPA Contributors see COPYING for license # import time import pytest from ipalib.constants import IPA_CA_RECORD from ipalib import x509 from ipatests.test_integration.base import IntegrationTest from ipatests.pytest_ipa.integration.firewall import Firewall from ipatests.pytest_ipa.integration import tasks from ipatests.test_integration.test_caless import CALessBase, ipa_certs_cleanup from ipatests.test_integration.test_random_serial_numbers import ( pki_supports_RSNv3 ) from ipaplatform.osinfo import osinfo from ipaplatform.paths import paths from ipatests.test_integration.test_external_ca import ( install_server_external_ca_step1, install_server_external_ca_step2, ) IPA_CA = "ipa_ca.crt" ROOT_CA = "root_ca.crt" # RHEL does not have certbot. EPEL's version is broken with # python-cryptography-2.3; likewise recent PyPI releases. # So for now, on RHEL we suppress tests that use certbot. skip_certbot_tests = osinfo.id not in ['fedora', 'rhel'] # Fedora mod_md package needs some patches before it will work. # RHEL version has the patches. skip_mod_md_tests = osinfo.id not in ['rhel', 'fedora', ] CERTBOT_DNS_IPA_SCRIPT = '/usr/libexec/ipa/acme/certbot-dns-ipa' def check_acme_status(host, exp_status, timeout=60): """Helper method to check the status of acme server""" for _i in range(0, timeout, 5): result = host.run_command(['ipa-acme-manage', 'status']) status = result.stdout_text.split(" ")[2].strip() print("ACME status: %s" % status) if status == exp_status: break time.sleep(5) else: raise RuntimeError("request timed out") return status def get_selinux_status(host): """ Return the SELinux enforcing status. Return True if enabled and enforcing, otherwise False """ result = host.run_command(['/usr/sbin/selinuxenabled'], raiseonerr=False) if result.returncode != 0: return False result = host.run_command(['/usr/sbin/getenforce'], raiseonerr=False) if 'Enforcing' in result.stdout_text: return True return False def server_install_teardown(func): def wrapped(*args): master = args[0].master try: func(*args) finally: ipa_certs_cleanup(master) return wrapped def prepare_acme_client(master, client): # cache the acme service uri acme_host = f'{IPA_CA_RECORD}.{master.domain.name}' acme_server = f'https://{acme_host}/acme/directory' # enable firewall rule on client Firewall(client).enable_services(["http", "https"]) # install acme client packages if not skip_certbot_tests: tasks.install_packages(client, ['certbot']) if not skip_mod_md_tests: tasks.install_packages(client, ['mod_md']) return acme_server def certbot_register(host, acme_server): """method to register the host to acme server""" # clean up any existing registration and certificates host.run_command( [ 'rm', '-rf', '/etc/letsencrypt/accounts', '/etc/letsencrypt/archive', '/etc/letsencrypt/csr', '/etc/letsencrypt/keys', '/etc/letsencrypt/live', '/etc/letsencrypt/renewal', '/etc/letsencrypt/renewal-hooks' ] ) # service is enabled; registration should succeed host.run_command( [ 'certbot', '--server', acme_server, 'register', '-m', 'nobody@example.test', '--agree-tos', '--no-eff-email', ], ) def certbot_standalone_cert(host, acme_server, no_of_cert=1): """method to issue a certbot's certonly standalone cert""" # Get a cert from ACME service using HTTP challenge and Certbot's # standalone HTTP server mode host.run_command(['systemctl', 'stop', 'httpd']) for _i in range(0, no_of_cert): host.run_command( [ 'certbot', '--server', acme_server, 'certonly', '--domain', host.hostname, '--standalone', '--key-type', 'rsa', '--force-renewal' ] ) class TestACME(CALessBase): """ Test the FreeIPA ACME service by using ACME clients on a FreeIPA client. We currently test: * service enable/disable (using Curl) * http-01 challenge with Certbot's standalone HTTP server * dns-01 challenge with Certbot and FreeIPA DNS via hook scripts * revocation with Certbot * http-01 challenge with mod_md Tests we should add: * dns-01 challenge with mod_md (see https://httpd.apache.org/docs/current/mod/mod_md.html#mdchallengedns01) Things that are not implmented/supported yet, but may be in future: * IP address SAN * tls-alpn-01 challenge * Other clients or service scenarios """ num_replicas = 1 num_clients = 1 @classmethod def install(cls, mh): super(TestACME, cls).install(mh) # install packages before client install in case of IPA DNS problems cls.acme_server = prepare_acme_client(cls.master, cls.clients[0]) # Each subclass handles its own server installation procedure if cls.__name__ != 'TestACME': return tasks.install_master(cls.master, setup_dns=True) tasks.install_client(cls.master, cls.clients[0]) tasks.install_replica(cls.master, cls.replicas[0]) def certinstall(self, certfile=None, keyfile=None, pin=None): """Small wrapper around ipa-server-certinstall We are always replacing only the web server with a fixed pre-generated value and returning the result for the caller to figure out. """ self.create_pkcs12('ca1/server', password=None, filename='server.p12') self.copy_cert(self.master, 'server.p12') if pin is None: pin = self.cert_password args = ['ipa-server-certinstall', '-p', self.master.config.dirman_password, '--pin', pin, '-w'] if certfile: # implies keyfile args.append(certfile) args.append(keyfile) else: args.append('server.p12') return self.master.run_command(args, raiseonerr=False) ####### # kinit ####### def test_kinit_master(self): # Some tests require executing ipa commands, e.g. to # check revocation status or add/remove DNS entries. # Preemptively kinit as admin on the master. tasks.kinit_admin(self.master) ##################### # Enable ACME service ##################### def test_acme_service_not_yet_enabled(self): # --fail makes curl exit code 22 when response status >= 400. # ACME service should return 503 because it was not enabled yet. self.clients[0].run_command( ['curl', '--fail', self.acme_server], ok_returncode=22, ) result = self.master.run_command(['ipa-acme-manage', 'status']) assert 'disabled' in result.stdout_text def test_enable_acme_service(self): self.master.run_command(['ipa-acme-manage', 'enable']) # wait a short time for Dogtag ACME service to observe config # change and reconfigure itself to service requests exc = None for _i in range(5): time.sleep(2) try: self.clients[0].run_command( ['curl', '--fail', self.acme_server]) break except Exception as e: exc = e else: raise exc def test_centralize_acme_enable(self): """Test if ACME enable on replica if enabled on master""" status = check_acme_status(self.replicas[0], 'enabled') assert status == 'enabled' ############### # Certbot tests ############### @pytest.mark.skipif(skip_certbot_tests, reason='certbot not available') def test_certbot_register(self): certbot_register(self.clients[0], self.acme_server) @pytest.mark.skipif(skip_certbot_tests, reason='certbot not available') def test_certbot_certonly_standalone(self): certbot_standalone_cert(self.clients[0], self.acme_server) @pytest.mark.skipif(skip_certbot_tests, reason='certbot not available') def test_certbot_revoke(self): # Assume previous certonly operation succeeded. # Read certificate to learn serial number. cert_path = \ f'/etc/letsencrypt/live/{self.clients[0].hostname}/cert.pem' data = self.clients[0].get_file_contents(cert_path) cert = x509.load_pem_x509_certificate(data) # revoke cert via ACME self.clients[0].run_command( [ 'certbot', '--server', self.acme_server, 'revoke', '--cert-name', self.clients[0].hostname, '--delete-after-revoke', ], ) # check cert is revoked (kinit already performed) result = self.master.run_command( ['ipa', 'cert-show', str(cert.serial_number), '--raw'] ) assert 'revocation_reason:' in result.stdout_text @pytest.mark.skipif(skip_certbot_tests, reason='certbot not available') def test_certbot_dns(self): # Assume previous revoke operation succeeded and cert was deleted. # We can now request a new certificate. # Get a cert from ACME service using dns-01 challenge and Certbot's # standalone HTTP server mode self.clients[0].run_command([ 'certbot', '--server', self.acme_server, 'certonly', '--non-interactive', '--domain', self.clients[0].hostname, '--preferred-challenges', 'dns', '--manual', '--manual-public-ip-logging-ok', '--manual-auth-hook', CERTBOT_DNS_IPA_SCRIPT, '--manual-cleanup-hook', CERTBOT_DNS_IPA_SCRIPT, '--key-type', 'rsa', ]) ############## # mod_md tests ############## @pytest.mark.skipif(skip_mod_md_tests, reason='mod_md not available') def test_mod_md(self): if get_selinux_status(self.clients[0]): # mod_md requires its own SELinux policy to grant perms to # maintaining ACME registration and cert state. raise pytest.skip("SELinux is enabled, this will fail") # write config self.clients[0].run_command(['mkdir', '-p', '/etc/httpd/conf.d']) self.clients[0].run_command(['mkdir', '-p', '/etc/httpd/md']) self.clients[0].put_file_contents( '/etc/httpd/conf.d/md.conf', '\n'.join([ f'MDCertificateAuthority {self.acme_server}', 'MDCertificateAgreement accepted', 'MDStoreDir /etc/httpd/md', f'MDomain {self.clients[0].hostname}', '<VirtualHost *:443>', f' ServerName {self.clients[0].hostname}', ' SSLEngine on', '</VirtualHost>\n', ]), ) # To check for successful cert issuance means knowing how mod_md # stores certificates, or looking for specific log messages. # If the thing we are inspecting changes, the test will break. # So I prefer a conservative sleep. # self.clients[0].run_command(['systemctl', 'restart', 'httpd']) time.sleep(15) # We expect mod_md has acquired the certificate by now. # Perform a graceful restart to begin using the cert. # (If mod_md ever learns to start using newly acquired # certificates /without/ the second restart, then both # of these sleeps can be replaced by "loop until good".) # self.clients[0].run_command(['systemctl', 'reload', 'httpd']) time.sleep(3) # HTTPS request from server to client (should succeed) self.master.run_command( ['curl', f'https://{self.clients[0].hostname}']) # clean-up self.clients[0].run_command(['rm', '-rf', '/etc/httpd/md']) self.clients[0].run_command(['rm', '-f', '/etc/httpd/conf.d/md.conf']) ###################### # Disable ACME service ###################### def test_disable_acme_service(self): """ Disable ACME service again, and observe that it no longer services requests. """ self.master.run_command(['ipa-acme-manage', 'disable']) # wait a short time for Dogtag ACME service to observe config # change and reconfigure itself to no longer service requests time.sleep(3) # should fail now self.clients[0].run_command( ['curl', '--fail', self.acme_server], ok_returncode=22, ) def test_centralize_acme_disable(self): """Test if ACME disable on replica if disabled on master""" status = check_acme_status(self.replicas[0], 'disabled') assert status == 'disabled' def test_acme_pruning_no_random_serial(self): """This ACME install is configured without random serial numbers. Verify that we can't enable pruning on it. This test is located here because by default installs don't enable RSNv3. """ if (tasks.get_pki_version(self.master) < tasks.parse_version('11.3.0')): raise pytest.skip("Certificate pruning is not available") self.master.run_command(['ipa-acme-manage', 'enable']) result = self.master.run_command( ['ipa-acme-manage', 'pruning', '--enable'], raiseonerr=False) assert result.returncode == 1 assert "requires random serial numbers" in result.stderr_text @server_install_teardown def test_third_party_certs(self): """Require ipa-ca SAN on replacement web certificates""" self.master.run_command(['ipa-acme-manage', 'enable']) self.create_pkcs12('ca1/server') self.prepare_cacert('ca1') # Re-install the existing Apache certificate that has a SAN to # verify that it will be accepted. pin = self.master.get_file_contents( paths.HTTPD_PASSWD_FILE_FMT.format(host=self.master.hostname) ) result = self.certinstall( certfile=paths.HTTPD_CERT_FILE, keyfile=paths.HTTPD_KEY_FILE, pin=pin ) assert result.returncode == 0 # Install using a 3rd party cert with a missing SAN for ipa-ca # which should be rejected. result = self.certinstall() assert result.returncode == 1 self.master.run_command(['ipa-acme-manage', 'disable']) # Install using a 3rd party cert with a missing SAN for ipa-ca # which should be ok since ACME is disabled. result = self.certinstall() assert result.returncode == 0 # Enable ACME which should fail since the Apache cert lacks the SAN result = self.master.run_command(['ipa-acme-manage', 'enable'], raiseonerr=False) assert result.returncode == 1 assert "invalid 'certificate'" in result.stderr_text class TestACMECALess(IntegrationTest): """Test to check the CA less replica setup""" num_replicas = 1 num_clients = 0 @pytest.fixture def test_setup_teardown(self): tasks.install_master(self.master, setup_dns=True) tasks.install_replica(self.master, self.replicas[0], setup_ca=False) yield tasks.uninstall_replica(self.master, self.replicas[0]) tasks.uninstall_master(self.master) def test_caless_to_cafull_replica(self, test_setup_teardown): """Test ACME is enabled on CA-less replica when converted to CA-full Deployment where one server is deployed as CA-less, when converted to CA full, should have ACME enabled by default. related: https://pagure.io/freeipa/issue/8524 """ tasks.kinit_admin(self.master) # enable acme on master self.master.run_command(['ipa-acme-manage', 'enable']) # check status of acme server on master status = check_acme_status(self.master, 'enabled') assert status == 'enabled' tasks.kinit_admin(self.replicas[0]) # check status of acme on replica, result: CA is not installed result = self.replicas[0].run_command(['ipa-acme-manage', 'status'], raiseonerr=False) assert result.returncode == 3 # Install CA on replica tasks.install_ca(self.replicas[0]) # check acme status, should be enabled now status = check_acme_status(self.replicas[0], 'enabled') assert status == 'enabled' # disable acme on replica self.replicas[0].run_command(['ipa-acme-manage', 'disable']) # check acme status on master, should be disabled status = check_acme_status(self.master, 'disabled') assert status == 'disabled' def test_enable_caless_to_cafull_replica(self, test_setup_teardown): """Test ACME with CA-less replica when converted to CA-full Deployment have one ca-less replica and ACME is not enabled. After converting ca-less replica to ca-full, ACME can be enabled or disabled. related: https://pagure.io/freeipa/issue/8524 """ tasks.kinit_admin(self.master) # check status of acme server on master status = check_acme_status(self.master, 'disabled') assert status == 'disabled' tasks.kinit_admin(self.replicas[0]) # check status of acme on replica, result: CA is not installed result = self.replicas[0].run_command(['ipa-acme-manage', 'status'], raiseonerr=False) assert result.returncode == 3 # Install CA on replica tasks.install_ca(self.replicas[0]) # check acme status on replica, should not throw error status = check_acme_status(self.replicas[0], 'disabled') assert status == 'disabled' # enable acme on replica self.replicas[0].run_command(['ipa-acme-manage', 'enable']) # check acme status on master status = check_acme_status(self.master, 'enabled') assert status == 'enabled' # check acme status on replica status = check_acme_status(self.replicas[0], 'enabled') assert status == 'enabled' # disable acme on master self.master.run_command(['ipa-acme-manage', 'disable']) # check acme status on replica, should be disabled status = check_acme_status(self.replicas[0], 'disabled') assert status == 'disabled' class TestACMEwithExternalCA(TestACME): """Test the FreeIPA ACME service with external CA""" num_replicas = 1 num_clients = 1 @classmethod def install(cls, mh): super(TestACMEwithExternalCA, cls).install(mh) # install master with external-ca result = install_server_external_ca_step1(cls.master) assert result.returncode == 0 root_ca_fname, ipa_ca_fname = tasks.sign_ca_and_transport( cls.master, paths.ROOT_IPA_CSR, ROOT_CA, IPA_CA ) install_server_external_ca_step2( cls.master, ipa_ca_fname, root_ca_fname ) tasks.kinit_admin(cls.master) tasks.install_client(cls.master, cls.clients[0]) tasks.install_replica(cls.master, cls.replicas[0]) @pytest.fixture def issue_and_expire_acme_cert(): """Fixture to expire cert by moving date past expiry of acme cert""" hosts = [] def _issue_and_expire_acme_cert( master, client, acme_server_url, no_of_cert=1 ): hosts.append(master) hosts.append(client) # enable the ACME service on master master.run_command(['ipa-acme-manage', 'enable']) # register the account with certbot certbot_register(client, acme_server_url) # request a standalone acme cert certbot_standalone_cert(client, acme_server_url, no_of_cert) # move system date to expire acme cert for host in hosts: tasks.kdestroy_all(host) tasks.move_date(host, 'stop', '+90days+2hours') # restart ipa services as date moved and wait to get things settle time.sleep(10) master.run_command(['ipactl', 'restart']) time.sleep(10) tasks.get_kdcinfo(master) # Note raiseonerr=False: # the assert is located after kdcinfo retrieval. # run kinit command repeatedly until sssd gets settle # after date change tasks.run_repeatedly( master, "KRB5_TRACE=/dev/stdout kinit admin", stdin_text='{0}\n{0}\n{0}\n'.format( master.config.admin_password ) ) # Retrieve kdc.$REALM after the password change, just in case SSSD # domain status flipped to online during the password change. tasks.get_kdcinfo(master) yield _issue_and_expire_acme_cert # move back date for host in hosts: tasks.move_date(host, 'start', '-90days-2hours') # restart ipa services as date moved and wait to get things settle # if the internal fixture was not called (for instance because the test # was skipped), hosts = [] and hosts[0] would produce an IndexError # exception. if hosts: time.sleep(10) hosts[0].run_command(['ipactl', 'restart']) time.sleep(10) class TestACMERenew(IntegrationTest): num_clients = 1 @classmethod def install(cls, mh): # install packages before client install in case of IPA DNS problems cls.acme_server = prepare_acme_client(cls.master, cls.clients[0]) tasks.install_master(cls.master, setup_dns=True) tasks.install_client(cls.master, cls.clients[0]) @pytest.mark.skipif(skip_certbot_tests, reason='certbot not available') def test_renew(self, issue_and_expire_acme_cert): """Test if ACME renews the issued cert with cerbot This test is to check if ACME certificate renews upon reaching expiry related: https://pagure.io/freeipa/issue/4751 """ issue_and_expire_acme_cert( self.master, self.clients[0], self.acme_server) data = self.clients[0].get_file_contents( f'/etc/letsencrypt/live/{self.clients[0].hostname}/cert.pem' ) cert = x509.load_pem_x509_certificate(data) initial_expiry = cert.not_valid_after_utc self.clients[0].run_command(['certbot', 'renew']) data = self.clients[0].get_file_contents( f'/etc/letsencrypt/live/{self.clients[0].hostname}/cert.pem' ) cert = x509.load_pem_x509_certificate(data) renewed_expiry = cert.not_valid_after_utc assert initial_expiry != renewed_expiry class TestACMEPrune(IntegrationTest): """Validate that ipa-acme-manage configures dogtag for pruning""" random_serial = True num_clients = 1 @classmethod def install(cls, mh): if not pki_supports_RSNv3(mh.master): raise pytest.skip("RNSv3 not supported") tasks.install_master(cls.master, setup_dns=True, random_serial=True) cls.acme_server = prepare_acme_client(cls.master, cls.clients[0]) tasks.install_client(cls.master, cls.clients[0]) @classmethod def uninstall(cls, mh): if not pki_supports_RSNv3(mh.master): raise pytest.skip("RSNv3 not supported") super(TestACMEPrune, cls).uninstall(mh) def test_enable_pruning(self): if (tasks.get_pki_version(self.master) < tasks.parse_version('11.3.0')): raise pytest.skip("Certificate pruning is not available") cs_cfg = self.master.get_file_contents(paths.CA_CS_CFG_PATH) assert "jobsScheduler.job.pruning.enabled=false".encode() in cs_cfg self.master.run_command(['ipa-acme-manage', 'pruning', '--enable']) cs_cfg = self.master.get_file_contents(paths.CA_CS_CFG_PATH) assert "jobsScheduler.enabled=true".encode() in cs_cfg assert "jobsScheduler.job.pruning.enabled=true".encode() in cs_cfg assert "jobsScheduler.job.pruning.owner=ipara".encode() in cs_cfg def test_pruning_options(self): if (tasks.get_pki_version(self.master) < tasks.parse_version('11.3.0')): raise pytest.skip("Certificate pruning is not available") self.master.run_command( ['ipa-acme-manage', 'pruning', '--certretention=60', '--certretentionunit=minute', '--certsearchsizelimit=2000', '--certsearchtimelimit=5',] ) cs_cfg = self.master.get_file_contents(paths.CA_CS_CFG_PATH) assert ( "jobsScheduler.job.pruning.certRetentionTime=60".encode() in cs_cfg ) assert ( "jobsScheduler.job.pruning.certRetentionUnit=minute".encode() in cs_cfg ) assert ( "jobsScheduler.job.pruning.certSearchSizeLimit=2000".encode() in cs_cfg ) assert ( "jobsScheduler.job.pruning.certSearchTimeLimit=5".encode() in cs_cfg ) self.master.run_command( ['ipa-acme-manage', 'pruning', '--requestretention=60', '--requestretentionunit=minute', '--requestsearchsizelimit=2000', '--requestsearchtimelimit=5',] ) cs_cfg = self.master.get_file_contents(paths.CA_CS_CFG_PATH) assert ( "jobsScheduler.job.pruning.requestRetentionTime=60".encode() in cs_cfg ) assert ( "jobsScheduler.job.pruning.requestRetentionUnit=minute".encode() in cs_cfg ) assert ( "jobsScheduler.job.pruning.requestSearchSizeLimit=2000".encode() in cs_cfg ) assert ( "jobsScheduler.job.pruning.requestSearchTimeLimit=5".encode() in cs_cfg ) self.master.run_command( ['ipa-acme-manage', 'pruning', '--cron=0 23 1 * *',] ) cs_cfg = self.master.get_file_contents(paths.CA_CS_CFG_PATH) assert ( "jobsScheduler.job.pruning.cron=0 23 1 * *".encode() in cs_cfg ) def test_pruning_negative_options(self): """Negative option testing for things we directly cover""" if (tasks.get_pki_version(self.master) < tasks.parse_version('11.3.0')): raise pytest.skip("Certificate pruning is not available") result = self.master.run_command( ['ipa-acme-manage', 'pruning', '--enable', '--disable'], raiseonerr=False ) assert result.returncode == 2 assert "Cannot both enable and disable" in result.stderr_text for cmd in ('--config-show', '--run'): result = self.master.run_command( ['ipa-acme-manage', 'pruning', cmd, '--enable'], raiseonerr=False ) assert result.returncode == 2 assert "Cannot change and show config" in result.stderr_text result = self.master.run_command( ['ipa-acme-manage', 'pruning', '--cron=* *'], raiseonerr=False ) assert result.returncode == 2 assert "Invalid format for --cron" in result.stderr_text result = self.master.run_command( ['ipa-acme-manage', 'pruning', '--cron=100 * * * *'], raiseonerr=False ) assert result.returncode == 1 assert "100 not within the range 0-59" in result.stderr_text result = self.master.run_command( ['ipa-acme-manage', 'pruning', '--cron=10 1-5 * * *'], raiseonerr=False ) assert result.returncode == 1 assert "1-5 ranges are not supported" in result.stderr_text def test_prune_cert_manual(self, issue_and_expire_acme_cert): """Test to prune expired certificate by manual run""" if (tasks.get_pki_version(self.master) < tasks.parse_version('11.3.0')): raise pytest.skip("Certificate pruning is not available") issue_and_expire_acme_cert( self.master, self.clients[0], self.acme_server) # check that the certificate issued for the client result = self.master.run_command( ['ipa', 'cert-find', '--subject', self.clients[0].hostname] ) assert f'CN={self.clients[0].hostname}' in result.stdout_text # run prune command manually self.master.run_command(['ipa-acme-manage', 'pruning', '--enable']) self.master.run_command(['ipactl', 'restart']) self.master.run_command(['ipa-acme-manage', 'pruning', '--run']) # wait for cert to get prune time.sleep(50) # check if client cert is removed result = self.master.run_command( ['ipa', 'cert-find', '--subject', self.clients[0].hostname], raiseonerr=False ) assert f'CN={self.clients[0].hostname}' not in result.stdout_text def test_prune_cert_cron(self, issue_and_expire_acme_cert): """Test to prune expired certificate by cron job""" if (tasks.get_pki_version(self.master) < tasks.parse_version('11.3.0')): raise pytest.skip("Certificate pruning is not available") issue_and_expire_acme_cert( self.master, self.clients[0], self.acme_server) # check that the certificate issued for the client result = self.master.run_command( ['ipa', 'cert-find', '--subject', self.clients[0].hostname] ) assert f'CN={self.clients[0].hostname}' in result.stdout_text # enable pruning self.master.run_command(['ipa-acme-manage', 'pruning', '--enable']) # cron would be set to run the next minute cron_minute = self.master.run_command( [ "python3", "-c", ( "from datetime import datetime, timedelta; " "print(int((datetime.now() + " "timedelta(minutes=5)).strftime('%M')))" ), ] ).stdout_text.strip() self.master.run_command( ['ipa-acme-manage', 'pruning', f'--cron={cron_minute} * * * *'] ) self.master.run_command(['ipactl', 'restart']) # wait for 5 minutes to cron to execute and 20 sec for just in case time.sleep(320) # check if client cert is removed result = self.master.run_command( ['ipa', 'cert-find', '--subject', self.clients[0].hostname], raiseonerr=False ) assert f'CN={self.clients[0].hostname}' not in result.stdout_text def test_prune_cert_retention_unit(self, issue_and_expire_acme_cert): """Test to prune expired certificate with retention unit option""" if (tasks.get_pki_version(self.master) < tasks.parse_version('11.3.0')): raise pytest.skip("Certificate pruning is not available") issue_and_expire_acme_cert( self.master, self.clients[0], self.acme_server) # check that the certificate issued for the client result = self.master.run_command( ['ipa', 'cert-find', '--subject', self.clients[0].hostname] ) assert f'CN={self.clients[0].hostname}' in result.stdout_text # enable pruning self.master.run_command(['ipa-acme-manage', 'pruning', '--enable']) # certretention set to 5 min self.master.run_command( ['ipa-acme-manage', 'pruning', '--certretention=5', '--certretentionunit=minute'] ) self.master.run_command(['ipactl', 'restart']) # wait for 5 min and check if expired cert is removed time.sleep(310) self.master.run_command(['ipa-acme-manage', 'pruning', '--run']) result = self.master.run_command( ['ipa', 'cert-find', '--subject', self.clients[0].hostname], raiseonerr=False ) assert f'CN={self.clients[0].hostname}' not in result.stdout_text def test_prune_cert_search_size_limit(self, issue_and_expire_acme_cert): """Test to prune expired certificate with search size limit option""" if (tasks.get_pki_version(self.master) < tasks.parse_version('11.3.0')): raise pytest.skip("Certificate pruning is not available") no_of_cert = 10 search_size_limit = 5 issue_and_expire_acme_cert( self.master, self.clients[0], self.acme_server, no_of_cert) # check that the certificate issued for the client result = self.master.run_command( ['ipa', 'cert-find', '--subject', self.clients[0].hostname] ) assert f'CN={self.clients[0].hostname}' in result.stdout_text assert f'Number of entries returned {no_of_cert}' # enable pruning self.master.run_command(['ipa-acme-manage', 'pruning', '--enable']) # certretention set to 5 min self.master.run_command( ['ipa-acme-manage', 'pruning', f'--certsearchsizelimit={search_size_limit}', '--certsearchtimelimit=100'] ) self.master.run_command(['ipactl', 'restart']) # prune the certificates self.master.run_command(['ipa-acme-manage', 'pruning', '--run']) # check if 5 expired cert is removed result = self.master.run_command( ['ipa', 'cert-find', '--subject', self.clients[0].hostname] ) assert f'Number of entries returned {no_of_cert - search_size_limit}' def test_prune_config_show(self): """Test to check config-show command shows set param""" if (tasks.get_pki_version(self.master) < tasks.parse_version('11.3.0')): raise pytest.skip("Certificate pruning is not available") self.master.run_command(['ipa-acme-manage', 'pruning', '--enable']) self.master.run_command( ['ipa-acme-manage', 'pruning', '--cron=0 0 1 * *'] ) self.master.run_command( ['ipa-acme-manage', 'pruning', '--certretention=30', '--certretentionunit=day'] ) self.master.run_command( ['ipa-acme-manage', 'pruning', '--certsearchsizelimit=1000', '--certsearchtimelimit=0'] ) self.master.run_command( ['ipa-acme-manage', 'pruning', '--requestretention=30', '--requestretentionunit=day'] ) self.master.run_command( ['ipa-acme-manage', 'pruning', '--requestsearchsizelimit=1000', '--requestsearchtimelimit=0'] ) result = self.master.run_command( ['ipa-acme-manage', 'pruning', '--config-show'] ) assert 'Status: enabled' in result.stdout_text assert 'Certificate Retention Time: 30' in result.stdout_text assert 'Certificate Retention Unit: day' in result.stdout_text assert 'Certificate Search Size Limit: 1000' in result.stdout_text assert 'Certificate Search Time Limit: 0' in result.stdout_text assert 'Request Retention Time: 30' in result.stdout_text assert 'Request Retention Unit: day' in result.stdout_text assert 'Request Search Size Limit: 1000' in result.stdout_text assert 'Request Search Time Limit: 0' in result.stdout_text assert 'cron Schedule: 0 0 1 * *' in result.stdout_text def test_prune_disable(self): """Test prune command throw error after disabling the pruning""" if (tasks.get_pki_version(self.master) < tasks.parse_version('11.3.0')): raise pytest.skip("Certificate pruning is not available") self.master.run_command(['ipa-acme-manage', 'pruning', '--disable']) result = self.master.run_command( ['ipa-acme-manage', 'pruning', '--cron=0 0 1 * *'] ) assert 'Status: disabled' in result.stdout_text
36,819
Python
.py
844
33.943128
81
0.610153
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,595
test_replication_layouts.py
freeipa_freeipa/ipatests/test_integration/test_replication_layouts.py
# # Copyright (C) 2017 FreeIPA Contributors see COPYING for license # import time import pytest from ipalib.constants import DOMAIN_LEVEL_0 from ipatests.pytest_ipa.integration.env_config import get_global_config from ipatests.test_integration.base import IntegrationTest from ipatests.pytest_ipa.integration import tasks config = get_global_config() class LayoutsBaseTest(IntegrationTest): @classmethod def install(cls, mh): # tests use custom installation pass def replication_is_working(self): test_user = 'replication-testuser' self.master.run_command( ['ipa', 'user-add', test_user, '--first', 'test', '--last', 'user'] ) time.sleep(60) # make sure the replication of user is done for r in self.replicas: r.run_command(['ipa', 'user-show', test_user]) @pytest.mark.skipif(config.domain_level == DOMAIN_LEVEL_0, reason='does not work on DOMAIN_LEVEL_0 by design') class TestLineTopologyWithoutCA(LayoutsBaseTest): num_replicas = 3 def test_line_topology_without_ca(self): tasks.install_topo('line', self.master, self.replicas, [], setup_replica_cas=False) self.replication_is_working() class TestLineTopologyWithCA(LayoutsBaseTest): num_replicas = 3 def test_line_topology_with_ca(self): tasks.install_topo('line', self.master, self.replicas, [], setup_replica_cas=True) self.replication_is_working() class TestLineTopologyWithCAKRA(LayoutsBaseTest): num_replicas = 3 def test_line_topology_with_ca_kra(self): tasks.install_topo('line', self.master, self.replicas, [], setup_replica_cas=True, setup_replica_kras=True) self.replication_is_working() class TestStarTopologyWithoutCA(LayoutsBaseTest): num_replicas = 3 def test_star_topology_without_ca(self): tasks.install_topo('star', self.master, self.replicas, [], setup_replica_cas=False) self.replication_is_working() class TestStarTopologyWithCA(LayoutsBaseTest): num_replicas = 3 def test_star_topology_with_ca(self): tasks.install_topo('star', self.master, self.replicas, [], setup_replica_cas=True) self.replication_is_working() class TestStarTopologyWithCAKRA(LayoutsBaseTest): num_replicas = 3 def test_star_topology_with_ca_kra(self): tasks.install_topo('star', self.master, self.replicas, [], setup_replica_cas=True, setup_replica_kras=True) self.replication_is_working() class TestCompleteTopologyWithoutCA(LayoutsBaseTest): num_replicas = 3 def test_complete_topology_without_ca(self): tasks.install_topo('complete', self.master, self.replicas, [], setup_replica_cas=False) self.replication_is_working() class TestCompleteTopologyWithCA(LayoutsBaseTest): num_replicas = 3 def test_complete_topology_with_ca(self): tasks.install_topo('complete', self.master, self.replicas, [], setup_replica_cas=True) self.replication_is_working() class TestCompleteTopologyWithCAKRA(LayoutsBaseTest): num_replicas = 3 def test_complete_topology_with_ca_kra(self): tasks.install_topo('complete', self.master, self.replicas, [], setup_replica_cas=True, setup_replica_kras=True) self.replication_is_working() @pytest.mark.skipif(config.domain_level == DOMAIN_LEVEL_0, reason='does not work on DOMAIN_LEVEL_0 by design') class Test2ConnectedTopologyWithoutCA(LayoutsBaseTest): num_replicas = 33 def test_2_connected_topology_without_ca(self): tasks.install_topo('2-connected', self.master, self.replicas, [], setup_replica_cas=False) self.replication_is_working() class Test2ConnectedTopologyWithCA(LayoutsBaseTest): num_replicas = 33 def test_2_connected_topology_with_ca(self): tasks.install_topo('2-connected', self.master, self.replicas, [], setup_replica_cas=True) self.replication_is_working() class Test2ConnectedTopologyWithCAKRA(LayoutsBaseTest): num_replicas = 33 def test_2_connected_topology_with_ca_kra(self): tasks.install_topo('2-connected', self.master, self.replicas, [], setup_replica_cas=True, setup_replica_kras=True) self.replication_is_working() @pytest.mark.skipif(config.domain_level == DOMAIN_LEVEL_0, reason='does not work on DOMAIN_LEVEL_0 by design') class TestDoubleCircleTopologyWithoutCA(LayoutsBaseTest): num_replicas = 29 def test_2_connected_topology_with_ca(self): tasks.install_topo('double-circle', self.master, self.replicas, [], setup_replica_cas=False) self.replication_is_working() class TestDoubleCircleTopologyWithCA(LayoutsBaseTest): num_replicas = 29 def test_2_connected_topology_with_ca(self): tasks.install_topo('double-circle', self.master, self.replicas, [], setup_replica_cas=True) self.replication_is_working() class TestDoubleCircleTopologyWithCAKRA(LayoutsBaseTest): num_replicas = 29 def test_2_connected_topology_with_ca_kra(self): tasks.install_topo('double-circle', self.master, self.replicas, [], setup_replica_cas=True, setup_replica_kras=True) self.replication_is_working()
5,661
Python
.py
119
38.352941
79
0.671228
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,596
test_sudo.py
freeipa_freeipa/ipatests/test_integration/test_sudo.py
# Authors: # Tomas Babej <tbabej@redhat.com> # # Copyright (C) 2014 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import pytest from ipaplatform.paths import paths from ipatests.test_integration.base import IntegrationTest from ipatests.pytest_ipa.integration.tasks import ( clear_sssd_cache, get_host_ip_with_hostmask, remote_sssd_config, FileBackup) class TestSudo(IntegrationTest): """ Test Sudo http://www.freeipa.org/page/V4/Sudo_Integration#Test_Plan """ num_clients = 1 topology = 'line' @classmethod def install(cls, mh): super(TestSudo, cls).install(mh) cls.client = cls.clients[0] cls.clientname = cls.client.run_command( ['hostname', '-s']).stdout_text.strip() for i in range(1, 3): # Add 1. and 2. testing user cls.master.run_command(['ipa', 'user-add', 'testuser%d' % i, '--first', 'Test', '--last', 'User%d' % i]) # Add 1. and 2. testing groups cls.master.run_command(['ipa', 'group-add', 'testgroup%d' % i, '--desc', '"%d. testing group"' % i]) # Add respective members to each group cls.master.run_command(['ipa', 'group-add-member', 'testgroup%d' % i, '--users', 'testuser%d' % i]) # Add hostgroup containing the client cls.master.run_command(['ipa', 'hostgroup-add', 'testhostgroup', '--desc', '"Contains client"']) # Add the client to the host group cls.master.run_command(['ipa', 'hostgroup-add-member', 'testhostgroup', '--hosts', cls.client.hostname]) # Create local user and local group he's member of cls.client.run_command(['groupadd', 'localgroup']) cls.client.run_command(['useradd', '-M', '-G', 'localgroup', 'localuser']) # Create sudorule 'defaults' for not requiring authentication cls.master.run_command(['ipa', 'sudorule-add', 'defaults']) cls.master.run_command(['ipa', 'sudorule-add-option', 'defaults', '--sudooption', "!authenticate"]) # Create test user -- member of group admins cls.master.run_command(['ipa', 'user-add', 'admin2', '--first', 'Admin', '--last', 'Second']) cls.master.run_command(['ipa', 'group-add-member', 'admins', '--users', 'admin2']) @classmethod def uninstall(cls, mh): cls.client.run_command(['groupdel', 'localgroup'], raiseonerr=False) cls.client.run_command(['userdel', 'localuser'], raiseonerr=False) super(TestSudo, cls).uninstall(mh) def list_sudo_commands(self, user, raiseonerr=False, verbose=False): clear_sssd_cache(self.client) list_flag = '-ll' if verbose else '-l' return self.client.run_command( 'su -c "sudo %s -n" %s' % (list_flag, user), raiseonerr=raiseonerr) def reset_rule_categories(self, safe_delete=True): if safe_delete: # Remove and then add the rule back, since the deletion of some # entries might cause setting categories to ALL to fail # and therefore cause false negatives in the tests self.master.run_command(['ipa', 'sudorule-del', 'testrule']) self.master.run_command(['ipa', 'sudorule-add', 'testrule']) self.master.run_command(['ipa', 'sudorule-add-option', 'testrule', '--sudooption', "!authenticate"]) # Reset testrule to allow everything result = self.master.run_command(['ipa', 'sudorule-mod', 'testrule', '--usercat=all', '--hostcat=all', '--cmdcat=all', '--runasusercat=all', '--runasgroupcat=all'], raiseonerr=False) return result # testcases test_admins_group_does_not_have_sudo_permission and # test_advise_script_enable_sudo_admins must be run before any other sudo # rules are applied def test_admins_group_does_not_have_sudo_permission(self): result = self.list_sudo_commands('admin2', raiseonerr=False) assert result.returncode == 1 assert "Sorry, user admin2 may not run sudo on {}.".format( self.clientname) in result.stderr_text def test_advise_script_enable_sudo_admins(self): """ Test for advise scipt to add sudo permissions for admin users https://pagure.io/freeipa/issue/7538 """ result = self.master.run_command('ipa-advise enable_admins_sudo') script = result.stdout_text self.master.run_command('bash', stdin_text=script) try: result = self.list_sudo_commands('admin2') assert '(root) ALL' in result.stdout_text finally: result1 = self.master.run_command( ['ipa', 'sudorule-del', 'admins_all'], raiseonerr=False) result2 = self.master.run_command( ['ipa', 'hbacrule-del', 'admins_sudo'], raiseonerr=False) assert result1.returncode == 0 and result2.returncode == 0,\ 'rules cleanup failed' @pytest.mark.skip_if_platform( "debian", reason="NISDOMAIN has not been set on Debian" ) @pytest.mark.skip_if_container( "any", reason="NISDOMAIN cannot be set in containerized environment" ) def test_nisdomainname(self): result = self.client.run_command('nisdomainname') assert self.client.domain.name in result.stdout_text def test_add_sudo_commands(self): # Group: Readers self.master.run_command(['ipa', 'sudocmd-add', '/bin/cat']) self.master.run_command(['ipa', 'sudocmd-add', '/bin/tail']) # No group self.master.run_command(['ipa', 'sudocmd-add', '/usr/bin/yum']) # Invalid command result = self.master.run_command( ['ipa', 'sudocmd-add', '/bin/cat.'], raiseonerr=False) assert result.returncode == 1 def test_add_sudo_command_groups(self): self.master.run_command(['ipa', 'sudocmdgroup-add', 'readers', '--desc', '"Applications that read"']) self.master.run_command(['ipa', 'sudocmdgroup-add-member', 'readers', '--sudocmds', '/bin/cat']) self.master.run_command(['ipa', 'sudocmdgroup-add-member', 'readers', '--sudocmds', '/bin/tail']) def test_create_allow_all_rule(self): # Create rule that allows everything self.master.run_command(['ipa', 'sudorule-add', 'testrule', '--usercat=all', '--hostcat=all', '--cmdcat=all', '--runasusercat=all', '--runasgroupcat=all']) # Add !authenticate option self.master.run_command(['ipa', 'sudorule-add-option', 'testrule', '--sudooption', "!authenticate"]) def test_add_sudo_rule(self): result1 = self.list_sudo_commands("testuser1") assert "(ALL : ALL) NOPASSWD: ALL" in result1.stdout_text result2 = self.list_sudo_commands("testuser2") assert "(ALL : ALL) NOPASSWD: ALL" in result2.stdout_text def test_sudo_rule_restricted_to_one_user_setup(self): # Configure the rule to not apply to anybody self.master.run_command(['ipa', 'sudorule-mod', 'testrule', '--usercat=']) # Add the testuser1 to the rule self.master.run_command(['ipa', 'sudorule-add-user', 'testrule', '--users', 'testuser1']) def test_sudo_rule_restricted_to_one_user(self): result1 = self.list_sudo_commands("testuser1") assert "(ALL : ALL) NOPASSWD: ALL" in result1.stdout_text result2 = self.list_sudo_commands("testuser2", raiseonerr=False) assert result2.returncode != 0 assert "Sorry, user testuser2 may not run sudo on {}.".format( self.clientname) in result2.stderr_text def test_sudo_rule_restricted_to_one_user_without_defaults_rule(self): # Verify password is requested with the 'defaults' sudorule disabled self.master.run_command(['ipa', 'sudorule-disable', 'defaults']) result3 = self.list_sudo_commands("testuser2", raiseonerr=False) assert result3.returncode != 0 assert "sudo: a password is required" in result3.stderr_text def test_setting_category_to_all_with_valid_entries_user(self): result = self.reset_rule_categories(safe_delete=False) assert result.returncode != 0 def test_sudo_rule_restricted_to_one_user_teardown(self): # Remove the testuser1 from the rule self.master.run_command(['ipa', 'sudorule-remove-user', 'testrule', '--users', 'testuser1']) self.master.run_command(['ipa', 'sudorule-enable', 'defaults']) def test_sudo_rule_restricted_to_one_group_setup(self): # Add the testgroup2 to the rule self.master.run_command(['ipa', 'sudorule-add-user', 'testrule', '--groups', 'testgroup2']) def test_sudo_rule_restricted_to_one_group(self): result1 = self.list_sudo_commands("testuser1", raiseonerr=False) assert result1.returncode != 0 assert "Sorry, user testuser1 may not run sudo on {}.".format( self.clientname) in result1.stderr_text result2 = self.list_sudo_commands("testuser2") assert "(ALL : ALL) NOPASSWD: ALL" in result2.stdout_text def test_setting_category_to_all_with_valid_entries_user_group(self): result = self.reset_rule_categories(safe_delete=False) assert result.returncode != 0 def test_sudo_rule_restricted_to_one_group_teardown(self): # Remove the testgroup2 from the rule self.master.run_command(['ipa', 'sudorule-remove-user', 'testrule', '--groups', 'testgroup2']) def test_sudo_rule_restricted_to_one_host_negative_setup(self): # Reset testrule configuration self.reset_rule_categories() # Configure the rule to not apply anywhere self.master.run_command(['ipa', 'sudorule-mod', 'testrule', '--hostcat=']) # Add the master to the rule self.master.run_command(['ipa', 'sudorule-add-host', 'testrule', '--hosts', self.master.hostname]) def test_sudo_rule_restricted_to_one_host_negative(self): result1 = self.list_sudo_commands("testuser1", raiseonerr=False) assert result1.returncode != 0 assert "Sorry, user testuser1 may not run sudo on {}.".format( self.clientname) in result1.stderr_text def test_sudo_rule_restricted_to_one_host_negative_teardown(self): # Remove the master from the rule self.master.run_command(['ipa', 'sudorule-remove-host', 'testrule', '--hosts', self.master.hostname]) def test_sudo_rule_restricted_to_one_host_setup(self): # Configure the rulle to not apply anywhere self.master.run_command(['ipa', 'sudorule-mod', 'testrule', '--hostcat='], raiseonerr=False) # Add the master to the rule self.master.run_command(['ipa', 'sudorule-add-host', 'testrule', '--hosts', self.client.hostname]) def test_sudo_rule_restricted_to_one_host(self): result1 = self.list_sudo_commands("testuser1", raiseonerr=False) assert "(ALL : ALL) NOPASSWD: ALL" in result1.stdout_text def test_setting_category_to_all_with_valid_entries_host(self): result = self.reset_rule_categories(safe_delete=False) assert result.returncode != 0 def test_sudo_rule_restricted_to_one_host_teardown(self): # Remove the master from the rule self.master.run_command(['ipa', 'sudorule-remove-host', 'testrule', '--hosts', self.client.hostname]) def test_sudo_rule_restricted_to_one_hostgroup_setup(self): # Add the testhostgroup to the rule self.master.run_command(['ipa', 'sudorule-add-host', 'testrule', '--hostgroups', 'testhostgroup']) def test_sudo_rule_restricted_to_one_hostgroup(self): result1 = self.list_sudo_commands("testuser1") assert "(ALL : ALL) NOPASSWD: ALL" in result1.stdout_text def test_setting_category_to_all_with_valid_entries_host_group(self): result = self.reset_rule_categories(safe_delete=False) assert result.returncode != 0 def test_sudo_rule_restricted_to_one_hostgroup_teardown(self): # Remove the testhostgroup from the rule self.master.run_command(['ipa', 'sudorule-remove-host', 'testrule', '--hostgroups', 'testhostgroup']) def test_sudo_rule_restricted_to_one_hostmask_setup(self): # We need to detect the hostmask first full_ip = get_host_ip_with_hostmask(self.client) # Make a note for the next test, which needs to be skipped # if hostmask detection failed self.__class__.skip_hostmask_based = False if not full_ip: self.__class__.skip_hostmask_based = True raise pytest.skip("Hostmask could not be detected") self.master.run_command(['ipa', '-n', 'sudorule-add-host', 'testrule', '--hostmask', full_ip]) # SSSD >= 1.13.3-3 uses native IPA schema instead of compat entries to # pull in sudoers. Since native schema does not (yet) support # hostmasks, we need to point ldap_sudo_search_base to the old schema self.__class__.client_sssd_conf_backup = FileBackup( self.client, paths.SSSD_CONF) domain = self.client.domain with remote_sssd_config(self.client) as sssd_conf: sssd_conf.edit_domain(domain, 'sudo_provider', 'ipa') sssd_conf.edit_domain(domain, 'ldap_sudo_search_base', 'ou=sudoers,{}'.format(domain.basedn)) def test_sudo_rule_restricted_to_one_hostmask(self): if self.__class__.skip_hostmask_based: raise pytest.skip("Hostmask could not be detected") result1 = self.list_sudo_commands("testuser1") assert "(ALL : ALL) NOPASSWD: ALL" in result1.stdout_text def test_setting_category_to_all_with_valid_entries_host_mask(self): result = self.reset_rule_categories(safe_delete=False) assert result.returncode != 0 def test_sudo_rule_restricted_to_one_hostmask_teardown(self): if self.__class__.skip_hostmask_based: raise pytest.skip("Hostmask could not be detected") # Detect the hostmask first to delete the hostmask based rule full_ip = get_host_ip_with_hostmask(self.client) # Remove the client's hostmask from the rule self.master.run_command(['ipa', '-n', 'sudorule-remove-host', 'testrule', '--hostmask', full_ip]) def test_sudo_rule_restricted_to_one_hostmask_negative_setup(self): # Add the master's hostmask to the rule ip = self.master.ip self.master.run_command(['ipa', '-n', 'sudorule-add-host', 'testrule', '--hostmask', '%s/32' % ip]) def test_sudo_rule_restricted_to_one_hostmask_negative(self): result1 = self.list_sudo_commands("testuser1") assert result1.returncode != 0 assert "Sorry, user testuser1 may not run sudo on {}.".format( self.clientname) in result1.stderr_text def test_sudo_rule_restricted_to_one_hostmask_negative_teardown(self): # Remove the master's hostmask from the rule ip = self.master.ip self.master.run_command(['ipa', '-n', 'sudorule-remove-host', 'testrule', '--hostmask', '%s/32' % ip]) # reset ldap_sudo_search_base back to the default value, the old # schema is not needed for the upcoming tests self.client_sssd_conf_backup.restore() def test_sudo_rule_restricted_to_one_command_setup(self): # Reset testrule configuration self.reset_rule_categories() # Configure the rule to not allow any command self.master.run_command(['ipa', 'sudorule-mod', 'testrule', '--cmdcat=']) # Add the yum command to the rule self.master.run_command(['ipa', 'sudorule-add-allow-command', 'testrule', '--sudocmds', '/usr/bin/yum']) def test_sudo_rule_restricted_to_one_command(self): result1 = self.list_sudo_commands("testuser1") assert "(ALL : ALL) NOPASSWD: /usr/bin/yum" in result1.stdout_text def test_sudo_rule_restricted_to_command_and_command_group_setup(self): # Add the readers command group to the rule self.master.run_command(['ipa', 'sudorule-add-allow-command', 'testrule', '--sudocmdgroups', 'readers']) def test_sudo_rule_restricted_to_command_and_command_group(self): result1 = self.list_sudo_commands("testuser1") assert "(ALL : ALL) NOPASSWD:" in result1.stdout_text assert "/usr/bin/yum" in result1.stdout_text assert "/bin/tail" in result1.stdout_text assert "/bin/cat" in result1.stdout_text def test_setting_category_to_all_with_valid_entries_command(self): result = self.reset_rule_categories(safe_delete=False) assert result.returncode != 0 def test_sudo_rule_restricted_to_command_and_command_group_teardown(self): # Remove the yum command from the rule self.master.run_command(['ipa', 'sudorule-remove-allow-command', 'testrule', '--sudocmds', '/usr/bin/yum']) # Remove the readers command group from the rule self.master.run_command(['ipa', 'sudorule-remove-allow-command', 'testrule', '--sudocmdgroups', 'readers']) def test_sudo_rule_restricted_to_running_as_single_user_setup(self): # Reset testrule configuration self.reset_rule_categories() # Configure the rule to not allow running commands as anybody self.master.run_command(['ipa', 'sudorule-mod', 'testrule', '--runasusercat=']) self.master.run_command(['ipa', 'sudorule-mod', 'testrule', '--runasgroupcat=']) # Allow running commands as testuser2 self.master.run_command(['ipa', 'sudorule-add-runasuser', 'testrule', '--users', 'testuser2']) def test_sudo_rule_restricted_to_running_as_single_user(self): result1 = self.list_sudo_commands("testuser1", verbose=True) assert "RunAsUsers: testuser2" in result1.stdout_text assert "RunAsGroups:" not in result1.stdout_text def test_setting_category_to_all_with_valid_entries_runasuser(self): result = self.reset_rule_categories(safe_delete=False) assert result.returncode != 0 def test_sudo_rule_restricted_to_running_as_single_user_teardown(self): # Remove permission to run commands as testuser2 self.master.run_command(['ipa', 'sudorule-remove-runasuser', 'testrule', '--users', 'testuser2']) def test_sudo_rule_restricted_to_running_as_single_local_user_setup(self): # Allow running commands as testuser2 self.master.run_command(['ipa', 'sudorule-add-runasuser', 'testrule', '--users', 'localuser']) def test_sudo_rule_restricted_to_running_as_single_local_user(self): result1 = self.list_sudo_commands("testuser1", verbose=True) assert "RunAsUsers: localuser" in result1.stdout_text assert "RunAsGroups:" not in result1.stdout_text def test_setting_category_to_all_with_valid_entries_runasuser_local(self): result = self.reset_rule_categories(safe_delete=False) assert result.returncode != 0 def test_sudo_rule_restricted_to_running_as_single_user_local_tear(self): # Remove permission to run commands as testuser2 self.master.run_command(['ipa', 'sudorule-remove-runasuser', 'testrule', '--users', 'localuser']) def test_sudo_rule_restricted_to_running_as_users_from_group_setup(self): # Allow running commands as users from testgroup2 self.master.run_command(['ipa', 'sudorule-add-runasuser', 'testrule', '--groups', 'testgroup2']) def test_sudo_rule_restricted_to_running_as_users_from_group(self): result1 = self.list_sudo_commands("testuser1", verbose=True) assert "RunAsUsers: %testgroup2" in result1.stdout_text assert "RunAsGroups:" not in result1.stdout_text def test_setting_category_to_all_with_valid_entries_runasuser_group(self): result = self.reset_rule_categories(safe_delete=False) assert result.returncode != 0 def test_sudo_rule_restricted_to_running_as_users_from_group_teardown(self): # Remove permission to run commands as testuser2 self.master.run_command(['ipa', 'sudorule-remove-runasuser', 'testrule', '--groups', 'testgroup2']) def test_sudo_rule_restricted_to_run_as_users_from_local_group_setup(self): # Allow running commands as users from localgroup self.master.run_command(['ipa', 'sudorule-add-runasuser', 'testrule', '--groups', 'localgroup']) def test_sudo_rule_restricted_to_run_as_users_from_local_group(self): result1 = self.list_sudo_commands("testuser1", verbose=True) assert "RunAsUsers: %localgroup" in result1.stdout_text assert "RunAsGroups:" not in result1.stdout_text def test_set_category_to_all_with_valid_entries_runasuser_group_local(self): result = self.reset_rule_categories(safe_delete=False) assert result.returncode != 0 def test_sudo_rule_restricted_to_run_as_users_from_local_group_tear(self): # Remove permission to run commands as testuser2 self.master.run_command(['ipa', 'sudorule-remove-runasuser', 'testrule', '--groups', 'localgroup']) def test_sudo_rule_restricted_to_running_as_single_group_setup(self): # Allow running commands as testgroup2 self.master.run_command(['ipa', 'sudorule-add-runasgroup', 'testrule', '--groups', 'testgroup2']) def test_sudo_rule_restricted_to_running_as_single_group(self): result1 = self.list_sudo_commands("testuser1", verbose=True) assert "RunAsUsers: testuser1" in result1.stdout_text assert "RunAsGroups: testgroup2" in result1.stdout_text def test_setting_category_to_all_with_valid_entries_runasgroup(self): result = self.reset_rule_categories(safe_delete=False) assert result.returncode != 0 def test_sudo_rule_restricted_to_running_as_single_group_teardown(self): # Remove permission to run commands as testgroup2 self.master.run_command(['ipa', 'sudorule-remove-runasgroup', 'testrule', '--groups', 'testgroup2']) def test_sudo_rule_restricted_to_running_as_single_local_group_setup(self): # Allow running commands as testgroup2 self.master.run_command(['ipa', 'sudorule-add-runasgroup', 'testrule', '--groups', 'localgroup']) def test_sudo_rule_restricted_to_running_as_single_local_group(self): result1 = self.list_sudo_commands("testuser1", verbose=True) assert "RunAsUsers: testuser1" in result1.stdout_text assert "RunAsGroups: localgroup" in result1.stdout_text def test_setting_category_to_all_with_valid_entries_runasgroup_local(self): result = self.reset_rule_categories(safe_delete=False) assert result.returncode != 0 def test_sudo_rule_restricted_to_running_as_single_local_group_tear(self): # Remove permission to run commands as testgroup2 self.master.run_command(['ipa', 'sudorule-remove-runasgroup', 'testrule', '--groups', 'localgroup']) def test_category_all_validation_setup(self): # Reset testrule configuration self.reset_rule_categories() def test_category_all_validation_user(self): # Add the testuser1 to the rule result = self.master.run_command(['ipa', 'sudorule-add-user', 'testrule', '--users', 'testuser1'], raiseonerr=False) assert result.returncode != 0 def test_category_all_validation_user_group(self): # Try to add the testgroup2 to the rule result = self.master.run_command(['ipa', 'sudorule-add-user', 'testrule', '--groups', 'testgroup2'], raiseonerr=False) assert result.returncode != 0 def test_category_all_validation_user_local(self): # Try to add the local user to the rule result = self.master.run_command(['ipa', 'sudorule-add-user', 'testrule', '--users', 'localuser'], raiseonerr=False) assert result.returncode != 0 def test_category_all_validation_host(self): # Try to add the master to the rule result = self.master.run_command(['ipa', 'sudorule-add-host', 'testrule', '--hosts', self.master.hostname], raiseonerr=False) assert result.returncode != 0 def test_category_all_validation_host_group(self): # Try to add the testhostgroup to the rule result = self.master.run_command(['ipa', 'sudorule-add-host', 'testrule', '--hostgroups', 'testhostgroup'], raiseonerr=False) assert result.returncode != 0 def test_category_all_validation_host_mask(self): # Try to add the client's /24 hostmask to the rule ip = self.client.ip result = self.master.run_command(['ipa', '-n', 'sudorule-add-host', 'testrule', '--hostmask', '%s/24' % ip], raiseonerr=False) assert result.returncode != 0 def test_category_all_validation_command_allow(self): # Try to add the yum command to the rule result = self.master.run_command(['ipa', 'sudorule-add-allow-command', 'testrule', '--sudocmds', '/usr/bin/yum'], raiseonerr=False) assert result.returncode != 0 def test_category_all_validation_command_allow_group(self): # Try to add the readers command group to the rule result = self.master.run_command(['ipa', 'sudorule-add-allow-command', 'testrule', '--sudocmdgroups', 'readers'], raiseonerr=False) assert result.returncode != 0 def test_category_all_validation_command_deny(self): # Try to add the yum command to the rule # This SHOULD be allowed self.master.run_command(['ipa', 'sudorule-add-deny-command', 'testrule', '--sudocmds', '/usr/bin/yum'], raiseonerr=False) self.master.run_command(['ipa', 'sudorule-remove-deny-command', 'testrule', '--sudocmds', '/usr/bin/yum'], raiseonerr=False) def test_category_all_validation_command_deny_group(self): # Try to add the readers command group to the rule # This SHOULD be allowed self.master.run_command(['ipa', 'sudorule-add-deny-command', 'testrule', '--sudocmdgroups', 'readers']) self.master.run_command(['ipa', 'sudorule-remove-deny-command', 'testrule', '--sudocmdgroups', 'readers']) def test_category_all_validation_runasuser(self): # Try to allow running commands as testuser2 result = self.master.run_command(['ipa', 'sudorule-add-runasuser', 'testrule', '--users', 'testuser2'], raiseonerr=False) assert result.returncode != 0 def test_category_all_validation_runasuser_group(self): # Try to allow running commands as users from testgroup2 result = self.master.run_command(['ipa', 'sudorule-add-runasuser', 'testrule', '--groups', 'testgroup2'], raiseonerr=False) assert result.returncode != 0 def test_category_all_validation_runasgroup(self): # Try to allow running commands as testgroup2 result = self.master.run_command(['ipa', 'sudorule-add-runasgroup', 'testrule', '--groups', 'testgroup2'], raiseonerr=False) assert result.returncode != 0 def test_domain_resolution_order(self): """Test sudo with runAsUser and domain resolution order. Regression test for bug https://pagure.io/SSSD/sssd/issue/3957. Running commands with sudo as specific user should succeed when sudo rule has ipasudorunas field defined with value of that user and domain-resolution-order is defined in ipa config. """ self.master.run_command( ['ipa', 'config-mod', '--domain-resolution-order', self.domain.name]) try: # prepare the sudo rule: set only one user for ipasudorunas self.reset_rule_categories() self.master.run_command( ['ipa', 'sudorule-mod', 'testrule', '--runasgroupcat=', '--runasusercat='], raiseonerr=False ) self.master.run_command( ['ipa', 'sudorule-add-runasuser', 'testrule', '--users', 'testuser2']) # check that testuser1 is allowed to run commands as testuser2 # according to listing of allowed commands result = self.list_sudo_commands('testuser1') expected_rule = ('(testuser2@%s) NOPASSWD: ALL' % self.domain.name) assert expected_rule in result.stdout_text # check that testuser1 can actually run commands as testuser2 self.client.run_command( ['su', 'testuser1', '-c', 'sudo -u testuser2 true']) finally: self.master.run_command( ['ipa', 'config-mod', '--domain-resolution-order='])
34,613
Python
.py
625
39.8384
80
0.563382
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,597
test_ipa_ipa_migration.py
freeipa_freeipa/ipatests/test_integration/test_ipa_ipa_migration.py
# Copyright (C) 2020 FreeIPA Contributors see COPYING for license # """ Tests to verify ipa-migrate tool. """ from __future__ import absolute_import from ipatests.test_integration.base import IntegrationTest from ipatests.pytest_ipa.integration import tasks from ipaplatform.paths import paths from collections import Counter import pytest import textwrap def prepare_ipa_server(master): """ Setup remote IPA server environment """ # Setup IPA users for i in range(1, 5): master.run_command( [ "ipa", "user-add", "testuser%d" % i, "--first", "Test", "--last", "User%d" % i, ] ) # Setup IPA group master.run_command(["ipa", "group-add", "testgroup"]) # Add respective members to each group master.run_command( ["ipa", "group-add-member", "testgroup", "--users=testuser1"] ) # Adding stage user master.run_command( [ "ipa", "stageuser-add", "--first=Tim", "--last=User", "--password", "tuser1", ] ) # Add Custom idrange master.run_command( [ "ipa", "idrange-add", "testrange", "--base-id=10000", "--range-size=10000", "--rid-base=300000", "--secondary-rid-base=400000", ] ) # Add Automount locations and maps master.run_command(["ipa", "automountlocation-add", "baltimore"]) master.run_command(["ipa", "automountmap-add", "baltimore", "auto.share"]) master.run_command( [ "ipa", "automountmap-add-indirect", "baltimore", "--parentmap=auto.share", "--mount=sub auto.man", ] ) master.run_command( [ "ipa", "automountkey-add", "baltimore", "auto.master", "--key=/share", "--info=auto.share", ] ) # Run ipa-adtrust-install master.run_command(["dnf", "install", "-y", "ipa-server-trust-ad"]) master.run_command( [ "ipa-adtrust-install", "-a", master.config.admin_password, "--add-sids", "-U", ] ) # Generate subids for users master.run_command(["ipa", "subid-generate", "--owner=testuser1"]) master.run_command(["ipa", "subid-generate", "--owner=admin"]) # Add Sudo rules master.run_command(["ipa", "sudorule-add", "readfiles"]) master.run_command(["ipa", "sudocmd-add", "/usr/bin/less"]) master.run_command( [ "ipa", "sudorule-add-allow-command", "readfiles", "--sudocmds", "/usr/bin/less", ] ) master.run_command( [ "ipa", "sudorule-add-host", "readfiles", "--hosts", "server.example.com", ] ) master.run_command( ["ipa", "sudorule-add-user", "readfiles", "--users", "testuser1"] ) # Add Custom CA master.run_command( [ "ipa", "ca-add", "puppet", "--desc", '"Puppet"', "--subject", "CN=Puppet CA,O=TESTRELM.TEST", ] ) # Add ipa roles and add privileges to the role master.run_command( ["ipa", "role-add", "--desc=Junior-level admin", "junioradmin"] ) master.run_command( [ "ipa", "role-add-privilege", "--privileges=User Administrators", "junioradmin", ] ) # Add permission master.run_command( [ "ipa", "permission-add", "--type=user", "--permissions=add", "Add Users", ] ) # Add otp token for testuser1 master.run_command( [ "ipa", "otptoken-add", "--type=totp", "--owner=testuser1", '--desc="My soft token', ] ) # Add a netgroup and user to the netgroup master.run_command( ["ipa", "netgroup-add", '--desc="NFS admins"', "admins"] ) master.run_command( ["ipa", "netgroup-add-member", "--users=testuser2", "admins"] ) # Set krbpolicy policy master.run_command( ["ipa", "krbtpolicy-mod", "--maxlife=99999", "--maxrenew=99999"] ) master.run_command(["ipa", "krbtpolicy-mod", "admin", "--maxlife=9600"]) # Add IPA location master.run_command( ["ipa", "location-add", "location", "--description", "My location"] ) # Add idviews and overrides master.run_command(["ipa", "idview-add", "idview1"]) master.run_command(["ipa", "idoverrideuser-add", "idview1", "testuser1"]) master.run_command( [ "ipa", "idoverrideuser-mod", "idview1", "testuser1", "--shell=/bin/sh", ] ) # Add DNSzone master.run_command( [ "ipa", "dnszone-add", "example.test", "--admin-email=admin@example.test", ] ) master.run_command( ["ipa", "dnszone-mod", "example.test", "--dynamic-update=TRUE"] ) # Add hbac rule master.run_command(["ipa", "hbacrule-add", "--usercat=all", "test1"]) master.run_command( ["ipa", "hbacrule-add", "--hostcat=all", "testuser_sshd"] ) master.run_command( ["ipa", "hbacrule-add-user", "--users=testuser1", "testuser_sshd"] ) master.run_command( ["ipa", "hbacrule-add-service", "--hbacsvcs=sshd", "testuser_sshd"] ) # Vault addition master.run_command( [ "ipa", "vault-add", "--password", "vault1234", "--type", "symmetric", ] ) # Add Selinuxusermap master.run_command( [ "ipa", "selinuxusermap-add", "--usercat=all", "--selinuxuser=xguest_u:s0", "test1", ] ) # Modify passkeyconfig master.run_command( ["ipa", "passkeyconfig-mod", "--require-user-verification=FALSE"] ) def run_migrate( host, mode, remote_host, bind_dn=None, bind_pwd=None, extra_args=None ): """ ipa-migrate tool command """ cmd = ["ipa-migrate"] if mode: cmd.append(mode) if remote_host: cmd.append(remote_host) if bind_dn: cmd.append("-D") cmd.append(bind_dn) if bind_pwd: cmd.append("-w") cmd.append(bind_pwd) if extra_args: for arg in extra_args: cmd.append(arg) result = host.run_command(cmd, raiseonerr=False) return result class TestIPAMigrateScenario1(IntegrationTest): """ Tier-1 tests for ipa-migrate tool with DNS enabled on local and remote server """ num_replicas = 1 num_clients = 1 topology = "line" @classmethod def install(cls, mh): tasks.install_master(cls.master, setup_dns=True, setup_kra=True) prepare_ipa_server(cls.master) tasks.install_client(cls.master, cls.clients[0], nameservers=None) def test_remote_server(self): """ This test installs IPA server instead of replica on system under test with the same realm and domain name. """ tasks.install_master(self.replicas[0], setup_dns=True, setup_kra=True) def test_ipa_migrate_without_kinit_as_admin(self): """ This test checks that ipa-migrate tool displays error when kerberos ticket is missing for admin """ self.replicas[0].run_command(["kdestroy", "-A"]) KINIT_ERR_MSG = "ipa: ERROR: Did not receive Kerberos credentials\n" result = run_migrate( self.replicas[0], "stage-mode", self.master.hostname, "cn=Directory Manager", self.master.config.admin_password, extra_args=['-x'], ) assert result.returncode == 1 assert KINIT_ERR_MSG in result.stderr_text tasks.kinit_admin(self.replicas[0]) def test_ipa_migrate_log_file_is_created(self): """ This test checks that ipa-migrate.log file is created when ipa-migrate tool is run """ run_migrate( self.replicas[0], "stage-mode", self.master.hostname, "cn=Directory Manager", self.master.config.admin_password, extra_args=['-x'], ) assert self.replicas[0].transport.file_exists(paths.IPA_MIGRATE_LOG) def test_ipa_migrate_with_incorrect_bind_pwd(self): """ This test checks that ipa-migrate tool fails with incorrect bind password """ ERR_MSG = ( "IPA to IPA migration starting ...\n" "Failed to bind to remote server: Insufficient access: " "Invalid credentials\n" ) result = run_migrate( self.replicas[0], "stage-mode", self.master.hostname, "cn=Directory Manager", "incorrect_bind_pwd", extra_args=['-x'], ) assert result.returncode == 1 assert ERR_MSG in result.stderr_text def test_ipa_migrate_with_incorrect_bind_dn(self): """ This test checks that ipa-migrate tool fails with incorrect bind dn """ ERR_MSG = ( "IPA to IPA migration starting ...\n" "Failed to bind to remote server: Insufficient access: " "Invalid credentials\n" ) result = run_migrate( self.replicas[0], "stage-mode", self.master.hostname, "cn=Dir Manager", self.master.config.admin_password, extra_args=['-x'], ) assert result.returncode == 1 assert ERR_MSG in result.stderr_text def test_ipa_migrate_with_invalid_host(self): """ This test checks that ipa-migrate tools fails with invalid host """ hostname = "server.invalid.host" ERR_MSG = ( "IPA to IPA migration starting ...\n" "Failed to bind to remote server: cannot connect to " "'ldap://" "{}': \n".format(hostname) ) result = run_migrate( self.replicas[0], "stage-mode", "server.invalid.host", "cn=Directory Manager", self.master.config.admin_password, extra_args=['-x'], ) assert result.returncode == 1 assert ERR_MSG in result.stderr_text def test_dry_run_record_output_ldif(self): """ This testcase run ipa-migrate tool with the -o option which captures the output to ldif file """ ldif_file = "/tmp/test.ldif" param = ['-x', '-o', ldif_file] run_migrate( self.replicas[0], "stage-mode", self.master.hostname, "cn=Directory Manager", self.master.config.admin_password, extra_args=param, ) assert self.replicas[0].transport.file_exists("/tmp/test.ldif") @pytest.fixture() def empty_log_file(self): """ This fixture empties the log file before ipa-migrate tool is run since the log is appended everytime the tool is run. """ self.replicas[0].run_command( ["truncate", "-s", "0", paths.IPA_MIGRATE_LOG] ) yield def test_ipa_sigden_plugin_fail_error(self, empty_log_file): """ This testcase checks that sidgen plugin fail error is not seen during migrate prod-mode """ SIDGEN_ERR_MSG = "SIDGEN task failed: \n" run_migrate( self.replicas[0], "stage-mode", self.master.hostname, "cn=Directory Manager", self.master.config.admin_password, extra_args=['-x'], ) error_msg = self.replicas[0].get_file_contents( paths.IPA_MIGRATE_LOG, encoding="utf-8" ) assert SIDGEN_ERR_MSG not in error_msg def test_ipa_migrate_stage_mode_dry_run(self, empty_log_file): """ Test ipa-migrate stage mode with dry-run option """ tasks.kinit_admin(self.master) tasks.kinit_admin(self.replicas[0]) IPA_MIGRATE_STAGE_DRY_RUN_LOG = "--dryrun=True\n" IPA_SERVER_UPRGADE_LOG = "Skipping ipa-server-upgrade in dryrun mode.\n" IPA_SKIP_SIDGEN_LOG = "Skipping SIDGEN task in dryrun mode." result = run_migrate( self.replicas[0], "stage-mode", self.master.hostname, "cn=Directory Manager", self.master.config.admin_password, extra_args=['-x'], ) install_msg = self.replicas[0].get_file_contents( paths.IPA_MIGRATE_LOG, encoding="utf-8" ) assert result.returncode == 0 assert IPA_MIGRATE_STAGE_DRY_RUN_LOG in install_msg assert IPA_SERVER_UPRGADE_LOG in install_msg assert IPA_SKIP_SIDGEN_LOG in install_msg def test_ipa_migrate_prod_mode_dry_run(self, empty_log_file): """ Test ipa-migrate prod mode with dry run option """ tasks.kinit_admin(self.master) tasks.kinit_admin(self.replicas[0]) IPA_MIGRATE_PROD_DRY_RUN_LOG = "--dryrun=True\n" IPA_SERVER_UPRGADE_LOG = ( "Skipping ipa-server-upgrade in dryrun mode.\n" ) IPA_SIDGEN_LOG = "Skipping SIDGEN task in dryrun mode.\n" result = run_migrate( self.replicas[0], "prod-mode", self.master.hostname, "cn=Directory Manager", self.master.config.admin_password, extra_args=['-x'], ) install_msg = self.replicas[0].get_file_contents( paths.IPA_MIGRATE_LOG, encoding="utf-8" ) assert result.returncode == 0 assert IPA_MIGRATE_PROD_DRY_RUN_LOG in install_msg assert IPA_SERVER_UPRGADE_LOG in install_msg assert IPA_SIDGEN_LOG in install_msg def test_ipa_migrate_with_skip_schema_option_dry_run(self, empty_log_file): """ This test checks that ipa-migrate tool works with -S(schema) options in stage mode """ param = ['-x', '-S'] tasks.kinit_admin(self.master) tasks.kinit_admin(self.replicas[0]) SKIP_SCHEMA_MSG_LOG = "Schema Migration " \ "(migrated 0 definitions)\n" run_migrate( self.replicas[0], "stage-mode", self.master.hostname, "cn=Directory Manager", self.master.config.admin_password, extra_args=param, ) install_msg = self.replicas[0].get_file_contents( paths.IPA_MIGRATE_LOG, encoding="utf-8" ) assert SKIP_SCHEMA_MSG_LOG in install_msg def test_ipa_migrate_with_skip_config_option_dry_run(self, empty_log_file): """ This test checks that ipa-migrate tool works with -C(config) options in stage mode """ SKIP_MIGRATION_CONFIG_LOG = "DS Configuration Migration " \ "(migrated 0 entries)\n" param = ['-x', '-C'] tasks.kinit_admin(self.master) tasks.kinit_admin(self.replicas[0]) run_migrate( self.replicas[0], "stage-mode", self.master.hostname, "cn=Directory Manager", self.master.config.admin_password, extra_args=param, ) install_msg = self.replicas[0].get_file_contents( paths.IPA_MIGRATE_LOG, encoding="utf-8" ) assert SKIP_MIGRATION_CONFIG_LOG in install_msg def test_ipa_migrate_reset_range(self, empty_log_file): """ This test checks the reset range option -r along with prod-mode, since stage-mode this is done automatically. """ param = ['-r', '-n'] tasks.kinit_admin(self.master) tasks.kinit_admin(self.replicas[0]) RESET_RANGE_LOG = "--reset-range=True\n" run_migrate( self.replicas[0], "prod-mode", self.master.hostname, "cn=Directory Manager", self.master.config.admin_password, extra_args=param, ) install_msg = self.replicas[0].get_file_contents( paths.IPA_MIGRATE_LOG, encoding="utf-8" ) assert RESET_RANGE_LOG in install_msg def test_ipa_migrate_stage_mode_dry_override_schema(self, empty_log_file): """ This test checks that -O option (override schema) works in dry mode """ param = ['-x', '-O', '-n'] tasks.kinit_admin(self.master) tasks.kinit_admin(self.replicas[0]) SCHEMA_OVERRIDE_LOG = "--schema-overwrite=True\n" run_migrate( self.replicas[0], "stage-mode", self.master.hostname, "cn=Directory Manager", self.master.config.admin_password, extra_args=param, ) install_msg = self.replicas[0].get_file_contents( paths.IPA_MIGRATE_LOG, encoding="utf-8" ) assert SCHEMA_OVERRIDE_LOG in install_msg def test_ipa_migrate_stage_mode(self, empty_log_file): """ This test checks that ipa-migrate is successful in dry run mode """ tasks.kinit_admin(self.master) tasks.kinit_admin(self.replicas[0]) MIGRATION_SCHEMA_LOG_MSG = "Migrating schema ...\n" MIGRATION_CONFIG_LOG_MSG = "Migrating configuration ...\n" IPA_UPGRADE_LOG_MSG = ( "Running ipa-server-upgrade ... (this may take a while)\n" ) SIDGEN_TASK_LOG_MSG = "Running SIDGEN task ...\n" MIGRATION_COMPLETE_LOG_MSG = "Migration complete!\n" result = run_migrate( self.replicas[0], "stage-mode", self.master.hostname, "cn=Directory Manager", self.master.config.admin_password, extra_args=['-n'], ) install_msg = self.replicas[0].get_file_contents( paths.IPA_MIGRATE_LOG, encoding="utf-8" ) assert result.returncode == 0 assert MIGRATION_SCHEMA_LOG_MSG in install_msg assert MIGRATION_CONFIG_LOG_MSG in install_msg assert IPA_UPGRADE_LOG_MSG in install_msg assert SIDGEN_TASK_LOG_MSG in install_msg assert MIGRATION_COMPLETE_LOG_MSG in install_msg def test_ipa_migrate_prod_mode(self, empty_log_file): """ This test checks that ipa-migrate is successful in prod run mode """ tasks.kinit_admin(self.master) tasks.kinit_admin(self.replicas[0]) MIGRATION_SCHEMA_LOG_MSG = "Migrating schema ...\n" MIGRATION_DATABASE_LOG_MSG = ( "Migrating database ... (this may take a while)\n" ) IPA_UPGRADE_LOG_MSG = ( "Running ipa-server-upgrade ... (this may take a while)\n" ) SIDGEN_TASK_LOG_MSG = "Running SIDGEN task ...\n" result = run_migrate( self.replicas[0], "prod-mode", self.master.hostname, "cn=Directory Manager", self.master.config.admin_password, extra_args=['-n'], ) install_msg = self.replicas[0].get_file_contents( paths.IPA_MIGRATE_LOG, encoding="utf-8" ) assert result.returncode == 0 assert MIGRATION_SCHEMA_LOG_MSG in install_msg assert MIGRATION_DATABASE_LOG_MSG in install_msg assert IPA_UPGRADE_LOG_MSG in install_msg assert SIDGEN_TASK_LOG_MSG in install_msg def test_ipa_migrate_with_bind_pwd_file_option(self, empty_log_file): """ This testcase checks that ipa-migrate tool works with valid bind_pwd specified in a file using '-j' option """ DEBUG_MSG = "--bind-pw-file=/tmp/pwd.txt\n" bind_pwd_file = "/tmp/pwd.txt" bind_pwd_file_content = self.master.config.admin_password self.replicas[0].put_file_contents( bind_pwd_file, bind_pwd_file_content ) param = ['-j', bind_pwd_file, '-x'] result = run_migrate( host=self.replicas[0], mode="stage-mode", remote_host=self.master.hostname, bind_dn="cn=Directory Manager", bind_pwd=None, extra_args=param, ) install_msg = self.replicas[0].get_file_contents( paths.IPA_MIGRATE_LOG, encoding="utf-8" ) assert DEBUG_MSG in install_msg assert result.returncode == 0 def test_ipa_migrate_using_db_ldif(self): """ This test checks that ipa-migrate tool works with db ldif file using -C option """ DB_LDIF_LOG = "--db-ldif=/tmp/dse.ldif\n" tasks.kinit_admin(self.master) tasks.kinit_admin(self.replicas[0]) ldif_file_path = "/tmp/dse.ldif" param = ["-f", ldif_file_path, "-n", "-x"] realm_name = self.master.domain.realm base_dn = str(self.master.domain.basedn) dse_ldif = textwrap.dedent( f""" dn: cn={realm_name},cn=kerberos,{base_dn} cn: {realm_name} objectClass: top objectClass: krbrealmcontainer """ ).format( realm_name=self.master.domain.realm, base_dn=str(self.master.domain.basedn), ) self.replicas[0].put_file_contents(ldif_file_path, dse_ldif) result = run_migrate( self.replicas[0], "stage-mode", self.master.hostname, "cn=Directory Manager", self.master.config.admin_password, extra_args=param, ) install_msg = self.replicas[0].get_file_contents( paths.IPA_MIGRATE_LOG, encoding="utf-8" ) assert result.returncode == 0 assert DB_LDIF_LOG in install_msg def test_ipa_migrate_using_invalid_dbldif_file(self): """ This testcase checks that proper error msg is displayed when invalid ldif file without realm is used as input to schema config option -f """ ERR_MSG = ( "IPA to IPA migration starting ...\n" "Unable to find realm from remote LDIF\n" ) tasks.kinit_admin(self.master) tasks.kinit_admin(self.replicas[0]) base_dn = str(self.master.domain.basedn) ldif_file = "/tmp/ldif_file" param = ["-f", ldif_file, "-n", "-x"] dse_ldif = textwrap.dedent( """ version: 1 dn: cn=schema,{} """ ).format(base_dn) self.replicas[0].put_file_contents(ldif_file, dse_ldif) result = run_migrate( self.replicas[0], "prod-mode", self.master.hostname, "cn=Directory Manager", self.master.config.admin_password, extra_args=param, ) assert result.returncode == 2 assert ERR_MSG in result.stderr_text def test_ipa_migrate_subtree_option(self): """ This testcase checks the subtree option -s along with the ipa-migrate command """ base_dn = str(self.master.domain.basedn) subtree = 'cn=security,{}'.format(base_dn) params = ['-s', subtree, '-n', '-x'] base_dn = str(self.master.domain.basedn) CUSTOM_SUBTREE_LOG = ( "Add db entry 'cn=security,{} - custom'" ).format(base_dn) dse_ldif = textwrap.dedent( """ dn: cn=security,{base_dn} changetype: add objectClass:top objectClass: nscontainer """ ).format(base_dn=base_dn) tasks.ldapmodify_dm(self.master, dse_ldif) result = run_migrate( self.replicas[0], "stage-mode", self.master.hostname, "cn=Directory Manager", self.master.config.admin_password, extra_args=params, ) assert result.returncode == 0 install_msg = self.replicas[0].get_file_contents( paths.IPA_MIGRATE_LOG, encoding="utf-8" ) assert CUSTOM_SUBTREE_LOG in install_msg @pytest.fixture() def modify_dns_zone(self): zone_name = 'ipatest.test' self.master.run_command( ["ipa", "dnszone-add", zone_name, "--force"] ) yield self.replicas[0].run_command( ["ipa", "dnszone-del", zone_name] ) def test_ipa_migrate_dns_option(self, modify_dns_zone): """ This testcase checks that when migrate dns option -B is used the dns entry is migrated to the local host. """ zone_name = "ipatest.test." base_dn = str(self.master.domain.basedn) DNS_LOG1 = "--migrate-dns=True\n" DNS_LOG2 = ( "DEBUG Added entry: idnsname={},cn=dns,{}\n" ).format(zone_name, base_dn) DNS_LOG3 = ( "DEBUG Added entry: idnsname=_kerberos," "idnsname={},cn=dns,{}\n" ).format(zone_name, base_dn) params = ["-B", "-n"] run_migrate( self.replicas[0], "prod-mode", self.master.hostname, "cn=Directory Manager", self.master.config.admin_password, extra_args=params, ) result = self.replicas[0].run_command(["ipa", "dnszone-find"]) assert "Zone name: ipatest.test." in result.stdout_text install_msg = self.replicas[0].get_file_contents( paths.IPA_MIGRATE_LOG, encoding="utf-8" ) assert DNS_LOG1 in install_msg assert DNS_LOG2 in install_msg assert DNS_LOG3 in install_msg def test_ipa_migrate_version_option(self): """ The -V option has been removed. """ CONSOLE_LOG = ( "ipa-migrate: error: the following arguments are " "required: mode, hostname" ) result = self.master.run_command(["ipa-migrate", "-V"], raiseonerr=False) assert result.returncode == 2 assert CONSOLE_LOG in result.stderr_text def test_ipa_migrate_with_log_file_option(self): """ This testcase checks that log file is created with -l option """ custom_log_file = "/tmp/test.log" params = ['-x', '-n', '-l', custom_log_file] run_migrate( self.replicas[0], "stage-mode", self.master.hostname, "cn=Directory Manager", self.master.config.admin_password, extra_args=params, ) assert self.replicas[0].transport.file_exists(custom_log_file) def test_ipa_migrate_stage_mode_with_cert(self): """ This testcase checks that ipa-migrate command works without the 'ValuerError' when -Z <cert> option is used with valid cert """ cert_file = '/tmp/ipa.crt' remote_server_cert = self.master.get_file_contents( paths.IPA_CA_CRT, encoding="utf-8" ) self.replicas[0].put_file_contents(cert_file, remote_server_cert) params = ['-x', '-n', '-Z', cert_file] result = run_migrate( self.replicas[0], "stage-mode", self.master.hostname, "cn=Directory Manager", self.master.config.admin_password, extra_args=params, ) assert result.returncode == 0 def test_ipa_migrate_stage_mode_with_invalid_cert(self): """ This test checks ipa-migrate tool throws error when invalid cert is specified with -Z option """ cert_file = '/tmp/invaid_cert.crt' invalid_cert = ( b'-----BEGIN CERTIFICATE-----\n' b'MIIFazCCDQYJKoZIhvcNAQELBQAw\n' b'-----END CERTIFICATE-----\n' ) ERR_MSG = "Failed to connect to remote server: " params = ['-x', '-n', '-Z', cert_file] self.replicas[0].put_file_contents(cert_file, invalid_cert) result = run_migrate( self.replicas[0], "stage-mode", self.master.hostname, "cn=Directory Manager", self.master.config.admin_password, extra_args=params, ) assert result.returncode == 1 assert ERR_MSG in result.stderr_text def test_ipa_hbac_rule_duplication(self): """ This testcase checks that default hbac rules are not duplicated on the local server when ipa-migrate command is run. """ run_migrate( self.replicas[0], "prod-mode", self.master.hostname, "cn=Directory Manager", self.master.config.admin_password, extra_args=['-n'] ) result = self.replicas[0].run_command( ['ipa', 'hbacrule-find'] ) lines = result.stdout_text.splitlines() line = [] for i in lines: line.append(i.strip()) count = Counter(line) assert count.get('Rule name: allow_all') < 2 assert count.get('Rule name: allow_systemd-user') < 2
29,915
Python
.py
886
24.022573
80
0.553354
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,598
test_testconfig.py
freeipa_freeipa/ipatests/test_integration/test_testconfig.py
# Authors: # Petr Viktorin <pviktori@redhat.com> # # Copyright (C) 2014 Red Hat # see file 'COPYING' for use and warranty information # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import json import copy from unittest.mock import patch, MagicMock from ipatests.pytest_ipa.integration import config import ipatests.pytest_ipa.integration.host from ipapython.ipautil import write_tmp_file from ipatests.util import assert_deepequal from ipalib.constants import MAX_DOMAIN_LEVEL DEFAULT_OUTPUT_DICT = { "nis_domain": "ipatest", "test_dir": "/root/ipatests", "ad_admin_name": "Administrator", "ipv6": False, "ssh_key_filename": "~/.ssh/id_rsa", "ssh_username": "root", "admin_name": "admin", "ad_admin_password": "Secret123", "ssh_password": None, "dns_forwarder": "8.8.8.8", "domains": [], "dirman_dn": "cn=Directory Manager", "dirman_password": "Secret123", "ntp_server": "ntp.clock.test", "admin_password": "Secret123", "domain_level": MAX_DOMAIN_LEVEL, "log_journal_since": "-1h", "fips_mode": False, "token_name": None, "token_password": None, "token_library": None, } DEFAULT_OUTPUT_ENV = { "IPATEST_DIR": "/root/ipatests", "IPA_ROOT_SSH_KEY": "~/.ssh/id_rsa", "IPA_ROOT_SSH_PASSWORD": "", "ADMINID": "admin", "ADMINPW": "Secret123", "ROOTDN": "cn=Directory Manager", "ROOTDNPWD": "Secret123", "DNSFORWARD": "8.8.8.8", "NISDOMAIN": "ipatest", "NTPSERVER": "ntp.clock.test", "ADADMINID": "Administrator", "ADADMINPW": "Secret123", "IPv6SETUP": "", "IPADEBUG": "", "DOMAINLVL": str(MAX_DOMAIN_LEVEL), "LOG_JOURNAL_SINCE": "-1h", "IPA_FIPS_MODE": "", } DEFAULT_INPUT_ENV = { 'NTPSERVER': 'ntp.clock.test', } DEFAULT_INPUT_DICT = { 'ntp_server': 'ntp.clock.test', 'domains': [], } def extend_dict(defaults, *others, **kwargs): result = dict(defaults) for other in others: result.update(other) result.update(kwargs) return copy.deepcopy(result) @patch.object(ipatests.pytest_ipa.integration.host, 'resolver', MagicMock()) class CheckConfig: def check_config(self, conf): pass def get_input_env(self): return extend_dict(DEFAULT_INPUT_ENV, self.extra_input_env) def get_output_env(self): return extend_dict(DEFAULT_OUTPUT_ENV, self.extra_output_env) def get_input_dict(self): return extend_dict(DEFAULT_INPUT_DICT, self.extra_input_dict) def get_output_dict(self): return extend_dict(DEFAULT_OUTPUT_DICT, self.extra_output_dict) def test_env_to_dict(self): conf = config.Config.from_env(self.get_input_env()) assert_deepequal(self.get_output_dict(), conf.to_dict()) self.check_config(conf) def test_env_to_env(self): conf = config.Config.from_env(self.get_input_env()) assert_deepequal(self.get_output_env(), dict(conf.to_env())) self.check_config(conf) def test_dict_to_env(self): conf = config.Config.from_dict(self.get_input_dict()) assert_deepequal(self.get_output_env(), dict(conf.to_env())) self.check_config(conf) def test_dict_to_dict(self): conf = config.Config.from_dict(self.get_input_dict()) assert_deepequal(self.get_output_dict(), conf.to_dict()) self.check_config(conf) def test_env_roundtrip(self): conf = config.Config.from_env(self.get_output_env()) assert_deepequal(self.get_output_env(), dict(conf.to_env())) self.check_config(conf) def test_dict_roundtrip(self): conf = config.Config.from_dict(self.get_output_dict()) assert_deepequal(self.get_output_dict(), conf.to_dict()) self.check_config(conf) def test_from_json_file(self): file = write_tmp_file(json.dumps(self.get_input_dict())) conf = config.Config.from_env({'IPATEST_JSON_CONFIG': file.name}) assert_deepequal(self.get_output_dict(), conf.to_dict()) self.check_config(conf) # Settings to override: extra_input_dict = {} extra_input_env = {} extra_output_dict = {} extra_output_env = {} class TestEmptyConfig(CheckConfig): extra_input_dict = {} extra_input_env = {} extra_output_dict = {} extra_output_env = {} class TestMinimalConfig(CheckConfig): extra_input_dict = dict( domains=[ dict(name='ipadomain.test', type='IPA', hosts=[ dict(name='master', ip='192.0.2.1', host_type=None), ]), ], ) extra_input_env = dict( MASTER='master.ipadomain.test', BEAKERMASTER1_IP_env1='192.0.2.1', ) extra_output_dict = dict( domains=[ dict( type="IPA", name="ipadomain.test", hosts=[ dict( name='master.ipadomain.test', ip="192.0.2.1", external_hostname="master.ipadomain.test", role="master", host_type=None, ), ], ), ], ) extra_output_env = dict( DOMAIN_env1="ipadomain.test", RELM_env1="IPADOMAIN.TEST", BASEDN_env1="dc=ipadomain,dc=test", MASTER_env1="master.ipadomain.test", BEAKERMASTER_env1="master.ipadomain.test", BEAKERMASTER_IP_env1="192.0.2.1", MASTER1_env1="master.ipadomain.test", BEAKERMASTER1_env1="master.ipadomain.test", BEAKERMASTER1_IP_env1="192.0.2.1", MASTER="master.ipadomain.test", BEAKERMASTER="master.ipadomain.test", MASTERIP="192.0.2.1", ) def check_config(self, conf): assert len(conf.domains) == 1 assert conf.domains[0].name == 'ipadomain.test' assert conf.domains[0].type == 'IPA' assert len(conf.domains[0].hosts) == 1 master = conf.domains[0].master assert master == conf.domains[0].hosts[0] assert master.hostname == 'master.ipadomain.test' assert master.role == 'master' assert conf.domains[0].replicas == [] assert conf.domains[0].clients == [] assert conf.domains[0].hosts_by_role('replica') == [] assert conf.domains[0].host_by_role('master') == master class TestComplexConfig(CheckConfig): extra_input_dict = dict( domains=[ dict(name='ipadomain.test', type='IPA', hosts=[ dict(name='master', ip='192.0.2.1', role='master', host_type=None), dict(name='replica1', ip='192.0.2.2', role='replica', host_type=None), dict(name='replica2', ip='192.0.2.3', role='replica', external_hostname='r2.ipadomain.test', host_type=None), dict(name='client1', ip='192.0.2.4', role='client', host_type=None), dict(name='client2', ip='192.0.2.5', role='client', external_hostname='c2.ipadomain.test', host_type=None), dict(name='extra', ip='192.0.2.6', role='extrarole', host_type=None), dict(name='extram1', ip='192.0.2.7', role='extrarolem', host_type=None), dict(name='extram2', ip='192.0.2.8', role='extrarolem', external_hostname='e2.ipadomain.test', host_type=None), ]), dict(name='addomain.test', type='AD', hosts=[ dict(name='ad', ip='192.0.2.33', role='ad', host_type=None), ]), dict(name='ipadomain2.test', type='IPA', hosts=[ dict(name='master.ipadomain2.test', ip='192.0.2.65', host_type=None), ]), dict(name='adsubdomain.test', type='AD_SUBDOMAIN', hosts=[ dict(name='child_ad', ip='192.0.2.77', role='ad_subdomain', host_type=None), ]), dict(name='adtreedomain.test', type='AD_TREEDOMAIN', hosts=[ dict(name='tree_ad', ip='192.0.2.88', role='ad_treedomain', host_type=None), ]), ], ) extra_input_env = dict( MASTER='master.ipadomain.test', BEAKERMASTER1_IP_env1='192.0.2.1', REPLICA='replica1.ipadomain.test replica2.ipadomain.test', BEAKERREPLICA1_IP_env1='192.0.2.2', BEAKERREPLICA2_IP_env1='192.0.2.3', BEAKERREPLICA2_env1='r2.ipadomain.test', CLIENT='client1.ipadomain.test client2.ipadomain.test', BEAKERCLIENT1_IP_env1='192.0.2.4', BEAKERCLIENT2_IP_env1='192.0.2.5', BEAKERCLIENT2_env1='c2.ipadomain.test', TESTHOST_EXTRAROLE_env1='extra.ipadomain.test', BEAKEREXTRAROLE1_IP_env1='192.0.2.6', TESTHOST_EXTRAROLEM_env1='extram1.ipadomain.test extram2.ipadomain.test', BEAKEREXTRAROLEM1_IP_env1='192.0.2.7', BEAKEREXTRAROLEM2_IP_env1='192.0.2.8', BEAKEREXTRAROLEM2_env1='e2.ipadomain.test', AD_env2='ad.addomain.test', BEAKERAD1_IP_env2='192.0.2.33', MASTER_env3='master.ipadomain2.test', BEAKERMASTER1_IP_env3='192.0.2.65', AD_SUBDOMAIN_env4='child_ad.adsubdomain.test', BEAKERAD_SUBDOMAIN1_IP_env4='192.0.2.77', AD_TREEDOMAIN_env5='tree_ad.adtreedomain.test', BEAKERAD_TREEDOMAIN1_IP_env5='192.0.2.88', ) extra_output_dict = dict( domains=[ dict( type="IPA", name="ipadomain.test", hosts=[ dict( name='master.ipadomain.test', ip="192.0.2.1", external_hostname="master.ipadomain.test", role="master", host_type=None, ), dict( name='replica1.ipadomain.test', ip="192.0.2.2", external_hostname="replica1.ipadomain.test", role="replica", host_type=None, ), dict( name='replica2.ipadomain.test', ip="192.0.2.3", external_hostname="r2.ipadomain.test", role="replica", host_type=None, ), dict( name='client1.ipadomain.test', ip="192.0.2.4", external_hostname="client1.ipadomain.test", role="client", host_type=None, ), dict( name='client2.ipadomain.test', ip="192.0.2.5", external_hostname="c2.ipadomain.test", role="client", host_type=None, ), dict( name='extra.ipadomain.test', ip="192.0.2.6", external_hostname="extra.ipadomain.test", role="extrarole", host_type=None, ), dict( name='extram1.ipadomain.test', ip="192.0.2.7", external_hostname="extram1.ipadomain.test", role="extrarolem", host_type=None, ), dict( name='extram2.ipadomain.test', ip="192.0.2.8", external_hostname="e2.ipadomain.test", role="extrarolem", host_type=None, ), ], ), dict( type="AD", name="addomain.test", hosts=[ dict( name='ad.addomain.test', ip="192.0.2.33", external_hostname="ad.addomain.test", role="ad", host_type=None, ), ], ), dict( type="IPA", name="ipadomain2.test", hosts=[ dict( name='master.ipadomain2.test', ip="192.0.2.65", external_hostname="master.ipadomain2.test", role="master", host_type=None, ), ], ), dict( type="AD_SUBDOMAIN", name="adsubdomain.test", hosts=[ dict( name='child_ad.adsubdomain.test', ip="192.0.2.77", external_hostname="child_ad.adsubdomain.test", role="ad_subdomain", host_type=None, ), ], ), dict( type="AD_TREEDOMAIN", name="adtreedomain.test", hosts=[ dict( name='tree_ad.adtreedomain.test', ip="192.0.2.88", external_hostname="tree_ad.adtreedomain.test", role="ad_treedomain", host_type=None, ), ], ), ], ) extra_output_env = extend_dict( extra_input_env, DOMAIN_env1="ipadomain.test", RELM_env1="IPADOMAIN.TEST", BASEDN_env1="dc=ipadomain,dc=test", MASTER_env1="master.ipadomain.test", BEAKERMASTER_env1="master.ipadomain.test", BEAKERMASTER_IP_env1="192.0.2.1", MASTER="master.ipadomain.test", BEAKERMASTER="master.ipadomain.test", MASTERIP="192.0.2.1", MASTER1_env1="master.ipadomain.test", BEAKERMASTER1_env1="master.ipadomain.test", BEAKERMASTER1_IP_env1="192.0.2.1", REPLICA_env1="replica1.ipadomain.test replica2.ipadomain.test", BEAKERREPLICA_env1="replica1.ipadomain.test r2.ipadomain.test", BEAKERREPLICA_IP_env1="192.0.2.2 192.0.2.3", REPLICA="replica1.ipadomain.test replica2.ipadomain.test", REPLICA1_env1="replica1.ipadomain.test", BEAKERREPLICA1_env1="replica1.ipadomain.test", BEAKERREPLICA1_IP_env1="192.0.2.2", REPLICA2_env1="replica2.ipadomain.test", BEAKERREPLICA2_env1="r2.ipadomain.test", BEAKERREPLICA2_IP_env1="192.0.2.3", SLAVE="replica1.ipadomain.test replica2.ipadomain.test", BEAKERSLAVE="replica1.ipadomain.test r2.ipadomain.test", SLAVEIP="192.0.2.2 192.0.2.3", CLIENT_env1="client1.ipadomain.test client2.ipadomain.test", BEAKERCLIENT_env1="client1.ipadomain.test c2.ipadomain.test", BEAKERCLIENT='client1.ipadomain.test', BEAKERCLIENT2='c2.ipadomain.test', BEAKERCLIENT_IP_env1="192.0.2.4 192.0.2.5", CLIENT="client1.ipadomain.test", CLIENT2="client2.ipadomain.test", CLIENT1_env1="client1.ipadomain.test", BEAKERCLIENT1_env1="client1.ipadomain.test", BEAKERCLIENT1_IP_env1="192.0.2.4", CLIENT2_env1="client2.ipadomain.test", BEAKERCLIENT2_env1="c2.ipadomain.test", BEAKERCLIENT2_IP_env1="192.0.2.5", TESTHOST_EXTRAROLE_env1="extra.ipadomain.test", BEAKEREXTRAROLE_env1="extra.ipadomain.test", BEAKEREXTRAROLE_IP_env1="192.0.2.6", TESTHOST_EXTRAROLE1_env1="extra.ipadomain.test", BEAKEREXTRAROLE1_env1="extra.ipadomain.test", BEAKEREXTRAROLE1_IP_env1="192.0.2.6", TESTHOST_EXTRAROLEM_env1="extram1.ipadomain.test extram2.ipadomain.test", BEAKEREXTRAROLEM_env1="extram1.ipadomain.test e2.ipadomain.test", BEAKEREXTRAROLEM_IP_env1="192.0.2.7 192.0.2.8", TESTHOST_EXTRAROLEM1_env1="extram1.ipadomain.test", BEAKEREXTRAROLEM1_env1="extram1.ipadomain.test", BEAKEREXTRAROLEM1_IP_env1="192.0.2.7", TESTHOST_EXTRAROLEM2_env1="extram2.ipadomain.test", BEAKEREXTRAROLEM2_env1="e2.ipadomain.test", BEAKEREXTRAROLEM2_IP_env1="192.0.2.8", DOMAIN_env2="addomain.test", RELM_env2="ADDOMAIN.TEST", BASEDN_env2="dc=addomain,dc=test", AD_env2="ad.addomain.test", BEAKERAD_env2="ad.addomain.test", BEAKERAD_IP_env2="192.0.2.33", AD1_env2="ad.addomain.test", BEAKERAD1_env2="ad.addomain.test", BEAKERAD1_IP_env2="192.0.2.33", DOMAIN_env3="ipadomain2.test", RELM_env3="IPADOMAIN2.TEST", BASEDN_env3="dc=ipadomain2,dc=test", MASTER_env3="master.ipadomain2.test", BEAKERMASTER_env3="master.ipadomain2.test", BEAKERMASTER_IP_env3="192.0.2.65", MASTER1_env3="master.ipadomain2.test", BEAKERMASTER1_env3="master.ipadomain2.test", BEAKERMASTER1_IP_env3="192.0.2.65", DOMAIN_env4="adsubdomain.test", RELM_env4="ADSUBDOMAIN.TEST", AD_SUBDOMAIN_env4='child_ad.adsubdomain.test', AD_SUBDOMAIN1_env4='child_ad.adsubdomain.test', BEAKERAD_SUBDOMAIN1_IP_env4='192.0.2.77', BEAKERAD_SUBDOMAIN1_env4='child_ad.adsubdomain.test', BEAKERAD_SUBDOMAIN_IP_env4='192.0.2.77', BEAKERAD_SUBDOMAIN_env4='child_ad.adsubdomain.test', BASEDN_env4='dc=adsubdomain,dc=test', DOMAIN_env5="adtreedomain.test", RELM_env5="ADTREEDOMAIN.TEST", AD_TREEDOMAIN_env5='tree_ad.adtreedomain.test', AD_TREEDOMAIN1_env5='tree_ad.adtreedomain.test', BEAKERAD_TREEDOMAIN1_IP_env5='192.0.2.88', BEAKERAD_TREEDOMAIN1_env5='tree_ad.adtreedomain.test', BEAKERAD_TREEDOMAIN_IP_env5='192.0.2.88', BEAKERAD_TREEDOMAIN_env5='tree_ad.adtreedomain.test', BASEDN_env5='dc=adtreedomain,dc=test', ) def check_config(self, conf): assert len(conf.domains) == 5 main_dom = conf.domains[0] (client1, client2, extra, extram1, extram2, _master, replica1, replica2) = sorted(main_dom.hosts, key=lambda h: h.role) assert main_dom.name == 'ipadomain.test' assert main_dom.type == 'IPA' assert sorted(main_dom.roles) == ['client', 'extrarole', 'extrarolem', 'master', 'replica'] assert main_dom.static_roles == ('master', 'replica', 'client', 'other') assert sorted(main_dom.extra_roles) == ['extrarole', 'extrarolem'] assert main_dom.replicas == [replica1, replica2] assert main_dom.clients == [client1, client2] assert main_dom.hosts_by_role('replica') == [replica1, replica2] assert main_dom.hosts_by_role('extrarolem') == [extram1, extram2] assert main_dom.host_by_role('extrarole') == extra assert extra.ip == '192.0.2.6' assert extram2.hostname == 'extram2.ipadomain.test' assert extram2.external_hostname == 'e2.ipadomain.test' ad_dom = conf.domains[1] assert ad_dom.roles == ['ad'] assert ad_dom.static_roles == ('ad',) assert ad_dom.extra_roles == [] ad_sub_domain = conf.domains[3] assert ad_sub_domain.roles == ['ad_subdomain'] assert ad_sub_domain.static_roles == ('ad_subdomain',) assert ad_sub_domain.extra_roles == [] ad_tree_domain = conf.domains[4] assert ad_tree_domain.roles == ['ad_treedomain'] assert ad_tree_domain.static_roles == ('ad_treedomain',) assert ad_tree_domain.extra_roles == []
20,536
Python
.py
493
29.977688
81
0.559758
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
16,599
test_idm_api.py
freeipa_freeipa/ipatests/test_integration/test_idm_api.py
# # Copyright (C) 2018 FreeIPA Contributors see COPYING for license # from __future__ import absolute_import from ipatests.test_integration.base import IntegrationTest import textwrap API_INIT = """ from ipalib import api, errors api.bootstrap_with_global_options(context="server") api.finalize() api.Backend.ldap2.connect() """ CERT = ( b"MIIEkDCCAvigAwIBAgIBCzANBgkqhkiG9w0BAQsFADA5MRcwFQYDVQQKD\n" b"A5URVNUUkVBTE0uVEVTVDEeMBwGA1UEAwwVQ2VydGlmaWNhdGUgQXV0aG\n" b"9yaXR5MB4XDTIzMDcyODE3MTIxOVoXDTI1MDcyODE3MTIxOVowKjEXMBU\n" b"GA1UECgwOVEVTVFJFQUxNLlRFU1QxDzANBgNVBAMMBmpzbWl0aDCCASIw\n" b"DQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAOF0XFrdVXmKp95AVZW5o\n" b"BWcij6vJPqeU3UpzTLbM+fROhNaKMX9S+yXrJHifOmhCOuNA8TtptKVJx\n" b"CIDZ1/5KwPBk4vrnwOBtVMCftHj87MabBqV/nmQQrCiKTcJu4aQEDI9Qh\n" b"yza09EJKvG8KkpnyuShtkP2LgkUxIqkjBg4DLV7grO+I+aG17QTuQxUTy\n" b"icfYDBnzD4hTKPLf7d9KNyG+sEeyN0gceLFMUYaQ4lyapcSzYJwOSAc2B\n" b"EU73tLaJlQORHL7HmhxrjD1IgZyxFjp/ofLVZFFoJAqjz2FWzOxmQw+bc\n" b"0WTzQjeSTGx+l3htj7MmhIRBMqr3Um6zXkLKMCAwEAAaOCATAwggEsMB8\n" b"GA1UdIwQYMBaAFCIXu6QtsiBVo1yZQZ7MMHTl5Wj6MEAGCCsGAQUFBwEB\n" b"BDQwMjAwBggrBgEFBQcwAYYkaHR0cDovL2lwYS1jYS50ZXN0cmVhbG0ud\n" b"GVzdC9jYS9vY3NwMA4GA1UdDwEB/wQEAwIE8DAdBgNVHSUEFjAUBggrBg\n" b"EFBQcDAQYIKwYBBQUHAwIweQYDVR0fBHIwcDBuoDagNIYyaHR0cDovL2l\n" b"wYS1jYS50ZXN0cmVhbG0udGVzdC9pcGEvY3JsL01hc3RlckNSTC5iaW6i\n" b"NKQyMDAxDjAMBgNVBAoMBWlwYWNhMR4wHAYDVQQDDBVDZXJ0aWZpY2F0Z\n" b"SBBdXRob3JpdHkwHQYDVR0OBBYEFNwQNQAG8MsKQPwMFyGzRiMzRAa5MA\n" b"0GCSqGSIb3DQEBCwUAA4IBgQB2g0mS8XAPI+aRBa5q7Vbp1245CvMP0Eq\n" b"Cz6gvCNwtxW0UDKnB++d/YQ13ft+x9Xj3rB/M2YXxdxTpQnQQv34CUcyh\n" b"PQKJthAsbKBpdusCGrbS54zKFR0MjxwOwIIDHuI6eu2AoSpsmYs5UGzQm\n" b"oCfQhbImK7iGLy0rOHaON1cWAFmC6lzJ2TFELc4N3eLYGVZy2ZtyZTgA3\n" b"l97rBCwbDDFF1JWoOByIq8Ij99ksyMXws++sNUpo/1l8Jt0Gn6RBiidZB\n" b"ef4+kJN+t6RAAwRQ / 3cmEggXcFoV13KZ70PeMXeX6CKMwXIwt3q7A78\n" b"Wc/0OIBREZLhXpkmogCzWCuatdzeBIhMhx0vDEzaxlhf32ZWfN5pFMpgq\n" b"wLZsdwMf6J65kGbE5Pg3Yxk7OiByxZJnR8UlvbU3r6RhMWutD6C0aqqNt\n" b"o3us5gTmfRc8Mf1l/BUgDqkBKOTU8FHREGemG1HoklBym/Pbua0VMUA+s\n" b"0nECR4LLM/o9PCJ2Y3QPBZy8Hg=\n" ) class TestAPIScenario(IntegrationTest): """ Tests for IDM API scenarios """ topology = "line" def create_and_run_script(self, filename, user_code_script): self.master.put_file_contents(filename, user_code_script) self.master.run_command(["python3", filename]) self.master.run_command(["rm", filename]) def test_idm_user_add(self): """ This test checks that ipa user using api.Command["user_add"] and then checks that user is displayed using api.Command["user_show"] """ user_code_script = textwrap.dedent( f""" {API_INIT} api.Command["user_add"]("jsmith", givenname="John", sn="Smith", ipauserauthtype="otp") cmd = api.Command["user_show"]("jsmith", all=True)["result"] assert 'otp' in cmd['ipauserauthtype'] assert 'John Smith' in cmd['cn'] """ ) self.create_and_run_script( "/tmp/user_add.py", user_code_script ) def test_idm_user_find(self): """ This test checks that user is displayed using api.Command["user_find"] """ user_code_script = textwrap.dedent( f""" {API_INIT} cmd = api.Command["user_find"]("jsmith") assert '1 user matched' in cmd['summary'] """ ) self.create_and_run_script( "/tmp/user_find.py", user_code_script ) def test_idm_user_mod(self): """ This test checks that user attribute is modified using api.Command["user_mod"] """ user_code_script = textwrap.dedent( f""" {API_INIT} cmd = api.Command["user_mod"]("jsmith", mail="jsmith@example.org")["result"] assert 'jsmith@example.org' in cmd['mail'] """ ) self.create_and_run_script( "/tmp/user_mod.py", user_code_script ) def test_disable_user(self): """ This test checks that user is disabled using api.Command["user_disable"] """ user_code_script = textwrap.dedent( f""" {API_INIT} cmd = api.Command["user_disable"]("jsmith") assert 'Disabled user account "jsmith"' in cmd['summary'] """ ) self.create_and_run_script( "/tmp/disable_user.py", user_code_script ) def test_enable_user(self): """ This test checks that user is enabled using api.Command["user_enable"] """ user_code_script = textwrap.dedent( f""" {API_INIT} cmd = api.Command["user_enable"]("jsmith") assert 'Enabled user account "jsmith"' in cmd['summary'] """ ) self.create_and_run_script( "/tmp/enable_user.py", user_code_script ) def test_create_ipa_group(self): """ This test checks that group is created using api.Command["group_add"] """ user_code_script = textwrap.dedent( f""" {API_INIT} cmd = api.Command["group_add"]("developers", gidnumber=500, description="Developers") assert 'Added group "developers"' in cmd['summary'] """ ) self.create_and_run_script( "/tmp/create_group.py", user_code_script ) def test_show_ipa_group(self): """ This test checks that group is displayed using api.Command["group_show"] """ user_code_script = textwrap.dedent( f""" {API_INIT} cmd = api.Command["group_show"]("developers") assert 'developers' in cmd['result']['cn'] """ ) self.create_and_run_script( "/tmp/group_show.py", user_code_script ) def test_ipa_group_mod(self): """ This test checks that group description is modified using api.Command["group_mod"] """ user_code_script = textwrap.dedent( f""" {API_INIT} cmd = api.Command["group_mod"]("developers", description='developer') ["result"] assert 'Modified group "developers"' in cmd['summary'] """ ) self.create_and_run_script( "/tmp/group_mod.py", user_code_script ) def test_add_members_to_ipa_group(self): """ This test checks that member is added to group using api.Command["group_add_member"] """ user_code_script = textwrap.dedent( f""" {API_INIT} cmd = api.Command["group_add_member"]("developers", user='jsmith')["result"] assert 'jsmith' in cmd['member_user'] """ ) self.create_and_run_script( "/tmp/create_group_members.py", user_code_script ) def test_ipa_group_find(self): """ This test checks that group is displayed using api.Command["group_find"] """ user_code_script = textwrap.dedent( f""" {API_INIT} cmd = api.Command["group_find"]("developers") assert '1 group matched' in cmd['summary'] """ ) self.create_and_run_script( "/tmp/group_find.py", user_code_script ) def test_remove_member_group(self): """ This test checks that group member is removed using api.Command["group_remove_member"] """ user_code_script = textwrap.dedent( f""" {API_INIT} cmd = api.Command["group_remove_member"]("developers", user="jsmith") assert 'member_user' not in cmd """ ) self.create_and_run_script( "/tmp/remove_member_group.py", user_code_script ) def test_add_permission(self): """ This test checks that permission is added using api.Command["permission_add"] """ user_code_script = textwrap.dedent( f""" {API_INIT} cmd = api.Command["permission_add"]("Create users", ipapermright='add', type='user') assert 'Added permission "Create users"' in cmd['summary'] """ ) self.create_and_run_script( "/tmp/add_perm.py", user_code_script ) def test_create_hbac_rule(self): """ This test checks that hbac rule is added using api.Command["hbacrule_add"] """ user_code_script = textwrap.dedent( f""" {API_INIT} cmd = api.Command["hbacrule_add"]("sshd_rule") assert 'Added HBAC rule "sshd_rule"' in cmd['summary'] """ ) self.create_and_run_script( "/tmp/add_hbac_rule.py", user_code_script ) def test_add_hbac_service(self): """ This test checks that hbac service is added using api.Command["hbacsvc_add"] """ user_code_script = textwrap.dedent( f""" {API_INIT} cmd = api.Command["hbacsvc_add"]("chronyd") assert 'Added HBAC service "chronyd"' in cmd['summary'] """ ) self.create_and_run_script( "/tmp/add_hbac_svc.py", user_code_script ) def test_enable_hbac_rule(self): """ This test checks that hbac rule is enabled using api.Command["hbacrule_enable"] """ user_code_script = textwrap.dedent( f""" {API_INIT} cmd = api.Command["hbacrule_enable"]("sshd_rule") assert 'Enabled HBAC rule "sshd_rule"' in cmd['summary'] """ ) self.create_and_run_script( "/tmp/enable_hbacrule.py", user_code_script ) def test_create_sudo_rule(self): """ This test checks that sudo rule is created using api.Command["sudorule_add"] """ user_code_script = textwrap.dedent( f""" {API_INIT} cmd = api.Command["sudorule_add"]("timechange") assert 'Added Sudo Rule "timechange"' in cmd['summary'] """ ) self.create_and_run_script( "/tmp/create_sudos.py", user_code_script ) def test_add_user_certificate(self): """ This test checks user certificate is added using api.Command["user_add_cert"] """ user_code_script = textwrap.dedent( f""" {API_INIT} msg = 'Added certificates to user "jsmith"' cmd = api.Command["user_add_cert"]("jsmith", usercertificate={CERT}) assert msg in cmd["summary"] """ ) self.create_and_run_script( "/tmp/add_cert.py", user_code_script ) def test_remove_user_certificate(self): """ This test checks that user certificate is removed using api.Command["user_remove_cert"] """ user_code_script = textwrap.dedent( f""" {API_INIT} msg = 'Removed certificates from user "jsmith"' cmd = api.Command["user_remove_cert"]("jsmith", usercertificate={CERT}) assert msg in cmd["summary"] """ ) self.create_and_run_script( "/tmp/remove_cert.py", user_code_script ) def test_certmaprule_add(self): """ This test checks that certmap rule is added using api.Command["certmaprule_add"] """ user_code_script = textwrap.dedent( f""" {API_INIT} msg = ('Added Certificate Identity Mapping Rule "testrule"') cmd = api.Command["certmaprule_add"]("testrule") assert msg in cmd['summary'] """ ) self.create_and_run_script( "/tmp/certmap_rule_add.py", user_code_script ) def test_certmaprule_enable(self): """ This test checks that certmap rule is enabled using api.Command["certmaprule_enable"] """ user_code_script = textwrap.dedent( f""" {API_INIT} msg = ('Enabled Certificate Identity Mapping Rule "testrule"') cmd = api.Command["certmaprule_enable"]("testrule") assert msg in cmd["summary"] """ ) self.create_and_run_script( "/tmp/certmap_rule_enable.py", user_code_script ) def test_certmaprule_disable(self): """ This test checks that certmap rule is disabled using api.Command["certmaprule_disable"] """ user_code_script = textwrap.dedent( f""" {API_INIT} msg = ('Disabled Certificate Identity Mapping Rule "testrule"') cmd = api.Command["certmaprule_disable"]("testrule") assert msg in cmd["summary"] """ ) self.create_and_run_script( "/tmp/certmap_rule_disable.py", user_code_script ) def test_certmaprule_del(self): """ This test checks that certmap rule is deleted using api.Command["certmaprule_del"] """ user_code_script = textwrap.dedent( f""" {API_INIT} msg = ('Deleted Certificate Identity Mapping Rule "testrule"') cmd = api.Command["certmaprule_del"]("testrule") assert msg in cmd['summary'] """ ) self.create_and_run_script( "/tmp/certmap_rule_del.py", user_code_script ) def test_add_role(self): """ This test checks that role and privilege is added using api.Command["role_add"] """ user_code_script = textwrap.dedent( f""" {API_INIT} cmd1 = api.Command["role_add"]("junioradmin", description="Junior admin") assert 'Added role "junioradmin"' in cmd1["summary"] cmd2 = api.Command.role_add_privilege("junioradmin", privilege="Vault Administrators")["result"] assert 'Vault Administrators' in cmd2["memberof_privilege"] """ ) self.create_and_run_script( "/tmp/add_role.py", user_code_script ) def test_add_subid(self): """ This test checks that subid is added for IPA user using api.Command["subid_add"] """ user_code_script = textwrap.dedent( f""" {API_INIT} cmd = api.Command["subid_add"](ipaowner="jsmith") assert 'Added subordinate id ' in cmd['summary'] """ ) self.create_and_run_script( "/tmp/add_subid.py", user_code_script ) def test_add_otptoken(self): """ This test checks that otp token is added for IPA user using api.Command["otptoken_add"] """ user_code_script = textwrap.dedent( f""" {API_INIT} cmd = api.Command["otptoken_add"]( type='HOTP', description='testotp', ipatokenotpalgorithm='sha512', ipatokenowner='jsmith', ipatokenotpdigits='6') assert 'Added OTP token' in cmd['summary'] """ ) self.create_and_run_script( "/tmp/add_otptoken.py", user_code_script ) def test_user_del(self): """ This test checks that user is deleted using api.Command["user_del"] """ user_code_script = textwrap.dedent( f""" {API_INIT} cmd = api.Command["user_del"]("jsmith") assert 'Deleted user "jsmith"' in cmd['summary'] """ ) self.create_and_run_script( "/tmp/user_del.py", user_code_script ) def test_remove_ipa_group(self): """ This test checks that group is removed using api.Command["group_del"] """ user_code_script = textwrap.dedent( f""" {API_INIT} cmd = api.Command["group_del"]("developers") assert 'Deleted group "developers"' in cmd['summary'] """ ) self.create_and_run_script( "/tmp/show_group.py", user_code_script ) def test_batch_command(self): """ This test checks that batch commands can be run using api. """ user_code_script = textwrap.dedent( f""" {API_INIT} batch_args = [] for i in range(5): user_id = "user%i" % i args = [user_id] kw = dict(givenname=user_id, sn=user_id, random=True) batch_args.append(dict(method='user_add', params=[args, kw])) batch_args.append(dict(method='ping', params=[(), dict()])) keeponly=('dn', 'uid', 'randompassword') batch = api.Command["batch"](methods=batch_args, keeponly=keeponly) # Make sure only the attributes from keeponly returned in result dict # The ping() test above will have no attributes returned for r in batch['results']: if r.get('result', None): assert set(keeponly) >= set(r['result'].keys()) """ ) self.create_and_run_script( "/tmp/batch.py", user_code_script )
16,937
Python
.py
506
25.468379
75
0.603782
freeipa/freeipa
975
339
31
GPL-3.0
9/5/2024, 5:12:14 PM (Europe/Amsterdam)