| 1 |
import os |
| 2 |
import sys |
| 3 |
import subprocess |
| 4 |
import tempfile |
| 5 |
import time |
| 6 |
|
| 7 |
import pytest |
| 8 |
from conftest import get_config, network_delay |
| 9 |
|
| 10 |
import bonsai |
| 11 |
from bonsai import LDAPDN |
| 12 |
from bonsai import LDAPClient |
| 13 |
from bonsai import LDAPConnection |
| 14 |
from bonsai import LDAPSearchScope |
| 15 |
import bonsai.errors |
| 16 |
from bonsai.errors import ClosedConnection, SizeLimitError |
| 17 |
from bonsai.ldapconnection import BaseLDAPConnection |
| 18 |
|
| 19 |
|
| 20 |
class SimpleAsyncConn(BaseLDAPConnection): |
| 21 |
def __init__(self, client): |
| 22 |
super().__init__(client, True) |
| 23 |
|
| 24 |
def _evaluate(self, msg_id, timeout=None): |
| 25 |
return msg_id |
| 26 |
|
| 27 |
|
| 28 |
@pytest.fixture(scope="module") |
| 29 |
def ipaddr(): |
| 30 |
"""Get IP address.""" |
| 31 |
cfg = get_config() |
| 32 |
return cfg["SERVER"]["hostip"] |
| 33 |
|
| 34 |
|
| 35 |
@pytest.fixture(scope="module") |
| 36 |
def ktpath(): |
| 37 |
"""Get keytab file path.""" |
| 38 |
cfg = get_config() |
| 39 |
proj_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir)) |
| 40 |
ktpath = os.path.abspath(os.path.join(proj_dir, cfg["GSSAPIAUTH"]["keytab"])) |
| 41 |
return ktpath |
| 42 |
|
| 43 |
|
| 44 |
@pytest.fixture |
| 45 |
def binding(): |
| 46 |
"""Create a binding with the server.""" |
| 47 |
|
| 48 |
def _create_binding(auth, mech, authzid=None, realm=None): |
| 49 |
cfg = get_config() |
| 50 |
host = "ldap://%s" % cfg["SERVER"]["hostname"] |
| 51 |
client = LDAPClient(host) |
| 52 |
client.set_credentials( |
| 53 |
mech, cfg[auth]["user"], cfg[auth]["password"], realm, authzid |
| 54 |
) |
| 55 |
return client.connect() |
| 56 |
|
| 57 |
return _create_binding |
| 58 |
|
| 59 |
|
| 60 |
@pytest.fixture |
| 61 |
def kinit(): |
| 62 |
def _create_kinit(authzid=None): |
| 63 |
try: |
| 64 |
cfg = get_config() |
| 65 |
user = cfg["GSSAPIAUTH"]["user"] |
| 66 |
password = cfg["GSSAPIAUTH"]["password"] |
| 67 |
proc = subprocess.Popen( |
| 68 |
["kinit", "--version"], |
| 69 |
stdout=subprocess.PIPE, |
| 70 |
stderr=subprocess.PIPE, |
| 71 |
universal_newlines=True, |
| 72 |
) |
| 73 |
output = " ".join(proc.communicate()) |
| 74 |
if "Heimdal" in output: |
| 75 |
|
| 76 |
with tempfile.NamedTemporaryFile() as psw_tmp: |
| 77 |
psw_tmp.write(password.encode()) |
| 78 |
psw_tmp.flush() |
| 79 |
cmd = ["kinit", "--password-file=%s" % psw_tmp.name, user] |
| 80 |
subprocess.check_call(cmd) |
| 81 |
else: |
| 82 |
|
| 83 |
cmd = 'echo "%s" | kinit %s' % (password, user) |
| 84 |
subprocess.check_output(cmd, shell=True) |
| 85 |
host = "ldap://%s" % cfg["SERVER"]["hostname"] |
| 86 |
client = LDAPClient(host) |
| 87 |
client.set_credentials( |
| 88 |
"GSSAPI", |
| 89 |
cfg["GSSAPIAUTH"]["user"], |
| 90 |
cfg["GSSAPIAUTH"]["password"], |
| 91 |
None, |
| 92 |
authzid, |
| 93 |
) |
| 94 |
return client.connect() |
| 95 |
except subprocess.CalledProcessError: |
| 96 |
pytest.fail("Receiving TGT is failed.") |
| 97 |
|
| 98 |
yield _create_kinit |
| 99 |
subprocess.call("kdestroy") |
| 100 |
|
| 101 |
|
| 102 |
@pytest.fixture |
| 103 |
def large_org(): |
| 104 |
"""Create a heavily populated organization LDAP entry.""" |
| 105 |
gconn = None |
| 106 |
entry = None |
| 107 |
gnum = None |
| 108 |
|
| 109 |
def _create_org(conn, org_dn, entry_num): |
| 110 |
nonlocal gconn |
| 111 |
nonlocal entry |
| 112 |
nonlocal gnum |
| 113 |
entry = bonsai.LDAPEntry(org_dn) |
| 114 |
entry["objectclass"] = ["top", "organizationalUnit"] |
| 115 |
entry["ou"] = entry.dn.rdns[0][0][1] |
| 116 |
gconn = conn |
| 117 |
gnum = entry_num |
| 118 |
try: |
| 119 |
conn.add(entry) |
| 120 |
except bonsai.AlreadyExists: |
| 121 |
conn.delete(entry.dn, recursive=True) |
| 122 |
conn.add(entry) |
| 123 |
for idx in range(entry_num): |
| 124 |
item = bonsai.LDAPEntry(f"cn=test_{idx},{entry.dn}") |
| 125 |
item["objectclass"] = [ |
| 126 |
"top", |
| 127 |
"inetOrgPerson", |
| 128 |
"person", |
| 129 |
"organizationalPerson", |
| 130 |
] |
| 131 |
item["sn"] = f"test_{idx}" |
| 132 |
conn.add(item) |
| 133 |
return entry |
| 134 |
|
| 135 |
yield _create_org |
| 136 |
|
| 137 |
if gconn.closed: |
| 138 |
gconn = gconn.open() |
| 139 |
for idx in range(gnum): |
| 140 |
|
| 141 |
item = bonsai.LDAPEntry(f"cn=test_{idx},{entry.dn}") |
| 142 |
gconn.delete(item.dn) |
| 143 |
gconn.delete(entry.dn, recursive=True) |
| 144 |
gconn.close() |
| 145 |
|
| 146 |
|
| 147 |
@pytest.fixture |
| 148 |
def external_binding(): |
| 149 |
"""Create a binding using external mechanism.""" |
| 150 |
|
| 151 |
def _create_external(authzid=None): |
| 152 |
tls_impl = bonsai.get_tls_impl_name() |
| 153 |
if tls_impl == "GnuTLS" or tls_impl == "OpenSSL": |
| 154 |
cfg = get_config() |
| 155 |
curdir = os.path.abspath(os.path.dirname(__file__)) |
| 156 |
cert_path = os.path.join(curdir, "testenv", "certs") |
| 157 |
host = "ldap://%s" % cfg["SERVER"]["hostname"] |
| 158 |
cli = LDAPClient(host, tls=True) |
| 159 |
cli.set_ca_cert(cert_path + "/cacert.pem") |
| 160 |
cli.set_client_cert(cert_path + "/client.pem") |
| 161 |
cli.set_client_key(cert_path + "/client.key") |
| 162 |
cli.set_credentials("EXTERNAL", authz_id=authzid) |
| 163 |
return cli.connect() |
| 164 |
else: |
| 165 |
pytest.skip("") |
| 166 |
|
| 167 |
return _create_external |
| 168 |
|
| 169 |
|
| 170 |
def _generate_client(cfg): |
| 171 |
srv = cfg["SERVER"] |
| 172 |
url = f"ldap://{srv['hostip']}:{srv['port']}/ou=nerdherd,{srv['basedn']}?{srv['search_attr']}?{srv['search_scope']}" |
| 173 |
client = LDAPClient(url) |
| 174 |
client.set_credentials( |
| 175 |
"SIMPLE", user=cfg["SIMPLEAUTH"]["user"], password=cfg["SIMPLEAUTH"]["password"] |
| 176 |
) |
| 177 |
client.auto_page_acquire = False |
| 178 |
return client |
| 179 |
|
| 180 |
|
| 181 |
@pytest.fixture |
| 182 |
def conn(): |
| 183 |
"""Create a connection.""" |
| 184 |
cfg = get_config() |
| 185 |
client = _generate_client(cfg) |
| 186 |
return client.connect() |
| 187 |
|
| 188 |
|
| 189 |
@pytest.fixture |
| 190 |
def anonym_conn(): |
| 191 |
"""Create a connection with anonymous user.""" |
| 192 |
cfg = get_config() |
| 193 |
client = _generate_client(cfg) |
| 194 |
client.set_credentials("SIMPLE") |
| 195 |
return client.connect() |
| 196 |
|
| 197 |
|
| 198 |
@pytest.fixture |
| 199 |
def async_conn(): |
| 200 |
cfg = get_config() |
| 201 |
client = _generate_client(cfg) |
| 202 |
return SimpleAsyncConn(client) |
| 203 |
|
| 204 |
|
| 205 |
def test_bind_digest(binding): |
| 206 |
"""Test DIGEST-MD5 connection.""" |
| 207 |
with binding("DIGESTAUTH", "DIGEST-MD5") as conn: |
| 208 |
assert "anonymous" != conn.whoami() |
| 209 |
|
| 210 |
|
| 211 |
@pytest.mark.skipif( |
| 212 |
sys.platform.startswith("win") or get_config()["DIGESTAUTH"]["authzid"] == "None", |
| 213 |
reason="Authzid is not set", |
| 214 |
) |
| 215 |
def test_bind_digest_with_authzid(binding, cfg): |
| 216 |
"""Test DIGEST-MD5 connection with authorization ID.""" |
| 217 |
authzid = cfg["DIGESTAUTH"]["authzid"] |
| 218 |
with binding("DIGESTAUTH", "DIGEST-MD5", authzid) as conn: |
| 219 |
assert cfg["DIGESTAUTH"]["dn"] == conn.whoami() |
| 220 |
|
| 221 |
|
| 222 |
@pytest.mark.skipif( |
| 223 |
sys.platform.startswith("win"), reason="NTLM is not enabled on Windows." |
| 224 |
) |
| 225 |
def test_bind_ntlm(binding): |
| 226 |
"""Test NTLM connection.""" |
| 227 |
with binding("NTLMAUTH", "NTLM") as conn: |
| 228 |
assert "anonymous" != conn.whoami() |
| 229 |
|
| 230 |
|
| 231 |
@pytest.mark.skipif( |
| 232 |
sys.platform == "darwin", reason="SCRAM is not supported on clients on Mac." |
| 233 |
) |
| 234 |
def test_bind_not_supported_auth(binding): |
| 235 |
"""Test not supported authentication mechanism by the server.""" |
| 236 |
with pytest.raises(bonsai.AuthMethodNotSupported): |
| 237 |
_ = binding("DIGESTAUTH", "SCRAM-SHA-1") |
| 238 |
|
| 239 |
|
| 240 |
@pytest.mark.skipif( |
| 241 |
sys.platform.startswith("win"), reason="Kinit is unavailable on Windows." |
| 242 |
) |
| 243 |
def test_bind_gssapi_kinit(kinit): |
| 244 |
"""Test GSSAPI connection.""" |
| 245 |
with kinit() as conn: |
| 246 |
assert "anonymous" != conn.whoami() |
| 247 |
|
| 248 |
|
| 249 |
@pytest.mark.skipif( |
| 250 |
sys.platform.startswith("win"), reason="Kinit is unavailable on Windows." |
| 251 |
) |
| 252 |
def test_bind_gssapi_with_authzid_kinit(kinit, cfg): |
| 253 |
"""Test GSSAPI connection with authorization ID.""" |
| 254 |
authzid = cfg["GSSAPIAUTH"]["authzid"] |
| 255 |
with kinit(authzid) as conn: |
| 256 |
assert cfg["GSSAPIAUTH"]["dn"] == conn.whoami() |
| 257 |
|
| 258 |
|
| 259 |
@pytest.mark.skipif( |
| 260 |
not bonsai.has_krb5_support() or sys.platform == "darwin", |
| 261 |
reason="Module doesn't have KRB5 support.", |
| 262 |
) |
| 263 |
def test_bind_gssapi(binding, cfg): |
| 264 |
"""Test GSSAPI connection with automatic TGT requesting.""" |
| 265 |
with binding( |
| 266 |
"GSSAPIAUTH", "GSSAPI", None, cfg["GSSAPIAUTH"]["realm"].upper() |
| 267 |
) as conn: |
| 268 |
assert "anonymous" != conn.whoami() |
| 269 |
|
| 270 |
|
| 271 |
@pytest.mark.skipif( |
| 272 |
not bonsai.has_krb5_support() or sys.platform == "darwin", |
| 273 |
reason="Module doesn't have KRB5 support.", |
| 274 |
) |
| 275 |
def test_bind_gssapi_error(cfg): |
| 276 |
"""Test automatic TGT requesting with wrong realm name.""" |
| 277 |
client = _generate_client(cfg) |
| 278 |
client.set_credentials( |
| 279 |
"GSSAPI", |
| 280 |
cfg["GSSAPIAUTH"]["user"], |
| 281 |
cfg["GSSAPIAUTH"]["password"], |
| 282 |
cfg["GSSAPIAUTH"]["realm"], |
| 283 |
None, |
| 284 |
) |
| 285 |
with pytest.raises(bonsai.AuthenticationError): |
| 286 |
_ = client.connect() |
| 287 |
|
| 288 |
|
| 289 |
@pytest.mark.skipif( |
| 290 |
not bonsai.has_krb5_support() or sys.platform != "linux", |
| 291 |
reason="Keytab-based auth only available on linux.", |
| 292 |
) |
| 293 |
def test_bind_gssapi_keytab_error(cfg, ktpath): |
| 294 |
client = LDAPClient("ldap://%s" % cfg["SERVER"]["hostname"]) |
| 295 |
client.set_credentials( |
| 296 |
"GSSAPI", |
| 297 |
user=cfg["GSSAPIAUTH"]["user"], |
| 298 |
realm=cfg["GSSAPIAUTH"]["realm"].upper(), |
| 299 |
keytab="invalid", |
| 300 |
) |
| 301 |
with pytest.raises(bonsai.AuthenticationError): |
| 302 |
_ = client.connect() |
| 303 |
client.set_credentials( |
| 304 |
"GSSAPI", |
| 305 |
user="invalid", |
| 306 |
realm=cfg["GSSAPIAUTH"]["realm"].upper(), |
| 307 |
keytab=ktpath, |
| 308 |
) |
| 309 |
with pytest.raises(bonsai.AuthenticationError): |
| 310 |
_ = client.connect() |
| 311 |
|
| 312 |
|
| 313 |
@pytest.mark.skipif( |
| 314 |
not bonsai.has_krb5_support() or sys.platform != "linux", |
| 315 |
reason="Keytab-based auth only available on linux.", |
| 316 |
) |
| 317 |
def test_bind_gssapi_keytab(cfg, ktpath): |
| 318 |
client = LDAPClient("ldap://%s" % cfg["SERVER"]["hostname"]) |
| 319 |
client.set_credentials( |
| 320 |
"GSSAPI", |
| 321 |
user=cfg["GSSAPIAUTH"]["user"], |
| 322 |
realm=cfg["GSSAPIAUTH"]["realm"].upper(), |
| 323 |
keytab=ktpath, |
| 324 |
) |
| 325 |
conn = client.connect() |
| 326 |
assert conn.whoami() == "dn:cn=chuck,ou=nerdherd,dc=bonsai,dc=test" |
| 327 |
client.set_credentials( |
| 328 |
"GSSAPI", user="admin", realm=cfg["GSSAPIAUTH"]["realm"].upper(), keytab=ktpath |
| 329 |
) |
| 330 |
conn = client.connect() |
| 331 |
assert conn.whoami() == "dn:cn=admin,dc=bonsai,dc=test" |
| 332 |
|
| 333 |
|
| 334 |
@pytest.mark.skipif( |
| 335 |
not sys.platform.startswith("win"), |
| 336 |
reason="No Windows logon credentials", |
| 337 |
) |
| 338 |
def test_bind_winlogon(cfg): |
| 339 |
"""Test connection with Windows logon credentials""" |
| 340 |
expected_user = f"u:{os.getenv('userdomain')}\\{os.getlogin()}" |
| 341 |
client = LDAPClient("ldap://%s" % cfg["SERVER"]["hostname"]) |
| 342 |
client.set_credentials("GSSAPI") |
| 343 |
with client.connect() as conn: |
| 344 |
assert conn.whoami() == expected_user |
| 345 |
client.set_credentials("GSS-SPNEGO") |
| 346 |
with client.connect() as conn: |
| 347 |
assert conn.whoami() == expected_user |
| 348 |
client.set_credentials("DIGEST-MD5") |
| 349 |
with pytest.raises(bonsai.AuthenticationError): |
| 350 |
_ = client.connect() |
| 351 |
|
| 352 |
|
| 353 |
@pytest.mark.skipif( |
| 354 |
not sys.platform.startswith("win"), reason="No GSS-SPNEGO mech on Ubuntu and Mac" |
| 355 |
) |
| 356 |
def test_bind_spnego(binding, cfg): |
| 357 |
"""Test GSS-SPNEGO connection with automatic TGT requesting.""" |
| 358 |
with binding( |
| 359 |
"GSSAPIAUTH", "GSS-SPNEGO", None, cfg["GSSAPIAUTH"]["realm"].upper() |
| 360 |
) as conn: |
| 361 |
assert "anonymous" != conn.whoami() |
| 362 |
|
| 363 |
|
| 364 |
def test_bind_external(external_binding): |
| 365 |
"""Test EXTERNAL connection.""" |
| 366 |
with external_binding() as conn: |
| 367 |
assert "anonymous" != conn.whoami() |
| 368 |
|
| 369 |
|
| 370 |
def test_bind_external_with_authzid(external_binding, cfg): |
| 371 |
"""Test EXTERNAL connection with authorization ID.""" |
| 372 |
authzid = cfg["EXTERNALAUTH"]["authzid"] |
| 373 |
with external_binding(authzid) as conn: |
| 374 |
assert cfg["EXTERNALAUTH"]["dn"] == conn.whoami() |
| 375 |
|
| 376 |
|
| 377 |
def test_search(conn, basedn): |
| 378 |
"""Test searching.""" |
| 379 |
res = conn.search("ou=nerdherd,%s" % basedn, LDAPSearchScope.SUB) |
| 380 |
assert res is not None |
| 381 |
assert len(res) == len(conn.search()) |
| 382 |
|
| 383 |
|
| 384 |
def test_search_ldapdn(conn, basedn): |
| 385 |
"""Test searching with LDAPDN object.""" |
| 386 |
ldap_dn = LDAPDN(basedn) |
| 387 |
obj = conn.search(ldap_dn, 1) |
| 388 |
assert obj is not None |
| 389 |
|
| 390 |
|
| 391 |
def test_search_attr(conn, basedn): |
| 392 |
"""Test searching with given list of attributes.""" |
| 393 |
obj = conn.search(basedn, 2, "(objectclass=person)", ["cn"])[0] |
| 394 |
assert obj is not None |
| 395 |
assert "cn" in obj.keys() |
| 396 |
|
| 397 |
|
| 398 |
def test_search_attrsonly(conn, basedn): |
| 399 |
"""Test search receiving only attributes.""" |
| 400 |
obj = conn.search(basedn, 2, "(objectclass=person)", ["cn"], attrsonly=True)[0] |
| 401 |
assert obj is not None |
| 402 |
assert obj["cn"] == [] |
| 403 |
|
| 404 |
|
| 405 |
def test_add_and_delete(conn, basedn): |
| 406 |
"""Test adding and removing an LDAP entry.""" |
| 407 |
entry = bonsai.LDAPEntry("cn=example,%s" % basedn) |
| 408 |
entry.update( |
| 409 |
{"objectclass": ["top", "inetorgperson"], "cn": "example", "sn": "example"} |
| 410 |
) |
| 411 |
try: |
| 412 |
conn.add(entry) |
| 413 |
res = conn.search(entry.dn, 0) |
| 414 |
assert res[0] == entry |
| 415 |
conn.delete("cn=example,%s" % basedn) |
| 416 |
res = conn.search(entry.dn, 0) |
| 417 |
assert res == [] |
| 418 |
with pytest.raises(ValueError): |
| 419 |
conn.add(bonsai.LDAPEntry("")) |
| 420 |
except bonsai.LDAPError: |
| 421 |
pytest.fail("Add and delete new entry is failed.") |
| 422 |
|
| 423 |
|
| 424 |
def test_recursive_delete(conn, basedn): |
| 425 |
"""Test removing a subtree recursively.""" |
| 426 |
org1 = bonsai.LDAPEntry("ou=testusers,%s" % basedn) |
| 427 |
org1.update({"objectclass": ["organizationalUnit", "top"], "ou": "testusers"}) |
| 428 |
org2 = bonsai.LDAPEntry("ou=tops,ou=testusers,%s" % basedn) |
| 429 |
org2.update({"objectclass": ["organizationalUnit", "top"], "ou": "tops"}) |
| 430 |
entry = bonsai.LDAPEntry("cn=tester,ou=tops,ou=testusers,%s" % basedn) |
| 431 |
entry.update( |
| 432 |
{"objectclass": ["top", "inetorgperson"], "cn": "tester", "sn": "example"} |
| 433 |
) |
| 434 |
try: |
| 435 |
conn.add(org1) |
| 436 |
conn.add(org2) |
| 437 |
conn.add(entry) |
| 438 |
conn.delete(org1.dn, recursive=True) |
| 439 |
res = conn.search(org1.dn, 2) |
| 440 |
assert res == [] |
| 441 |
except bonsai.LDAPError: |
| 442 |
pytest.fail("Recursive delete is failed.") |
| 443 |
|
| 444 |
|
| 445 |
def test_whoami(conn, cfg): |
| 446 |
"""Test whoami.""" |
| 447 |
obj = conn.whoami() |
| 448 |
expected_res = [ |
| 449 |
"dn:%s" % cfg["SIMPLEAUTH"]["user"], |
| 450 |
cfg["SIMPLEAUTH"]["adusername"], |
| 451 |
] |
| 452 |
assert obj in expected_res |
| 453 |
|
| 454 |
|
| 455 |
def test_connection_error(): |
| 456 |
"""Test connection error.""" |
| 457 |
client = LDAPClient("ldap://invalid") |
| 458 |
with pytest.raises(bonsai.ConnectionError): |
| 459 |
_ = client.connect() |
| 460 |
|
| 461 |
|
| 462 |
def test_simple_auth_error(cfg): |
| 463 |
"""Test simple authentication error.""" |
| 464 |
client = LDAPClient("ldap://%s" % cfg["SERVER"]["hostname"]) |
| 465 |
client.set_credentials("SIMPLE", "cn=wrong", "wronger") |
| 466 |
with pytest.raises(bonsai.AuthenticationError): |
| 467 |
_ = client.connect() |
| 468 |
|
| 469 |
|
| 470 |
def test_digest_auth_error(cfg): |
| 471 |
"""Test DIGEST-MD5 authentication error.""" |
| 472 |
client = LDAPClient("ldap://%s" % cfg["SERVER"]["hostname"]) |
| 473 |
if cfg["DIGESTAUTH"]["realm"] == "None": |
| 474 |
realm = None |
| 475 |
else: |
| 476 |
realm = cfg["DIGESTAUTH"]["realm"].upper() |
| 477 |
client.set_credentials( |
| 478 |
"DIGEST-MD5", cfg["DIGESTAUTH"]["user"], "wrongpassword", realm, None |
| 479 |
) |
| 480 |
with pytest.raises(bonsai.AuthenticationError): |
| 481 |
_ = client.connect() |
| 482 |
|
| 483 |
|
| 484 |
def test_sort_order(conn, basedn): |
| 485 |
"""Test setting sort order.""" |
| 486 |
obj = conn.search(basedn, 2, attrlist=["uidNumber"], sort_order=["-uidNumber"]) |
| 487 |
sort = [o["uidNumber"][0] for o in obj if "uidNumber" in o] |
| 488 |
assert all(sort[i] >= sort[i + 1] for i in range(len(sort) - 1)) |
| 489 |
|
| 490 |
|
| 491 |
def test_fileno(conn, cfg): |
| 492 |
"""Test fileno method.""" |
| 493 |
assert isinstance(conn.fileno(), int) |
| 494 |
try: |
| 495 |
import socket |
| 496 |
|
| 497 |
sock = socket.fromfd(conn.fileno(), socket.AF_INET, socket.SOCK_RAW) |
| 498 |
assert sock.getpeername() == ( |
| 499 |
cfg["SERVER"]["hostip"], |
| 500 |
int(cfg["SERVER"]["port"]), |
| 501 |
) |
| 502 |
sock.close() |
| 503 |
except OSError: |
| 504 |
pytest.fail("Not a valid socket descriptor.") |
| 505 |
|
| 506 |
|
| 507 |
def test_close(conn): |
| 508 |
"""Test close method.""" |
| 509 |
conn.close() |
| 510 |
assert conn.closed |
| 511 |
with pytest.raises(bonsai.ClosedConnection): |
| 512 |
_ = conn.whoami() |
| 513 |
|
| 514 |
conn.close() |
| 515 |
assert conn.closed |
| 516 |
|
| 517 |
|
| 518 |
def test_close_with_abandon(async_conn, basedn): |
| 519 |
"""Test close method with abandon requests option.""" |
| 520 |
msgid = async_conn.open() |
| 521 |
while async_conn.get_result(msgid) is None: |
| 522 |
pass |
| 523 |
msgid = async_conn.search(basedn, 2) |
| 524 |
async_conn.close(abandon_requests=True) |
| 525 |
assert async_conn.closed |
| 526 |
|
| 527 |
|
| 528 |
def test_abandon(async_conn, basedn): |
| 529 |
"""Test abandon method.""" |
| 530 |
msgid = async_conn.open() |
| 531 |
while async_conn.get_result(msgid) is None: |
| 532 |
pass |
| 533 |
msgid = async_conn.search(basedn, 2) |
| 534 |
async_conn.abandon(msgid) |
| 535 |
with pytest.raises(bonsai.InvalidMessageID): |
| 536 |
_ = async_conn.get_result(msgid) |
| 537 |
|
| 538 |
|
| 539 |
def test_async_close_remove_pendig_ops(async_conn, basedn): |
| 540 |
"""Test remove pending operations after close.""" |
| 541 |
msgid = async_conn.open() |
| 542 |
while async_conn.get_result(msgid) is None: |
| 543 |
pass |
| 544 |
async_conn.search(basedn, 2) |
| 545 |
async_conn.search(basedn, 0) |
| 546 |
async_conn.close() |
| 547 |
assert async_conn.closed |
| 548 |
|
| 549 |
|
| 550 |
def test_vlv_offset(conn, basedn): |
| 551 |
"""Test VLV control with offset.""" |
| 552 |
search_dn = "ou=nerdherd,%s" % basedn |
| 553 |
res, ctrl = conn.virtual_list_search( |
| 554 |
search_dn, |
| 555 |
1, |
| 556 |
attrlist=["uidNumber"], |
| 557 |
offset=2, |
| 558 |
sort_order=["-uidNumber"], |
| 559 |
before_count=1, |
| 560 |
after_count=1, |
| 561 |
est_list_count=6, |
| 562 |
) |
| 563 |
assert len(res) == 3 |
| 564 |
assert ctrl["target_position"] == 2 |
| 565 |
assert ctrl["list_count"] == 6 |
| 566 |
assert res[1]["uidNumber"][0] == 4 |
| 567 |
|
| 568 |
|
| 569 |
def test_vlv_attrvalue(conn, basedn): |
| 570 |
"""Test VLV control with attribute value.""" |
| 571 |
search_dn = "ou=nerdherd,%s" % basedn |
| 572 |
res, ctrl = conn.virtual_list_search( |
| 573 |
search_dn, |
| 574 |
1, |
| 575 |
attrlist=["uidNumber"], |
| 576 |
attrvalue=2, |
| 577 |
sort_order=["uidNumber"], |
| 578 |
before_count=1, |
| 579 |
after_count=2, |
| 580 |
est_list_count=6, |
| 581 |
) |
| 582 |
assert len(res) == 4 |
| 583 |
assert ctrl["target_position"] == 3 |
| 584 |
assert res[0]["uidNumber"][0] == 1 |
| 585 |
|
| 586 |
|
| 587 |
def test_vlv_without_sort_order(conn, basedn): |
| 588 |
"""Test VLV control without sort control.""" |
| 589 |
search_dn = "ou=nerdherd,%s" % basedn |
| 590 |
with pytest.raises(bonsai.UnwillingToPerform): |
| 591 |
_ = conn.virtual_list_search( |
| 592 |
search_dn, |
| 593 |
1, |
| 594 |
attrlist=["uidNumber"], |
| 595 |
offset=1, |
| 596 |
before_count=1, |
| 597 |
after_count=2, |
| 598 |
est_list_count=6, |
| 599 |
) |
| 600 |
|
| 601 |
|
| 602 |
def test_paged_search(conn, basedn): |
| 603 |
"""Test paged results control.""" |
| 604 |
search_dn = "ou=nerdherd,%s" % basedn |
| 605 |
res = conn.paged_search(search_dn, 1, page_size=2) |
| 606 |
for ent in res: |
| 607 |
assert isinstance(ent, bonsai.LDAPEntry) |
| 608 |
page = 1 |
| 609 |
while True: |
| 610 |
if len(res) > 2: |
| 611 |
pytest.fail("The size of the page is greater than expected.") |
| 612 |
msgid = res.acquire_next_page() |
| 613 |
if msgid is None: |
| 614 |
break |
| 615 |
res = conn.get_result(msgid) |
| 616 |
page += 1 |
| 617 |
assert page == 3 |
| 618 |
|
| 619 |
|
| 620 |
def test_paged_search_with_auto_acq(cfg, basedn): |
| 621 |
"""Test paged results control with automatic page acquiring.""" |
| 622 |
client = LDAPClient("ldap://%s" % cfg["SERVER"]["hostname"]) |
| 623 |
conn = client.connect() |
| 624 |
search_dn = "ou=nerdherd,%s" % basedn |
| 625 |
res = conn.paged_search(search_dn, 1, page_size=3) |
| 626 |
if len(res) != 3: |
| 627 |
pytest.fail("The size of the page is not what is expected.") |
| 628 |
entry = 0 |
| 629 |
for ent in res: |
| 630 |
assert isinstance(ent, bonsai.LDAPEntry) |
| 631 |
entry += 1 |
| 632 |
assert entry == 6 |
| 633 |
assert res.acquire_next_page() is None |
| 634 |
|
| 635 |
|
| 636 |
@pytest.mark.timeout(15) |
| 637 |
def test_search_timeout(conn, basedn): |
| 638 |
"""Test search method's timeout.""" |
| 639 |
search_dn = "ou=nerdherd,%s" % basedn |
| 640 |
with pytest.raises(TypeError): |
| 641 |
_ = conn.search(search_dn, 1, timeout=True) |
| 642 |
with pytest.raises(ValueError): |
| 643 |
_ = conn.search(search_dn, 1, timeout=-15) |
| 644 |
with network_delay(6.1): |
| 645 |
with pytest.raises(bonsai.TimeoutError): |
| 646 |
_ = conn.search(search_dn, 1, timeout=3.0) |
| 647 |
|
| 648 |
|
| 649 |
@pytest.mark.timeout(10) |
| 650 |
def test_whoami_timeout(conn): |
| 651 |
"""Test whoami's timeout.""" |
| 652 |
with pytest.raises(TypeError): |
| 653 |
_ = conn.whoami(timeout="A") |
| 654 |
with pytest.raises(ValueError): |
| 655 |
_ = conn.whoami(timeout=-10) |
| 656 |
with pytest.raises(bonsai.TimeoutError): |
| 657 |
_ = conn.whoami(timeout=0) |
| 658 |
with network_delay(6.1): |
| 659 |
with pytest.raises(bonsai.TimeoutError): |
| 660 |
_ = conn.whoami(timeout=3.2) |
| 661 |
|
| 662 |
|
| 663 |
def test_wrong_conn_param(): |
| 664 |
"""Test passing wrong parameters for LDAPConnection.""" |
| 665 |
with pytest.raises(TypeError): |
| 666 |
_ = LDAPConnection("wrong") |
| 667 |
with pytest.raises(TypeError): |
| 668 |
_ = LDAPConnection(1) |
| 669 |
|
| 670 |
|
| 671 |
def test_wrong_search_param(ipaddr): |
| 672 |
"""Test passing wrong parameters for search method.""" |
| 673 |
with pytest.raises(ClosedConnection): |
| 674 |
cli = LDAPClient("ldap://%s" % ipaddr) |
| 675 |
LDAPConnection(cli).search() |
| 676 |
with pytest.raises(ValueError): |
| 677 |
cli = LDAPClient("ldap://%s" % ipaddr) |
| 678 |
LDAPConnection(cli).open().search() |
| 679 |
with pytest.raises(TypeError): |
| 680 |
cli = LDAPClient("ldap://%s" % ipaddr) |
| 681 |
LDAPConnection(cli).open().search("", 0, 3) |
| 682 |
|
| 683 |
|
| 684 |
def test_wrong_add_param(conn, ipaddr): |
| 685 |
"""Test passing wrong parameter for add method.""" |
| 686 |
with pytest.raises(ClosedConnection): |
| 687 |
cli = LDAPClient("ldap://%s" % ipaddr) |
| 688 |
LDAPConnection(cli).add(bonsai.LDAPEntry("cn=dummy")) |
| 689 |
with pytest.raises(TypeError): |
| 690 |
conn.add("wrong") |
| 691 |
|
| 692 |
|
| 693 |
def test_wrong_delete_param(conn, ipaddr): |
| 694 |
"""Test passing wrong parameter for delete method.""" |
| 695 |
with pytest.raises(ClosedConnection): |
| 696 |
cli = LDAPClient("ldap://%s" % ipaddr) |
| 697 |
LDAPConnection(cli).delete("cn=dummy") |
| 698 |
with pytest.raises(TypeError): |
| 699 |
conn.delete(0) |
| 700 |
|
| 701 |
|
| 702 |
@pytest.mark.skipif( |
| 703 |
sys.platform == "win32", reason="Cannot use password policy on Windows." |
| 704 |
) |
| 705 |
def test_password_lockout(conn, ipaddr): |
| 706 |
"""Test password locking with password policy.""" |
| 707 |
user_dn = "cn=jeff,ou=nerdherd,dc=bonsai,dc=test" |
| 708 |
cli = LDAPClient("ldap://%s" % ipaddr) |
| 709 |
cli.set_password_policy(True) |
| 710 |
try: |
| 711 |
cli.set_credentials("SIMPLE", user_dn, "wrong_pass") |
| 712 |
test_conn, ctrl = cli.connect() |
| 713 |
except bonsai.errors.AuthenticationError: |
| 714 |
with pytest.raises(bonsai.errors.AccountLocked): |
| 715 |
cli.set_credentials("SIMPLE", user_dn, "p@ssword") |
| 716 |
test_conn, ctrl = cli.connect() |
| 717 |
finally: |
| 718 |
entry = conn.search(user_dn, 0, attrlist=["pwdAccountLockedTime"])[0] |
| 719 |
if "pwdAccountLockedTime" in entry.keys(): |
| 720 |
del entry["pwdAccountLockedTime"] |
| 721 |
entry.modify() |
| 722 |
|
| 723 |
|
| 724 |
@pytest.mark.skipif( |
| 725 |
sys.platform.startswith("win"), reason="Cannot use password policy on Windows." |
| 726 |
) |
| 727 |
def test_password_expire(conn, ipaddr): |
| 728 |
"""Test password expiring with password policy.""" |
| 729 |
user_dn = "cn=skip,ou=nerdherd,dc=bonsai,dc=test" |
| 730 |
cli = LDAPClient("ldap://%s" % ipaddr) |
| 731 |
cli.set_password_policy(True) |
| 732 |
cli.set_credentials("SIMPLE", user_dn, "p@ssword") |
| 733 |
test_conn, ctrl = cli.connect() |
| 734 |
entry = test_conn.search(user_dn, 0)[0] |
| 735 |
entry["userPassword"] = "newvalidpassword" |
| 736 |
entry.modify() |
| 737 |
test_conn.close() |
| 738 |
cli.set_credentials("SIMPLE", user_dn, "newvalidpassword") |
| 739 |
time.sleep(2.0) |
| 740 |
test_conn, ctrl = cli.connect() |
| 741 |
if not (ctrl["expire"] <= 10 and ctrl["expire"] > 0): |
| 742 |
pytest.fail("Expire time is in the wrong range (Expire: %d)." % ctrl["expire"]) |
| 743 |
test_conn.close() |
| 744 |
time.sleep(10) |
| 745 |
test_conn, ctrl = cli.connect() |
| 746 |
assert ctrl["grace"] == 1 |
| 747 |
test_conn.close() |
| 748 |
with pytest.raises(bonsai.errors.PasswordExpired): |
| 749 |
test_conn, ctrl = cli.connect() |
| 750 |
entry = conn.search(user_dn, 0, attrlist=["userPassword"])[0] |
| 751 |
entry["userPassword"] = "p@ssword" |
| 752 |
entry.modify() |
| 753 |
entry = conn.search(user_dn, 0, attrlist=["pwdChangeTime", "pwdGraceUseTime"])[0] |
| 754 |
if ("pwdChangeTime", "pwdGraceUseTime") in entry.keys(): |
| 755 |
del entry["pwdChangeTime"] |
| 756 |
del entry["pwdGraceUseTime"] |
| 757 |
entry.modify() |
| 758 |
|
| 759 |
|
| 760 |
@pytest.mark.skipif( |
| 761 |
sys.platform.startswith("win"), |
| 762 |
reason="Cannot use password modify extended operation on Windows.", |
| 763 |
) |
| 764 |
def test_password_modify_extop(conn, ipaddr): |
| 765 |
"""Test Password Modify extended operation.""" |
| 766 |
user_dn = LDAPDN("cn=skip,ou=nerdherd,dc=bonsai,dc=test") |
| 767 |
cli = LDAPClient("ldap://%s" % ipaddr) |
| 768 |
cli.set_credentials("SIMPLE", str(user_dn), "p@ssword") |
| 769 |
test_conn = cli.connect() |
| 770 |
with pytest.raises(TypeError): |
| 771 |
test_conn.modify_password(new_password=0) |
| 772 |
test_conn.modify_password(user_dn, "newpassword", "p@ssword") |
| 773 |
test_conn.close() |
| 774 |
with pytest.raises(ClosedConnection): |
| 775 |
test_conn.modify_password() |
| 776 |
try: |
| 777 |
cli.set_credentials("SIMPLE", str(user_dn), "newpassword") |
| 778 |
cli.set_password_policy(True) |
| 779 |
test_conn, ctrl = cli.connect() |
| 780 |
newpass = test_conn.modify_password() |
| 781 |
test_conn.close() |
| 782 |
assert isinstance(newpass, str) |
| 783 |
cli.set_credentials("SIMPLE", str(user_dn), newpass) |
| 784 |
test_conn, ctrl = cli.connect() |
| 785 |
test_conn.close() |
| 786 |
except bonsai.AuthenticationError: |
| 787 |
pytest.fail("Failed to authenticate with the new password.") |
| 788 |
finally: |
| 789 |
entry = conn.search(user_dn, 0, attrlist=["userPassword"])[0] |
| 790 |
entry["userPassword"] = "p@ssword" |
| 791 |
entry.modify() |
| 792 |
entry = conn.search(user_dn, 0, attrlist=["pwdChangeTime", "pwdGraceUseTime"])[ |
| 793 |
0 |
| 794 |
] |
| 795 |
if ("pwdChangeTime", "pwdGraceUseTime") in entry.keys(): |
| 796 |
del entry["pwdChangeTime"] |
| 797 |
del entry["pwdGraceUseTime"] |
| 798 |
entry.modify() |
| 799 |
|
| 800 |
|
| 801 |
@pytest.mark.skipif( |
| 802 |
sys.platform.startswith("win"), reason="Cannot use ManageDsaIT on Windows" |
| 803 |
) |
| 804 |
def test_search_with_managedsait_ctrl(ipaddr): |
| 805 |
"""Test searching with manageDsaIT control.""" |
| 806 |
refdn = LDAPDN("o=admin,ou=nerdherd-refs,dc=bonsai,dc=test") |
| 807 |
cli = LDAPClient("ldap://%s" % ipaddr) |
| 808 |
cli.set_server_chase_referrals(True) |
| 809 |
with cli.connect() as conn: |
| 810 |
res = conn.search(refdn, LDAPSearchScope.BASE, attrlist=["ref"])[0] |
| 811 |
assert str(res.dn) == "cn=admin,dc=bonsai,dc=test" |
| 812 |
cli.set_managedsait(True) |
| 813 |
with cli.connect() as conn: |
| 814 |
res = conn.search(refdn, LDAPSearchScope.BASE, attrlist=["ref"])[0] |
| 815 |
assert refdn == res.dn |
| 816 |
assert "ldap://bonsai.test/cn=admin,dc=bonsai,dc=test" == res["ref"][0] |
| 817 |
|
| 818 |
|
| 819 |
@pytest.mark.skipif( |
| 820 |
sys.platform.startswith("win"), reason="Cannot use ManageDsaIT on Windows" |
| 821 |
) |
| 822 |
def test_add_and_delete_referrals(cfg, ipaddr): |
| 823 |
"""Test add and delete an LDAP referral with ManageDdsIT control.""" |
| 824 |
refdn = bonsai.LDAPDN("o=test-ref,ou=nerdherd,dc=bonsai,dc=test") |
| 825 |
ref = "ldap://test.host/cn=nobody" |
| 826 |
cli = LDAPClient("ldap://%s" % ipaddr) |
| 827 |
cli.set_credentials( |
| 828 |
"SIMPLE", user=cfg["SIMPLEAUTH"]["user"], password=cfg["SIMPLEAUTH"]["password"] |
| 829 |
) |
| 830 |
cli.managedsait = True |
| 831 |
with cli.connect() as conn: |
| 832 |
entry = bonsai.LDAPEntry(refdn, conn) |
| 833 |
entry["objectClass"] = ["referral", "extensibleObject"] |
| 834 |
entry["o"] = "test-ref" |
| 835 |
entry["ref"] = ref |
| 836 |
conn.add(entry) |
| 837 |
res = conn.search(refdn, 0, attrlist=["ref"])[0] |
| 838 |
assert entry.dn == res.dn |
| 839 |
assert entry["ref"] == res["ref"] |
| 840 |
cli.managedsait = False |
| 841 |
with cli.connect() as conn: |
| 842 |
with pytest.raises(bonsai.LDAPError): |
| 843 |
conn.delete(entry.dn) |
| 844 |
cli.managedsait = True |
| 845 |
with cli.connect() as conn: |
| 846 |
conn.delete(entry.dn) |
| 847 |
res = conn.search(refdn, 0, attrlist=["ref"]) |
| 848 |
assert res == [] |
| 849 |
|
| 850 |
|
| 851 |
def test_client_sizelimit_error(conn, basedn): |
| 852 |
"""Test raising SizeLimitError when reaching client side size limit.""" |
| 853 |
with pytest.raises(SizeLimitError): |
| 854 |
conn.search( |
| 855 |
"ou=nerdherd,dc=bonsai,dc=test", LDAPSearchScope.SUBTREE, sizelimit=2 |
| 856 |
) |
| 857 |
|
| 858 |
|
| 859 |
def test_server_sizelimit_error(conn, anonym_conn, basedn, large_org): |
| 860 |
"""Test raising SizeLimitError when reaching server side size limit.""" |
| 861 |
import math |
| 862 |
|
| 863 |
entry_num = 1048 |
| 864 |
page_size = 4 |
| 865 |
org = large_org(conn, f"ou=limited,{basedn}", entry_num) |
| 866 |
with pytest.raises(SizeLimitError): |
| 867 |
anonym_conn.search(org.dn, 1) |
| 868 |
paged = anonym_conn.paged_search(org.dn, 1, page_size=page_size) |
| 869 |
page_num = 1 |
| 870 |
try: |
| 871 |
while True: |
| 872 |
msgid = paged.acquire_next_page() |
| 873 |
if msgid is None: |
| 874 |
break |
| 875 |
paged = anonym_conn.get_result(msgid) |
| 876 |
page_num += 1 |
| 877 |
except SizeLimitError as err: |
| 878 |
if sys.platform.startswith("win"): |
| 879 |
raise err |
| 880 |
expected = math.ceil(entry_num / page_size) |
| 881 |
expected = ( |
| 882 |
expected |
| 883 |
if sys.platform.startswith("win") |
| 884 |
else expected - (entry_num - 1024) / page_size |
| 885 |
) |
| 886 |
assert page_num == expected |
| 887 |
|
| 888 |
|
| 889 |
@pytest.mark.skipif( |
| 890 |
not sys.platform.startswith("win"), |
| 891 |
reason="Large page result test is tested only with AD", |
| 892 |
) |
| 893 |
def test_paged_search_large_result(conn, anonym_conn, basedn, large_org): |
| 894 |
page_size = 128 |
| 895 |
entry_num = 65535 |
| 896 |
org = large_org(conn, f"ou=large,{basedn}", entry_num) |
| 897 |
collected_entry = 0 |
| 898 |
result = anonym_conn.paged_search(org.dn, 1, page_size=page_size) |
| 899 |
while True: |
| 900 |
collected_entry += sum(1 for _ in result) |
| 901 |
msgid = result.acquire_next_page() |
| 902 |
if msgid is None: |
| 903 |
break |
| 904 |
result = anonym_conn.get_result(msgid) |
| 905 |
|
| 906 |
assert entry_num == collected_entry |