Debian Codegraph @

tests/test_ldapclient.py

raw symbols SCIP
1 import sys
2
3 import pytest
4 from conftest import get_config, network_delay
5
6 import bonsai
7 from bonsai import LDAPClient
8 from bonsai.ldapconnection import LDAPConnection
9
10
11 @pytest.fixture(scope="module")
12 def url():
13 """Get the LDAPURL."""
14 cfg = get_config()
15 url = "ldap://%s:%s" % (cfg["SERVER"]["hostip"], cfg["SERVER"]["port"])
16 return bonsai.LDAPURL(url)
17
18
19 @pytest.fixture(scope="module")
20 def ldaps_url():
21 """Get the LDAPURL for LDAP over TLS."""
22 cfg = get_config()
23 url = "ldaps://%s" % (cfg["SERVER"]["hostname"])
24 return bonsai.LDAPURL(url)
25
26
27 def test_ldapurl(url):
28 """Test setting LDAPURL."""
29 cli = LDAPClient(url)
30 assert cli.url == url
31 with pytest.raises(TypeError):
32 _ = LDAPClient(None)
33 cli.url = "ldap://localhost"
34 assert cli.url == "ldap://localhost"
35
36
37 def test_connect(client):
38 """Test connect method."""
39 assert client.connect() is not None
40
41
42 def test_rootdse(client):
43 """Test receiving root DSE."""
44 root_dse = client.get_rootDSE()
45 assert root_dse["supportedLDAPVersion"][0] == 3
46
47
48 def test_raw_attributes(client):
49 """Test setting raw attributes to keep in bytearray format."""
50 with pytest.raises(TypeError):
51 client.set_raw_attributes([5])
52 with pytest.raises(ValueError):
53 client.raw_attributes = ["ou", "cn", "ou"]
54 client.set_raw_attributes(["ou"])
55 conn = client.connect()
56 result = conn.search("ou=nerdherd,dc=bonsai,dc=test", 0)[0]
57 assert isinstance(result["ou"][0], bytes)
58 assert not isinstance(result["objectClass"][0], bytes)
59
60
61 def test_set_credentials(url):
62 """Test set_credentials method, mechanism and credentials properties."""
63 client = LDAPClient(url)
64 with pytest.raises(TypeError):
65 client.set_credentials(2323, user=None)
66 with pytest.raises(TypeError):
67 client.set_credentials("Simple", "Name", 2, None, None)
68 with pytest.raises(TypeError):
69 client.set_credentials(
70 "Simple", user="name", password="password", keytab="./keytab"
71 )
72 client.set_credentials("SIMPLE", "cn=admin", "password")
73 assert client.mechanism == "SIMPLE"
74 assert client.credentials == {
75 "user": "cn=admin",
76 "password": "password",
77 "realm": None,
78 "authz_id": None,
79 "keytab": None,
80 }
81 client.set_credentials("EXTERNAL", authz_id="authzid")
82 assert client.credentials["authz_id"] == "authzid"
83
84
85 def test_vendor_info():
86 """Test vendor information."""
87 info = bonsai.get_vendor_info()
88 assert len(info) == 2
89 assert isinstance(info[0], str)
90 assert isinstance(info[1], int)
91
92
93 def test_tls_impl_name():
94 """Test TLS implementation name."""
95 tls_impl = bonsai.get_tls_impl_name()
96 assert tls_impl in ("GnuTLS", "MozNSS", "OpenSSL", "SChannel")
97
98
99 def test_debug():
100 """Test setting debug mode."""
101 import subprocess
102
103 code = "import bonsai; bonsai.set_debug(True); bonsai.LDAPClient('ldap://a.com').connect()"
104 try:
105 output = subprocess.check_output(
106 [sys.executable, "-c", code], universal_newlines=True
107 )
108 except subprocess.CalledProcessError as exc:
109 output = exc.output
110 assert "DBG: ldapconnection_new " in output
111
112
113 @pytest.mark.timeout(18)
114 def test_connection_timeout(client):
115 """Test connection timeout."""
116 with pytest.raises(TypeError):
117 _ = client.connect(timeout="Wrong")
118 with pytest.raises(ValueError):
119 _ = client.connect(timeout=-1.5)
120 with pytest.raises(bonsai.TimeoutError):
121 _ = client.connect(timeout=0)
122 with network_delay(9.0):
123 with pytest.raises(bonsai.TimeoutError):
124 client.connect(timeout=5.0)
125
126
127 def test_ppolicy(url):
128 """Test password policy setting."""
129 client = LDAPClient(url)
130 with pytest.raises(TypeError):
131 client.set_password_policy("F")
132 client.password_policy = True
133 client.set_credentials(
134 "SIMPLE", "cn=chuck,ou=nerdherd,dc=bonsai,dc=test", "p@ssword"
135 )
136 ret_val = client.connect()
137 assert isinstance(ret_val, tuple)
138 assert isinstance(ret_val[0], LDAPConnection)
139 if ret_val[1] is None:
140 pass # Password policy is not supported.
141 elif isinstance(ret_val[1], dict):
142 assert "oid" in ret_val[1].keys()
143 assert "expire" in ret_val[1].keys()
144 assert "grace" in ret_val[1].keys()
145 assert "1.3.6.1.4.1.42.2.27.8.5.1" == ret_val[1]["oid"]
146 else:
147 pytest.fail("Invalid second object in the tuple.")
148 ret_val[0].close()
149
150
151 def test_extended_dn(url):
152 """Test extended dn control."""
153 client = LDAPClient(url)
154 with pytest.raises(TypeError):
155 client.set_extended_dn("A")
156 with pytest.raises(ValueError):
157 client.set_extended_dn(2)
158 client.extended_dn_format = 0
159 assert client.extended_dn_format == 0
160 conn = client.connect()
161 root_dse = client.get_rootDSE()
162 result = conn.search("ou=nerdherd,dc=bonsai,dc=test", 0)[0]
163 if "1.2.840.113556.1.4.529" in root_dse["supportedControl"]:
164 assert result.extended_dn is not None
165 assert result.extended_dn.split(";")[-1] == str(result.dn)
166 else:
167 assert result.extended_dn is None
168
169
170 def test_readonly_attributes(client):
171 """Test read-only attributes of LDAPClient."""
172 with pytest.raises(AttributeError):
173 client.mechanism = "SIMPLE"
174 with pytest.raises(AttributeError):
175 client.credentials = {"user": "test", "password": "test"}
176 with pytest.raises(AttributeError):
177 client.tls = False
178
179
180 def test_auto_acquire_prop(client):
181 """Test auto_page_acquire property."""
182 with pytest.raises(TypeError):
183 client.set_auto_page_acquire("A")
184 assert client.auto_page_acquire
185 client.auto_page_acquire = False
186 assert not client.auto_page_acquire
187
188
189 def test_server_chase_referrals(client):
190 """Test server_chase_referrals property."""
191 with pytest.raises(TypeError):
192 client.set_server_chase_referrals(2)
193 assert client.server_chase_referrals == False
194 client.server_chase_referrals = True
195 assert client.server_chase_referrals
196
197
198 def test_ignore_referrals(client):
199 """Test ignore_referrals property."""
200 with pytest.raises(TypeError):
201 client.set_ignore_referrals("A")
202 assert client.ignore_referrals
203 client.ignore_referrals = False
204 assert not client.ignore_referrals
205
206
207 def test_managedsait(client):
208 """Test managedsait property."""
209 with pytest.raises(TypeError):
210 client.set_managedsait("B")
211 assert not client.managedsait
212 client.managedsait = True
213 assert client.managedsait
214
215
216 @pytest.mark.skipif(
217 get_config()["SERVER"]["has_tls"] == "False", reason="TLS is not set"
218 )
219 def test_ldap_over_tls(ldaps_url):
220 """Test LDAP over TLS connection."""
221 client = LDAPClient(ldaps_url)
222 client.set_cert_policy("ALLOW")
223 client.set_ca_cert(None)
224 client.set_ca_cert_dir(None)
225 try:
226 conn = client.connect()
227 assert conn is not None
228 conn.close()
229 except Exception as exc:
230 pytest.fail("TLS connection is failed with: %s" % str(exc))
231
232
233 @pytest.mark.skipif(
234 get_config()["SERVER"]["has_tls"] == "False", reason="TLS is not set"
235 )
236 def test_starttls(url):
237 """Test STARTTLS connection."""
238 client = LDAPClient(url, True)
239 client.set_cert_policy("ALLOW")
240 client.set_ca_cert(None)
241 client.set_ca_cert_dir(None)
242 try:
243 conn = client.connect()
244 assert conn is not None
245 conn.close()
246 except Exception as exc:
247 pytest.fail("TLS connection is failed with: %s" % str(exc))
248
249
250 @pytest.mark.skipif(
251 get_config()["SERVER"]["has_tls"] == "False", reason="TLS is not set"
252 )
253 @pytest.mark.timeout(18)
254 def test_tls_timeout(url):
255 """Test TLS connection timeout."""
256 client = LDAPClient(url, True)
257 client.set_cert_policy("ALLOW")
258 client.set_ca_cert(None)
259 client.set_ca_cert_dir(None)
260 with network_delay(9.0):
261 with pytest.raises(bonsai.TimeoutError):
262 client.connect(timeout=5.0)
263
264
265 @pytest.mark.skipif(
266 sys.platform != "linux", reason="No IPC support on Windows or Mac with Docker"
267 )
268 def test_ldapi():
269 """Test making connection via IPC."""
270 client = LDAPClient("ldapi://%2Ftmp%2Fbonsai%2Fldapi")
271 assert client.connect() is not None
272
273
274 def test_set_sasl_sec_properties(url):
275 client = LDAPClient(url)
276 with pytest.raises(TypeError):
277 client.set_sasl_security_properties(no_anonymous="false")
278 with pytest.raises(TypeError):
279 client.set_sasl_security_properties(no_anonymous=True, no_dict="false")
280 with pytest.raises(TypeError):
281 client.set_sasl_security_properties(no_anonymous=True, no_plain=0)
282 with pytest.raises(TypeError):
283 client.set_sasl_security_properties(
284 no_anonymous=True, no_plain=True, forward_sec=-2
285 )
286 with pytest.raises(TypeError):
287 client.set_sasl_security_properties(
288 no_anonymous=True, no_plain=True, min_ssf="aas"
289 )
290 with pytest.raises(TypeError):
291 client.set_sasl_security_properties(max_ssf="false")
292 with pytest.raises(TypeError):
293 client.set_sasl_security_properties(max_bufsize=0.5)
294 with pytest.raises(ValueError):
295 client.set_sasl_security_properties(min_ssf=-123)
296 with pytest.raises(ValueError):
297 client.set_sasl_security_properties(max_ssf=-1)
298 with pytest.raises(ValueError):
299 client.set_sasl_security_properties(max_bufsize=-1)
300 client.set_sasl_security_properties(no_anonymous=True)
301 assert client.sasl_security_properties == "noanonymous"
302 client.set_sasl_security_properties(no_anonymous=True, no_plain=True)
303 assert client.sasl_security_properties == "noanonymous,noplain"
304 client.set_sasl_security_properties(
305 no_anonymous=True, no_plain=True, forward_sec=True
306 )
307 assert client.sasl_security_properties == "noanonymous,noplain,forwardsec"
308 client.set_sasl_security_properties(no_plain=True, pass_cred=True)
309 assert client.sasl_security_properties == "noplain,passcred"
310 client.set_sasl_security_properties(max_ssf=128)
311 assert client.sasl_security_properties == "maxssf=128"
312 client.set_sasl_security_properties(no_plain=True, max_ssf=128)
313 assert client.sasl_security_properties == "noplain,maxssf=128"
314 client.set_sasl_security_properties(
315 no_anonymous=True,
316 no_dict=True,
317 no_plain=True,
318 forward_sec=True,
319 pass_cred=True,
320 min_ssf=16,
321 max_ssf=1024,
322 max_bufsize=2048,
323 )
324 assert (
325 client.sasl_security_properties
326 == "noanonymous,nodict,noplain,forwardsec,passcred,minssf=16,maxssf=1024,maxbufsize=2048"
327 )
328 with client.connect() as conn:
329 assert conn is not None