def verify_users(group_dn, users): print(" Checking Ldap Objects") utils.verify_ldap_object( group_dn, { 'uniqueMember': [user for user in users], 'memberUid': [ldap.dn.str2dn(user)[0][0][1] for user in users] })
def test_deregistration(umc_client, mails, testudm, readudm): password = '******' dn, username = testudm.create_user(**{ 'PasswordRecoveryEmail': 'root@localhost', 'password': password, }) utils.verify_ldap_object( dn, { 'univentionDeregisteredThroughSelfService': [], 'univentionDeregistrationTimestamp': [] }) timestamp = datetime.datetime.strftime(datetime.datetime.utcnow(), '%Y%m%d%H%M%SZ') umc_client.umc_command('passwordreset/deregister_account', { 'username': username, 'password': password }) user = readudm.obj_by_dn(dn) assert user.props.disabled is True assert user.props.DeregisteredThroughSelfService == 'TRUE' assert user.props.DeregistrationTimestamp.startswith( timestamp[:3]) # checking seconds from the timestamp is too flaky mail = _get_mail(mails) with open( '/usr/share/univention-self-service/email_bodies/deregistration_notification_email_body.txt', 'r') as fd: expected_body = fd.read().format(username=username) assert mail['body'].strip() == expected_body.strip()
def test_dhcp_pool_creation_with_all_attributes(self, udm): """Check dhcp/pool attributes""" dhcp_service = udm.create_object('dhcp/service', service=uts.random_name()) dhcp_subnet = udm.create_object('dhcp/subnet', subnet=SUBNET_IP4, subnetmask=SUBNET_MASK_IP4, superordinate=dhcp_service) dhcp_pool_properties = { 'name': uts.random_string(), 'range': '10.20.30.40 10.20.30.50', 'failover_peer': uts.random_string(), 'known_clients': 'deny', 'unknown_clients': 'allow', 'dynamic_bootp_clients': 'deny', 'all_clients': 'allow' } dhcp_pool = udm.create_object('dhcp/pool', superordinate=dhcp_subnet, **dhcp_pool_properties) utils.verify_ldap_object( dhcp_pool, { 'dhcpRange': [dhcp_pool_properties['range']], 'univentionDhcpFailoverPeer': [dhcp_pool_properties['failover_peer']], 'dhcpPermitList': [ 'deny known clients', 'allow unknown clients', 'deny dynamic bootp clients', 'allow all clients' ] })
def test_usercontainer_ucr_var(umc_client, get_registration_info): info = get_registration_info(container_without_base='cn=users') umc_client.umc_command('passwordreset/create_self_registered_account', info['data']) utils.verify_ldap_object(info['dn'], { 'univentionPasswordRecoveryEmailVerified': ['FALSE'], 'univentionRegisteredThroughSelfService': ['TRUE'], })
def test_modify_printer_and_check_cupsd(ucr, udm): """Create and modify shares/printer, check if cupsd still running""" ucr.load() name = uts.random_name() printer_properties = { 'model': 'foomatic-rip/Alps-MD-5000-md5k.ppd', 'uri': 'file:/ tmp/%s' % name, 'spoolHost': '%s.%s' % (ucr['hostname'], ucr['domainname']), 'name': name, } printer = udm.create_object('shares/printer', position='cn=printers,%s' % ucr['ldap/base'], **printer_properties) utils.verify_ldap_object( printer, { 'univentionPrinterModel': [printer_properties['model']], 'univentionPrinterURI': [printer_properties['uri'].replace(' ', '')], 'univentionPrinterSpoolHost': [printer_properties['spoolHost']] }) udm.modify_object('shares/printer', dn=printer, ACLUsers=['cn=test,cn=users'], ACLtype='allow') time.sleep(3) # check if cups is still running subprocess.check_call(['lpstat', '-a'])
def test_email_change(selenium, mails, get_registration_info, change_email): _navigate_self_service(selenium, '#page=createaccount') info = get_registration_info() _enter_attributes(selenium, info['attributes'], 'Create account') mail = _get_mail(mails) selenium.driver.get(mail['auto_verify_link']) selenium.wait_until_standby_animation_appears_and_disappears() utils.verify_ldap_object(info['dn'], { 'univentionRegisteredThroughSelfService': ['TRUE'], 'univentionPasswordRecoveryEmailVerified': ['TRUE'], }) _navigate_self_service(selenium, '#page=setcontactinformation') selenium.enter_input('username', info['attributes']['username']) selenium.enter_input('password', info['attributes']['password']) selenium.click_button('Next') selenium.wait_for_text('Email') if change_email: new_email = '*****@*****.**' e = selenium.driver.find_element_by_id('email') e.clear() e.send_keys(new_email) e = selenium.driver.find_element_by_id('email_check') e.clear() e.send_keys(new_email) selenium.click_button('Save') selenium.wait_for_text('Your contact data has been successfully changed.') selenium.driver.find_element_by_xpath('//p[text()="Your account has to be verified again after changing your email. We have sent you an email to "]') selenium.driver.find_element_by_xpath('//p[text()="Your account has to be verified again after changing your email. We have sent you an email to "]/b[text()="{}"]//parent::p[text()=". Please follow the instructions in the email to verify your account."]'.format(new_email)) else: selenium.click_button('Save') selenium.wait_for_text('Your contact data has been successfully changed.') with pytest.raises(NoSuchElementException): selenium.driver.find_element_by_xpath('//p[text()="Your account has to be verified again after changing your email. We have sent you an email to "]')
def test_dhcp_servoce_removal(self, udm): """Remove dhcp/service""" dhcp_service = udm.create_object('dhcp/service', service=uts.random_name()) udm.remove_object('dhcp/service', dn=dhcp_service) utils.verify_ldap_object(dhcp_service, should_exist=False)
def test_modify_user_homePostalAddress_as_dict(self): addresses = [ PostalAddress(random_string(), random_string(), random_string()), PostalAddress(random_string(), random_string(), random_string()), PostalAddress(random_string(), random_string(), random_string()), ] dn, username = self.udm_test.create_user() utils.verify_ldap_object( dn, expected_attr={ 'uid': [username], 'homePostalAddress': [], }, ) obj = UDM.admin().version(1).get('users/user').get(dn) assert username == obj.props.username obj.props.homePostalAddress.extend([ad._asdict() for ad in addresses]) obj.save() utils.verify_ldap_object( dn, expected_attr={ 'homePostalAddress': [ '{street}${zipcode}${city}'.format(**ad._asdict()) for ad in addresses ], }, )
def test_modify_user(self): user_mod = self.udm.get('users/user') obj = user_mod.get(self.user_objects[0].dn) attrs = { 'firstname': random_username(), 'lastname': random_username(), 'description': random_string(), 'mailPrimaryAddress': '{}@{}'.format(random_string(), self.mail_domain.lower()), 'departmentNumber': random_string(), } print('Modifying {!r} with attrs: {!r}'.format(obj, attrs)) for k, v in attrs.items(): setattr(obj.props, k, v) obj.save() print('Verifying...') utils.verify_ldap_object( obj.dn, expected_attr={ 'sn': [attrs['lastname']], 'givenName': [attrs['firstname']], 'description': [attrs['description']], 'mailPrimaryAddress': [attrs['mailPrimaryAddress']], 'departmentNumber': [attrs['departmentNumber']], 'displayName': ['{} {}'.format(attrs['firstname'], attrs['lastname'])], }, strict=False, should_exist=True )
def _check_ldap_object_doesnt_exist(self): try: utils.verify_ldap_object(self._get_dn(), should_exist=False) except utils.LDAPUnexpectedObjectFound as e: return self._fail("Found unexpected: " + str(e)) print("OK - LDAP object removed after uninstallation.") return True
def _create_and_verify_extended_attribute(udm, ucr): properties = { 'CLIName': 'mail', 'copyable': '0', 'deleteObjectClass': '0', 'disableUDMWeb': '0', 'doNotSearch': '0', 'fullWidth': '0', 'groupName': 'User account', 'groupPosition': '11', 'ldapMapping': 'mail', 'longDescription': 'Mail Attribut', 'mayChange': '1', 'module': 'users/user', 'module': 'settings/usertemplate', 'name': 'mail', 'objectClass': 'inetOrgPerson', 'overwritePosition': 'None', 'overwriteTab': '0', 'shortDescription': 'Mail Attribut', 'syntax': 'String', 'tabAdvanced': '0', 'tabName': 'General', 'tabPosition': '11', 'valueRequired': '0' } extended_attribute = udm.create_object( 'settings/extended_attribute', position='cn=custom attributes,cn=univention,%s' % (ucr.get('ldap/base')), **properties) utils.verify_ldap_object(extended_attribute, should_exist=True)
def test_container_cn_rename_uppercase_rollback(self, udm, ucr): """Rename a container/cn with un-moveable subobjects from lower to upper case""" user_name = uts.random_string() network_name = uts.random_string() cn_name = uts.random_string() cn_name_new = cn_name.upper() cn = udm.create_object('container/cn', name=cn_name) wait_for_drs_replication('cn=%s' % cn_name) udm.create_user(position=cn, username=user_name) udm.create_object('networks/network', position=cn, name=network_name, network='1.1.1.1', netmask='24') with pytest.raises(udm_test.UCSTestUDM_ModifyUDMObjectFailed): udm.modify_object('container/cn', dn=cn, name=cn_name_new) new_cn = 'cn=%s,%s' % (ldap.dn.escape_dn_chars(cn_name_new), ucr.get('ldap/base')) new_user = '******' % (ldap.dn.escape_dn_chars(user_name), ldap.dn.escape_dn_chars(cn_name_new), ucr.get('ldap/base')) utils.verify_ldap_object(new_cn, should_exist=True) utils.verify_ldap_object(new_user, should_exist=True) lo = utils.get_ldap_connection() for dn, entry in lo.search( filter=ldap.filter.filter_format('cn=%s', [cn_name])): assert entry.get('cn')[0] == cn_name.encode( 'UTF-8'), 'cn = %s; expected: %s' % (entry.get('cn')[0], cn_name)
def _check_ldap_object_exists(self): try: utils.verify_ldap_object(self._get_dn()) except utils.LDAPObjectNotFound as e: return self._fail("Not Found: " + str(e)) print("OK - LDAP object created after installation.") return True
def test_user_creation(selenium, mails, get_registration_info, verification_process): # creates user _navigate_self_service(selenium, '#page=createaccount') info = get_registration_info() _enter_attributes(selenium, info['attributes'], 'Create account') utils.verify_ldap_object(info['dn'], { 'univentionRegisteredThroughSelfService': ['TRUE'], 'univentionPasswordRecoveryEmailVerified': ['FALSE'], }) selenium.driver.find_element_by_xpath('//p[text()="Hello "]/b[text()="{}"]//parent::p[text()=", we have sent you an email to "]/b[text()="{}"]//parent::p[text()=". Please follow the instructions in the email to verify your account."]'.format(info['attributes']['username'], info['attributes']['PasswordRecoveryEmail'])) # tests email mail = _get_mail(mails) if verification_process == 'automatic': # tests automatic link selenium.driver.get(mail['auto_verify_link']) selenium.wait_until_standby_animation_appears_and_disappears() elif verification_process == 'manual': # tests manual link selenium.driver.get(mail['verify_link']) _enter_attributes(selenium, { 'username': mail['verify_data']['username'], 'token': mail['verify_data']['token'], }, 'Verify account') selenium.driver.find_element_by_xpath('//p[text()="Welcome "]/b[text()="{}"]//parent::p[text()=", your account has been successfully verified."]'.format(info['attributes']['username'])) selenium.driver.find_element_by_xpath('//p[text()="Continue to the "]/a[text()="Univention Portal"]') utils.verify_ldap_object(info['dn'], { 'univentionRegisteredThroughSelfService': ['TRUE'], 'univentionPasswordRecoveryEmailVerified': ['TRUE'], })
def test_check_univentionDefaultGroup_membership_after_create(udm): """Check default primary group membership after users/user create""" # from users/user: lookup univentionDefaultGroup lo = utils.get_ldap_connection() pos = position(lo.base) searchResult = lo.search(filter='(objectClass=univentionDefault)', base='cn=univention,' + pos.getDomain(), attr=['univentionDefaultGroup']) if not searchResult or not searchResult[0][1]: utils.fail( 'Test system is broken: univentionDefaultGroup value not found') groupdn = searchResult[0][1]['univentionDefaultGroup'][0].decode('utf-8') # lookup previous members for comparison searchResult = lo.search(base=groupdn, scope='base', attr=['uniqueMember', 'memberUid']) if not searchResult or not searchResult[0][1]: utils.fail( 'Test system is broken: univentionDefaultGroup object missing: %s' % groupdn) uniqueMember = searchResult[0][1]['uniqueMember'] memberUid = searchResult[0][1]['memberUid'] # now create users/user object userdn, uid = udm.create_user(primaryGroup=groupdn) # and check if the object has been added to univentionDefaultGroup uniqueMember.append(userdn.encode('utf-8')) memberUid.append(uid.encode('utf-8')) utils.verify_ldap_object(groupdn, {'uniqueMember': uniqueMember}) utils.verify_ldap_object(groupdn, {'memberUid': memberUid})
def test_create_user(self): user_mod = self.udm.get('users/user') obj = user_mod.new() self.user_objects.append(obj) attrs = { 'firstname': random_username(), 'lastname': random_username(), 'username': random_username(), 'password': random_username(), } self._user0_attrs.update(attrs) print('Creating user with attrs: {!r}'.format(attrs)) for k, v in attrs.items(): setattr(obj.props, k, v) obj.save() print('Created {!r}.'.format(obj)) print('Verifying...') assert obj.props.password != attrs['password'], 'Password was not hased or object not reloaded!' utils.verify_ldap_object( obj.dn, expected_attr={ 'uid': [attrs['username']], 'sn': [attrs['lastname']], 'givenName': [attrs['firstname']], 'displayName': ['{} {}'.format(attrs['firstname'], attrs['lastname'])], }, strict=False, should_exist=True ) obj2 = user_mod.get_by_id(obj.props.username) assert obj2.dn == obj.dn
def test_user_univentionLastUsedValue(udm, ucr): """Create users/user and check univentionLastUsedValue""" # Please note: modification of uidNumber is not allowed according to users/user.py --> not tested here luv_dn = 'cn=uidNumber,cn=temporary,cn=univention,%s' % ( ucr.get('ldap/base'), ) lo = univention.uldap.getAdminConnection() lastUsedValue_old = lo.get(luv_dn).get('univentionLastUsedValue', [-1])[0] user_dn = udm.create_user()[0] utils.verify_ldap_object(user_dn) lastUsedValue_new = lo.get(luv_dn).get('univentionLastUsedValue', [-1])[0] if lastUsedValue_old == lastUsedValue_new: utils.fail( 'Create user with automatic uidNumber: univentionLastUsedValue did not change, but it should!' ) lastUsedValue_old = lo.get(luv_dn).get('univentionLastUsedValue', [-1])[0] uidNumber = str(random.randint(100000, 200000)) user_dn = udm.create_user(uidNumber=uidNumber)[0] utils.verify_ldap_object(user_dn, expected_attr={'uidNumber': [uidNumber]}) lastUsedValue_new = lo.get(luv_dn).get('univentionLastUsedValue', [-1])[0] if lastUsedValue_old != lastUsedValue_new: utils.fail( 'Create user with specified uidNumber: univentionLastUsedValue did change, but it should not!' )
def verify(self): print('verify %s: %s' % (self.role, self.username)) utils.wait_for_replication() # reload UCR configRegistry.load() if self.mode == 'D': utils.verify_ldap_object(self.dn, should_exist=False) return utils.verify_ldap_object(self.dn, expected_attr=self.expected_attributes(), strict=True, should_exist=True) default_group_dn = 'cn=Domain Users %s,cn=groups,%s' % (self.school, self.school_base) utils.verify_ldap_object(default_group_dn, expected_attr={'uniqueMember': [self.dn], 'memberUid': [self.username]}, strict=False, should_exist=True) for school, classes in self.school_classes.iteritems(): for cl in classes: cl_group_dn = 'cn=%s,cn=klassen,cn=%s,cn=groups,%s' % (cl, cn_pupils, get_school_base(school)) utils.verify_ldap_object(cl_group_dn, expected_attr={'uniqueMember': [self.dn], 'memberUid': [self.username]}, strict=False, should_exist=True) assert self.school in self.schools for school in self.schools: role_group_dn = 'cn=%s%s,cn=groups,%s' % (self.grp_prefix, school, get_school_base(school)) utils.verify_ldap_object(role_group_dn, expected_attr={'uniqueMember': [self.dn], 'memberUid': [self.username]}, strict=False, should_exist=True) print 'person OK: %s' % self.username
def test_user_creation_with_umlaut_in_username(self, udm): """Create users/user with umlaut in username""" # bugs: [11415] user = udm.create_user( username='******' % (uts.random_name(length=4), uts.random_name(length=4)))[0] utils.verify_ldap_object(user)
def test_group_removal(udm): """Remove groups/group""" group = udm.create_group(wait_for=True)[0] udm.remove_object('groups/group', dn=group) utils.verify_ldap_object(group, should_exist=False)
def test_group_creation_set_single_letter_name_nestedGroup(udm): """Add nestedGroup with single letter name to groups/group during creation""" nestedGroup = udm.create_group(name=uts.random_groupname(1))[0] group = udm.create_group(nestedGroup=nestedGroup)[0] utils.verify_ldap_object(group, {'uniqueMember': [nestedGroup]})
def test_dhcp_sharedsubnet_creation_with_all_attributes(self, udm): """Create dhcp/sharedsubnet with all attributes set""" dhcp_service = udm.create_object('dhcp/service', service=uts.random_name()) dhcp_shared_network = udm.create_object('dhcp/shared', name=uts.random_name(), superordinate=dhcp_service) dhcp_shared_subnet_properties = { 'subnet': SUBNET_IP4, 'subnetmask': SUBNET_MASK_IP4, 'broadcastaddress': '10.20.30.255', 'range': '10.20.30.1 10.20.30.254' } dhcp_shared_subnet = udm.create_object( 'dhcp/sharedsubnet', superordinate=dhcp_shared_network, **dhcp_shared_subnet_properties) utils.verify_ldap_object( dhcp_shared_subnet, { 'dhcpNetMask': [dhcp_shared_subnet_properties['subnetmask']], 'dhcpRange': [dhcp_shared_subnet_properties['range']], 'univentionDhcpBroadcastAddress': [dhcp_shared_subnet_properties['broadcastaddress']] })
def test_user_modification_set_birthday(self, udm): """Set userBirthday during users/user modification""" user = udm.create_user()[0] userBirthday = '2005-01-01' udm.modify_object('users/user', dn=user, birthday=userBirthday) utils.verify_ldap_object(user, {'univentionBirthday': [userBirthday]})
def test_container_ou_creation_set_description(self, udm): """Set description during container/ou creation""" description = uts.random_string() ou = udm.create_object('container/ou', name=uts.random_name(), description=description) utils.verify_ldap_object(ou, {'description': [description]})
def test_dhcp_sharednetwork_creation(self, udm): dhcp_service = udm.create_object('dhcp/service', service=uts.random_name()) dhcp_shared_network = udm.create_object('dhcp/shared', name=uts.random_name(), superordinate=dhcp_service) utils.verify_ldap_object(dhcp_shared_network)
def self_service_user(email=None, **kwargs): with udm_test.UCSTestUDM() as udm: password = uts.random_string() if email: kwargs['PasswordRecoveryEmail'] = email dn, username = udm.create_user(password=password, **kwargs) utils.verify_ldap_object(dn) yield SelfServiceUser(username, password)
def verify(self): print 'verify printer: %s' % self.name if self.mode == 'D': utils.verify_ldap_object(self.dn, should_exist=False) return utils.verify_ldap_object(self.dn, expected_attr=self.expected_attributes(), should_exist=True)
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')
def random_reverse_zone(): while True: ip_parts = [str(random.randrange(1, 254)) for i in range(3)] random_reverse_zone = '.'.join(ip_parts) try: utils.verify_ldap_object(random_reverse_zone) except Exception: break return random_reverse_zone
def test_container_ou_creation_set_description_with_special_characters( self, udm): """Set description during container/ou creation with special characters""" description = uts.random_string() ou = udm.create_object('container/ou', name=uts.random_name_special_characters(), description=description) utils.verify_ldap_object(ou, {'description': [description]})