Debian Codegraph @

dirsrvtests/tests/suites/basic/basic_test.py

raw
1 # --- BEGIN COPYRIGHT BLOCK ---
2 # Copyright (C) 2026 Red Hat, Inc.
3 # All rights reserved.
4 #
5 # License: GPL (version 3 or any later version).
6 # See LICENSE for details.
7 # --- END COPYRIGHT BLOCK ---
8 #
9
10 from subprocess import check_output, PIPE, run
11 from lib389 import DirSrv
12 from lib389.idm.user import UserAccount, UserAccounts
13 import pytest
14 from lib389.tasks import *
15 from lib389.utils import *
16 from lib389.dseutils import get_ldapurl_from_serverid
17 from test389.topologies import topology_st
18 from lib389.dbgen import dbgen_users
19 from lib389.idm.organizationalunit import OrganizationalUnits
20 from lib389._constants import DN_DM, PASSWORD, PW_DM, ReplicaRole
21 from lib389.paths import Paths
22 from lib389.idm.directorymanager import DirectoryManager
23 from lib389.config import LDBMConfig, CertmapLegacy
24 from lib389.dseldif import DSEldif
25 from lib389.rootdse import RootDSE
26 from ....conftest import get_rpm_version
27 from lib389._mapped_object import DSLdapObjects
28 from lib389.replica import Replicas, Changelog
29 from lib389.backend import Backends, BackendSuffixView
30 from lib389.idm.domain import Domain
31 from lib389.nss_ssl import NssSsl
32 from lib389._constants import *
33 from lib389 import DirSrv
34 from lib389.instance.setup import SetupDs
35 from lib389.instance.options import General2Base, Slapd2Base
36 import os
37 import random
38 import ldap
39 import time
40 import subprocess
41
42
43 pytestmark = pytest.mark.tier0
44
45 default_paths = Paths()
46
47 log = logging.getLogger(__name__)
48 DEBUGGING = os.getenv("DEBUGGING", default=False)
49
50 # Globals
51 USER1_DN = 'uid=user1,' + DEFAULT_SUFFIX
52 USER2_DN = 'uid=user2,' + DEFAULT_SUFFIX
53 USER3_DN = 'uid=user3,' + DEFAULT_SUFFIX
54 USER4_DN = 'uid=user4,' + DEFAULT_SUFFIX
55
56 ROOTDSE_DEF_ATTR_LIST = ('namingContexts',
57 'supportedLDAPVersion',
58 'supportedControl',
59 'supportedExtension',
60 'supportedSASLMechanisms',
61 'vendorName',
62 'vendorVersion')
63
64 # This MAX_FDS value left about 22 connections available with bdb
65 # (should have more connections with lmdb)
66 MAX_FDS = 150
67
68 default_paths = Paths()
69
70 log = logging.getLogger(__name__)
71 DEBUGGING = os.getenv("DEBUGGING", default=False)
72
73
74 class CustomSetup():
75 DEFAULT_GENERAL = { 'config_version': 2,
76 'full_machine_name': 'localhost.localdomain',
77 'strict_host_checking': False,
78 # Not setting 'systemd' because it is not used.
79 # (that is the global default.inf setting that matters)
80 }
81 DEFAULT_SLAPD = { 'root_password': PW_DM,
82 'defaults': INSTALL_LATEST_CONFIG,
83 }
84 DEFAULT_BACKENDS = [ {
85 'cn': 'userroot',
86 'nsslapd-suffix': DEFAULT_SUFFIX,
87 'sample_entries': 'yes',
88 BACKEND_SAMPLE_ENTRIES: INSTALL_LATEST_CONFIG,
89 }, ]
90
91 WRAPPER_FORMAT = '''#!/bin/sh
92 {wrapper_options}
93 exec {nsslapd} -D {cfgdir} -i {pidfile}
94 '''
95
96
97 class CustomDirSrv(DirSrv):
98 def __init__(self, verbose=False, external_log=log):
99 super().__init__(verbose=verbose, external_log=external_log)
100 self.wrapper = None # placeholder for the wrapper file name
101
102 def _reset_systemd(self):
103 self.systemd_override = False
104
105 def status(self):
106 self._reset_systemd()
107 return super().status()
108
109 def start(self, timeout=120, *args):
110 if self.status():
111 return
112 tmp_env = os.environ
113 # Unset PYTHONPATH to avoid mixing old CLI tools and new lib389
114 if "PYTHONPATH" in tmp_env:
115 del tmp_env["PYTHONPATH"]
116 try:
117 subprocess.check_call([
118 '/usr/bin/sh',
119 self.wrapper
120 ], env=tmp_env, stderr=subprocess.STDOUT)
121 except subprocess.CalledProcessError as e:
122 log.fatal("%s failed! Error (%s) %s" % (self.wrapper, e.returncode, e.output))
123 raise e from None
124 for count in range(timeout):
125 if self.status():
126 return
127 time.sleep(1)
128 raise TimeoutError('Failed to start ns-slpad')
129
130 def stop(self, timeout=120):
131 self._reset_systemd()
132 super().stop(timeout=timeout)
133
134 def _search_be(self, belist, beinfo):
135 for be in belist:
136 if be['cn'] == beinfo['cn']:
137 return be
138 return None
139
140 def __init__(self, serverid, general=None, slapd=None, backends=None, log=log):
141 verbose = log.level > logging.DEBUG
142 self.log = log
143 self.serverid = serverid
144 self.verbose = verbose
145 self.wrapper = f'/tmp/ds_{serverid}_wrapper.sh'
146 if serverid.startswith('slapd-'):
147 self.instname = server.id
148 else:
149 self.instname = 'slapd-'+serverid
150 self.ldapi = None
151 self.pid_file = None
152 self.inst = None
153
154 # Lets prepare the options
155 general_options = General2Base(log)
156 for d in (CustomSetup.DEFAULT_GENERAL, general):
157 if d:
158 for key,val in d.items():
159 general_options.set(key,val)
160 log.debug('[general]: %s' % general_options._options)
161 self.general = general_options
162
163 slapd_options = Slapd2Base(self.log)
164 slapd_options.set('instance_name', serverid)
165 for d in (CustomSetup.DEFAULT_SLAPD, slapd):
166 if d:
167 for key,val in d.items():
168 slapd_options.set(key,val)
169 log.debug('[slapd]: %s' % slapd_options._options)
170 self.slapd = slapd_options
171
172 backend_options = []
173 for backend_list in (CustomSetup.DEFAULT_BACKENDS, backends):
174 if not backend_list:
175 continue
176 for backend in backend_list:
177 target_be = CustomSetup._search_be(self, backend_options, backend)
178 if not target_be:
179 target_be = {}
180 backend_options.append(target_be)
181 for key,val in backend.items():
182 target_be[key] = val
183 log.debug('[backends]: %s' % backend_options)
184 self.backends = backend_options
185
186 def _to_dirsrv_args(self):
187 args = {}
188 slapd = self.slapd.collect()
189 general = self.general.collect()
190 args["SER_HOST"] = general['full_machine_name']
191 args["SER_PORT"] = slapd['port']
192 args["SER_SECURE_PORT"] = slapd['secure_port']
193 args["SER_SERVERID_PROP"] = self.serverid
194 return args
195
196 def create_instance(self):
197 sds = SetupDs(verbose=self.verbose, dryrun=False, log=self.log)
198 self.general.verify()
199 general = self.general.collect()
200 self.slapd.verify()
201 slapd = self.slapd.collect()
202 sds.create_from_args(general, slapd, self.backends, None)
203 self.ldapi = get_ldapurl_from_serverid(self.serverid)[0]
204 args = self._to_dirsrv_args()
205 log.debug('DirSrv.allocate args = %s' % str(args))
206 log.debug('ldapi = %s' % str(self.ldapi))
207 root_dn = slapd['root_dn']
208 root_password = slapd['root_password']
209 inst = DirSrv(verbose=self.verbose, external_log=self.log)
210 inst.local_simple_allocate(self.serverid, ldapuri=self.ldapi, binddn=root_dn, password=root_password)
211 self.pid_file = inst.pid_file()
212 # inst.setup_ldapi()
213 log.debug('DirSrv = %s' % str(inst.__dict__))
214 inst.open()
215 inst.stop()
216 inst = CustomSetup.CustomDirSrv(verbose=self.verbose, external_log=self.log)
217 inst.local_simple_allocate(self.serverid, ldapuri=self.ldapi, binddn=root_dn, password=root_password)
218 self.inst = inst
219 return inst
220
221 def create_wrapper(self, maxfds=None):
222 self.inst.wrapper = self.wrapper
223 slapd = self.slapd.collect()
224 sbin_dir = slapd['sbin_dir']
225 config_dir = slapd['config_dir']
226 fmtvalues = {
227 'nsslapd': f'{sbin_dir}/ns-slapd',
228 'cfgdir': config_dir.format(instance_name=self.instname),
229 'pidfile': self.pid_file,
230 'wrapper_options': ''
231 }
232 if maxfds:
233 fmtvalues['wrapper_options']=f'ulimit -n {maxfds}\nulimit -H -n {maxfds}'
234 with open(self.wrapper, 'w') as f:
235 f.write(CustomSetup.WRAPPER_FORMAT.format(**fmtvalues))
236
237 def cleanup(self):
238 self.inst.stop()
239 self.inst.delete()
240 if os.path.exists(self.wrapper):
241 os.remove(self.wrapper)
242
243
244 @pytest.fixture(scope="function")
245 def _reset_attr(request, topology_st):
246 """ Reset nsslapd-close-on-failed-bind attr to the default (off) """
247
248 def fin():
249 dm = DirectoryManager(topology_st.standalone)
250 try:
251 dm_conn = dm.bind()
252 dm_conn.config.replace('nsslapd-close-on-failed-bind', 'off')
253 assert (dm_conn.config.get_attr_val_utf8('nsslapd-close-on-failed-bind')) == 'off'
254 except ldap.LDAPError as e:
255 log.error('Failure reseting attr: ' + str(e))
256 assert False
257 topology_st.standalone.restart()
258
259 request.addfinalizer(fin)
260
261
262 @pytest.fixture(scope="module")
263 def import_example_ldif(topology_st):
264 """Import the Example LDIF for the tests in this suite"""
265
266 log.info('Initializing the "basic" test suite')
267
268 ldif = '%s/dirsrv/data/Example.ldif' % topology_st.standalone.get_data_dir()
269 import_ldif = topology_st.standalone.get_ldif_dir() + "/Example.ldif"
270 shutil.copy(ldif, import_ldif)
271
272 import_task = ImportTask(topology_st.standalone)
273 import_task.import_suffix_from_ldif(ldiffile=import_ldif, suffix=DEFAULT_SUFFIX)
274 import_task.wait()
275
276
277 def check_db_sanity(topology_st):
278 try:
279 entries = topology_st.standalone.search_s(DEFAULT_SUFFIX,
280 ldap.SCOPE_SUBTREE,
281 '(uid=scarter)')
282 if entries is None:
283 log.fatal('Unable to find user uid=scarter. DB or indexes are probably corrupted !')
284 assert False
285 except ldap.LDAPError as e:
286 log.fatal('test_basic_acl: Search suffix failed: ' + e.args[0]['desc'])
287 assert False
288
289
290 @pytest.fixture(params=ROOTDSE_DEF_ATTR_LIST)
291 def rootdse_attr(topology_st, request):
292 """Adds an attr from the list
293 as the default attr to the rootDSE
294 """
295 # Ensure the server is started and connected
296 topology_st.standalone.start()
297
298 RETURN_DEFAULT_OPATTR = "nsslapd-return-default-opattr"
299 rootdse_attr_name = ensure_bytes(request.param)
300
301 log.info(" Add the %s: %s to rootdse" % (RETURN_DEFAULT_OPATTR,
302 rootdse_attr_name))
303 mod = [(ldap.MOD_ADD, RETURN_DEFAULT_OPATTR, rootdse_attr_name)]
304 try:
305 topology_st.standalone.modify_s("", mod)
306 except ldap.LDAPError as e:
307 log.fatal('Failed to add attr: error (%s)' % (e.args[0]['desc']))
308 assert False
309
310 def fin():
311 log.info(" Delete the %s: %s from rootdse" % (RETURN_DEFAULT_OPATTR,
312 rootdse_attr_name))
313 mod = [(ldap.MOD_DELETE, RETURN_DEFAULT_OPATTR, rootdse_attr_name)]
314 try:
315 topology_st.standalone.modify_s("", mod)
316 except ldap.LDAPError as e:
317 log.fatal('Failed to delete attr: error (%s)' % (e.args[0]['desc']))
318 assert False
319
320 request.addfinalizer(fin)
321
322 return rootdse_attr_name
323
324
325 def change_conf_attr(topology_st, suffix, attr_name, attr_value):
326 """Change configuration attribute in the given suffix.
327
328 Returns previous attribute value.
329 """
330
331 entry = DSLdapObject(topology_st.standalone, suffix)
332
333 attr_value_bck = entry.get_attr_val_bytes(attr_name)
334 log.info('Set %s to %s. Previous value - %s. Modified suffix - %s.' % (
335 attr_name, attr_value, attr_value_bck, suffix))
336 if attr_value is None:
337 entry.remove_all(attr_name)
338 else:
339 entry.replace(attr_name, attr_value)
340 return attr_value_bck
341
342
343 @pytest.fixture(scope="function")
344 def ldapagent_config(topology_st, request):
345 """Creates agent.conf for snmp agent
346 """
347
348 var_dir = topology_st.standalone.get_local_state_dir()
349 config_file = os.path.join(topology_st.standalone.get_sysconf_dir(), 'dirsrv/config/agent.conf')
350 config = f"""agentx-supplier {var_dir}/agentx/supplier
351 agent-logdir {var_dir}/log/dirsrv
352 server slapd-{topology_st.standalone.serverid}
353 """
354
355 with open(config_file, 'w') as agent_config_file:
356 agent_config_file.write(config)
357
358 def fin():
359 os.remove(config_file)
360
361 request.addfinalizer(fin)
362
363 return config_file
364
365
366 def test_basic_ops(topology_st, import_example_ldif):
367 """Tests adds, mods, modrdns, and deletes operations
368
369 :id: 33f97f55-60bf-46c7-b880-6c488517ae19
370
371 :setup: Standalone instance
372
373 :steps:
374 1. Add 3 test users USER1, USER2 and USER3 to database
375 2. Modify (ADD, REPLACE and DELETE) description for USER1 in database
376 3. Rename USER1, USER2 and USER3 using Modrds
377 4. Delete test entries USER1, USER2 and USER3
378
379 :expectedresults:
380 1. Add operation should PASS.
381 2. Modify operations should PASS.
382 3. Rename operations should PASS.
383 4. Delete operations should PASS.
384 """
385 log.info('Running test_basic_ops...')
386 USER1_NEWDN = 'cn=user1'
387 USER2_NEWDN = 'cn=user2'
388 USER3_NEWDN = 'cn=user3'
389 NEW_SUPERIOR = 'ou=people,' + DEFAULT_SUFFIX
390 USER1_RDN_DN = 'cn=user1,' + DEFAULT_SUFFIX
391 USER2_RDN_DN = 'cn=user2,' + DEFAULT_SUFFIX
392 USER3_RDN_DN = 'cn=user3,' + NEW_SUPERIOR # New superior test
393
394 #
395 # Adds#
396 try:
397 topology_st.standalone.add_s(Entry((USER1_DN,
398 {'objectclass': "top extensibleObject".split(),
399 'sn': '1',
400 'cn': 'user1',
401 'uid': 'user1',
402 'userpassword': 'password'})))
403 except ldap.LDAPError as e:
404 log.error('Failed to add test user' + USER1_DN + ': error ' + e.args[0]['desc'])
405 assert False
406
407 try:
408 topology_st.standalone.add_s(Entry((USER2_DN,
409 {'objectclass': "top extensibleObject".split(),
410 'sn': '2',
411 'cn': 'user2',
412 'uid': 'user2',
413 'userpassword': 'password'})))
414 except ldap.LDAPError as e:
415 log.error('Failed to add test user' + USER2_DN + ': error ' + e.args[0]['desc'])
416 assert False
417
418 try:
419 topology_st.standalone.add_s(Entry((USER3_DN,
420 {'objectclass': "top extensibleObject".split(),
421 'sn': '3',
422 'cn': 'user3',
423 'uid': 'user3',
424 'userpassword': 'password'})))
425 except ldap.LDAPError as e:
426 log.error('Failed to add test user' + USER3_DN + ': error ' + e.args[0]['desc'])
427 assert False
428
429 #
430 # Mods
431 #
432 try:
433 topology_st.standalone.modify_s(USER1_DN, [(ldap.MOD_ADD, 'description',
434 b'New description')])
435 except ldap.LDAPError as e:
436 log.error('Failed to add description: error ' + e.args[0]['desc'])
437 assert False
438
439 try:
440 topology_st.standalone.modify_s(USER1_DN, [(ldap.MOD_REPLACE, 'description',
441 b'Modified description')])
442 except ldap.LDAPError as e:
443 log.error('Failed to modify description: error ' + e.args[0]['desc'])
444 assert False
445
446 try:
447 topology_st.standalone.modify_s(USER1_DN, [(ldap.MOD_DELETE, 'description',
448 None)])
449 except ldap.LDAPError as e:
450 log.error('Failed to delete description: error ' + e.args[0]['desc'])
451 assert False
452
453 #
454 # Modrdns
455 #
456 try:
457 topology_st.standalone.rename_s(USER1_DN, USER1_NEWDN, delold=1)
458 except ldap.LDAPError as e:
459 log.error('Failed to modrdn user1: error ' + e.args[0]['desc'])
460 assert False
461
462 try:
463 topology_st.standalone.rename_s(USER2_DN, USER2_NEWDN, delold=0)
464 except ldap.LDAPError as e:
465 log.error('Failed to modrdn user2: error ' + e.args[0]['desc'])
466 assert False # Modrdn - New superior
467
468 try:
469 topology_st.standalone.rename_s(USER3_DN, USER3_NEWDN,
470 newsuperior=NEW_SUPERIOR, delold=1)
471 except ldap.LDAPError as e:
472 log.error('Failed to modrdn(new superior) user3: error ' + e.args[0]['desc'])
473 assert False
474 #
475 # Deletes
476 #
477 try:
478 topology_st.standalone.delete_s(USER1_RDN_DN)
479 except ldap.LDAPError as e:
480 log.error('Failed to delete test entry1: ' + e.args[0]['desc'])
481 assert False
482
483 try:
484 topology_st.standalone.delete_s(USER2_RDN_DN)
485 except ldap.LDAPError as e:
486 log.error('Failed to delete test entry2: ' + e.args[0]['desc'])
487 assert False
488
489 try:
490 topology_st.standalone.delete_s(USER3_RDN_DN)
491 except ldap.LDAPError as e:
492 log.error('Failed to delete test entry3: ' + e.args[0]['desc'])
493 assert False
494 check_db_sanity(topology_st)
495 log.info('test_basic_ops: PASSED')
496
497 def test_basic_search_asynch(topology_st, request):
498 """
499 Tests asynchronous searches generate string 'notes=B'
500 and 'notes=N' in access logs
501
502 :id: 1b761421-d2bb-487b-813e-2278123fd13c
503 :parametrized: no
504 :setup: Standalone instance, create test user to search with filter (uid=*).
505
506 :steps:
507 1. Create a test user
508 2. trigger async searches
509 3. Verify access logs contains 'notes=B' up to 10 attempts
510 4. Verify access logs contains 'notes=N' up to 10 attempts
511
512 :expectedresults:
513 1. Success
514 2. Success
515 3. Success
516 4. Success
517
518 """
519
520 log.info('Running test_basic_search_asynch...')
521
522 search_filter = "(uid=*)"
523 topology_st.standalone.restart()
524 topology_st.standalone.config.set("nsslapd-accesslog-logbuffering", "off")
525 topology_st.standalone.config.set("nsslapd-maxthreadsperconn", "3")
526
527 try:
528 users = UserAccounts(topology_st.standalone, DEFAULT_SUFFIX, rdn=None)
529 user = users.create_test_user()
530 except ldap.LDAPError as e:
531 log.fatal('Failed to create test user: error ' + e.args[0]['desc'])
532 assert False
533
534 for attempt in range(10):
535 msgids = []
536 for i in range(5):
537 searchid = topology_st.standalone.search(DEFAULT_SUFFIX, ldap.SCOPE_SUBTREE, search_filter)
538 msgids.append(searchid)
539
540 for msgid in msgids:
541 rtype, rdata = topology_st.standalone.result(msgid)
542
543 # verify if some operations got blocked
544 error_lines = topology_st.standalone.ds_access_log.match('.*notes=.*B.* details.*')
545 if len(error_lines) > 0:
546 log.info('test_basic_search_asynch: found "notes=B" after %d attempt(s)' % (attempt + 1))
547 break
548
549 assert attempt < 10
550
551 # verify if some operations got flagged Not synchronous
552 error_lines = topology_st.standalone.ds_access_log.match('.*notes=.*N.* details.*')
553 assert len(error_lines) > 0
554
555 def fin():
556 user.delete()
557 topology_st.standalone.config.set("nsslapd-accesslog-logbuffering", "on")
558 topology_st.standalone.config.set("nsslapd-maxthreadsperconn", "5")
559
560 request.addfinalizer(fin)
561
562 log.info('test_basic_search_asynch: PASSED')
563
564 def test_basic_import_export(topology_st, import_example_ldif):
565 """Test online and offline LDIF import & export
566
567 :id: 3ceeea11-9235-4e20-b80e-7203b2c6e149
568
569 :setup: Standalone instance
570
571 :steps:
572 1. Generate a test ldif (50k entries)
573 2. Import test ldif file using Online import.
574 3. Import test ldif file using Offline import (ldif2db).
575 4. Export test ldif file using Online export.
576 5. Export test ldif file using Offline export (db2ldif).
577 6. Cleanup - Import the Example LDIF for the other tests in this suite
578
579 :expectedresults:
580 1. Test ldif file creation should PASS.
581 2. Online import should PASS.
582 3. Offline import should PASS.
583 4. Online export should PASS.
584 5. Offline export should PASS.
585 6. Cleanup should PASS.
586 """
587
588 log.info('Running test_basic_import_export...')
589 #
590 # Test online/offline LDIF imports
591 #
592 topology_st.standalone.restart()
593 # topology_st.standalone.config.set('nsslapd-errorlog-level', '1')
594
595 # Generate a test ldif (50k entries)
596 log.info("Generating LDIF...")
597 ldif_dir = topology_st.standalone.get_ldif_dir()
598 import_ldif = ldif_dir + '/basic_import.ldif'
599 dbgen_users(topology_st.standalone, 50000, import_ldif, DEFAULT_SUFFIX)
600
601 # Online
602 log.info("Importing LDIF online...")
603 import_task = ImportTask(topology_st.standalone)
604 import_task.import_suffix_from_ldif(ldiffile=import_ldif, suffix=DEFAULT_SUFFIX)
605
606 # Wait a bit till the task is created and available for searching
607 time.sleep(1)
608
609 # Good as place as any to quick test the task has some expected attributes
610 assert import_task.present('nstaskcreated')
611 assert import_task.present('nstasklog')
612 assert import_task.present('nstaskcurrentitem')
613 assert import_task.present('nstasktotalitems')
614 assert import_task.present('ttl')
615
616 import_task.wait()
617
618 # Offline
619 log.info("Importing LDIF offline...")
620 topology_st.standalone.stop()
621 if not topology_st.standalone.ldif2db(DEFAULT_BENAME, None, None, None, import_ldif):
622 log.fatal('test_basic_import_export: Offline import failed')
623 assert False
624 topology_st.standalone.start()
625
626 #
627 # Test online and offline LDIF export
628 #
629
630 # Online export
631 log.info("Exporting LDIF online...")
632 export_ldif = ldif_dir + '/export.ldif'
633
634 export_task = ExportTask(topology_st.standalone)
635 export_task.export_suffix_to_ldif(ldiffile=export_ldif, suffix=DEFAULT_SUFFIX)
636 export_task.wait()
637
638 # Offline export
639 log.info("Exporting LDIF offline...")
640 topology_st.standalone.stop()
641 if not topology_st.standalone.db2ldif(DEFAULT_BENAME, (DEFAULT_SUFFIX,),
642 None, None, None, export_ldif):
643 log.fatal('test_basic_import_export: Failed to run offline db2ldif')
644 assert False
645
646 topology_st.standalone.start()
647
648 #
649 # Cleanup - Import the Example LDIF for the other tests in this suite
650 #
651 log.info("Restore datrabase, import initial LDIF...")
652 ldif = '%s/dirsrv/data/Example.ldif' % topology_st.standalone.get_data_dir()
653 import_ldif = topology_st.standalone.get_ldif_dir() + "/Example.ldif"
654 shutil.copyfile(ldif, import_ldif)
655
656 import_task = ImportTask(topology_st.standalone)
657 import_task.import_suffix_from_ldif(ldiffile=import_ldif, suffix=DEFAULT_SUFFIX)
658 import_task.wait()
659
660 check_db_sanity(topology_st)
661 log.info('test_basic_import_export: PASSED')
662
663
664 def test_basic_backup(topology_st, import_example_ldif):
665 """Tests online and offline backup and restore
666
667 :id: 0e9d91f8-8748-40b6-ab03-fbd1998eb985
668
669 :setup: Standalone instance and import example.ldif
670
671 :steps:
672 1. Test online backup using db2bak.
673 2. Test config files are backed up
674 3. Test online restore using bak2db.
675 4. Test offline backup using db2bak.
676 5. Test config files are backed up
677 6. Test offline restore using bak2db.
678
679 :expectedresults:
680 1. Online backup should PASS.
681 2. Config files were backed up
682 3. Online restore should PASS.
683 4. Offline backup should PASS.
684 5. Config files were backed up
685 6. Offline restore should PASS.
686 """
687
688 log.info('Running test_basic_backup...')
689
690 topology_st.standalone.restart()
691
692 backup_dir = topology_st.standalone.get_bak_dir() + '/backup_test_online'
693 log.info(f'Backup directory is {backup_dir}')
694
695 # Test online backup
696 try:
697 topology_st.standalone.tasks.db2bak(backup_dir=backup_dir,
698 args={TASK_WAIT: True})
699 except ValueError:
700 log.fatal('test_basic_backup: Online backup failed')
701 assert False
702
703 # Test config files were backed up
704 assert os.path.isfile(backup_dir + "/config_files/dse.ldif")
705 assert os.path.isfile(backup_dir + "/config_files/schema/99user.ldif")
706 assert os.path.isfile(backup_dir + "/config_files/certmap.conf")
707 assert os.path.isfile(backup_dir + "/config_files/cert9.db")
708
709 # Test online restore
710 try:
711 topology_st.standalone.tasks.bak2db(backup_dir=backup_dir,
712 args={TASK_WAIT: True})
713 except ValueError:
714 log.fatal('test_basic_backup: Online restore failed')
715 assert False
716
717 # Test offline backup
718 backup_dir = topology_st.standalone.get_bak_dir() + '/backup_test_offline'
719 topology_st.standalone.stop()
720 if not topology_st.standalone.db2bak(backup_dir):
721 log.fatal('test_basic_backup: Offline backup failed')
722 assert False
723
724 # Test config files wre backed up
725 assert os.path.isfile(backup_dir + "/config_files/dse.ldif")
726 assert os.path.isfile(backup_dir + "/config_files/schema/99user.ldif")
727 assert os.path.isfile(backup_dir + "/config_files/certmap.conf")
728 assert os.path.isfile(backup_dir + "/config_files/cert9.db")
729
730 # Test offline restore
731 if not topology_st.standalone.bak2db(backup_dir):
732 log.fatal('test_basic_backup: Offline backup failed')
733 assert False
734 topology_st.standalone.start()
735
736 check_db_sanity(topology_st)
737 log.info('test_basic_backup: PASSED')
738
739
740 def test_basic_db2index(topology_st):
741 """Assert db2index can operate correctly.
742
743 :id: 191fc0fd-9722-46b5-a7c3-e8760effe119
744
745 :setup: Standalone instance
746
747 :steps:
748 1: Call db2index with a single index attribute
749 2: Call db2index with multiple index attributes
750 3: Call db2index with no index attributes
751
752 :expectedresults:
753 1: Index succeeds for single index attribute
754 2: Index succeeds for multiple index attributes
755 3: Index succeeds for all backend indexes which have been obtained from dseldif
756
757 """
758
759 # Error log message to confirm a reindex
760 if get_default_db_lib() == "mdb":
761 dbprefix = "dbmdb"
762 else:
763 dbprefix = "bdb"
764 info_message = f'INFO - {dbprefix}_db2index - {DEFAULT_BENAME}: Indexing attribute: '
765
766 log.info('Start the server')
767 topology_st.standalone.start()
768 check_db_sanity(topology_st)
769
770 log.info('Offline reindex, stopping the server')
771 topology_st.standalone.stop()
772
773 log.info('Reindex with a single index attribute')
774 topology_st.standalone.db2index(bename=DEFAULT_BENAME, attrs=['uid'])
775 assert topology_st.standalone.searchErrorsLog(info_message + 'uid')
776
777 log.info('Restart the server to clear the logs')
778 topology_st.standalone.start()
779 check_db_sanity(topology_st)
780 topology_st.standalone.stop()
781
782 log.info('Reindex with multiple attributes')
783 topology_st.standalone.db2index(bename=DEFAULT_BENAME, attrs=['cn','aci','givenname'])
784 assert topology_st.standalone.searchErrorsLog(info_message + 'cn')
785 assert topology_st.standalone.searchErrorsLog(info_message + 'aci')
786 assert topology_st.standalone.searchErrorsLog(info_message + 'givenname')
787
788 log.info('Restart the server to clear the logs')
789 topology_st.standalone.start()
790 check_db_sanity(topology_st)
791 topology_st.standalone.stop()
792
793 log.info('Start the server and get all indexes for specified backend')
794 topology_st.standalone.start()
795 check_db_sanity(topology_st)
796 dse_ldif = DSEldif(topology_st.standalone)
797 indexes = dse_ldif.get_indexes(DEFAULT_BENAME)
798 numIndexes = len(indexes)
799 assert numIndexes > 0
800
801 log.info('Stop the server and reindex with all backend indexes')
802 topology_st.standalone.stop()
803 topology_st.standalone.db2index(bename=DEFAULT_BENAME, attrs=indexes)
804 log.info('Checking the server logs for %d backend indexes INFO' % numIndexes)
805 for indexNum, index in enumerate(indexes):
806 if index in ["entryrdn", "ancestorid"]:
807 assert topology_st.standalone.searchErrorsLog(
808 f'INFO - {dbprefix}_db2index - {DEFAULT_BENAME}: Indexing: {index}')
809 else:
810 assert topology_st.standalone.searchErrorsLog(
811 f'INFO - {dbprefix}_db2index - {DEFAULT_BENAME}: Indexing attribute: {index}')
812
813 assert indexNum+1 == numIndexes
814
815 topology_st.standalone.start()
816 check_db_sanity(topology_st)
817 log.info('test_basic_db2index: PASSED')
818
819
820 def test_basic_acl(topology_st, import_example_ldif):
821 """Run some basic access control (ACL) tests
822
823 :id: 4f4e705f-32f4-4065-b3a8-2b0c2525798b
824
825 :setup: Standalone instance
826
827 :steps:
828 1. Add two test users USER1_DN and USER2_DN.
829 2. Add an aci that denies USER1 from doing anything.
830 3. Set the default anonymous access for USER2.
831 4. Try searching entries using USER1.
832 5. Try searching entries using USER2.
833 6. Try searching entries using root dn.
834 7. Cleanup - delete test users and test ACI.
835
836 :expectedresults:
837 1. Test Users should be added.
838 2. ACI should be added.
839 3. This operation should PASS.
840 4. USER1 should not be able to search anything.
841 5. USER2 should be able to search everything except password.
842 6. RootDN should be allowed to search everything.
843 7. Cleanup should PASS.
844 """
845
846 """Run some basic access control(ACL) tests"""
847 log.info('Running test_basic_acl...')
848
849 DENY_ACI = ensure_bytes('(targetattr = "*")(version 3.0;acl "deny user";deny (all)(userdn = "ldap:///%s");)' % USER1_DN)
850
851 #
852 # Add two users
853 #
854 try:
855 topology_st.standalone.add_s(Entry((USER1_DN,
856 {'objectclass': "top extensibleObject".split(),
857 'sn': '1',
858 'cn': 'user 1',
859 'uid': 'user1',
860 'userpassword': PASSWORD})))
861 except ldap.LDAPError as e:
862 log.fatal('test_basic_acl: Failed to add test user ' + USER1_DN +
863 ': error ' + e.args[0]['desc'])
864 assert False
865
866 try:
867 topology_st.standalone.add_s(Entry((USER2_DN,
868 {'objectclass': "top extensibleObject".split(),
869 'sn': '2',
870 'cn': 'user 2',
871 'uid': 'user2',
872 'userpassword': PASSWORD})))
873 except ldap.LDAPError as e:
874 log.fatal('test_basic_acl: Failed to add test user ' + USER1_DN +
875 ': error ' + e.args[0]['desc'])
876 assert False
877
878 #
879 # Add an aci that denies USER1 from doing anything,
880 # and also set the default anonymous access
881 #
882 try:
883 topology_st.standalone.modify_s(DEFAULT_SUFFIX, [(ldap.MOD_ADD, 'aci', DENY_ACI)])
884 except ldap.LDAPError as e:
885 log.fatal('test_basic_acl: Failed to add DENY ACI: error ' + e.args[0]['desc'])
886 assert False
887
888 #
889 # Make sure USER1_DN can not search anything, but USER2_dn can...
890 #
891 try:
892 topology_st.standalone.simple_bind_s(USER1_DN, PASSWORD)
893 except ldap.LDAPError as e:
894 log.fatal('test_basic_acl: Failed to bind as user1, error: ' + e.args[0]['desc'])
895 assert False
896
897 try:
898 entries = topology_st.standalone.search_s(DEFAULT_SUFFIX,
899 ldap.SCOPE_SUBTREE,
900 '(uid=*)')
901 if entries:
902 log.fatal('test_basic_acl: User1 was incorrectly able to search the suffix!')
903 assert False
904 except ldap.LDAPError as e:
905 log.fatal('test_basic_acl: Search suffix failed(as user1): ' + e.args[0]['desc'])
906 assert False
907
908 # Now try user2... Also check that userpassword is stripped out
909 try:
910 topology_st.standalone.simple_bind_s(USER2_DN, PASSWORD)
911 except ldap.LDAPError as e:
912 log.fatal('test_basic_acl: Failed to bind as user2, error: ' + e.args[0]['desc'])
913 assert False
914
915 try:
916 entries = topology_st.standalone.search_s(DEFAULT_SUFFIX,
917 ldap.SCOPE_SUBTREE,
918 '(uid=user1)')
919 if not entries:
920 log.fatal('test_basic_acl: User1 incorrectly not able to search the suffix')
921 assert False
922 if entries[0].hasAttr('userpassword'):
923 # The default anonymous access aci should have stripped out userpassword
924 log.fatal('test_basic_acl: User2 was incorrectly able to see userpassword')
925 assert False
926 except ldap.LDAPError as e:
927 log.fatal('test_basic_acl: Search for user1 failed(as user2): ' + e.args[0]['desc'])
928 assert False
929
930 # Make sure RootDN can also search (this also resets the bind dn to the
931 # Root DN for future operations)
932 try:
933 topology_st.standalone.simple_bind_s(DN_DM, PW_DM)
934 except ldap.LDAPError as e:
935 log.fatal('test_basic_acl: Failed to bind as ROotDN, error: ' + e.args[0]['desc'])
936 assert False
937
938 try:
939 entries = topology_st.standalone.search_s(DEFAULT_SUFFIX,
940 ldap.SCOPE_SUBTREE,
941 '(uid=*)')
942 if not entries:
943 log.fatal('test_basic_acl: Root DN incorrectly not able to search the suffix')
944 assert False
945 except ldap.LDAPError as e:
946 log.fatal('test_basic_acl: Search for user1 failed(as user2): ' + e.args[0]['desc'])
947 assert False
948
949 #
950 # Cleanup
951 #
952 try:
953 topology_st.standalone.modify_s(DEFAULT_SUFFIX, [(ldap.MOD_DELETE, 'aci', DENY_ACI)])
954 except ldap.LDAPError as e:
955 log.fatal('test_basic_acl: Failed to delete DENY ACI: error ' + e.args[0]['desc'])
956 assert False
957
958 try:
959 topology_st.standalone.delete_s(USER1_DN)
960 except ldap.LDAPError as e:
961 log.fatal('test_basic_acl: Failed to delete test entry1: ' + e.args[0]['desc'])
962 assert False
963
964 try:
965 topology_st.standalone.delete_s(USER2_DN)
966 except ldap.LDAPError as e:
967 log.fatal('test_basic_acl: Failed to delete test entry2: ' + e.args[0]['desc'])
968 assert False
969
970 log.info('test_basic_acl: PASSED')
971
972
973 def test_basic_searches(topology_st, import_example_ldif):
974 """Tests basic search operations with filters.
975
976 :id: 426a59ff-49b8-4a70-b377-0c0634a29b6f
977
978 :setup: Standalone instance, add example.ldif to the database
979
980 :steps:
981 1. Execute search command while using different filters.
982 2. Check number of entries returned by search filters.
983
984 :expectedresults:
985 1. Search command should PASS.
986 2. Number of result entries returned should match number of the database entries according to the search filter.
987 """
988
989 log.info('Running test_basic_searches...')
990
991 filters = (('(uid=scarter)', 1),
992 ('(uid=tmorris*)', 1),
993 ('(uid=*hunt*)', 4),
994 ('(uid=*cope)', 2),
995 ('(mail=*)', 150),
996 ('(roomnumber>=4000)', 35),
997 ('(roomnumber<=4000)', 115),
998 ('(&(roomnumber>=4000)(roomnumber<=4500))', 18),
999 ('(!(l=sunnyvale))', 120),
1000 ('(&(uid=t*)(l=santa clara))', 7),
1001 ('(|(uid=k*)(uid=r*))', 18),
1002 ('(|(uid=t*)(l=sunnyvale))', 50),
1003 ('(&(!(uid=r*))(ou=people))', 139),
1004 ('(&(uid=m*)(l=sunnyvale)(ou=people)(mail=*example*)(roomNumber=*))', 3),
1005 ('(&(|(uid=m*)(l=santa clara))(roomNumber=22*))', 5),
1006 ('(&(|(uid=m*)(l=santa clara))(roomNumber=22*)(!(roomnumber=2254)))', 4),)
1007
1008 for (search_filter, search_result) in filters:
1009 try:
1010 entries = topology_st.standalone.search_s(DEFAULT_SUFFIX,
1011 ldap.SCOPE_SUBTREE,
1012 search_filter)
1013 if len(entries) != search_result:
1014 log.fatal('test_basic_searches: An incorrect number of entries\
1015 was returned from filter (%s): (%d) expected (%d)' %
1016 (search_filter, len(entries), search_result))
1017 assert False
1018 except ldap.LDAPError as e:
1019 log.fatal('Search failed: ' + e.args[0]['desc'])
1020 assert False
1021
1022 log.info('test_basic_searches: PASSED')
1023
1024
1025 @pytest.mark.parametrize('limit,resp',
1026 ((('200'), 'PASS'),
1027 (('50'), ldap.ADMINLIMIT_EXCEEDED)))
1028 def test_basic_search_lookthroughlimit(topology_st, limit, resp, import_example_ldif):
1029 """
1030 Tests normal search with lookthroughlimit set high and low.
1031
1032 :id: b5119970-6c9f-41b7-9649-de9233226fec
1033 :parametrized: yes
1034 :setup: Standalone instance, add example.ldif to the database, search filter (uid=*).
1035
1036 :steps:
1037 1. Import ldif user file.
1038 2. Change lookthroughlimit to 200.
1039 3. Bind to server as low priv user
1040 4. Run search 1 with "high" lookthroughlimit.
1041 5. Change lookthroughlimit to 50.
1042 6. Run search 2 with "low" lookthroughlimit.
1043 7. Delete user from DB.
1044 8. Reset lookthroughlimit to original.
1045
1046 :expectedresults:
1047 1. Success
1048 2. Success
1049 3. Success
1050 4. Success, first search should complete with no error.
1051 5. Success
1052 6. Success, second search should return ldap.ADMINLIMIT_EXCEEDED error.
1053 7. Success
1054 8. Success
1055
1056 """
1057
1058 log.info('Running test_basic_search_lookthroughlimit...')
1059
1060 search_filter = "(uid=*)"
1061
1062 ltl_orig = change_conf_attr(topology_st, 'cn=config,cn=ldbm database,cn=plugins,cn=config', 'nsslapd-lookthroughlimit', limit)
1063
1064 try:
1065 users = UserAccounts(topology_st.standalone, DEFAULT_SUFFIX, rdn=None)
1066 user = users.create_test_user()
1067 user.replace('userPassword', PASSWORD)
1068 except ldap.LDAPError as e:
1069 log.fatal('Failed to create test user: error ' + e.args[0]['desc'])
1070 assert False
1071
1072 try:
1073 conn = UserAccount(topology_st.standalone, user.dn).bind(PASSWORD)
1074 except ldap.LDAPError as e:
1075 log.fatal('Failed to bind test user: error ' + e.args[0]['desc'])
1076 assert False
1077
1078 try:
1079 if resp == ldap.ADMINLIMIT_EXCEEDED:
1080 with pytest.raises(ldap.ADMINLIMIT_EXCEEDED):
1081 searchid = conn.search(DEFAULT_SUFFIX, ldap.SCOPE_SUBTREE, search_filter)
1082 rtype, rdata = conn.result(searchid)
1083 else:
1084 searchid = conn.search(DEFAULT_SUFFIX, ldap.SCOPE_SUBTREE, search_filter)
1085 rtype, rdata = conn.result(searchid)
1086 assert(len(rdata) == 151) #151 entries in the imported ldif file using "(uid=*)"
1087 except ldap.LDAPError as e:
1088 log.fatal('Failed to perform search: error ' + e.args[0]['desc'])
1089 assert False
1090
1091 finally:
1092 #Cleanup
1093 change_conf_attr(topology_st, 'cn=config,cn=ldbm database,cn=plugins,cn=config', 'nsslapd-lookthroughlimit', ltl_orig)
1094 user.delete()
1095
1096 log.info('test_basic_search_lookthroughlimit: PASSED')
1097
1098
1099 @pytest.fixture(scope="module")
1100 def add_test_entry(topology_st, request):
1101 # Add test entry
1102 topology_st.standalone.add_s(Entry((USER4_DN,
1103 {'objectclass': "top extensibleObject".split(),
1104 'cn': 'user1', 'uid': 'user1'})))
1105
1106
1107 search_params = [(['1.1'], 'cn', False),
1108 (['1.1', 'cn'], 'cn', True),
1109 (['+'], 'nsUniqueId', True),
1110 (['*'], 'cn', True),
1111 (['cn'], 'cn', True)]
1112 @pytest.mark.skipif(ds_is_older("1.4.2.0"), reason="Not implemented")
1113 @pytest.mark.parametrize("attrs, attr, present", search_params)
1114 def test_search_req_attrs(topology_st, add_test_entry, attrs, attr, present):
1115 """Test requested attributes in search operations.
1116
1117 :id: 426a59ff-49b8-4a70-b377-0c0634a29b6e
1118 :parametrized: yes
1119 :setup: Standalone instance
1120 :steps:
1121 1. Test "1.1" does not return any attributes.
1122 2. Test "1.1" is ignored if there are other requested attributes
1123 3. Test "+" returns all operational attributes
1124 4. Test "*" returns all attributes
1125 5. Test requested attributes
1126
1127 :expectedresults:
1128 1. Success
1129 2. Success
1130 3. Success
1131 4. Success
1132 5. Success
1133 """
1134
1135 log.info("Testing attrs: {} attr: {} present: {}".format(attrs, attr, present))
1136 entry = topology_st.standalone.search_s(USER4_DN,
1137 ldap.SCOPE_BASE,
1138 'objectclass=top',
1139 attrs)
1140 if present:
1141 assert entry[0].hasAttr(attr)
1142 else:
1143 assert not entry[0].hasAttr(attr)
1144
1145
1146 def test_basic_referrals(topology_st, import_example_ldif):
1147 """Test LDAP server in referral mode.
1148
1149 :id: c586aede-7ac3-4e8d-a1cf-bfa8b8d78cc2
1150
1151 :setup: Standalone instance
1152
1153 :steps:
1154 1. Set the referral and the backend state
1155 2. Set backend state to referral mode.
1156 3. Set server to not follow referral.
1157 4. Search using referral.
1158 5. Make sure server can restart in referral mode.
1159 6. Cleanup - Delete referral.
1160
1161 :expectedresults:
1162 1. Set the referral, and the backend state should PASS.
1163 2. Set backend state to referral mode should PASS.
1164 3. Set server to not follow referral should PASS.
1165 4. referral error(10) should occur.
1166 5. Restart should PASS.
1167 6. Cleanup should PASS.
1168 """
1169
1170 log.info('Running test_basic_referrals...')
1171 backends = Backends(topology_st.standalone)
1172 backend = backends.list()[0]
1173 bev = BackendSuffixView(topology_st.standalone, backend)
1174 bev.set('nsslapd-referral', 'ldap://localhost.localdomain:389/o%3dnetscaperoot')
1175 bev.set('nsslapd-state', 'referral')
1176
1177 log.info('Checking that the settings were applied...')
1178 assert bev.get_attr_val_utf8('nsslapd-referral') == 'ldap://localhost.localdomain:389/o%3dnetscaperoot'
1179 assert bev.get_attr_val_utf8('nsslapd-state') == 'referral'
1180
1181 log.info('Testing that a referral error is returned...')
1182 log.info('When bound as directory manager')
1183 topology_st.standalone.set_option(ldap.OPT_REFERRALS, 0) # Do not follow referral
1184 with pytest.raises(ldap.REFERRAL):
1185 topology_st.standalone.search_s(DEFAULT_SUFFIX, ldap.SCOPE_SUBTREE, 'objectclass=top')
1186 log.info('When anonymous')
1187 ldc = ldap.initialize(f'ldap://localhost:{topology_st.standalone.port}')
1188 ldc.set_option(ldap.OPT_TIMEOUT, 5)
1189 ldc.set_option(ldap.OPT_REFERRALS, 0) # Do not follow referral
1190 with pytest.raises(ldap.REFERRAL):
1191 ldc.search_s(DEFAULT_SUFFIX, ldap.SCOPE_SUBTREE, 'objectclass=top')
1192 ldc.unbind()
1193
1194 # Make sure server can restart in referral mode
1195 log.info('Restarting the server...')
1196 topology_st.standalone.restart(timeout=10)
1197
1198 log.info('Cleaning up...')
1199 bev.set('nsslapd-state', 'backend')
1200 bev.remove_all('nsslapd-referral')
1201 topology_st.standalone.set_option(ldap.OPT_REFERRALS, 1)
1202
1203
1204 def test_basic_systemctl(topology_st, import_example_ldif):
1205 """Tests systemctl/lib389 can stop and start the server.
1206
1207 :id: a92a7438-ecfa-4583-a89c-5fbfc0220b69
1208
1209 :setup: Standalone instance
1210
1211 :steps:
1212 1. Stop the server.
1213 2. Start the server.
1214 3. Stop the server, break the dse.ldif and dse.ldif.bak, so a start fails.
1215 4. Verify that systemctl detects the failed start.
1216 5. Fix the dse.ldif, and make sure the server starts up.
1217 6. Verify systemctl correctly identifies the successful start.
1218
1219 :expectedresults:
1220 1. Server should be stopped.
1221 2. Server should start
1222 3. Stop should work but start after breaking dse.ldif should fail.
1223 4. Systemctl should be able to detect the failed start.
1224 5. Server should start.
1225 6. Systemctl should be able to detect the successful start.
1226 """
1227
1228 log.info('Running test_basic_systemctl...')
1229
1230 config_dir = topology_st.standalone.get_config_dir()
1231
1232 #
1233 # Stop the server
1234 #
1235 log.info('Stopping the server...')
1236 topology_st.standalone.stop()
1237 log.info('Stopped the server.')
1238
1239 #
1240 # Start the server
1241 #
1242 log.info('Starting the server...')
1243 topology_st.standalone.start()
1244 log.info('Started the server.')
1245
1246 #
1247 # Stop the server, break the dse.ldif so a start fails,
1248 # and verify that systemctl detects the failed start
1249 #
1250 log.info('Stopping the server...')
1251 topology_st.standalone.stop()
1252 log.info('Stopped the server before breaking the dse.ldif.')
1253
1254 shutil.copy(config_dir + '/dse.ldif', config_dir + '/dse.ldif.correct')
1255 open(config_dir + '/dse.ldif', 'w').close()
1256 # We need to kill the .bak file too, DS is just too smart!
1257 open(config_dir + '/dse.ldif.bak', 'w').close()
1258
1259 log.info('Attempting to start the server with broken dse.ldif...')
1260 try:
1261 topology_st.standalone.start()
1262 except Exception as e:
1263 log.info('Server failed to start as expected: ' + str(e))
1264 log.info('Check the status...')
1265 assert (not topology_st.standalone.status())
1266 log.info('Server failed to start as expected')
1267 time.sleep(5)
1268
1269 #
1270 # Fix the dse.ldif, and make sure the server starts up,
1271 # and systemctl correctly identifies the successful start
1272 #
1273 shutil.copy(config_dir + '/dse.ldif.correct', config_dir + '/dse.ldif')
1274 log.info('Starting the server with good dse.ldif...')
1275 topology_st.standalone.start()
1276 log.info('Check the status...')
1277 assert (topology_st.standalone.status())
1278 log.info('Server started after fixing dse.ldif.')
1279
1280 log.info('test_basic_systemctl: PASSED')
1281
1282
1283 def test_basic_ldapagent(topology_st, import_example_ldif, ldapagent_config):
1284 """Tests that the ldap agent starts
1285
1286 :id: da1d1846-8fc4-4b8c-8e53-4c9c16eff1ba
1287
1288 :setup: Standalone instance
1289
1290 :steps:
1291 1. Start SNMP ldap agent using command.
1292 2. Cleanup - Kill SNMP agent process.
1293
1294 :expectedresults:
1295 1. SNMP agent should start.
1296 2. SNMP agent process should be successfully killed.
1297 """
1298
1299 log.info('Running test_basic_ldapagent...')
1300
1301 if not os.path.exists(os.path.join(topology_st.standalone.get_sbin_dir(), 'ldap-agent')):
1302 pytest.skip("ldap-agent is not present")
1303
1304 # Remember, this is *forking*
1305 check_output([os.path.join(topology_st.standalone.get_sbin_dir(), 'ldap-agent'), ldapagent_config])
1306 # First kill any previous agents ....
1307 run_dir = topology_st.standalone.get_run_dir()
1308 pidpath = os.path.join(run_dir, 'ldap-agent.pid')
1309 pid = None
1310 with open(pidpath, 'r') as pf:
1311 pid = pf.readlines()[0].strip()
1312 if pid:
1313 log.debug('test_basic_ldapagent: Terminating agent %s', pid)
1314 check_output(['kill', pid])
1315
1316 log.info('test_basic_ldapagent: PASSED')
1317
1318
1319 @pytest.mark.skipif(not get_user_is_ds_owner(),
1320 reason="process ownership permission is required")
1321 def test_basic_dse_survives_kill9(topology_st, import_example_ldif):
1322 """Tests that the dse.ldif is not wiped out after the process is killed (bug 910581)
1323
1324 :id: 10f141da-9b22-443a-885c-87271dcd7a59
1325
1326 :setup: Standalone instance
1327
1328 :steps:
1329 1. Check out pid of ns-slapd process and Kill ns-slapd process.
1330 2. Check the contents of dse.ldif file.
1331 3. Start server.
1332
1333 :expectedresults:
1334 1. ns-slapd process should be killed.
1335 2. dse.ldif should not be corrupted.
1336 3. Server should start successfully.
1337 """
1338 log.info('Running test_basic_dse...')
1339
1340 dse_file = topology_st.standalone.confdir + '/dse.ldif'
1341 pid = check_output(['pidof', '-s', 'ns-slapd']).strip()
1342 # We can't guarantee we have access to sudo in any environment ... Either
1343 # run py.test with sudo, or as the same user as the dirsrv.
1344 check_output(['kill', '-9', ensure_str(pid)])
1345 if os.path.getsize(dse_file) == 0:
1346 log.fatal('test_basic_dse: dse.ldif\'s content was incorrectly removed!')
1347 assert False
1348
1349 topology_st.standalone.start(timeout=60)
1350 log.info('dse.ldif was not corrupted, and the server was restarted')
1351
1352 log.info('test_basic_dse: PASSED')
1353 # Give the server time to startup, in some conditions this can be racey without systemd notification.
1354 # Only affects this one test though...
1355 time.sleep(10)
1356
1357
1358 @pytest.mark.parametrize("rootdse_attr_name", ROOTDSE_DEF_ATTR_LIST)
1359 def test_def_rootdse_attr(topology_st, import_example_ldif, rootdse_attr_name):
1360 """Tests that operational attributes are not returned by default in rootDSE searches
1361
1362 :id: 4fee33cc-4019-4c27-89e8-998e6c770dc0
1363 :parametrized: yes
1364 :setup: Standalone instance
1365
1366 :steps:
1367 1. Make an ldapsearch for rootdse attribute
1368 2. Check the returned entries.
1369
1370 :expectedresults:
1371 1. Search should not fail
1372 2. Operational attributes should not be returned.
1373 """
1374
1375 topology_st.standalone.start()
1376
1377 log.info(" Assert rootdse search hasn't %s attr" % rootdse_attr_name)
1378 try:
1379 entry = topology_st.standalone.search_s("", ldap.SCOPE_BASE)[0]
1380 assert not entry.hasAttr(rootdse_attr_name)
1381
1382 except ldap.LDAPError as e:
1383 log.fatal('Search failed, error: ' + e.args[0]['desc'])
1384 assert False
1385
1386
1387 def test_mod_def_rootdse_attr(topology_st, import_example_ldif, rootdse_attr):
1388 """Tests that operational attributes are returned by default in rootDSE searches after config modification
1389
1390 :id: c7831e04-f458-4e23-83c7-b6f66109f639
1391 :parametrized: yes
1392 :setup: Standalone instance and we are using rootdse_attr fixture which
1393 adds nsslapd-return-default-opattr attr with value of one operation attribute.
1394
1395 :steps:
1396 1. Make an ldapsearch for rootdse attribute
1397 2. Check the returned entries.
1398
1399 :expectedresults:
1400 1. Search should not fail
1401 2. Operational attributes should be returned after the config modification
1402 """
1403
1404 log.info(" Assert rootdse search has %s attr" % rootdse_attr)
1405 try:
1406 entry = topology_st.standalone.search_s("", ldap.SCOPE_BASE)[0]
1407 assert entry.hasAttr(rootdse_attr)
1408
1409 except ldap.LDAPError as e:
1410 log.fatal('Search failed, error: ' + e.args[0]['desc'])
1411 assert False
1412
1413
1414 @pytest.fixture(scope="module")
1415 def create_users(topology_st):
1416 """Add users to the default suffix
1417 """
1418
1419 users = UserAccounts(topology_st.standalone, DEFAULT_SUFFIX)
1420 user_names = ["Directory", "Server", "389", "lib389", "pytest"]
1421
1422 log.info('Adding 5 test users')
1423 for name in user_names:
1424 users.create(properties={
1425 'uid': name,
1426 'sn': name,
1427 'cn': name,
1428 'uidNumber': '1000',
1429 'gidNumber': '1000',
1430 'homeDirectory': '/home/%s' % name,
1431 'mail': '%[email protected]' % name,
1432 'userpassword': 'pass%s' % name,
1433 })
1434
1435
1436 def test_basic_anonymous_search(topology_st, create_users):
1437 """Tests basic anonymous search operations
1438
1439 :id: c7831e04-f458-4e50-83c7-b6f77109f639
1440 :setup: Standalone instance
1441 Add 5 test users with different user names
1442 :steps:
1443 1. Execute anonymous search with different filters
1444 :expectedresults:
1445 1. Search should be successful
1446 """
1447
1448 filters = ["uid=Directory", "(|(uid=S*)(uid=3*))", "(&(uid=l*)(mail=l*))", "(&(!(uid=D*))(ou=People))"]
1449 log.info("Execute anonymous search with different filters")
1450 for filtr in filters:
1451 entries = topology_st.standalone.search_s(DEFAULT_SUFFIX, ldap.SCOPE_SUBTREE, filtr)
1452 assert len(entries) != 0
1453
1454
1455 def test_search_original_type(topology_st, create_users):
1456 """Test ldapsearch returning original attributes
1457 using nsslapd-search-return-original-type-switch
1458
1459 :id: d7831d04-f558-4e50-93c7-b6f77109f640
1460 :setup: Standalone instance
1461 Add some test entries
1462 :steps:
1463 1. Set nsslapd-search-return-original-type-switch to ON
1464 2. Check that ldapsearch *does* return unknown attributes
1465 3. Turn off nsslapd-search-return-original-type-switch
1466 4. Check that ldapsearch doesn't return any unknown attributes
1467 :expectedresults:
1468 1. nsslapd-search-return-original-type-switch should be set to ON
1469 2. ldapsearch should return unknown attributes
1470 3. nsslapd-search-return-original-type-switch should be OFF
1471 4. ldapsearch should not return any unknown attributes
1472 """
1473
1474 log.info("Set nsslapd-search-return-original-type-switch to ON")
1475 topology_st.standalone.config.set('nsslapd-search-return-original-type-switch', 'on')
1476
1477 log.info("Check that ldapsearch *does* return unknown attributes")
1478 entries = topology_st.standalone.search_s(DEFAULT_SUFFIX, ldap.SCOPE_SUBTREE, 'uid=Directory',
1479 ['objectclass overflow', 'unknown'])
1480 assert "objectclass overflow" in entries[0].getAttrs()
1481
1482 log.info("Set nsslapd-search-return-original-type-switch to Off")
1483 topology_st.standalone.config.set('nsslapd-search-return-original-type-switch', 'off')
1484 log.info("Check that ldapsearch *does not* return unknown attributes")
1485 entries = topology_st.standalone.search_s(DEFAULT_SUFFIX, ldap.SCOPE_SUBTREE, 'uid=Directory',
1486 ['objectclass overflow', 'unknown'])
1487 assert "objectclass overflow" not in entries[0].getAttrs()
1488
1489
1490 def test_search_ou(topology_st):
1491 """Test that DS should not return an entry that does not match the filter
1492
1493 :id: d7831d05-f117-4e89-93c7-b6f77109f640
1494 :setup: Standalone instance
1495 :steps:
1496 1. Create an OU entry without sub entries
1497 2. Search from the OU with the filter that does not match the OU
1498 :expectedresults:
1499 1. Creation of OU should be successful
1500 2. Search should not return any results
1501 """
1502
1503 log.info("Create a test OU without sub entries")
1504 ou = OrganizationalUnits(topology_st.standalone, DEFAULT_SUFFIX)
1505 ou.create(properties={
1506 'ou': 'test_ou',
1507 })
1508
1509 search_base = ("ou=test_ou,%s" % DEFAULT_SUFFIX)
1510 log.info("Search from the OU with the filter that does not match the OU, it should not return anything")
1511 entries = topology_st.standalone.search_s(search_base, ldap.SCOPE_SUBTREE, 'uid=*', ['dn'])
1512 assert len(entries) == 0
1513
1514
1515 def test_bind_invalid_entry(topology_st):
1516 """Test the failing bind does not return information about the entry
1517
1518 :id: 5cd9b083-eea6-426b-84ca-83c26fc49a6f
1519 :customerscenario: True
1520 :setup: Standalone instance
1521 :steps:
1522 1: bind as non existing entry
1523 2: check that bind info does not report 'No such entry'
1524 :expectedresults:
1525 1: pass
1526 2: pass
1527 """
1528
1529 topology_st.standalone.restart()
1530 INVALID_ENTRY="cn=foooo,%s" % DEFAULT_SUFFIX
1531 try:
1532 topology_st.standalone.simple_bind_s(INVALID_ENTRY, PASSWORD)
1533 except ldap.LDAPError as e:
1534 log.info('test_bind_invalid_entry: Failed to bind as %s (expected)' % INVALID_ENTRY)
1535 log.info('exception description: ' + e.args[0]['desc'])
1536 if 'info' in e.args[0]:
1537 log.info('exception info: ' + e.args[0]['info'])
1538 assert e.args[0]['desc'] == 'Invalid credentials'
1539 assert 'info' not in e.args[0]
1540 pass
1541
1542 log.info('test_bind_invalid_entry: PASSED')
1543
1544 # reset credentials
1545 topology_st.standalone.simple_bind_s(DN_DM, PW_DM)
1546
1547
1548 def test_bind_entry_missing_passwd(topology_st):
1549 """
1550 :id: af209149-8fb8-48cb-93ea-3e82dd7119d2
1551 :setup: Standalone Instance
1552 :steps:
1553 1. Bind as database entry that does not have userpassword set
1554 2. Bind as database entry that does not exist
1555 3. Bind as cn=config entry that does not have userpassword set
1556 4. Bind as cn=config entry that does not exist
1557 :expectedresults:
1558 1. Fails with error 49
1559 2. Fails with error 49
1560 3. Fails with error 49
1561 4. Fails with error 49
1562 """
1563 user = UserAccount(topology_st.standalone, DEFAULT_SUFFIX)
1564 with pytest.raises(ldap.INVALID_CREDENTIALS):
1565 # Bind as the suffix root entry which does not have a userpassword
1566 user.bind("some_password")
1567
1568 user = UserAccount(topology_st.standalone, "cn=not here," + DEFAULT_SUFFIX)
1569 with pytest.raises(ldap.INVALID_CREDENTIALS):
1570 # Bind as the entry which does not exist
1571 user.bind("some_password")
1572
1573 # Test cn=config since it has its own code path
1574 user = UserAccount(topology_st.standalone, "cn=config")
1575 with pytest.raises(ldap.INVALID_CREDENTIALS):
1576 # Bind as the config entry which does not have a userpassword
1577 user.bind("some_password")
1578
1579 user = UserAccount(topology_st.standalone, "cn=does not exist,cn=config")
1580 with pytest.raises(ldap.INVALID_CREDENTIALS):
1581 # Bind as an entry under cn=config that does not exist
1582 user.bind("some_password")
1583
1584
1585 def test_connection_buffer_size(topology_st):
1586 """Test connection buffer size adjustable with different values(valid values and invalid)
1587
1588 :id: e7831d05-f117-4ec9-1203-b6f77109f117
1589 :setup: Standalone instance
1590 :steps:
1591 1. Set nsslapd-connection-buffer to some valid values (2, 0 , 1)
1592 2. Set nsslapd-connection-buffer to some invalid values (-1, a)
1593 :expectedresults:
1594 1. This should pass
1595 2. This should fail
1596 """
1597
1598 valid_values = ['2', '0', '1']
1599 for value in valid_values:
1600 topology_st.standalone.config.replace('nsslapd-connection-buffer', value)
1601
1602 invalid_values = ['-1', 'a']
1603 for value in invalid_values:
1604 with pytest.raises(ldap.OPERATIONS_ERROR):
1605 topology_st.standalone.config.replace('nsslapd-connection-buffer', value)
1606
1607
1608 def test_critical_msg_on_empty_range_idl(topology_st):
1609 """Doing a range index lookup should not report a critical message even if IDL is empty
1610
1611 :id: a07a2222-0551-44a6-b113-401d23799364
1612 :setup: Standalone instance
1613 :steps:
1614 1. Create an index for internationalISDNNumber. (attribute chosen because it is
1615 unlikely that previous tests used it)
1616 2. telephoneNumber being indexed by default create 20 users without telephoneNumber
1617 3. add a telephoneNumber value and delete it to trigger an empty index database
1618 4. Do a search that triggers a range lookup on empty telephoneNumber
1619 5. Check that the critical message is not logged in error logs
1620 :expectedresults:
1621 1. This should pass
1622 2. This should pass
1623 3. This should pass
1624 4. This should pass on normal build but could abort a debug build
1625 5. This should pass
1626 """
1627 indexedAttr = 'internationalISDNNumber'
1628
1629 # Step 1
1630 from lib389.index import Indexes
1631
1632 indexes = Indexes(topology_st.standalone)
1633 indexes.create(properties={
1634 'cn': indexedAttr,
1635 'nsSystemIndex': 'false',
1636 'nsIndexType': 'eq'
1637 })
1638 topology_st.standalone.restart()
1639
1640 # Step 2
1641 users = UserAccounts(topology_st.standalone, DEFAULT_SUFFIX)
1642 log.info('Adding 20 users without "%s"' % indexedAttr)
1643 for i in range(20):
1644 name = 'user_%d' % i
1645 last_user = users.create(properties={
1646 'uid': name,
1647 'sn': name,
1648 'cn': name,
1649 'uidNumber': '1000',
1650 'gidNumber': '1000',
1651 'homeDirectory': '/home/%s' % name,
1652 'mail': '%[email protected]' % name,
1653 'userpassword': 'pass%s' % name,
1654 })
1655
1656 # Step 3
1657 # required update to create the indexAttr (i.e. 'loginShell') database, and then make it empty
1658 topology_st.standalone.modify_s(last_user.dn, [(ldap.MOD_ADD, indexedAttr, b'1234')])
1659 ent = topology_st.standalone.getEntry(last_user.dn, ldap.SCOPE_BASE,)
1660 assert ent
1661 assert ent.hasAttr(indexedAttr)
1662 topology_st.standalone.modify_s(last_user.dn, [(ldap.MOD_DELETE, indexedAttr, None)])
1663 ent = topology_st.standalone.getEntry(last_user.dn, ldap.SCOPE_BASE,)
1664 assert ent
1665 assert not ent.hasAttr(indexedAttr)
1666
1667 # Step 4
1668 # The first component being not indexed the range on second is evaluated
1669 try:
1670 ents = topology_st.standalone.search_s(DEFAULT_SUFFIX, ldap.SCOPE_SUBTREE, '(&(sudoNotAfter=*)(%s>=111))' % indexedAttr)
1671 assert len(ents) == 0
1672 except ldap.SERVER_DOWN:
1673 log.error('Likely testing against a debug version that asserted')
1674 pass
1675
1676 # Step 5
1677 assert not topology_st.standalone.searchErrorsLog('CRIT - list_candidates - NULL idl was recieved from filter_candidates_ext.')
1678
1679
1680 @pytest.mark.parametrize("case,value", [('positive', ['cn','','']),
1681 ("positive", ['cn', '', '', '', '', '', '', '', '', '', '']),
1682 ("negative", ['cn', '', '', '', '', '', '', '', '', '', '', ''])])
1683 def test_attr_description_limit(topology_st, case, value):
1684 """Test that up to 10 empty attributeDescription is allowed
1685
1686 :id: 5afd3dcd-1028-428d-822d-a489ecf4b67e
1687 :customerscenario: True
1688 :parametrized: yes
1689 :setup: Standalone instance
1690 :steps:
1691 1. Check that 2 empty values are allowed
1692 2. Check that 10 empty values are allowed
1693 3. Check that more than 10 empty values are allowed
1694 :expectedresults:
1695 1. Should succeed
1696 2. Should succeed
1697 3. Should fail
1698 """
1699 if case == 'positive':
1700 DSLdapObjects(topology_st.standalone, basedn='').filter("(objectclass=*)", attrlist=value, scope=0)
1701 else:
1702 with pytest.raises(ldap.PROTOCOL_ERROR):
1703 DSLdapObjects(topology_st.standalone, basedn='').filter("(objectclass=*)", attrlist=value, scope=0)
1704
1705
1706 def test_ldbm_modification_audit_log(topology_st):
1707 """When updating LDBM config attributes, those attributes/values are not listed
1708 in the audit log
1709
1710 :id: 5bf75c47-a283-430e-a65c-3c5fd8dbadb8
1711 :setup: Standalone Instance
1712 :steps:
1713 1. Bind as DM
1714 2. Enable audit log
1715 3. Update a set of config attrs in LDBM config
1716 4. Restart the server
1717 5. Check that config attrs are listed in the audit log
1718 :expectedresults:
1719 1. Operation successful
1720 2. Operation successful
1721 3. Operation successful
1722 4. Operation successful
1723 5. Audit log should contain modification of attrs"
1724 """
1725
1726 VALUE = '10001'
1727
1728 d_manager = DirectoryManager(topology_st.standalone)
1729 conn = d_manager.bind()
1730 config_ldbm = LDBMConfig(conn)
1731
1732 log.info("Enable audit logging")
1733 conn.config.enable_log('audit')
1734
1735 attrs = ['nsslapd-lookthroughlimit', 'nsslapd-pagedidlistscanlimit', 'nsslapd-idlistscanlimit', 'nsslapd-db-locks']
1736
1737 for attr in attrs:
1738 log.info("Set attribute %s to value %s" % (attr, VALUE))
1739 config_ldbm.set(attr, VALUE)
1740
1741 log.info('Restart the server to flush the logs')
1742 conn.restart()
1743
1744 for attr in attrs:
1745 log.info("Check if attribute %s is replaced in the audit log" % attr)
1746 assert conn.searchAuditLog('replace: %s' % attr)
1747 assert conn.searchAuditLog('%s: %s' % (attr, VALUE))
1748
1749
1750 def test_suffix_case(topology_st):
1751 """Test that the suffix case is preserved when creating a new backend
1752
1753 :id: 4eff15be-6cde-4312-b492-c88941876bda
1754 :setup: Standalone Instance
1755 :steps:
1756 1. Create backend with uppercase characters
1757 2. Create root node entry
1758 3. Search should return suffix with upper case characters
1759 :expectedresults:
1760 1. Success
1761 2. Success
1762 3. Success
1763 """
1764
1765 # Start with a clean slate
1766 topology_st.standalone.restart()
1767
1768 TEST_SUFFIX = 'dc=UPPER_CASE'
1769
1770 backends = Backends(topology_st.standalone)
1771 backends.create(properties={'nsslapd-suffix': TEST_SUFFIX,
1772 'name': 'upperCaseRoot',
1773 'sample_entries': '001004002'})
1774
1775 domain = Domain(topology_st.standalone, TEST_SUFFIX)
1776 assert domain.dn == TEST_SUFFIX
1777
1778
1779 def test_bind_disconnect_invalid_entry(topology_st, _reset_attr):
1780 """Test close connection on failed bind with invalid entry
1781
1782 :id: b378543e-32dc-432a-9756-ce318d6d654b
1783 :setup: Standalone instance
1784 :steps:
1785 1. create/get user
1786 2. bind and search as user
1787 3. enable nsslapd-close-on-failed-bind attr
1788 4. bind as non existing entry to trigger connection closure
1789 5. verify connection has been closed and server is still running
1790 6. cleanup
1791 :expectedresults:
1792 1. success
1793 2. success
1794 3. nsslapd-close-on-failed-bind attr set to on
1795 4. returns INVALID_CREDENTIALS, triggering connection closure
1796 5. success
1797 6. success
1798 """
1799
1800 INVALID_ENTRY="cn=foooo,%s" % DEFAULT_SUFFIX
1801 inst = topology_st.standalone
1802
1803 dm = DirectoryManager(inst)
1804
1805 # create/get user
1806 users = UserAccounts(inst, DEFAULT_SUFFIX)
1807 try:
1808 user = users.create_test_user()
1809 user.set("userPassword", PW_DM)
1810 except ldap.ALREADY_EXISTS:
1811 user = users.get('test_user_1000')
1812
1813 # verify user can bind and search
1814 try:
1815 inst.simple_bind_s(user.dn, PW_DM)
1816 except ldap.LDAPError as e:
1817 log.error('Failed to bind {}'.format(user.dn))
1818 raise e
1819 try:
1820 inst.search_s(DEFAULT_SUFFIX, ldap.SCOPE_SUBTREE, '(objectclass=top)', ['dn'])
1821 except ldap.LDAPError as e:
1822 log.error('Search failed on {}'.format(DEFAULT_SUFFIX))
1823 raise e
1824
1825 # enable and verify attr
1826 try:
1827 dm_conn = dm.bind()
1828 dm_conn.config.replace('nsslapd-close-on-failed-bind', 'on')
1829 assert (dm_conn.config.get_attr_val_utf8('nsslapd-close-on-failed-bind')) == 'on'
1830 except ldap.LDAPError as e:
1831 log.error('Failed to replace nsslapd-close-on-failed-bind attr')
1832 raise e
1833
1834 # bind as non existing entry which triggers connection close
1835 with pytest.raises(ldap.INVALID_CREDENTIALS):
1836 inst.simple_bind_s(INVALID_ENTRY, PW_DM)
1837
1838 # verify the connection is closed but the server is still running
1839 assert (inst.status())
1840 with pytest.raises(ldap.SERVER_DOWN):
1841 inst.search_s(DEFAULT_SUFFIX, ldap.SCOPE_SUBTREE, '(objectclass=top)', ['dn'])
1842 try:
1843 dm_conn = dm.bind()
1844 except ldap.LDAPError as e:
1845 log.error('DM bind failed')
1846 raise e
1847
1848
1849 def test_bind_disconnect_cert_map_failed(topology_st, _reset_attr):
1850 """Test close connection on failed bind with a failed cert mapping
1851
1852 :id: 0ac60f76-1fd9-4080-a82b-21807e6bc292
1853 :setup: Standalone Instance
1854 :steps:
1855 1. enable TLS
1856 2. create/get a user
1857 3. get details of ssca key and cert
1858 4. create 2 user certificates, one good, one bad
1859 5. configure certmap
1860 6. check that EXTERNAL is listed in supported mechns.
1861 7. bind with good cert
1862 8. bind with bad cert
1863 9. enable nsslapd-close-on-failed-bind attr
1864 10. bind with bad cert
1865 11. verify connection has been closed and server is still running
1866 12. cleanup
1867 :expectedresults:
1868 1. success
1869 2. success
1870 3. success
1871 4. success
1872 5. success
1873 6. success
1874 7. success
1875 8. generates INVALID_CREDENTIALS exception
1876 9. success
1877 10. generates INVALID_CREDENTIALS exception, triggering connection closure
1878 11. success
1879 12. success
1880 """
1881
1882 RDN_TEST_USER = 'test_user_1000'
1883 RDN_TEST_USER_WRONG = 'test_user_wrong'
1884 inst = topology_st.standalone
1885
1886 inst.enable_tls()
1887 dm = DirectoryManager(inst)
1888
1889 # create/get user
1890 users = UserAccounts(inst, DEFAULT_SUFFIX)
1891 try:
1892 user = users.create_test_user()
1893 user.set("userPassword", PW_DM)
1894 except ldap.ALREADY_EXISTS:
1895 user = users.get(RDN_TEST_USER)
1896
1897 ssca_dir = inst.get_ssca_dir()
1898 ssca = NssSsl(dbpath=ssca_dir)
1899
1900 ssca.create_rsa_user(RDN_TEST_USER)
1901 ssca.create_rsa_user(RDN_TEST_USER_WRONG)
1902
1903 # Get the details of where the key and crt are.
1904 tls_locs = ssca.get_rsa_user(RDN_TEST_USER)
1905 tls_locs_wrong = ssca.get_rsa_user(RDN_TEST_USER_WRONG)
1906
1907 user.enroll_certificate(tls_locs['crt_der_path'])
1908
1909 # Turn on the certmap.
1910 cm = CertmapLegacy(inst)
1911 certmaps = cm.list()
1912 certmaps['default']['DNComps'] = ''
1913 certmaps['default']['FilterComps'] = ['cn']
1914 certmaps['default']['VerifyCert'] = 'off'
1915 cm.set(certmaps)
1916
1917 # Check that EXTERNAL is listed in supported mechns.
1918 assert(inst.rootdse.supports_sasl_external())
1919
1920 # Restart to allow certmaps to be re-read: Note, we CAN NOT use post_open
1921 # here, it breaks on auth. see lib389/__init__.py
1922 inst.restart(post_open=False)
1923
1924 # bind with good cert
1925 try:
1926 inst.open(saslmethod='EXTERNAL', connOnly=True, certdir=ssca_dir, userkey=tls_locs['key'], usercert=tls_locs['crt'])
1927 except ldap.LDAPError as e:
1928 log.error('Bind with good cert failed')
1929 raise e
1930
1931 inst.restart()
1932
1933 # bind with bad cert
1934 with pytest.raises(ldap.INVALID_CREDENTIALS):
1935 inst.open(saslmethod='EXTERNAL', connOnly=True, certdir=ssca_dir, userkey=tls_locs_wrong['key'], usercert=tls_locs_wrong['crt'])
1936
1937 # enable and verify attr
1938 try:
1939 dm_conn = dm.bind()
1940 dm_conn.config.replace('nsslapd-close-on-failed-bind', 'on')
1941 assert (dm_conn.config.get_attr_val_utf8('nsslapd-close-on-failed-bind')) == 'on'
1942 except ldap.LDAPError as e:
1943 log.error('Failed to replace nsslapd-close-on-failed-bind attr')
1944 raise e
1945
1946 # bind with bad cert
1947 with pytest.raises(ldap.INVALID_CREDENTIALS):
1948 inst.open(saslmethod='EXTERNAL', connOnly=True, certdir=ssca_dir, userkey=tls_locs_wrong['key'], usercert=tls_locs_wrong['crt'])
1949
1950 # check the connection is closed but the server is still running
1951 assert (inst.status())
1952 with pytest.raises(ldap.SERVER_DOWN):
1953 inst.search_s(DEFAULT_SUFFIX, ldap.SCOPE_SUBTREE, '(objectclass=top)', ['dn'])
1954 try:
1955 dm_conn = dm.bind()
1956 except ldap.LDAPError as e:
1957 log.error('DM bind failed')
1958 raise e
1959
1960
1961 def test_bind_disconnect_account_lockout(topology_st, _reset_attr):
1962 """Test close connection on failed bind with user account lockout
1963
1964 :id: 12e56d79-ce57-4574-a80a-d3b6d1d74d8f
1965 :setup: Standalone Instance
1966 :steps:
1967 1. configure account lockout
1968 2. create/get a user
1969 3. bind and search as user
1970 4. force account lock out
1971 5. enable nsslapd-close-on-failed-bind attr
1972 6. attempt user bind
1973 7. verify connection has been closed and server is still running
1974 8. cleanup
1975 :expectedresults:
1976 1. success
1977 2. success
1978 3. success
1979 4. generates CONSTRAINT_VIOLATION exception
1980 5. success
1981 6. generates CONSTRAINT_VIOLATION exception, triggering connection closure
1982 7. success
1983 8. success
1984 """
1985
1986 inst = topology_st.standalone
1987 dm = DirectoryManager(inst)
1988 inst.config.set('passwordlockout', 'on')
1989 inst.config.set('passwordMaxFailure', '2')
1990
1991 # create/get user
1992 users = UserAccounts(inst, DEFAULT_SUFFIX)
1993 try:
1994 user = users.create_test_user()
1995 user.set("userPassword", PW_DM)
1996 except ldap.ALREADY_EXISTS:
1997 user = users.get('test_user_1000')
1998
1999 # verify user bind and search
2000 try:
2001 inst.simple_bind_s(user.dn, PW_DM)
2002 except ldap.LDAPError as e:
2003 log.error('Failed to bind {}'.format(user.dn))
2004 raise e
2005 try:
2006 inst.search_s(DEFAULT_SUFFIX, ldap.SCOPE_SUBTREE, '(objectclass=top)', ['dn'])
2007 except ldap.LDAPError as e:
2008 log.error('Search failed on {}'.format(DEFAULT_SUFFIX))
2009 raise e
2010
2011 # Force entry to get locked out
2012 with pytest.raises(ldap.INVALID_CREDENTIALS):
2013 inst.simple_bind_s(user.dn, 'whateverlike')
2014 with pytest.raises(ldap.INVALID_CREDENTIALS):
2015 inst.simple_bind_s(user.dn, 'whateverlike')
2016 with pytest.raises(ldap.CONSTRAINT_VIOLATION):
2017 # Should fail with good or bad password
2018 inst.simple_bind_s(user.dn, PW_DM)
2019
2020 # enable and verify attr
2021 try:
2022 dm_conn = dm.bind()
2023 dm_conn.config.replace('nsslapd-close-on-failed-bind', 'on')
2024 assert (dm_conn.config.get_attr_val_utf8('nsslapd-close-on-failed-bind')) == 'on'
2025 except ldap.LDAPError as e:
2026 log.error('Failed to replace nsslapd-close-on-failed-bind attr')
2027 raise e
2028
2029 # Should fail with good or bad password
2030 with pytest.raises(ldap.CONSTRAINT_VIOLATION):
2031 inst.simple_bind_s(user.dn, PW_DM)
2032
2033 # check the connection is closed but the server is still running
2034 assert (inst.status())
2035 with pytest.raises(ldap.SERVER_DOWN):
2036 inst.search_s(DEFAULT_SUFFIX, ldap.SCOPE_SUBTREE, '(objectclass=top)', ['dn'])
2037 try:
2038 dm_conn = dm.bind()
2039 except ldap.LDAPError as e:
2040 log.error('DM bind failed')
2041 raise e
2042
2043
2044 def test_dscreate(request):
2045 """Test that dscreate works
2046
2047 :id: 5bf75c47-a283-430e-a65c-3c5fd8dbadb9
2048 :setup: None
2049 :steps:
2050 1. Create template file for dscreate
2051 2. Create instance using template file
2052 :expectedresults:
2053 1. Should succeeds
2054 2. Should succeeds
2055 """
2056
2057 template_file = "/tmp/dssetup.inf"
2058 template_text = """[general]
2059 config_version = 2
2060 # This invalid hostname ...
2061 full_machine_name = localhost.localdomain
2062 # Means we absolutely require this.
2063 strict_host_checking = False
2064 # In tests, we can be run in containers, NEVER trust
2065 # that systemd is there, or functional in any capacity
2066 systemd = False
2067
2068 [slapd]
2069 instance_name = test_dscreate
2070 root_dn = cn=directory manager
2071 root_password = someLongPassword_123
2072 # We do not have access to high ports in containers,
2073 # so default to something higher.
2074 port = 38999
2075 secure_port = 63699
2076
2077
2078 [backend-userroot]
2079 suffix = dc=example,dc=com
2080 sample_entries = yes
2081 """
2082
2083 with open(template_file, "w") as template_fd:
2084 template_fd.write(template_text)
2085
2086 # Unset PYTHONPATH to avoid mixing old CLI tools and new lib389
2087 tmp_env = os.environ
2088 if "PYTHONPATH" in tmp_env:
2089 del tmp_env["PYTHONPATH"]
2090 try:
2091 subprocess.check_call([
2092 'dscreate',
2093 'from-file',
2094 template_file
2095 ], env=tmp_env)
2096 except subprocess.CalledProcessError as e:
2097 log.fatal("dscreate failed! Error ({}) {}".format(e.returncode, e.output))
2098 assert False
2099
2100 def fin():
2101 os.remove(template_file)
2102 try:
2103 subprocess.check_call(['dsctl', 'test_dscreate', 'remove', '--do-it'])
2104 except subprocess.CalledProcessError as e:
2105 log.fatal("Failed to remove test instance Error ({}) {}".format(e.returncode, e.output))
2106
2107 request.addfinalizer(fin)
2108
2109
2110 def test_dscreate_with_replication(request):
2111 """Test dscreate works with replication shortcuts
2112
2113 :id: 8391ffc4-5158-4141-9312-0f47ae56f1ed
2114 :setup: Standalone Instance
2115 :steps:
2116 1. Create instance and prepare DirSrv object
2117 2. Check replication is enabled
2118 3. Check repl role
2119 4. Check rid
2120 5. Check bind dn
2121 6. Changelog trimming settings
2122 :expectedresults:
2123 1. Success
2124 2. Success
2125 3. Success
2126 4. Success
2127 5. Success
2128 6. Success
2129 """
2130 template_file = "/tmp/dssetup.inf"
2131 template_text = """[general]
2132 config_version = 2
2133 # This invalid hostname ...
2134 full_machine_name = localhost.localdomain
2135 # Means we absolutely require this.
2136 strict_host_checking = False
2137 # In tests, we can be run in containers, NEVER trust
2138 # that systemd is there, or functional in any capacity
2139 systemd = False
2140
2141 [slapd]
2142 instance_name = dscreate_repl
2143 root_dn = cn=directory manager
2144 root_password = someLongPassword_123
2145 # We do not have access to high ports in containers,
2146 # so default to something higher.
2147 port = 38999
2148 secure_port = 63699
2149
2150 [backend-userroot]
2151 suffix = dc=example,dc=com
2152 sample_entries = yes
2153 enable_replication = True
2154 replica_binddn = cn=replication manager,cn=config
2155 replica_bindpw = password
2156 replica_id = 111
2157 replica_role = supplier
2158 changelog_max_age = 8d
2159 changelog_max_entries = 200000
2160 """
2161
2162 with open(template_file, "w") as template_fd:
2163 template_fd.write(template_text)
2164
2165 # Unset PYTHONPATH to avoid mixing old CLI tools and new lib389
2166 tmp_env = os.environ
2167 if "PYTHONPATH" in tmp_env:
2168 del tmp_env["PYTHONPATH"]
2169 try:
2170 subprocess.check_call([
2171 'dscreate',
2172 'from-file',
2173 template_file
2174 ], env=tmp_env)
2175 except subprocess.CalledProcessError as e:
2176 log.fatal("dscreate failed! Error ({}) {}".format(e.returncode, e.output))
2177 assert False
2178
2179 def fin():
2180 os.remove(template_file)
2181 try:
2182 subprocess.check_call(['dsctl', 'dscreate_repl', 'remove', '--do-it'])
2183 except subprocess.CalledProcessError as e:
2184 log.fatal("Failed to remove test instance Error ({}) {}".format(e.returncode, e.output))
2185
2186 request.addfinalizer(fin)
2187
2188 # Prepare Dirsrv instance
2189 from lib389 import DirSrv
2190 container_result = subprocess.run(["systemd-detect-virt", "-c"], stdout=subprocess.PIPE)
2191 if container_result.returncode == 0:
2192 ds_instance = DirSrv(False, containerised=True)
2193 else:
2194 ds_instance = DirSrv(False)
2195 args = {
2196 SER_HOST: "localhost.localdomain",
2197 SER_PORT: 38999,
2198 SER_SECURE_PORT: 63699,
2199 SER_SERVERID_PROP: 'dscreate_repl',
2200 SER_ROOT_DN: 'cn=directory manager',
2201 SER_ROOT_PW: 'someLongPassword_123',
2202 SER_LDAPI_ENABLED: 'on',
2203 SER_LDAPI_AUTOBIND: 'on'
2204 }
2205 ds_instance.allocate(args)
2206 ds_instance.start(timeout=60)
2207
2208 dse_ldif = DSEldif(ds_instance, serverid="dscreate_repl")
2209 socket_path = dse_ldif.get("cn=config", "nsslapd-ldapifilepath")
2210 ldapiuri=f"ldapi://{socket_path[0].replace('/', '%2f')}"
2211 ds_instance.open(uri=ldapiuri)
2212
2213 # Check replication is enabled
2214 replicas = Replicas(ds_instance)
2215 replica = replicas.get(DEFAULT_SUFFIX)
2216 assert replica
2217
2218 # Check role
2219 assert replica.get_role() == ReplicaRole.SUPPLIER
2220
2221 # Check rid
2222 assert replica.get_rid() == '111'
2223
2224 # Check bind dn is in config
2225 assert replica.get_attr_val_utf8('nsDS5ReplicaBindDN') == 'cn=replication manager,cn=config'
2226
2227 # Check repl manager entry was created
2228 repl_mgr = UserAccount(ds_instance, 'cn=replication manager,cn=config')
2229 assert repl_mgr.exists()
2230
2231 # Changelog trimming settings
2232 cl = Changelog(ds_instance, DEFAULT_SUFFIX)
2233 assert cl.get_attr_val_utf8('nsslapd-changelogmaxage') == '8d'
2234 assert cl.get_attr_val_utf8('nsslapd-changelogmaxentries') == '200000'
2235
2236
2237 @pytest.fixture(scope="function")
2238 def dscreate_long_instance(request):
2239 template_file = "/tmp/dssetup.inf"
2240 longname_serverid = "test-longname-deadbeef-deadbeef-deadbeef-deadbeef-deadbeef"
2241 template_text = """[general]
2242 config_version = 2
2243 # This invalid hostname ...
2244 full_machine_name = localhost.localdomain
2245 # Means we absolutely require this.
2246 strict_host_checking = False
2247 # In tests, we can be run in containers, NEVER trust
2248 # that systemd is there, or functional in any capacity
2249 systemd = False
2250
2251 [slapd]
2252 instance_name = %s
2253 root_dn = cn=directory manager
2254 root_password = someLongPassword_123
2255 # We do not have access to high ports in containers,
2256 # so default to something higher.
2257 port = 38999
2258 secure_port = 63699
2259
2260
2261 [backend-userroot]
2262 suffix = dc=example,dc=com
2263 sample_entries = yes
2264 """ % longname_serverid
2265
2266 with open(template_file, "w") as template_fd:
2267 template_fd.write(template_text)
2268
2269 # Unset PYTHONPATH to avoid mixing old CLI tools and new lib389
2270 tmp_env = os.environ
2271 if "PYTHONPATH" in tmp_env:
2272 del tmp_env["PYTHONPATH"]
2273 try:
2274 subprocess.check_call([
2275 'dscreate',
2276 'from-file',
2277 template_file
2278 ], env=tmp_env)
2279 except subprocess.CalledProcessError as e:
2280 log.fatal("dscreate failed! Error ({}) {}".format(e.returncode, e.output))
2281 assert False
2282
2283 inst = DirSrv(verbose=True, external_log=log)
2284 dse_ldif = DSEldif(inst, serverid=longname_serverid)
2285
2286 socket_path = dse_ldif.get("cn=config", "nsslapd-ldapifilepath")
2287 inst.local_simple_allocate(
2288 serverid=longname_serverid,
2289 ldapuri=f"ldapi://{socket_path[0].replace('/', '%2f')}",
2290 password="someLongPassword_123"
2291 )
2292 inst.ldapi_enabled = 'on'
2293 inst.ldapi_socket = socket_path
2294 inst.ldapi_autobind = 'off'
2295 try:
2296 inst.open()
2297 except:
2298 log.fatal("Failed to connect via ldapi to %s instance" % longname_serverid)
2299 os.remove(template_file)
2300 try:
2301 subprocess.check_call(['dsctl', longname_serverid, 'remove', '--do-it'])
2302 except subprocess.CalledProcessError as e:
2303 log.fatal("Failed to remove test instance Error ({}) {}".format(e.returncode, e.output))
2304
2305 def fin():
2306 os.remove(template_file)
2307 try:
2308 subprocess.check_call(['dsctl', longname_serverid, 'remove', '--do-it'])
2309 except subprocess.CalledProcessError as e:
2310 log.fatal("Failed to remove test instance Error ({}) {}".format(e.returncode, e.output))
2311
2312 request.addfinalizer(fin)
2313
2314 return inst
2315
2316
2317 @pytest.mark.skipif(not get_user_is_root() or ds_is_older('1.4.2.0'),
2318 reason="This test is only required with new admin cli, and requires root.")
2319 def test_dscreate_ldapi(dscreate_long_instance):
2320 """Test that an instance with a long name can
2321 handle ldapi connection using a long socket name
2322
2323 :id: 5d72d955-aff8-4741-8c9a-32c1c707cf1f
2324 :setup: None
2325 :steps:
2326 1. Ccreate an instance with a long serverId name, that open a ldapi connection
2327 2. Connect with ldapi, that hit 50581 and crash the instance
2328 :expectedresults:
2329 1. Should succeeds
2330 2. Should succeeds
2331 """
2332
2333 root_dse = RootDSE(dscreate_long_instance)
2334 log.info(root_dse.get_supported_ctrls())
2335
2336
2337 @pytest.mark.skipif(not get_user_is_root() or ds_is_older('1.4.2.0'),
2338 reason="This test is only required with new admin cli, and requires root.")
2339 def test_dscreate_multiple_dashes_name(dscreate_long_instance):
2340 """Test that an instance with a multiple dashes in the name
2341 can be removed with dsctl --remove-all
2342
2343 :id: 265c3ac7-5ba6-4278-b8f4-4e7692afd1a5
2344 :setup: An instance with a few dashes in its name
2345 :steps:
2346 1. Run 'dsctl --remove-all' command
2347 2. Check if the instance exists
2348 :expectedresults:
2349 1. Should succeeds
2350 2. Instance doesn't exists
2351 """
2352
2353 p = run(['dsctl', '--remove-all'], stdout=PIPE, input='Yes\n', encoding='ascii')
2354 assert not dscreate_long_instance.exists()
2355
2356
2357 @pytest.fixture(scope="module", params=('c=uk', 'cn=test_user', 'dc=example,dc=com', 'o=south', 'ou=sales', 'wrong=some_value'))
2358 def dscreate_test_rdn_value(request):
2359 template_file = "/tmp/dssetup.inf"
2360 template_text = f"""[general]
2361 config_version = 2
2362 # This invalid hostname ...
2363 full_machine_name = localhost.localdomain
2364 # Means we absolutely require this.
2365 strict_host_checking = False
2366 # In tests, we can be run in containers, NEVER trust
2367 # that systemd is there, or functional in any capacity
2368 systemd = False
2369
2370 [slapd]
2371 instance_name = test_different_rdn
2372 root_dn = cn=directory manager
2373 root_password = someLongPassword_123
2374 # We do not have access to high ports in containers,
2375 # so default to something higher.
2376 port = 38999
2377 secure_port = 63699
2378
2379 [backend-userroot]
2380 create_suffix_entry = True
2381 suffix = {request.param}
2382 """
2383
2384 with open(template_file, "w") as template_fd:
2385 template_fd.write(template_text)
2386
2387 # Unset PYTHONPATH to avoid mixing old CLI tools and new lib389
2388 tmp_env = os.environ
2389 if "PYTHONPATH" in tmp_env:
2390 del tmp_env["PYTHONPATH"]
2391
2392 def fin():
2393 os.remove(template_file)
2394 if request.param != "wrong=some_value":
2395 try:
2396 subprocess.check_call(['dsctl', 'test_different_rdn', 'remove', '--do-it'])
2397 except subprocess.CalledProcessError as e:
2398 log.fatal(f"Failed to remove test instance Error ({e.returncode}) {e.output}")
2399 else:
2400 log.info("Wrong RDN is passed, instance not created")
2401 request.addfinalizer(fin)
2402 return template_file, tmp_env, request.param,
2403
2404
2405 @pytest.mark.skipif(not get_user_is_root() or ds_is_older('1.4.0.0'),
2406 reason="This test is only required with new admin cli, and requires root.")
2407 def test_dscreate_with_different_rdn(dscreate_test_rdn_value):
2408 """Test that dscreate works with different RDN attributes as suffix
2409
2410 :id: 77ed6300-6a2f-4e79-a862-1f1105f1e3ef
2411 :customerscenario: True
2412 :parametrized: yes
2413 :setup: None
2414 :steps:
2415 1. Create template file for dscreate with different RDN attributes as suffix
2416 2. Create instance using template file
2417 3. Create instance with 'wrong=some_value' as suffix's RDN attribute
2418 :expectedresults:
2419 1. Should succeeds
2420 2. Should succeeds
2421 3. Should fail
2422 """
2423 try:
2424 subprocess.check_call([
2425 'dscreate',
2426 'from-file',
2427 dscreate_test_rdn_value[0]
2428 ], env=dscreate_test_rdn_value[1])
2429 except subprocess.CalledProcessError as e:
2430 log.fatal(f"dscreate failed! Error ({e.returncode}) {e.output}")
2431 if dscreate_test_rdn_value[2] != "wrong=some_value":
2432 assert False
2433 else:
2434 assert True
2435
2436
2437 @pytest.fixture(scope="module")
2438 def dscreate_custom_instance(request):
2439 topo = CustomSetup('custom')
2440
2441 def fin():
2442 topo.cleanup()
2443
2444 request.addfinalizer(fin)
2445 topo.create_instance()
2446 # Return CustomSetup object associated with
2447 # a stopped instance named "custom"
2448 return topo
2449
2450 obj.create_wrapper(maxfds=150)
2451 log.info("Starting wrapper")
2452 inst.start()
2453 log.info("Server is started.")
2454 log.info("Open connection")
2455 inst.open()
2456
2457
2458 @pytest.fixture(scope="module", params=set(range(1,5)))
2459 def dscreate_with_numlistener(request, dscreate_custom_instance):
2460 numlisteners = request.param
2461 dscreate_custom_instance.create_wrapper(maxfds=MAX_FDS)
2462 inst = dscreate_custom_instance.inst
2463 inst.stop()
2464 dse_ldif = DSEldif(inst)
2465 dse_ldif.replace('cn=config', 'nsslapd-numlisteners', str(numlisteners))
2466 inst.start()
2467 inst.open()
2468 return inst
2469
2470 @pytest.mark.skipif(ds_is_older('2.2.0.0'),
2471 reason="This test is only required with multiple listener support.")
2472 def test_conn_limits(dscreate_with_numlistener):
2473 """Check the connections limits for various number of listeners.
2474
2475 :id: 7be2eb5c-4d8f-11ee-ae3d-482ae39447e5
2476 :parametrized: yes
2477 :setup: Setup an instance then set nsslapd-numlisteners and maximum file descriptors
2478 :steps:
2479 1. Loops on:
2480 Open new connection and perform search until timeout expires
2481 2. Close one of the previously open connections
2482 3. Loops MAX_FDS times on:
2483 - opening a new connection
2484 - perform a search
2485 - close the connection
2486 4. Close all open connections
2487 5. Remove the instance
2488 :expectedresults:
2489 1. Should get a timeout (because the server has no more any connections)
2490 2. Should success
2491 3. Should success (otherwise issue #5924 has probably been hit)
2492 4. Should success
2493 5. Should success
2494 """
2495 inst = dscreate_with_numlistener
2496
2497 conns = []
2498 timeout_occured = False
2499 for i in range(MAX_FDS):
2500 try:
2501 ldc = ldap.initialize(f'ldap://localhost:{inst.port}')
2502 ldc.set_option(ldap.OPT_TIMEOUT, 5)
2503 ldc.search_s(DEFAULT_SUFFIX, ldap.SCOPE_SUBTREE, "(uid=demo)")
2504 conns.append(ldc)
2505 except ldap.TIMEOUT:
2506 timeout_occured = True
2507 break
2508 # Should not be able to open MAX_FDS connections (some file descriptor are
2509 # reserved (for example for the listening socket )
2510 assert timeout_occured
2511
2512 conn = random.choice(conns)
2513 conn.unbind()
2514 conns.remove(conn)
2515
2516 # Should loop enough time so trigger issue #5924 if it is not fixed.
2517 for i in range(MAX_FDS):
2518 ldc = ldap.initialize(f'ldap://localhost:{inst.port}')
2519 # Set a timeout long enough so that the test fails if server is unresponsive
2520 ldc.set_option(ldap.OPT_TIMEOUT, 60)
2521 ldc.search_s(DEFAULT_SUFFIX, ldap.SCOPE_SUBTREE, "(uid=demo)")
2522 ldc.unbind()
2523
2524 # Close all open connections
2525 for c in conns:
2526 c.unbind()
2527
2528 # Step 6 is done in teardown phase by dscreate_instance finalizer
2529
2530
2531 if __name__ == '__main__':
2532 # Run isolated
2533 # -s for DEBUG mode
2534 CURRENT_FILE = os.path.realpath(__file__)
2535 pytest.main("-s %s" % CURRENT_FILE)