forked from rroemhild/flask-ldapconn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_flask_ldapconn.py
559 lines (462 loc) · 20.2 KB
/
test_flask_ldapconn.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import ssl
import json
import time
import random
import string
import unittest
import flask
from ldap3 import SUBTREE, STRING_TYPES
from ldap3.core.exceptions import LDAPAttributeError, LDAPStartTLSError
from flask_ldapconn import LDAPConn
from flask_ldapconn.entry import LDAPEntry
from flask_ldapconn.attribute import LdapField
TESTING = True
USER_EMAIL = 'fry@planetexpress.com'
USER_PASSWORD = 'fry'
LDAP_SERVER = 'localhost'
LDAP_BINDDN = 'cn=admin,dc=planetexpress,dc=com'
LDAP_SECRET = 'GoodNewsEveryone'
LDAP_BASEDN = 'dc=planetexpress,dc=com'
LDAP_SEARCH_ATTR = 'mail'
LDAP_SEARCH_FILTER = '(mail=%s)' % USER_EMAIL
LDAP_QUERY_FILTER = 'email: %s' % USER_EMAIL
LDAP_TLS_VERSION = ssl.PROTOCOL_TLSv1
LDAP_REQUIRE_CERT = ssl.CERT_NONE
LDAP_AUTH_BASEDN = 'ou=people,dc=planetexpress,dc=com'
LDAP_AUTH_ATTR = 'mail'
LDAP_AUTH_SEARCH_FILTER = '(objectClass=inetOrgPerson)'
UID_SUFFIX = ''.join(random.choice(
string.ascii_lowercase + string.digits
) for _ in range(6))
def is_json(myjson):
try:
json.loads(myjson)
except (ValueError, TypeError):
return False
return True
class User(LDAPEntry):
# LDAP meta-data
base_dn = LDAP_AUTH_BASEDN
entry_rdn = ['cn', 'uid']
object_classes = ['inetOrgPerson']
# inetOrgPerson
name = LdapField('cn')
email = LdapField('mail')
title = LdapField('title')
userid = LdapField('uid')
surname = LdapField('sn')
givenname = LdapField('givenName')
class Account(User):
# LDAP meta-data
object_classes = ['posixAccount']
# posixAccount
uidnumber = LdapField('uidNumber')
gidnumber = LdapField('gidNumber')
shell = LdapField('loginShell')
home = LdapField('homeDirectory')
password = LdapField('userPassword')
class LDAPConnTestCase(unittest.TestCase):
def setUp(self):
app = flask.Flask(__name__)
app.config.from_object(__name__)
app.config.from_envvar('LDAP_SETTINGS', silent=True)
ldap = LDAPConn(app)
self.app = app
self.ldap = ldap
class LDAPConnSearchTestCase(LDAPConnTestCase):
def test_connection_search(self):
attr = self.app.config['LDAP_SEARCH_ATTR']
with self.app.test_request_context():
ldapc = self.ldap.connection
ldapc.search(self.app.config['LDAP_BASEDN'],
self.app.config['LDAP_SEARCH_FILTER'],
SUBTREE, attributes=[attr])
result = ldapc.result
response = ldapc.response
self.assertTrue(response)
self.assertEqual(response[0]['attributes'][attr][0],
self.app.config['USER_EMAIL'])
def test_whoami(self):
with self.app.test_request_context():
conn = self.ldap.connection
self.assertEqual(conn.extend.standard.who_am_i(),
'dn:{}'.format(self.app.config['LDAP_BINDDN']))
class LDAPConnModelTestCase(unittest.TestCase):
def setUp(self):
app = flask.Flask(__name__)
app.config.from_object(__name__)
app.config.from_envvar('LDAP_SETTINGS', silent=True)
ldap = LDAPConn(app)
self.app = app
self.ldap = ldap
self.user = User
def test_model_search(self):
with self.app.test_request_context():
entry = self.user.query.filter(
'email: %s' % self.app.config['USER_EMAIL']
).first()
self.assertEqual(entry.email,
self.app.config['USER_EMAIL'])
def test_model_search_set_attribute(self):
new_email = 'philip@planetexpress.com'
with self.app.test_request_context():
entry = self.user.query.filter(
'email: %s' % self.app.config['USER_EMAIL']
).first()
entry.email = new_email
self.assertEqual(entry.email, new_email)
def test_model_search_set_attribute_list(self):
new_email_list = ['philip@planetexpress.com',
'a.fry@planetexpress.com']
with self.app.test_request_context():
entry = self.user.query.filter(
'email: %s' % self.app.config['USER_EMAIL']
).first()
entry.email = new_email_list
self.assertEqual(entry.email, new_email_list)
def test_model_search_set_undefined_attr(self):
def new_model():
user = self.user(active='1')
with self.app.test_request_context():
self.assertRaises(LDAPAttributeError, new_model)
def test_model_new(self):
with self.app.test_request_context():
user = self.user(name='Rafael Römhild',
email='rafael@planetexpress.com')
self.assertEqual(user.email, 'rafael@planetexpress.com')
def test_model_fetch_entry(self):
uid = 'bender'
with self.app.test_request_context():
user = self.user.query.filter('userid: {}'.format(uid)).first()
self.assertEqual(user.userid, uid)
def test_model_fetch_entry_with_components_in_and_false(self):
uid = 'bender'
with self.app.test_request_context():
user = self.user.query.filter(
'email: {0}, userid: {0}'.format(uid)
).all(components_in_and=False)
self.assertEqual(user[0].userid, uid)
def test_model_fetch_entry_authenticate(self):
uid = 'fry'
with self.app.test_request_context():
user = self.user.query.filter('userid: {}'.format(uid)).first()
password = self.app.config['USER_PASSWORD']
self.assertTrue(user.authenticate(password))
def test_model_fetch_entry_exception(self):
uid = 'xyz'
with self.app.test_request_context():
user = self.user.query.filter('userid: {}'.format(uid)).first()
self.assertEqual(user, None)
def test_model_fetch_multible_entries(self):
expected_uids = ['bender', 'fry', 'hermes', 'leela', 'professor',
'zoidberg']
response_uids = []
query_filter = 'email: *@planetexpress.com'
with self.app.test_request_context():
entries = self.user.query.filter(query_filter).all()
for entry in entries:
response_uids.append(entry.userid)
matched_uids = set(expected_uids).intersection(response_uids)
self.assertEqual(len(expected_uids), len(matched_uids))
def test_model_get_dn(self):
dn = 'cn=Philip J. Fry,ou=people,dc=planetexpress,dc=com'
with self.app.test_request_context():
user = self.user.query.get(dn)
self.assertEqual(dn, user.dn)
def test_model_get_multivalued_rdn(self):
dn = 'cn=Amy Wong+sn=Kroker,ou=people,dc=planetexpress,dc=com'
with self.app.test_request_context():
user = self.user.query.get(dn)
self.assertEqual('Kroker', user.surname)
def test_model_get_attributes_dict(self):
with self.app.test_request_context():
user = self.user.query.filter('userid: bender').first()
attrs = ['name', 'email', 'userid']
attr_dict = user.get_attributes_dict()
self.assertTrue(isinstance(attr_dict, dict))
for attr in attrs:
self.assertTrue(isinstance(attr_dict[attr], list))
def test_model_to_json(self):
with self.app.test_request_context():
user = self.user.query.filter('userid: bender').first()
self.assertTrue(is_json(user.to_json()))
def test_model_to_json_str_values(self):
with self.app.test_request_context():
user = self.user.query.filter('userid: bender').first()
self.assertTrue(is_json(user.to_json(str_values=True)))
def test_model_iter(self):
with self.app.test_request_context():
user = self.user.query.filter('userid: bender').first()
for name, field in user._fields.items():
self.assertTrue(isinstance(field, self.ldap.Attribute))
def test_model_contains(self):
with self.app.test_request_context():
user = self.user.query.filter('userid: bender').first()
self.assertTrue(hasattr(user, 'userid'))
def test_model_getarr_att_not_found(self):
with self.app.test_request_context():
user = self.user.query.filter('userid: bender').first()
self.assertFalse(hasattr(user, 'active'))
def test_model_setattr(self):
with self.app.test_request_context():
user = self.user.query.filter('userid: fry').first()
user.userid = 'xyz'
self.assertEqual(user.userid, 'xyz')
def test_model_attribute_str(self):
with self.app.test_request_context():
user = self.user.query.filter('userid: fry').first()
self.assertTrue(isinstance(user.userid, STRING_TYPES))
def test_model_attribute_value_force_list(self):
with self.app.test_request_context():
self.app.config['FORCE_ATTRIBUTE_VALUE_AS_LIST'] = True
user = self.user.query.filter('userid: fry').first()
self.assertTrue(isinstance(user.userid, list))
def test_model_attribute_iter(self):
with self.app.test_request_context():
user = self.user.query.filter('userid: professor').first()
self.assertTrue(isinstance(user.email, list))
for mail in user.email:
pass
def test_model_operation_add(self):
uid = 'rafael-{}'.format(UID_SUFFIX)
query_filter = 'userid: {}'.format(uid)
with self.app.test_request_context():
new_user = self.user(name='Rafael Römhild',
userid=uid,
email='rafael@planetexpress.com',
surname='Römhild',
givenname='Raphael')
self.assertTrue(new_user.save())
user = self.user.query.filter(query_filter).first()
self.assertEqual(new_user.userid, user.userid)
def test_model_operation_modify(self):
uid = 'rafael-{}'.format(UID_SUFFIX)
query_filter = 'userid: {}'.format(uid)
with self.app.test_request_context():
mod_user = self.user.query.filter(query_filter).first()
mod_user.givenname = 'Rafael'
mod_user.title = 'SysAdmin'
mod_user.email = [mod_user.email, 'it@planetexpress.co']
self.assertTrue(mod_user.save())
user = self.user.query.filter(query_filter).first()
self.assertEqual(user.givenname, 'Rafael')
self.assertEqual(user.surname, u'Römhild')
self.assertEqual(user.title, 'SysAdmin')
self.assertTrue('it@planetexpress.co' in user.email)
def test_model_operation_remove(self):
uid = 'rafael-{}'.format(UID_SUFFIX)
query_filter = 'userid: {}'.format(uid)
with self.app.test_request_context():
user = self.user.query.filter(query_filter).first()
self.assertTrue(user.delete())
user = self.user.query.filter(query_filter).first()
self.assertEqual(user, None)
class LDAPConnModelInheritanceTestCase(unittest.TestCase):
def setUp(self):
app = flask.Flask(__name__)
app.config.from_object(__name__)
app.config.from_envvar('LDAP_SETTINGS', silent=True)
ldap = LDAPConn(app)
self.app = app
self.ldap = ldap
self.user = Account
def test_model_operation_add(self):
uid = 'rafael-{}'.format(UID_SUFFIX)
query_filter = 'userid: {}'.format(uid)
with self.app.test_request_context():
new_user = self.user(name='Rafael Römhild',
userid=uid,
email='rafael@planetexpress.com',
surname='Römhild',
givenname='Raphael',
uidnumber=1000,
gidnumber=1000,
shell='/bin/false',
home='/home/' + uid)
self.assertTrue(new_user.save())
user = self.user.query.filter(query_filter).first()
self.assertEqual(new_user.userid, user.userid)
def test_model_operation_modify(self):
uid = 'rafael-{}'.format(UID_SUFFIX)
query_filter = 'userid: {}'.format(uid)
with self.app.test_request_context():
mod_user = self.user.query.filter(query_filter).first()
mod_user.givenname = 'Rafael'
mod_user.title = 'SysAdmin'
mod_user.shell = '/bin/bash'
mod_user.email = [mod_user.email, 'it@planetexpress.co']
self.assertTrue(mod_user.save())
user = self.user.query.filter(query_filter).first()
self.assertEqual(user.givenname, 'Rafael')
self.assertEqual(user.surname, u'Römhild')
self.assertEqual(user.title, 'SysAdmin')
self.assertTrue('it@planetexpress.co' in user.email)
def test_model_operation_remove(self):
uid = 'rafael-{}'.format(UID_SUFFIX)
query_filter = 'userid: {}'.format(uid)
with self.app.test_request_context():
user = self.user.query.filter(query_filter).first()
self.assertTrue(user.delete())
user = self.user.query.filter(query_filter).first()
self.assertEqual(user, None)
class LDAPConnAuthTestCase(LDAPConnTestCase):
def test_authenticate_user(self):
with self.app.test_request_context():
retval = self.ldap.authenticate(
username=self.app.config['USER_EMAIL'],
password=self.app.config['USER_PASSWORD'],
base_dn=self.app.config['LDAP_AUTH_BASEDN'],
attribute=self.app.config['LDAP_SEARCH_ATTR'],
)
self.assertTrue(retval)
def test_authenticate_user_with_dn(self):
dn = 'cn=Philip J. Fry,ou=people,dc=planetexpress,dc=com'
with self.app.test_request_context():
retval = self.ldap.authenticate(
username=dn,
password=self.app.config['USER_PASSWORD'],
)
self.assertTrue(retval)
def test_authenticate_user_basedn_filter(self):
with self.app.test_request_context():
retval = self.ldap.authenticate(
username=self.app.config['USER_EMAIL'],
password=self.app.config['USER_PASSWORD'],
attribute=self.app.config['LDAP_SEARCH_ATTR'],
base_dn=self.app.config['LDAP_AUTH_BASEDN'],
search_filter=self.app.config['LDAP_AUTH_SEARCH_FILTER']
)
self.assertTrue(retval)
def test_authenticate_user_invalid_credentials(self):
with self.app.test_request_context():
retval = self.ldap.authenticate(
username=self.app.config['USER_EMAIL'],
password='testpass',
attribute=self.app.config['LDAP_SEARCH_ATTR'],
base_dn=self.app.config['LDAP_AUTH_BASEDN'],
)
self.assertFalse(retval)
def test_authenticate_user_invalid_search_filter(self):
with self.app.test_request_context():
retval = self.ldap.authenticate(
username=self.app.config['USER_EMAIL'],
password=self.app.config['USER_PASSWORD'],
attribute=self.app.config['LDAP_SEARCH_ATTR'],
base_dn=self.app.config['LDAP_AUTH_BASEDN'],
search_filter='x=y'
)
self.assertFalse(retval)
def test_authenticate_user_search_filter_no_result(self):
with self.app.test_request_context():
retval = self.ldap.authenticate(
username=self.app.config['USER_EMAIL'],
password=self.app.config['USER_PASSWORD'],
attribute=self.app.config['LDAP_SEARCH_ATTR'],
base_dn=self.app.config['LDAP_AUTH_BASEDN'],
search_filter='(uidNumber=*)'
)
self.assertFalse(retval)
class LDAPConnSSLTestCase(unittest.TestCase):
def setUp(self):
app = flask.Flask(__name__)
app.config.from_object(__name__)
app.config.from_envvar('LDAP_SETTINGS', silent=True)
app.config['LDAP_PORT'] = app.config.get('LDAP_SSL_PORT', 636)
app.config['LDAP_USE_SSL'] = True
ldap = LDAPConn(app)
self.app = app
self.ldap = ldap
def test_whoami(self):
with self.app.test_request_context():
conn = self.ldap.connection
self.assertEqual(conn.extend.standard.who_am_i(),
'dn:{}'.format(self.app.config['LDAP_BINDDN']))
class LDAPConnAnonymousTestCase(unittest.TestCase):
def setUp(self):
app = flask.Flask(__name__)
app.config.from_object(__name__)
app.config.from_envvar('LDAP_SETTINGS', silent=True)
app.config['LDAP_BINDDN'] = None
app.config['LDAP_SECRET'] = None
ldap = LDAPConn(app)
self.app = app
self.ldap = ldap
def test_whoami(self):
with self.app.test_request_context():
conn = self.ldap.connection
self.assertEqual(conn.extend.standard.who_am_i(), None)
class LDAPConnTLSCertRequiredTestCase(unittest.TestCase):
def setUp(self):
app = flask.Flask(__name__)
app.config.from_object(__name__)
app.config.from_envvar('LDAP_SETTINGS', silent=True)
app.config['LDAP_BINDDN'] = None
app.config['LDAP_SECRET'] = None
app.config['LDAP_REQUIRE_CERT'] = ssl.CERT_REQUIRED
ldap = LDAPConn(app)
self.app = app
self.ldap = ldap
def connect(self):
return self.ldap.connection
def test_connection(self):
with self.app.test_request_context():
self.assertRaises(LDAPStartTLSError, self.connect)
class LDAPConnNoTLSAnonymousTestCase(unittest.TestCase):
def setUp(self):
app = flask.Flask(__name__)
app.config.from_object(__name__)
app.config.from_envvar('LDAP_SETTINGS', silent=True)
app.config['LDAP_BINDDN'] = None
app.config['LDAP_SECRET'] = None
app.config['LDAP_USE_TLS'] = False
ldap = LDAPConn(app)
self.app = app
self.ldap = ldap
def test_whoami(self):
with self.app.test_request_context():
conn = self.ldap.connection
self.assertEqual(conn.extend.standard.who_am_i(), None)
class LDAPConnDeprecatedTestCase(LDAPConnTestCase):
def test_connection_search(self):
attr = self.app.config['LDAP_SEARCH_ATTR']
with self.app.test_request_context():
self.ldap.search(self.app.config['LDAP_BASEDN'],
self.app.config['LDAP_SEARCH_FILTER'],
SUBTREE, attributes=[attr])
result = self.ldap.result()
response = self.ldap.response()
self.assertTrue(response)
self.assertEqual(response[0]['attributes'][attr][0],
self.app.config['USER_EMAIL'])
def test_whoami_deprecated(self):
with self.app.test_request_context():
whoami = self.ldap.whoami()
self.assertEqual(whoami,
'dn:{}'.format(self.app.config['LDAP_BINDDN']))
if __name__ == '__main__':
success = False
try:
import docker
client = docker.from_env()
container = client.containers.run('rroemhild/test-openldap',
ports={'389/tcp': 389,
'636/tcp': 636},
detach=True,
privileged=True,
remove=True)
print('Docker container {0} started'.format(container.id))
print('Wait 3 seconds until slapd is started...')
time.sleep(3)
print('Run unit test...')
runner = unittest.main(exit=False)
success = runner.result.wasSuccessful()
print('Stop and removing container...')
container.stop()
except (ImportError, ValueError):
print('Can\'t run docker image. Try to run tests without.')
unittest.main()
if success is not True:
sys.exit(1)