def test_ldapurl(url): """ Test setting LDAPURL. """ cli = LDAPClient(url) assert cli.url == url with pytest.raises(TypeError): _ = LDAPClient(None) cli.url = "ldap://localhost" assert cli.url == "ldap://localhost"
def test_ldapurl(self): """ Test setting LDAPURL. """ url = bonsai.LDAPURL(self.url) client = LDAPClient(url) self.assertEqual(client.url, url) self.assertRaises(TypeError, lambda: LDAPClient(None)) client.url = "ldap://localhost" self.assertEqual(client.url, "ldap://localhost")
def test_client_prop(host_url): """ Testing client property. """ client = LDAPClient(host_url) ref = LDAPReference(client, []) assert ref.client == client with pytest.raises(TypeError): ref.client = "b" ref.client = LDAPClient() assert ref.client != client
def test_wrong_search_param(ipaddr): """ Test passing wrong parameters for search method. """ with pytest.raises(ClosedConnection): cli = LDAPClient("ldap://%s" % ipaddr) LDAPConnection(cli).search() with pytest.raises(ValueError): cli = LDAPClient("ldap://%s" % ipaddr) LDAPConnection(cli).open().search() with pytest.raises(TypeError): cli = LDAPClient("ldap://%s" % ipaddr) LDAPConnection(cli).open().search("", 0, 3)
def test_client_prop(self): """ Testing client property. """ client = LDAPClient(self.url) ref = LDAPReference(client, []) self.assertEqual(ref.client, client) def error(): ref.client = "b" self.assertRaises(TypeError, error) ref.client = LDAPClient() self.assertNotEqual(ref.client, client)
def test_managedsait(self): """ Test managedsait property. """ client = LDAPClient(self.url) self.assertRaises(TypeError, lambda: client.set_managedsait("B")) self.assertFalse(client.managedsait) client.managedsait = True self.assertTrue(client.managedsait)
def test_auto_acquire_prop(self): """ Test auto_page_acquire property. """ client = LDAPClient(self.url) self.assertRaises(TypeError, lambda: client.set_auto_page_acquire("A")) self.assertTrue(client.auto_page_acquire) client.auto_page_acquire = False self.assertFalse(client.auto_page_acquire)
def test_password_modify_extop(conn, ipaddr): """ Test Password Modify extended operation. """ user_dn = LDAPDN("cn=skip,ou=nerdherd,dc=bonsai,dc=test") cli = LDAPClient("ldap://%s" % ipaddr) cli.set_credentials("SIMPLE", str(user_dn), "p@ssword") test_conn = cli.connect() with pytest.raises(TypeError): test_conn.modify_password(new_password=0) test_conn.modify_password(user_dn, "newpassword", "p@ssword") test_conn.close() with pytest.raises(ClosedConnection): test_conn.modify_password() try: cli.set_credentials("SIMPLE", str(user_dn), "newpassword") cli.set_password_policy(True) test_conn, ctrl = cli.connect() newpass = test_conn.modify_password() test_conn.close() assert isinstance(newpass, str) cli.set_credentials("SIMPLE", str(user_dn), newpass) test_conn, ctrl = cli.connect() test_conn.close() except bonsai.AuthenticationError: pytest.fail("Failed to authenticate with the new password.") finally: entry = conn.search(user_dn, 0, attrlist=["userPassword"])[0] entry["userPassword"] = "******" entry.modify() entry = conn.search(user_dn, 0, attrlist=["pwdChangeTime", "pwdGraceUseTime"])[0] if ("pwdChangeTime", "pwdGraceUseTime") in entry.keys(): del entry["pwdChangeTime"] del entry["pwdGraceUseTime"] entry.modify()
def test_password_modify_extop(self): """ Test Password Modify extended operation. """ user_dn = LDAPDN("cn=skip,ou=nerdherd,dc=bonsai,dc=test") cli = LDAPClient("ldap://%s" % self.ipaddr) cli.set_credentials("SIMPLE", (str(user_dn), "p@ssword")) conn = cli.connect() self.assertRaises(TypeError, lambda: conn.modify_password(new_password=0)) conn.modify_password(user_dn, "newpassword", "p@ssword") conn.close() self.assertRaises(ClosedConnection, conn.modify_password) try: cli.set_credentials("SIMPLE", (str(user_dn), "newpassword")) cli.set_password_policy(True) conn, ctrl = cli.connect() newpass = conn.modify_password() conn.close() self.assertIsInstance(newpass, str) cli.set_credentials("SIMPLE", (str(user_dn), newpass)) conn, ctrl = cli.connect() conn.close() except bonsai.AuthenticationError: self.fail("Failed to authenticate with the new password.") finally: entry = self.conn.search(user_dn, 0, attrlist=["userPassword"])[0] entry['userPassword'] = "******" entry.modify() entry = self.conn.search(user_dn, 0, attrlist=["pwdChangeTime", "pwdGraceUseTime"])[0] if ("pwdChangeTime", "pwdGraceUseTime") in entry.keys(): del entry['pwdChangeTime'] del entry['pwdGraceUseTime'] entry.modify()
def test_add_and_delete_referrals(cfg, ipaddr): """ Test add and delete an LDAP referral with ManageDdsIT control. """ refdn = bonsai.LDAPDN("o=test-ref,ou=nerdherd,dc=bonsai,dc=test") ref = "ldap://test.host/cn=nobody" cli = LDAPClient("ldap://%s" % ipaddr) cli.set_credentials("SIMPLE", user=cfg["SIMPLEAUTH"]["user"], password=cfg["SIMPLEAUTH"]["password"]) cli.managedsait = True with cli.connect() as conn: entry = bonsai.LDAPEntry(refdn, conn) entry["objectClass"] = ["referral", "extensibleObject"] entry["o"] = "test-ref" entry["ref"] = ref conn.add(entry) res = conn.search(refdn, 0, attrlist=["ref"])[0] assert entry.dn == res.dn assert entry["ref"] == res["ref"] cli.managedsait = False with cli.connect() as conn: with pytest.raises(bonsai.LDAPError): conn.delete(entry.dn) cli.managedsait = True with cli.connect() as conn: conn.delete(entry.dn) res = conn.search(refdn, 0, attrlist=["ref"]) assert res == []
def _create_binding(auth, mech, authzid=None, realm=None): cfg = get_config() host = "ldap://%s" % cfg["SERVER"]["hostname"] client = LDAPClient(host) client.set_credentials(mech, cfg[auth]["user"], cfg[auth]["password"], realm, authzid) return client.connect()
def _bind_external(self, authzid): if 'EXTERNALAUTH' not in self.cfg: self.skipTest("EXTERNAL authentication is not set.") if sys.platform == "win32": self.skipTest("Windows relies on set certs in its cert store.") tls_impl = bonsai.get_tls_impl_name() if tls_impl == "GnuTLS" or tls_impl == "OpenSSL": curdir = os.path.abspath(os.path.dirname(__file__)) cert_path = os.path.join(curdir, 'testenv', 'certs') cli = LDAPClient("ldap://%s" % self.cfg['SERVER']['hostname'], tls=True) cli.set_ca_cert(cert_path + '/cacert.pem') cli.set_client_cert(cert_path + '/client.pem') cli.set_client_key(cert_path + '/client.key') cli.set_credentials('EXTERNAL', (authzid, )) try: conn = cli.connect() except (bonsai.errors.ConnectionError, \ bonsai.errors.AuthenticationError): self.fail() else: self.assertNotEqual( "anonymous", conn.whoami(), "EXTERNAL authentication was" " unsuccessful.") return conn else: self.skipTest("")
def test_wrong_delete_param(conn, ipaddr): """ Test passing wrong parameter for delete method. """ with pytest.raises(ClosedConnection): cli = LDAPClient("ldap://%s" % ipaddr) LDAPConnection(cli).delete("cn=dummy") with pytest.raises(TypeError): conn.delete(0)
def test_password_modify(client): """ Test modifying password with simple modify operation and password policy. """ cli = LDAPClient(client.url) user_dn = "cn=jeff,ou=nerdherd,dc=bonsai,dc=test" cli.set_password_policy(True) cli.set_credentials("SIMPLE", user_dn, "p@ssword") conn, _ = cli.connect() entry = conn.search(user_dn, 0)[0] try: entry["userPassword"] = "******" entry.modify() except Exception as exc: assert isinstance(exc, bonsai.errors.PasswordModNotAllowed) user_dn = "cn=skip,ou=nerdherd,dc=bonsai,dc=test" cli.set_credentials("SIMPLE", user_dn, "p@ssword") conn, _ = cli.connect() entry = conn.search(user_dn, 0)[0] try: entry["userPassword"] = "******" entry.modify() except Exception as exc: assert isinstance(exc, bonsai.errors.PasswordTooShort) try: entry["userPassword"] = "******" entry.modify() except Exception as exc: assert isinstance(exc, bonsai.errors.PasswordInHistory)
def test_password_expire(conn, ipaddr): """ Test password expiring with password policy. """ user_dn = "cn=skip,ou=nerdherd,dc=bonsai,dc=test" cli = LDAPClient("ldap://%s" % ipaddr) cli.set_password_policy(True) cli.set_credentials("SIMPLE", user_dn, "p@ssword") test_conn, ctrl = cli.connect() entry = test_conn.search(user_dn, 0)[0] entry["userPassword"] = "******" entry.modify() test_conn.close() cli.set_credentials("SIMPLE", user_dn, "newvalidpassword") time.sleep(2.0) test_conn, ctrl = cli.connect() if not (ctrl["expire"] <= 10 and ctrl["expire"] > 0): pytest.fail("Expire time is in the wrong range (Expire: %d)." % ctrl["expire"]) test_conn.close() time.sleep(10) test_conn, ctrl = cli.connect() assert ctrl["grace"] == 1 test_conn.close() with pytest.raises(bonsai.errors.PasswordExpired): test_conn, ctrl = cli.connect() entry = conn.search(user_dn, 0, attrlist=["userPassword"])[0] entry["userPassword"] = "******" entry.modify() entry = conn.search(user_dn, 0, attrlist=["pwdChangeTime", "pwdGraceUseTime"])[0] if ("pwdChangeTime", "pwdGraceUseTime") in entry.keys(): del entry["pwdChangeTime"] del entry["pwdGraceUseTime"] entry.modify()
def _create_kinit(authzid=None): try: cfg = get_config() user = cfg["GSSAPIAUTH"]["user"] password = cfg["GSSAPIAUTH"]["password"] proc = subprocess.Popen( ["kinit", "--version"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, ) output = " ".join(proc.communicate()) if "Heimdal" in output: # Heimdal Kerberos implementation. with tempfile.NamedTemporaryFile() as psw_tmp: psw_tmp.write(password.encode()) psw_tmp.flush() cmd = ["kinit", "--password-file=%s" % psw_tmp.name, user] subprocess.check_call(cmd) else: # MIT Kerberos implementation. cmd = 'echo "%s" | kinit %s' % (password, user) subprocess.check_output(cmd, shell=True) host = "ldap://%s" % cfg["SERVER"]["hostname"] client = LDAPClient(host) client.set_credentials( "GSSAPI", cfg["GSSAPIAUTH"]["user"], cfg["GSSAPIAUTH"]["password"], None, authzid, ) return client.connect() except subprocess.CalledProcessError: pytest.fail("Receiving TGT is failed.")
def test_wrong_add_param(conn, ipaddr): """ Test passing wrong parameter for add method. """ with pytest.raises(ClosedConnection): cli = LDAPClient("ldap://%s" % ipaddr) LDAPConnection(cli).add(bonsai.LDAPEntry("cn=dummy")) with pytest.raises(TypeError): conn.add("wrong")
def test_init_errors(self): """ Testing errors during initialization of LDAPReference. """ client = LDAPClient(self.url) self.assertRaises(TypeError, lambda: LDAPReference(None, ["ldap://a"])) self.assertRaises(TypeError, lambda: LDAPReference(client, [0])) self.assertRaises( ValueError, lambda: LDAPReference(client, ["asd", LDAPURL("ldap://b")]))
def test_references_prop(host_url): """ Testing references property. """ client = LDAPClient(host_url) reflist = [LDAPURL("ldap://localhost"), host_url] ref = LDAPReference(client, reflist) assert ref.references == reflist with pytest.raises(ValueError): ref.references = None
def test_server_chase_referrals(self): """ Test server_chase_referrals property. """ client = LDAPClient(self.url) self.assertRaises(TypeError, lambda: client.set_server_chase_referrals(2)) self.assertTrue(client.server_chase_referrals) client.server_chase_referrals = False self.assertFalse(client.server_chase_referrals)
def setUpClass(cls): """ Set host url and connection. """ curdir = os.path.abspath(os.path.dirname(__file__)) cfg = configparser.ConfigParser() cfg.read(os.path.join(curdir, 'test.ini')) cls.url = "ldap://%s:%s" % (cfg["SERVER"]["hostip"], cfg["SERVER"]["port"]) cls.client = LDAPClient(cls.url)
def test_tls_timeout(url): """ Test TLS connection timeout. """ client = LDAPClient(url, True) client.set_cert_policy("ALLOW") client.set_ca_cert(None) client.set_ca_cert_dir(None) with network_delay(9.0): with pytest.raises(bonsai.TimeoutError): client.connect(timeout=5.0)
def test_init_errors(host_url): """ Testing errors during initialization of LDAPReference. """ client = LDAPClient(host_url) with pytest.raises(TypeError): _ = LDAPReference(None, ["ldap://a"]) with pytest.raises(TypeError): _ = LDAPReference(client, [0]) with pytest.raises(ValueError): _ = LDAPReference(client, ["asd", LDAPURL("ldap://b")])
def test_max_connection(): """ Test max_connection property. """ cli = LDAPClient("ldap://dummy.nfo") pool = ConnectionPool(cli, minconn=5, maxconn=5) assert pool.max_connection == 5 with pytest.raises(ValueError): pool.max_connection = 4 pool.max_connection = 10 assert pool.max_connection == 10
def setUpClass(cls): curdir = os.path.abspath(os.path.dirname(__file__)) """ Set LDAP client, get config parameters. """ cfg = configparser.ConfigParser() cfg.read(os.path.join(curdir, 'test.ini')) url = "ldap://%s:%s" % (cfg["SERVER"]["hostip"], cfg["SERVER"]["port"]) cls.client = LDAPClient(url) cls.creds = ("SIMPLE", (cfg["SIMPLEAUTH"]["user"], cfg["SIMPLEAUTH"]["password"])) cls.basedn = cfg["SERVER"]["basedn"]
def setUpClass(cls): """ Set host url and connection. """ curdir = os.path.abspath(os.path.dirname(__file__)) cfg = configparser.ConfigParser() cfg.read(os.path.join(curdir, 'test.ini')) cls.ipaddr = cfg["SERVER"]["hostip"] cls.url = "ldap://%s:%s" % (cls.ipaddr, cfg["SERVER"]["port"]) cls.client = LDAPClient(cls.url) cls.has_tls = cfg['SERVER']['has_tls'] != 'False' proxy = rpc.ServerProxy("http://%s:%d/" % (cls.ipaddr, 8000)) proxy.remove_delay()
def test_references_prop(self): """ Testing references property. """ client = LDAPClient(self.url) reflist = [LDAPURL("ldap://localhost"), self.url] ref = LDAPReference(client, reflist) self.assertCountEqual(ref.references, reflist) def error(): ref.references = None self.assertRaises(ValueError, error)
def test_tls(url): """ Test TLS connection. """ client = LDAPClient(url, True) client.set_cert_policy("ALLOW") client.set_ca_cert(None) client.set_ca_cert_dir(None) try: conn = client.connect() conn.close() except Exception as exc: pytest.fail("TLS connection is failed with: %s" % str(exc))
def test_digest_auth_error(cfg): """ Test DIGEST-MD5 authentication error. """ client = LDAPClient("ldap://%s" % cfg["SERVER"]["hostname"]) if cfg["DIGESTAUTH"]["realm"] == "None": realm = None else: realm = cfg["DIGESTAUTH"]["realm"].upper() client.set_credentials("DIGEST-MD5", cfg["DIGESTAUTH"]["user"], "wrongpassword", realm, None) with pytest.raises(bonsai.AuthenticationError): _ = client.connect()
def test_search_with_managedsait_ctrl(ipaddr): """ Test searching with manageDsaIT control. """ refdn = LDAPDN("o=admin-ref,ou=nerdherd,dc=bonsai,dc=test") cli = LDAPClient("ldap://%s" % ipaddr) with cli.connect() as conn: res = conn.search(refdn, LDAPSearchScope.BASE, attrlist=["ref"])[0] assert str(res.dn) == "cn=admin,dc=bonsai,dc=test" cli.set_managedsait(True) with cli.connect() as conn: res = conn.search(refdn, LDAPSearchScope.BASE, attrlist=["ref"])[0] assert refdn == res.dn assert "ldap://bonsai.test/cn=admin,dc=bonsai,dc=test" == res["ref"][0]