Ejemplo n.º 1
0
def check_values(dn, inodeSoftLimit, inodeHardLimit, spaceSoftLimit, spaceHardLimit, reapplyQuota):
	cache = get_cache_values(dn)

	#if cache['univentionSharePath'] != path:
	#	utils.fail('univentionSharePath is set to %s. Expected: %s' % (cache['univentionSharePath'], path))
	print cache
	if cache['inodeSoftLimit'] != inodeSoftLimit:
		utils.fail('inodeSoftLimit is set to %s. Expected: %s' % (cache['inodeSoftLimit'], inodeSoftLimit))
	if cache['inodeHardLimit'] != inodeHardLimit:
		utils.fail('inodeHardLimit is set to %s. Expected: %s' % (cache['inodeHardLimit'], inodeHardLimit))
	if cache['spaceSoftLimit'] != spaceSoftLimit:
		utils.fail('spaceSoftLimit is set to %s. Expected: %s' % (cache['spaceSoftLimit'], spaceSoftLimit))
	if cache['spaceHardLimit'] != spaceHardLimit:
		utils.fail('spaceHardLimit is set to %s. Expected: %s' % (cache['spaceHardLimit'], spaceHardLimit))
	if cache['reapplyQuota'] != reapplyQuota:
		utils.fail('reapplyQuota is set to %s. Expected: %s' % (cache['reapplyQuota'], reapplyQuota))
 def test_dhcp_pool_creation_with_wrong_superordinate(self, udm):
     """Create dhcp/pool with wrong superordinate"""
     # bugs: [13817, 31518]
     dhcpService = udm.create_object('dhcp/service',
                                     service=uts.random_string())
     try:
         udm.create_object('dhcp/pool',
                           name=uts.random_string(),
                           range='10.20.30.1 10.20.30.154',
                           superordinate=dhcpService)
     except udm_test.UCSTestUDM_CreateUDMObjectFailed:
         pass
     else:
         utils.fail(
             'UDM did not report an error while trying to create a dhcp/pool with DHCP service as superordinate'
         )
Ejemplo n.º 3
0
    def check_collect(self, users):
        """Checks if the collection was successful
		by checking the file system.\n
		:param users: names of users to have the material collected form
		:type users: list of str
		"""
        print 'Checking %s collection' % (self.name, )
        for user in users:
            path = self.getUserFilesPath(user, 'collect')
            print 'file_path=', path
            existingFiles = self.idir(path)
            print 'existingFiles=', existingFiles
            files = [x for x, y in self.files]
            if files != existingFiles:
                utils.fail('Project files were not collected for user %s' %
                           (user, ))
Ejemplo n.º 4
0
    def wait_rejoin_to_complete(self, poll_attempts):
        """
		Polls the join process via UMC 'join/running' request to make
		sure joining is still going on, sleeps 10 secs after every poll
		attempt, fails in case process still going after the given
		'poll_attempts'. Returns when process is not reported as running.
		"""
        for attempt in range(poll_attempts):
            request_result = self.client.umc_command('join/running').result
            if request_result is None:
                utils.fail("No response on UMC 'join/running' request")
            elif request_result is False:
                return
            print "Waiting 10 seconds before next poll request..."
            sleep(10)
        utils.fail("Failed to wait for join script(-s) to finish")
Ejemplo n.º 5
0
 def define(self):
     """Define internet rule via UMCP"""
     param = [{
         'object': {
             'name': self.name,
             'type': self.typ,
             'domains': self.domains,
             'wlan': self.wlan,
             'priority': self.priority
         }
     }]
     print 'defining rule %s with UMCP:%s' % (self.name,
                                              'internetrules/add')
     print 'param = %r' % (param, )
     reqResult = self.client.umc_command('internetrules/add', param).result
     if not reqResult[0]['success']:
         utils.fail('Unable to define rule (%r)' % (param, ))
Ejemplo n.º 6
0
def check_delivery(token, recipient_email, should_be_delivered, spam=False):
    print "%s is waiting for an email; should be delivered = %r" % (
        recipient_email, should_be_delivered)
    if spam:
        delivered = spam_delivered(token, mail_address=recipient_email)
    else:
        delivered = mail_delivered(token, mail_address=recipient_email)
    spam_str = 'Spam ' if spam else ''
    if should_be_delivered != delivered:
        if delivered:
            utils.fail(
                '%sMail sent with token = %r to %s un-expectedly delivered' %
                (spam_str, token, recipient_email))
        else:
            utils.fail(
                '%sMail sent with token = %r to %s un-expectedly not delivered'
                % (spam_str, token, recipient_email))
Ejemplo n.º 7
0
    def redirector_is(self, expected_redirector):
        """Check if the redirector is the same as the passed parameter\n
		:param expected_redirector: in the config file
		:type expected_redirector: string
		:return boolean:True if match, False if not match
		"""
        result = False
        with ucr_test.UCSTestConfigRegistry():
            config_lines = get_lines_containing(self.conf,
                                                'url_rewrite_program')
            if config_lines:
                # in config file the first line setting the redirector is activated
                config_line = config_lines[0]
                result = ('url_rewrite_program %s\n' %
                          (expected_redirector, ) == config_line)
            else:
                utils.fail("Squid config redirector line does not exist")
        return result
Ejemplo n.º 8
0
 def check_marktplatz_read(self,
                           user,
                           ip_address,
                           passwd='univention',
                           expected_result=0):
     print '.... Check Marktplatz read ....'
     cmd_read_marktplatz = [
         'smbclient', '//%(ip)s/Marktplatz', '-U', '%(user)s', '-c', 'dir'
     ]
     read = run_commands([cmd_read_marktplatz], {
         'ip': ip_address,
         'user': '******'.format(user, passwd)
     })
     if read[0] != expected_result:
         print 'FAIL .. Read Marktplatz directory result (%r), expected (%r)' % (
             read[0], expected_result)
         utils.fail('Read Marktplatz directory result (%r), expected (%r)' %
                    (read[0], expected_result))
Ejemplo n.º 9
0
    def test_time_settings(self, client):
        self.aquire_room(client)
        settings = self.get_room_settings(client)
        period = datetime.time.strftime(
            (datetime.datetime.now() + datetime.timedelta(0, 120)).time(),
            '%H:%M')
        new_settings = {
            'customRule': '',
            'printMode': 'none',
            'internetRule': 'none',
            'shareMode': 'home',
            'period': period
        }

        ula_length = len(ula.list())
        time_out = 30  # seconds
        self.set_room_settings(client, new_settings)
        for i in xrange(time_out, 0, -1):
            print i
            if len(ula.list()) > ula_length:
                break
            else:
                time.sleep(1)
                continue

        # Checking Atjobs list
        self.check_atjobs(period, True)

        # TODO FAILS because of Bug #35195
        # self.check_displayTime(client, period)

        print '*** Waiting 2 mins for settings to expire.............'
        time.sleep(2 * 60 + 2)
        current_settings = self.get_room_settings(client)

        # Time field is not considered in the comparision
        current_settings['period'] = settings['period']
        if current_settings != settings:
            utils.fail(
                'Current settings (%r) are not reset back after the time out, expected (%r)'
                % (current_settings, settings))

        # Checking Atjobs list
        self.check_atjobs(period, False)
Ejemplo n.º 10
0
def get_cache_values(dn):
	filename = os.path.join(SHARE_CACHE_DIR, dn)
	if not os.path.exists(filename):
		utils.fail('%s does not exist' % filename)
		return None

	f = open(filename, 'r')
	dn, attrs, policy_result = cPickle.load(f)
	f.close()

	share = {}
	share['univentionSharePath'] = attrs['univentionSharePath'][0]
	share['inodeSoftLimit'] = policy_result.get('univentionQuotaSoftLimitInodes', [None])[0]
	share['inodeHardLimit'] = policy_result.get('univentionQuotaHardLimitInodes', [None])[0]
	share['spaceSoftLimit'] = policy_result.get('univentionQuotaSoftLimitSpace', [None])[0]
	share['spaceHardLimit'] = policy_result.get('univentionQuotaHardLimitSpace', [None])[0]
	share['reapplyQuota'] = policy_result.get('univentionQuotaReapplyEveryLogin', [None])[0]

	return share
Ejemplo n.º 11
0
 def check_atjobs(self, period, expected_existence):
     exist = False
     for item in ula.list():
         if period == datetime.time.strftime(item.execTime.time(), '%H:%M'):
             exist = True
             break
     if exist == expected_existence:
         print 'Atjob result at(%r) existance is expected (%r)' % (period,
                                                                   exist)
     else:
         print 'FAIL: Atjob result at(%r) is unexpected (should_exist=%r  exists=%r)' % (
             period, expected_existence, exist)
         print 'Found the following atjobs:'
         for i, item in enumerate(ula.list()):
             print 'Job %s: %s  owner=%s\n%s' % (i, item, item.owner,
                                                 item.command)
         utils.fail(
             'Atjob result at(%r) is unexpected (should_exist=%r  exists=%r)'
             % (period, expected_existence, exist))
Ejemplo n.º 12
0
def remove_extension_by_name(extension_type,
                             extension_name,
                             fail_on_error=True):
    """
    Remove all extensions of given type and name from LDAP.
    """
    assert (extension_type in VALID_EXTENSION_TYPES)
    for dn in get_dn_of_extension_by_name(extension_type, extension_name):
        cmd = [
            '/usr/sbin/udm-test',
            'settings/udm_%s' % extension_type, 'remove', '--dn', dn
        ]
        print 'CMD: %r' % cmd
        sys.stdout.flush()
        if subprocess.call(cmd):
            if fail_on_error:
                fail('Failed to remove %s' % dn)
            else:
                print 'ERROR: failed to remove %s' % dn
Ejemplo n.º 13
0
 def check_room_settings(self, client, expected_settings):
     print 'Checking computerroom (%s) settings ...........' % self.name
     try:
         current_settings = self.get_room_settings(client)
         d = dict(expected_settings)  # copy dictionary
         d['period'] = current_settings['period']
         d['customRule'] = current_settings[
             'customRule']  # TODO Bug 35258 remove
         if current_settings != d:
             print 'FAIL: Current settings (%r) do not match expected ones (%r)' % (
                 current_settings, d)
             utils.fail(
                 'Current settings (%r) do not match expected ones (%r)' %
                 (current_settings, d))
     except ConnectionError as exc:
         if '[Errno 4] ' in str(exc):
             print 'failed to check room (%s) settings, exception [Errno4]' % self.name
         print("Exception: '%s' '%s' '%r'" % (str(exc), type(exc), exc))
         raise
Ejemplo n.º 14
0
 def check_smb_print(self, ip, printer, user, expected_result):
     print 'Checking print mode', '.' * 40
     f = tempfile.NamedTemporaryFile(dir='/tmp')
     cmd_print = [
         'smbclient', '//%(ip)s/%(printer)s', '-U', '%(user)s', '-c',
         'print %(filename)s'
     ]
     result = run_commands(
         [cmd_print], {
             'ip': ip,
             'printer': printer,
             'user': '******'.format(user, 'univention'),
             'filename': f.name
         })[0]
     f.close()
     if result != expected_result:
         print 'FAIL .... smbclient print result (%r), expected (%r)' % (
             result, expected_result)
         utils.fail('smbclient print result (%r), expected (%r)' %
                    (result, expected_result))
Ejemplo n.º 15
0
 def check_home_read(self,
                     user,
                     ip_address,
                     passwd='univention',
                     expected_result=0):
     print '.... Check home read ....'
     cmd_read_home = [
         'smbclient', '//%(ip)s/%(username)s', '-U', '%(user)s', '-c', 'dir'
     ]
     read = run_commands(
         [cmd_read_home], {
             'ip': ip_address,
             'username': user,
             'user': '******'.format(user, passwd)
         })
     if read[0] != expected_result:
         print 'FAIL .. Read home directory result (%r), expected (%r)' % (
             read[0], expected_result)
         utils.fail('Read home directory result (%r), expected (%r)' %
                    (read[0], expected_result))
Ejemplo n.º 16
0
 def _check_quota_settings(self, loop_dev, expected_values={}):
     print("Check quota settings")
     options = {"filter": "*", "partitionDevice": loop_dev}
     user_quotas = self.umc_client.umc_command('quota/users/query',
                                               options).result
     expected_user_quota = {
         u'fileLimitHard': u'{}'.format(expected_values.get('fhard', 15)),
         u'fileLimitSoft': u'{}'.format(expected_values.get('fsoft', 10)),
         u'fileLimitTime': u'-',
         u'fileLimitUsed': u'1',
         u'id': u'{}@{}'.format(self.username, loop_dev),
         u'partitionDevice': u'{}'.format(loop_dev),
         u'sizeLimitHard': float(expected_values.get('bhard', 4)),
         u'sizeLimitSoft': float(expected_values.get('bsoft', 1)),
         u'sizeLimitTime': u'-',
         u'sizeLimitUsed': float(0),
         u'user': u'{}'.format(self.username),
     }
     if expected_user_quota not in user_quotas:
         utils.fail("Quota was not set through pam")
Ejemplo n.º 17
0
    def add(self):
        """Create files and upload them then add the project,
		calls: 'distribution/add'
		"""
        # creatng and uploading the files
        content_type = 'text/plain'
        for filename, encoding in self.files:
            with open(filename, 'w') as g:
                g.write('test_content')
            self.uploadFile(filename, content_type)
        print 'Adding Project %s' % (self.name)
        flavor = self.flavor
        recipients = []
        for item in self.recipients:
            recipients.append(item.dn())
        print 'recipients=', recipients
        files = [
            file_name.decode(encoding).encode('UTF-8')
            for file_name, encoding in self.files
        ]
        param = [{
            'object': {
                'collectDate': self.collectDate,
                'collectTime': self.collectTime,
                'collectType': self.collectType,
                'description': self.description,
                'distributeDate': self.distributeDate,
                'distributeTime': self.distributeTime,
                'distributeType': self.distributeType,
                'files': files,
                'name': self.name,
                'recipients': recipients
            },
            'options': None
        }]
        print 'param=', param
        reqResult = self.client.umc_command('distribution/add', param,
                                            flavor).result
        print 'reqResult =', reqResult
        if not reqResult[0]['success']:
            utils.fail('Unable to add project (%r)' % (param, ))
Ejemplo n.º 18
0
def test_disabled_user_creation_activation(disabled_cronjob, udm, ucr):
    """Check cron based activation of users/user with accountActivationDate"""

    now = datetime.now()
    with open("/etc/timezone", "r") as tzfile:
        timezone = tzfile.read().strip()
    ts_later = (now + timedelta(minutes=1)).strftime("%Y-%m-%d %H:%M " +
                                                     timezone)
    userdn, username = udm.create_user(accountActivationDate=ts_later)
    try:
        udm.verify_udm_object("users/user", userdn, {"disabled": "1"})
    except (utils.LDAPObjectNotFound, utils.LDAPUnexpectedObjectFound):
        utils.fail("User creation failed")
    except (utils.LDAPObjectValueMissing, utils.LDAPObjectUnexpectedValue):
        utils.fail(
            "User is not disabled, despite setting future accountActivationDate"
        )

    # verify that account can't bind
    with pytest.raises(univention.admin.uexceptions.authFail):
        lo = univention.admin.uldap.access(binddn=userdn, bindpw="univention")
        lo.lo.lo.whoami_s()

    handler_set(['%s=%s' % (ucrv, "*/1 *  * * *")])

    time.sleep(2 * 60)

    try:
        udm.verify_udm_object("users/user", userdn, {"disabled": "0"})
    except (utils.LDAPObjectValueMissing, utils.LDAPObjectUnexpectedValue):
        utils.fail("User is still disabled, after accountActivationDate")
Ejemplo n.º 19
0
	def delete_obj(self, name, obj_type, flavor):
		"""
		Deletes object with a 'name' by making UMC-request 'udm/remove'
		with relevant options and flavor depending on 'obj_type'
		Supported types are: users, groups, policies, extended attributes,
		networks and computers.
		"""
		print "Deleting test object '%s' with a name: '%s'" % (obj_type, name)

		if obj_type in ('users', 'users/user', 'users/ldap'):
			obj_type = 'users'
			obj_identifier = "uid=" + name + ",cn=" + obj_type + ","
		elif obj_type == 'policies':
			obj_identifier = "cn=" + name + ",cn=UMC,cn=" + obj_type + ","
		elif obj_type == 'custom attributes':
			obj_identifier = "cn=" + name + ",cn=" + obj_type + ",cn=univention,"
		elif obj_type in ('groups', 'networks', 'computers'):
			obj_identifier = "cn=" + name + ",cn=" + obj_type + ","
		else:
			utils.fail("The object identifier format is unknown for the provided object type '%s'" % obj_type)

		obj_identifier = obj_identifier + self.ldap_base
		options = [{
			"object": obj_identifier,
			"options": {
				"cleanup": True,
				"recursive": True
			}
		}]
		request_result = self.client.umc_command('udm/remove', options, flavor).result
		if not request_result:
			utils.fail("Request 'udm/remove' to delete object with options '%s' failed, hostname %s" % (options, self.hostname))
		if not request_result[0].get('success'):
			utils.fail("Request 'udm/remove' to delete object with options '%s' failed, no success = True in response, hostname '%s', response '%s'" % (options, self.hostname, request_result))
def test_umc_ldap_con():
    def assert_slapd_testing():
        samlSession.test_slapd()
        # Ensure an ldap connection will be opened
        subprocess.check_call(['systemctl', 'stop', 'slapd'])
        samlSession.test_slapd()

    try:
        samlSession = __get_samlSession()
        __test_umc_sp(samlSession, assert_slapd_testing)
    except samltest.SamlError:
        if samlSession.page.status_code == 503:
            pass
        else:
            raise
    else:
        utils.fail('test_slapd() should not work without slapd running')
    finally:
        subprocess.check_call(['systemctl', 'start', 'slapd'])

    for _ in range(2):
        samlSession = __get_samlSession()
        __test_umc_sp(samlSession, samlSession.test_slapd)
Ejemplo n.º 21
0
    def assign(self, school, groupName, groupType, default=False):
        """Assign internet rule via UMCP\n
		:param school: name of the ou
		:type school: str
		:param groupName: name of the group or class
		:type groupName: str
		:param groupType: 'workgroup' or 'class'
		:type groupType: str
		:param default: if the group is assigned to default values
		:type default: bool
		"""
        self.ucr.load()
        groupdn = ''
        schoolenv = utu.UCSTestSchool()
        school_basedn = schoolenv.get_ou_base_dn(school)

        if groupType == 'workgroup':
            ucsschool = UCSTestSchool()
            groupdn = ucsschool.get_workinggroup_dn(school, groupName)
        elif groupType == 'class':
            groupdn = 'cn=%s-%s,cn=klassen,cn=schueler,cn=groups,%s' % (
                school, groupName, school_basedn)

        if default:
            name = '$default$'
        else:
            name = self.name
        param = [{'group': groupdn, 'rule': name}]
        print 'Assigning rule %s to %s: %s' % (self.name, groupType, groupName)
        print 'param = %r' % (param, )
        result = self.client.umc_command('internetrules/groups/assign',
                                         param).result
        if not result:
            utils.fail('Unable to assign internet rule to workgroup (%r)' %
                       (param, ))
        else:
            return (groupName, self.name)
Ejemplo n.º 22
0
def test_execute_udm_users_list_as_administrator(ucr):
    """Execute "udm users/user list --filter uid=Administrator" as Administrator"""
    # bugs: [37331]

    # get the Administrator username translation if case of non English domain:
    admin_username = ucr.get('users/default/administrator') or "Administrator"
    print("Administrator username is:", admin_username)

    cmd = (
        'su', admin_username, '-c',
        '/usr/sbin/univention-directory-manager users/user list --filter uid='
        + admin_username)
    udm = subprocess.Popen(cmd, stdout=subprocess.PIPE)
    output = udm.communicate()[0].decode('utf-8', 'replace')

    if udm.returncode != 0:
        utils.fail(
            'UDM-CLI returned "%d" while trying to execute "%s" as Administrator. Returncode "0" was expected.'
            % (udm.returncode, cmd[3:]))

    if ('DN: uid=' + admin_username) not in output:
        utils.fail(
            'Could not find DN of "%s" user in the UDM-CLI output:\n%s' %
            (admin_username, output))
	def test_read_user(self):
		obj = self.user_objects[0]
		print('Checking properties of previously created user {!r}...'.format(obj.props.username))
		expected_properties = deepcopy(self._user0_attrs)
		del expected_properties['password']
		expected_properties.update({
			'e-mail': [],
			'displayName': '{} {}'.format(self._user0_attrs['firstname'], self._user0_attrs['lastname']),
		})
		if hasattr(obj.props, 'oxDisplayName'):
			expected_properties['oxDisplayName'] = expected_properties['displayName']
			expected_properties['oxTimeZone'] = self.udm.obj_by_dn(
				'cn=oxTimeZone,cn=open-xchange,cn=custom attributes,cn=univention,{}'.format(self.ucr_test['ldap/base'])
			).props.default
		if hasattr(obj.props, 'mailUserQuota'):
			expected_properties['mailUserQuota'] = 0
		for k, v in expected_properties.items():
			got = getattr(obj.props, k)
			if got != v:
				utils.fail('Expected for {!r}: {!r} got: {!r}'.format(k, v, got))
		with self.assertRaises(UnknownProperty):
			obj.props.unknown = 'Unknown'
		with self.assertRaises(AttributeError):
			obj.props.unknown
Ejemplo n.º 24
0
 def check_marktplatz_write(self,
                            user,
                            ip_address,
                            passwd='univention',
                            expected_result=0):
     print '.... Check Marktplatz write ....'
     f = tempfile.NamedTemporaryFile(dir='/tmp')
     cmd_write_marktplatz = [
         'smbclient', '//%(ip)s/Marktplatz', '-U', '%(user)s', '-c',
         'put %(filename)s'
     ]
     write = run_commands(
         [cmd_write_marktplatz], {
             'ip': ip_address,
             'user': '******'.format(user, passwd),
             'filename': '%s %s' % (f.name, f.name.split('/')[-1])
         })
     f.close()
     if write[0] != expected_result:
         print 'FAIL .. Write to Marktplatz directory result (%r), expected (%r)' % (
             write[0], expected_result)
         utils.fail(
             'Write to Marktplatz directory result (%r), expected (%r)' %
             (write[0], expected_result))
Ejemplo n.º 25
0
def check_sending_mail(username=None,
                       password=None,
                       recipient_email=None,
                       tls=True,
                       allowed=True,
                       local=True):
    token = 'The token is {}.'.format(time.time())
    try:
        ret_code = send_mail(recipients=recipient_email,
                             msg=token,
                             port=587,
                             server='4.3.2.1',
                             tls=tls,
                             username=username,
                             password=password)
        if bool(ret_code) == allowed:
            utils.fail(
                'Sending allowed = %r, but return code = %r\n {} means there are no refused recipient'
                % (allowed, ret_code))
        if local:
            check_delivery(token, recipient_email, allowed)
    except smtplib.SMTPException as ex:
        if allowed and (tls or 'access denied' in str(ex)):
            utils.fail('Mail sent failed with exception: %s' % ex)
Ejemplo n.º 26
0
def test_disabled_user_creation(disabled_cronjob, udm):
    """Create users/user with accountActivationDate"""
    now = datetime.now()
    with open("/etc/timezone", "r") as tzfile:
        timezone = tzfile.read().strip()
    ts_earlier = now.strftime("%Y-%m-%d %H:%M " + timezone)
    ts_later = (now + timedelta(minutes=2)).strftime("%Y-%m-%d %H:%M " +
                                                     timezone)
    userdn, username = udm.create_user(accountActivationDate=ts_later)
    try:
        udm.verify_udm_object("users/user", userdn, {"disabled": "1"})
    except (utils.LDAPObjectNotFound, utils.LDAPUnexpectedObjectFound):
        utils.fail("User creation failed")
    except (utils.LDAPObjectValueMissing, utils.LDAPObjectUnexpectedValue):
        utils.fail(
            "User is not disabled, despite setting future accountActivationDate"
        )

    # verify that account can't bind
    with pytest.raises(univention.admin.uexceptions.authFail):
        univention.admin.uldap.access(binddn=userdn, bindpw="univention")

    # Now that the accountActivationDate is still in the future, run the script
    run_activation_script()
    try:
        udm.verify_udm_object("users/user", userdn, {"disabled": "1"})
    except (utils.LDAPObjectValueMissing, utils.LDAPObjectUnexpectedValue):
        utils.fail(
            "User is not disabled any longer, after running univention-delayed-account-activation despite future accountActivationDate"
        )

    # Now set the accountActivationDate a bit back, so the date has passed
    udm.modify_object('users/user',
                      dn=userdn,
                      accountActivationDate=ts_earlier)
    run_activation_script()
    try:
        udm.verify_udm_object("users/user", userdn, {"disabled": "0"})
    except (utils.LDAPObjectValueMissing, utils.LDAPObjectUnexpectedValue):
        utils.fail(
            "User is still disabled, after running univention-delayed-account-activation after accountActivationDate"
        )

    # verify that account can bind
    univention.admin.uldap.access(binddn=userdn, bindpw="univention")
Ejemplo n.º 27
0
	def copy_file(self, src, dst):
		"""
		Makes a copy of the 'src' file to 'dst' file if 'src' exists
		"""
		try:
			if os.path.exists(src):
				shutil.copy2(src, dst)
				if not os.path.exists(dst):
					utils.fail("The 'shutil' did not copy file '%s' to '%s'" % (src, dst))
			else:
				utils.fail("Failed to find the file at the provided " "path '%s'" % src)
		except (OSError, shutil.Error) as exc:
			utils.fail("An exception while coping the file from '%s', to '%s', error '%s'" % (src, dst, exc))
Ejemplo n.º 28
0
def test_script_lock_expired_accounts(stopped_s4_connector,
                                      udm):  # TODO: parametrize
    """Check cron job script lock_expired_accounts"""
    # bugs: [35088]

    print(time.ctime())
    udm_modules.update()
    lo, position = univention.admin.uldap.getAdminConnection()
    udm_modules.init(lo, position, udm_modules.get('users/user'))

    def create_user(expiry_days_delta, locked_status):
        expiry_time = datetime.utcnow() + timedelta(days=expiry_days_delta)
        userdn, username = udm.create_user(
            userexpiry=expiry_time.strftime("%Y-%m-%d"),
            check_for_drs_replication=False,
            wait_for=False)
        if locked_status == '1':
            locktime = time.strftime("%Y%m%d%H%M%SZ", time.gmtime())
            subprocess.check_call([
                '/usr/bin/python2.7', '-m', 'univention.lib.account', 'lock',
                '--dn', userdn, '--lock-time', locktime
            ])
        return username

    userdata = {}
    for delta, initial_state, expected_state in [
        [-9, '0', '0'],
        [-8, '0', '0'],
            # [-7, '0', '0'],  disabled due to bug #36210
            # [-6, '0', '1'],  disabled due to bug #36210
        [-5, '0', '1'],
        [-4, '0', '1'],
        [-3, '0', '1'],
        [-2, '0', '1'],
        [-1, '0', '1'],
            # [0, '0', '1'],  disabled due to bug #36210
        [1, '0', '0'],
        [2, '0', '0'],
        [-4, '1', '1'],
            # [0, '1', '1'],  disabled due to bug #36210
        [2, '1', '1'],
    ]:
        userdata[create_user(delta,
                             initial_state)] = [initial_state, expected_state]

    ldap_filter = '(|(uid=' + ')(uid='.join(userdata.keys()) + '))'

    results = udm_modules.lookup('users/user',
                                 None,
                                 lo,
                                 scope='sub',
                                 filter=ldap_filter)
    if len(results) != len(userdata):
        print('RESULTS: %r' %
              (pprint.PrettyPrinter(indent=2).pformat(results), ))
        utils.fail('Did not find all users prior to script execution!')
    for entry in results:
        entry.open()
        if not entry['locked'] == userdata[entry['username']][0]:
            utils.fail(
                'uid=%s should not be locked for posix prior to script execution!'
                % (entry['username'], ))

    print('Calling lock_expired_accounts...')
    subprocess.check_call([
        '/usr/share/univention-directory-manager-tools/lock_expired_accounts',
        '--only-last-week'
    ])
    print('DONE')

    results = udm_modules.lookup('users/user',
                                 None,
                                 lo,
                                 scope='sub',
                                 filter=ldap_filter)
    if len(results) != len(userdata):
        print('RESULTS: %r' %
              (pprint.PrettyPrinter(indent=2).pformat(results), ))
        utils.fail('Did not find all users after script execution!')
    for entry in results:
        entry.open()
        if not entry['locked'] == userdata[entry['username']][1]:
            utils.fail(
                'The account uid=%r is not in expected locking state: expected=%r  current=%r'
                % (entry['username'], userdata[entry['username']][1],
                   entry['locked']))
Ejemplo n.º 29
0
def test_ignore_user_with_functional_flag(stopped_s4_connector, udm):
    """Create users/user and test "functional" object flag"""
    # bugs: [34395]
    license_before = subprocess.Popen(['univention-license-check'],
                                      stdout=subprocess.PIPE).communicate()[0]

    # create user and check its existence
    user_dn = udm.create_user(check_for_drs_replication=False,
                              wait_for=False)[0]
    utils.verify_ldap_object(user_dn)
    stdout = subprocess.Popen(
        [udm_test.UCSTestUDM.PATH_UDM_CLI_CLIENT, 'users/user', 'list'],
        stdout=subprocess.PIPE).communicate()[0]
    if not user_dn.lower().encode('UTF-8') in stdout.lower():
        utils.fail(
            'Cannot find user DN %s in output of "udm users/user list":\n%s' %
            (user_dn, stdout))

    # perform a license check
    license_after = subprocess.Popen(['univention-license-check'],
                                     stdout=subprocess.PIPE).communicate()[0]
    if license_before == license_after:
        utils.fail('License check failed to detect normal user')

    # add 'functional' flag to user
    lo = utils.get_ldap_connection()
    lo.modify(user_dn, (('univentionObjectFlag', b'', b'functional'), ))
    utils.wait_for_replication()
    stdout = subprocess.Popen(
        [udm_test.UCSTestUDM.PATH_UDM_CLI_CLIENT, 'users/user', 'list'],
        stdout=subprocess.PIPE).communicate()[0]
    if user_dn.lower().encode('UTF-8') in stdout.lower():
        utils.fail(
            '"udm users/user list" still finds user object with functional flag'
        )

    # perform a license check
    license_after = subprocess.Popen(['univention-license-check'],
                                     stdout=subprocess.PIPE).communicate()[0]
    if license_before != license_after:
        utils.fail('License check detected to "functional" user')

    # remove 'functional' flag to user
    lo.modify(user_dn, (('univentionObjectFlag', b'functional', b''), ))
    utils.wait_for_replication()
    stdout = subprocess.Popen(
        [udm_test.UCSTestUDM.PATH_UDM_CLI_CLIENT, 'users/user', 'list'],
        stdout=subprocess.PIPE).communicate()[0]
    if not user_dn.lower().encode('UTF-8') in stdout.lower():
        utils.fail(
            'Cannot find user DN %s in output of "udm users/user list" after removing flag:\n%s'
            % (user_dn, stdout))

    # perform a license check
    license_after = subprocess.Popen(['univention-license-check'],
                                     stdout=subprocess.PIPE).communicate()[0]
    if license_before == license_after:
        utils.fail('License check failed to detect normal user')
Ejemplo n.º 30
0
def check_s4_rejected(existing_rejects):
	new_rejects = get_s4_rejected()
	fail = [x for x in new_rejects if x not in existing_rejects]
	if fail:
		utils.fail('There is at least one new rejected object: %r' % fail)