-
Notifications
You must be signed in to change notification settings - Fork 4
/
test_model.py
843 lines (653 loc) · 30.8 KB
/
test_model.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
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
import base64
import hashlib
import string
import time
from authlib import jose
import arrow
import flask
from keg.db import db
import pytest
from freezegun import freeze_time
import sqlalchemy as sa
import bcrypt
from keg_auth.model import InvalidToken, entity_registry, utils
from keg_auth_ta.model import entities as ents
from keg_auth.testing import with_crypto_context
import mock
class TestUserTokenMixin(object):
def setup_method(self):
ents.UserWithToken.delete_cascaded()
@with_crypto_context(ents.UserWithToken.token)
def test_token_storage_with_real_bcrypt(self):
raw_token = b'a' * 32
uwt = ents.UserWithToken.testing_create(token=raw_token)
assert bcrypt.checkpw(raw_token, uwt.token.hash)
@with_crypto_context(ents.UserWithToken.token)
def test_reset_auth_token(self):
original_token = b'a' * 32
uwt = ents.UserWithToken.testing_create(token=original_token)
assert bcrypt.checkpw(original_token, uwt.token.hash)
new_token = uwt.reset_auth_token()
assert bcrypt.checkpw(new_token.encode(), uwt.token.hash)
assert not bcrypt.checkpw(original_token, uwt.token.hash)
def test_generate_auth_token(self):
assert len(ents.UserWithToken.generate_raw_auth_token(length=1)) == 1
assert len(ents.UserWithToken.generate_raw_auth_token()) == 32
assert len(ents.UserWithToken.generate_raw_auth_token(entropy='secure')) == 32
assert len(ents.UserWithToken.generate_raw_auth_token(length=None, entropy='secure')) == 11
assert (string.ascii_uppercase not in
ents.UserWithToken.generate_raw_auth_token(charset='hex'))
@pytest.mark.parametrize('raw,test,result', [
('123', '123', True),
('123', 'abc', False),
('a' * 400, 'abc', False),
(b'abc', b'abc', True),
(b'abc', 'abc', True),
('abc', b'abc', True),
(None, b'abc', False),
('abc', None, False),
])
def test_verify_token(self, raw, test, result):
uwt = ents.UserWithToken.testing_create(token=raw)
assert uwt.verify_token(test) is result
def test_generate_api_token(self):
u1 = ents.UserWithToken.testing_create()
raw_token = u1.generate_api_token()
raw_email, token = raw_token.split('.')
real_email = base64.urlsafe_b64decode(raw_email.encode()).decode()
assert (real_email, token) == (u1.email, u1.token.hash.decode())
def test_get_user_for_api_token_happy_path(self):
u1 = ents.UserWithToken.testing_create(email='test@test.com', token='1234')
ents.UserWithToken.testing_create(email='test-2@test.com', token='5678')
u1_api_token = u1.generate_api_token('1234')
assert ents.UserWithToken.get_user_for_api_token(u1_api_token).id == u1.id
def test_get_user_for_api_token_wrong_token(self):
u1 = ents.UserWithToken.testing_create(email='test@test.com', token='1234')
ents.UserWithToken.testing_create(email='test-2@test.com', token='5678')
u1_api_token = u1.generate_api_token('1234')
u1_raw_email, u1_raw_token = u1_api_token.split('.')
u1_fake_token = '{email}.faketoken'.format(email=u1_raw_email)
assert ents.UserWithToken.get_user_for_api_token(u1_fake_token) is None
@pytest.mark.parametrize('token', [
None, # Bad
'test@testcom', # No period
'tes.t@te.stcom', # three periods
b'test@thing.token', # not b64encoded
])
def test_get_user_for_api_token_bad_token(self, token):
assert ents.UserWithToken.get_user_for_api_token(token) is None
class TestUser(object):
def setup_method(self):
ents.User.delete_cascaded()
ents.Permission.delete_cascaded()
def test_email_case_insensitive(self):
ents.User.testing_create(email='foo@BAR.com')
assert ents.User.get_by(email='foo@bar.com')
def test_is_verified_default(self):
# testing_create() overrides the is_enabled default to make testing easier. So, make sure
# that we have set enabled to False when not used in a testing environment.
user = ents.User.add(email='foo', password='bar')
assert not user.is_verified
assert user.password == 'bar'
@pytest.mark.parametrize('is_enabled, is_verified, disabled_utc, is_active', [
(True, True, None, True),
(True, True, arrow.utcnow().shift(minutes=+5), True),
(True, False, None, False),
(False, True, None, False),
(True, True, arrow.utcnow().shift(minutes=-5), False),
])
def test_is_active_python_attribute(self, is_enabled, is_verified, disabled_utc, is_active):
user = ents.User.testing_create(
is_verified=is_verified,
is_enabled=is_enabled,
disabled_utc=disabled_utc,
)
assert user.is_active == is_active
@pytest.mark.parametrize('is_enabled, is_verified, disabled_utc, is_active', [
(True, True, None, True),
(True, True, arrow.utcnow().shift(minutes=+5), True),
(True, False, None, False),
(False, True, None, False),
(True, True, arrow.utcnow().shift(minutes=-5), False),
])
def test_is_active_sql_expression(self, is_enabled, is_verified, disabled_utc, is_active):
ents.User.testing_create(
email='email',
is_verified=is_verified,
is_enabled=is_enabled,
disabled_utc=disabled_utc,
)
assert ents.User.query.filter_by(email='email', is_active=is_active).one()
def test_token_validation(self):
user = ents.User.testing_create()
assert not hasattr(user, '_token_plain')
assert not user.token_verify(None)
token = user.token_generate()
assert token
assert not user.token_verify('foo')
assert user.token_verify(token)
assert user.token_verify(user._token_plain)
def test_legacy_token(self):
"""
Mimic an itsdangerous token and validate it only verifies in legacy mode.
- sha1 signature instead of sha512
- iat/exp claims are in header, not payload
"""
user = ents.User.testing_create()
base_key = user.get_token_salt() + 'signer' + flask.current_app.config.get('SECRET_KEY')
signature = hashlib.sha1(base_key.encode()).digest()
now = int(time.time())
exp = now + (flask.current_app.config.get('KEGAUTH_TOKEN_EXPIRE_MINS') * 60)
header = {'alg': 'HS512', 'iat': now, 'exp': exp}
payload = {'user_id': user.id}
token = jose.jwt.encode(header, payload, signature)
assert user.token_verify(token)
assert not user.token_verify(token, _block_legacy=True)
def test_token_salt_info_changed(self):
def check_field(field, new_value):
user = ents.User.testing_create(last_login_utc=None)
token = user.token_generate()
setattr(user, field, new_value)
db.session.flush()
db.session.commit()
db.session.refresh(user)
assert not user.token_verify(token)
check_field('email', 'foobar')
check_field('is_enabled', False)
check_field('is_verified', False)
check_field('password', 'foobar')
check_field('last_login_utc', arrow.utcnow())
def test_token_expiration(self):
user = ents.User.add(email='foo', password='bar')
with mock.patch.dict(flask.current_app.config, KEGAUTH_TOKEN_EXPIRE_MINS=10):
token = user.token_generate()
now = arrow.get()
assert user.token_verify(token)
plus_9_58 = now.shift(minutes=9, seconds=58).datetime
with freeze_time(plus_9_58):
assert user.token_verify(token)
plus_10_01 = now.shift(minutes=10, seconds=1).datetime
with freeze_time(plus_10_01):
assert not user.token_verify(token)
def test_change_password(self):
user = ents.User.testing_create(is_verified=False)
token = user.token_generate()
user.change_password(token, 'abc123')
assert not user.token_verify(token)
assert user.password == 'abc123'
assert user.is_verified
def test_change_password_invalid_token(self):
user = ents.User.testing_create(is_verified=False)
with pytest.raises(InvalidToken):
user.change_password('bad-token', 'abc123')
def test_permissions_mapping(self):
perm1 = ents.Permission.testing_create()
perm2 = ents.Permission.testing_create()
perm3 = ents.Permission.testing_create()
perm4 = ents.Permission.testing_create()
perm5 = ents.Permission.testing_create()
bundle1 = ents.Bundle.testing_create()
bundle2 = ents.Bundle.testing_create()
bundle3 = ents.Bundle.testing_create()
group1 = ents.Group.testing_create()
group2 = ents.Group.testing_create()
group3 = ents.Group.testing_create()
user1 = ents.User.testing_create()
user2 = ents.User.testing_create()
# Directly assigned
user1.permissions = [perm1]
# Assigned via user bundle
bundle1.permissions = [perm2]
user1.bundles = [bundle1]
# Assigned via group
group1.permissions = [perm3]
# Assigned via group bundle
bundle2.permissions = [perm4]
group1.bundles = [bundle2]
user1.groups = [group1, group2]
assert user1.get_all_permissions() == {perm1, perm2, perm3, perm4}
assert user2.get_all_permissions() == set()
user2.permissions = [perm1, perm2]
group3.permissions = [perm2, perm3]
bundle3.permissions = [perm1, perm5]
group3.bundles = [bundle3]
user2.groups = [group3]
assert user1.get_all_permissions() == {perm1, perm2, perm3, perm4}
assert user2.get_all_permissions() == {perm1, perm2, perm3, perm5}
user1.is_superuser = True
assert user1.get_all_permissions() == {perm1, perm2, perm3, perm4, perm5}
def test_get_all_permission_tokens(self):
ents.Permission.delete_cascaded()
perm1 = ents.Permission.testing_create(token='perm-1')
perm2 = ents.Permission.testing_create(token='perm-2')
perm3 = ents.Permission.testing_create(token='perm-3')
user = ents.User.testing_create(permissions=[perm1, perm2, perm3])
assert user.get_all_permission_tokens() == {'perm-1', 'perm-2', 'perm-3'}
def test_get_all_permission_tokens_cached(self):
ents.Permission.delete_cascaded()
perm1 = ents.Permission.testing_create(token='perm-1')
perm2 = ents.Permission.testing_create(token='perm-2')
perm3 = ents.Permission.testing_create(token='perm-3')
user = ents.User.testing_create(permissions=[perm1, perm2])
# trigger the cache storage
assert user.get_all_permission_tokens() == {'perm-1', 'perm-2'}
# permissions in cache go stale
user.permissions = [perm1, perm2, perm3]
db.session.commit()
assert user.get_all_permission_tokens() == {'perm-1', 'perm-2'}
# reset the cache
delattr(user, '_permission_cache')
assert user.get_all_permission_tokens() == {'perm-1', 'perm-2', 'perm-3'}
def test_has_all_permissions(self):
ents.Permission.delete_cascaded()
perm1 = ents.Permission.testing_create(token='perm-1')
perm2 = ents.Permission.testing_create(token='perm-2')
ents.Permission.testing_create(token='perm-3')
user = ents.User.testing_create(permissions=[perm1, perm2])
assert user.has_all_permissions('perm-1', 'perm-2') is True
assert user.has_all_permissions('perm-1', 'perm-3') is False
assert user.has_all_permissions('perm-1') is True
assert user.has_all_permissions('perm-3') is False
def test_has_any_permission(self):
ents.Permission.delete_cascaded()
perm1 = ents.Permission.testing_create(token='perm-1')
perm2 = ents.Permission.testing_create(token='perm-2')
ents.Permission.testing_create(token='perm-3')
user = ents.User.testing_create(permissions=[perm1, perm2])
assert user.has_any_permission('perm-1', 'perm-2') is True
assert user.has_any_permission('perm-1', 'perm-3') is True
assert user.has_any_permission('perm-1') is True
assert user.has_any_permission('perm-3') is False
def test_superuser_update_resets_session_key(self):
user = ents.User.testing_create(is_superuser=True)
original_session_key = user.session_key
ents.User.edit(user.id, is_superuser=False)
db.session.expire(user)
assert user.session_key != original_session_key
def test_enabled_update_resets_session_key(self):
user = ents.User.testing_create(is_enabled=True)
original_session_key = user.session_key
ents.User.edit(user.id, is_enabled=False)
db.session.expire(user)
assert user.session_key != original_session_key
def test_permission_update_resets_session_key(self):
perm1 = ents.Permission.testing_create(token='perm-1')
perm2 = ents.Permission.testing_create(token='perm-2')
user = ents.User.testing_create(permissions=[perm1])
original_session_key = user.session_key
ents.User.edit(user.id, permissions=[perm2])
db.session.expire(user)
assert user.session_key != original_session_key
def test_group_update_resets_session_key(self):
group1 = ents.Group.testing_create(name='group-1')
group2 = ents.Group.testing_create(name='group-2')
user = ents.User.testing_create(groups=[group1])
original_session_key = user.session_key
ents.User.edit(user.id, groups=[group2])
db.session.expire(user)
assert user.session_key != original_session_key
def test_bundle_update_resets_session_key(self):
bundle1 = ents.Bundle.testing_create(name='bundle-1')
bundle2 = ents.Bundle.testing_create(name='bundle-2')
user = ents.User.testing_create(bundles=[bundle1])
original_session_key = user.session_key
ents.User.edit(user.id, bundles=[bundle2])
db.session.expire(user)
assert user.session_key != original_session_key
def test_non_permission_update_does_not_reset_session_key(self):
user = ents.User.testing_create()
original_session_key = user.session_key
ents.User.edit(user.id, email='foo@bar.baz')
db.session.expire(user)
assert user.session_key == original_session_key
def test_re_enabling_user_clears_disabled_utc(self):
user = ents.User.testing_create(disabled_utc=arrow.utcnow(), is_enabled=False)
ents.User.edit(user.id, is_enabled=True)
db.session.expire(user)
assert user.disabled_utc is None
def test_re_enabling_user_does_not_clear_disabled_utc_if_changed(self):
user = ents.User.testing_create(disabled_utc=arrow.utcnow().shift(days=-1), is_enabled=False)
ents.User.edit(user.id, is_enabled=True, disabled_utc=arrow.utcnow())
db.session.expire(user)
assert user.disabled_utc
def test_disabling_user_does_not_clear_disabled_utc(self):
user = ents.User.testing_create(disabled_utc=arrow.utcnow(), is_enabled=True)
ents.User.edit(user.id, is_enabled=False)
db.session.expire(user)
assert user.disabled_utc
class TestUserNoEmail(object):
def setup_method(self):
ents.UserNoEmail.delete_cascaded()
@pytest.mark.parametrize('is_enabled, disabled_utc, is_active', [
(True, None, True),
(True, arrow.utcnow().shift(minutes=+5), True),
(False, None, False),
(True, arrow.utcnow().shift(minutes=-5), False),
])
def test_is_active_python_attribute(self, is_enabled, disabled_utc, is_active):
user = ents.UserNoEmail.testing_create(
is_enabled=is_enabled,
disabled_utc=disabled_utc,
)
assert user.is_active == is_active
@pytest.mark.parametrize('is_enabled, disabled_utc, is_active', [
(True, None, True),
(True, arrow.utcnow().shift(minutes=+5), True),
(False, None, False),
(True, arrow.utcnow().shift(minutes=-5), False),
])
def test_is_active_sql_expression(self, is_enabled, disabled_utc, is_active):
ents.UserNoEmail.testing_create(
username='name',
is_enabled=is_enabled,
disabled_utc=disabled_utc,
)
assert ents.UserNoEmail.query.filter_by(username='name', is_active=is_active).one()
class TestPermission(object):
def setup_method(self):
ents.Permission.delete_cascaded()
def test_token_unique(self):
ents.Permission.testing_create(token='some-permission')
with pytest.raises(sa.exc.IntegrityError) as exc:
# use `add` here instead of `testing_create`, because it is more helpful for the
# `testing_create` method to return the existing permission if there is a match
ents.Permission.add(token='some-permission')
assert 'unique' in str(exc.value).lower()
class TestBundle(object):
def setup_method(self):
ents.Bundle.delete_cascaded()
def test_name_unique(self):
ents.Bundle.testing_create(name='Bundle 1')
with pytest.raises(sa.exc.IntegrityError) as exc:
ents.Bundle.testing_create(name='Bundle 1')
assert 'unique' in str(exc.value).lower()
def test_permission_update_resets_user_session_keys(self):
perm1 = ents.Permission.testing_create(token='perm-1')
perm2 = ents.Permission.testing_create(token='perm-2')
user = ents.User.testing_create()
bundle = ents.Bundle.testing_create(permissions=[perm1], users=[user])
original_session_key = user.session_key
ents.Bundle.edit(bundle.id, permissions=[perm2])
db.session.expire(user)
assert user.session_key != original_session_key
def test_permission_update_resets_group_user_session_keys(self):
perm1 = ents.Permission.testing_create(token='perm-1')
perm2 = ents.Permission.testing_create(token='perm-2')
user = ents.User.testing_create()
group = ents.Group.testing_create(users=[user])
bundle = ents.Bundle.testing_create(permissions=[perm1], groups=[group])
original_session_key = user.session_key
ents.Bundle.edit(bundle.id, permissions=[perm2])
db.session.expire(user)
assert user.session_key != original_session_key
def test_group_addition_resets_user_session_keys(self):
user = ents.User.testing_create()
group = ents.Group.testing_create(users=[user])
bundle = ents.Bundle.testing_create()
original_session_key = user.session_key
ents.Bundle.edit(bundle.id, groups=[group])
db.session.expire(user)
assert user.session_key != original_session_key
def test_group_removal_resets_user_session_keys(self):
user = ents.User.testing_create()
group = ents.Group.testing_create(users=[user])
bundle = ents.Bundle.testing_create(groups=[group])
original_session_key = user.session_key
ents.Bundle.edit(bundle.id, groups=[])
db.session.expire(user)
assert user.session_key != original_session_key
def test_user_addition_resets_user_session_keys(self):
user = ents.User.testing_create()
bundle = ents.Bundle.testing_create()
original_session_key = user.session_key
ents.Bundle.edit(bundle.id, users=[user])
db.session.expire(user)
assert user.session_key != original_session_key
def test_user_removal_resets_user_session_keys(self):
user = ents.User.testing_create()
bundle = ents.Bundle.testing_create(users=[user])
original_session_key = user.session_key
ents.Bundle.edit(bundle.id, users=[])
db.session.expire(user)
assert user.session_key != original_session_key
def test_bundle_removal_resets_user_session_keys(self):
user = ents.User.testing_create()
bundle = ents.Bundle.testing_create(users=[user])
original_session_key = user.session_key
ents.Bundle.delete(bundle.id)
db.session.expire(user)
assert user.session_key != original_session_key
def test_bundle_removal_resets_group_session_keys(self):
user = ents.User.testing_create()
group = ents.Group.testing_create(users=[user])
bundle = ents.Bundle.testing_create(groups=[group])
original_session_key = user.session_key
ents.Bundle.delete(bundle.id)
db.session.expire(user)
assert user.session_key != original_session_key
def test_non_permission_update_does_not_reset_user_session_keys(self):
user = ents.User.testing_create()
bundle = ents.Bundle.testing_create(users=[user])
original_session_key = user.session_key
ents.Bundle.edit(bundle.id, name='foo')
db.session.expire(user)
assert user.session_key == original_session_key
class TestGroup(object):
def setup_method(self):
ents.Group.delete_cascaded()
def test_name_unique(self):
ents.Group.testing_create(name='Group 1')
with pytest.raises(sa.exc.IntegrityError) as exc:
ents.Group.testing_create(name='Group 1')
assert 'unique' in str(exc.value).lower()
def test_get_all_permissions(self):
perm1 = ents.Permission.testing_create()
perm2 = ents.Permission.testing_create()
perm3 = ents.Permission.testing_create()
bundle = ents.Bundle.testing_create()
group1 = ents.Group.testing_create()
group2 = ents.Group.testing_create()
# Assigned directly
group1.permissions = [perm1]
# Assigned via bundle
bundle.permissions = [perm2]
group1.bundles = [bundle]
assert group1.get_all_permissions() == {perm1, perm2}
assert group2.get_all_permissions() == set()
group2.bundles = [bundle]
group2.permissions = [perm2, perm3]
assert group1.get_all_permissions() == {perm1, perm2}
assert group2.get_all_permissions() == {perm2, perm3}
def test_permission_update_resets_user_session_keys(self):
perm1 = ents.Permission.testing_create(token='perm-1')
perm2 = ents.Permission.testing_create(token='perm-2')
user = ents.User.testing_create()
original_session_key = user.session_key
group = ents.Group.testing_create(permissions=[perm1], users=[user])
ents.Group.edit(group.id, permissions=[perm2])
db.session.expire(user)
assert user.session_key != original_session_key
def test_bundle_update_resets_user_session_keys(self):
bundle1 = ents.Bundle.testing_create(name='bundle-1')
bundle2 = ents.Bundle.testing_create(name='bundle-2')
user = ents.User.testing_create()
original_session_key = user.session_key
group = ents.Group.testing_create(bundles=[bundle1], users=[user])
ents.Group.edit(group.id, bundles=[bundle2])
db.session.expire(user)
assert user.session_key != original_session_key
def test_user_addition_resets_user_session_keys(self):
user = ents.User.testing_create()
original_session_key = user.session_key
group = ents.Group.testing_create()
ents.Group.edit(group.id, users=[user])
db.session.expire(user)
assert user.session_key != original_session_key
def test_user_removal_resets_user_session_keys(self):
user = ents.User.testing_create()
original_session_key = user.session_key
group = ents.Group.testing_create(users=[user])
ents.Group.edit(group.id, users=[])
db.session.expire(user)
assert user.session_key != original_session_key
def test_group_removal_resets_user_session_keys(self):
user = ents.User.testing_create()
group = ents.Group.testing_create(users=[user])
original_session_key = user.session_key
ents.Group.delete(group.id)
db.session.expire(user)
assert user.session_key != original_session_key
def test_non_permission_update_does_not_reset_user_session_keys(self):
user = ents.User.testing_create()
group = ents.Group.testing_create(users=[user])
original_session_key = user.session_key
ents.Group.edit(group.id, name='foo')
db.session.expire(user)
assert user.session_key == original_session_key
class TestEntityRegistry(object):
def test_bad_type(self):
registry = entity_registry.EntityRegistry()
with pytest.raises(entity_registry.RegistryError):
registry.get_entity_cls('foo')
def test_entity_not_defined(self):
registry = entity_registry.EntityRegistry()
with pytest.raises(entity_registry.RegistryError):
registry.get_entity_cls('user')
def test_register_entities(self):
registry = entity_registry.EntityRegistry()
@registry.register_user
class TestingUser(object):
pass
@registry.register_permission
class TestingPermission(object):
pass
@registry.register_bundle
class TestingBundle(object):
pass
@registry.register_group
class TestingGroup(object):
pass
assert registry.user_cls is TestingUser
assert registry.permission_cls is TestingPermission
assert registry.bundle_cls is TestingBundle
assert registry.group_cls is TestingGroup
def test_duplicate_registration(self):
registry = entity_registry.EntityRegistry()
@registry.register_user
class TestingUser1(object):
pass
with pytest.raises(entity_registry.RegistryError) as exc:
@registry.register_user
class TestingUser2(object):
pass
assert str(exc.value) == 'Entity class already registered for user'
def test_register_unknown_type(self):
registry = entity_registry.EntityRegistry()
class Foo(object):
pass
with pytest.raises(entity_registry.RegistryError) as exc:
registry.register_entity('foo', Foo)
assert str(exc.value) == 'Attempting to register unknown type foo'
def test_register_nonclass(self):
registry = entity_registry.EntityRegistry()
with pytest.raises(entity_registry.RegistryError) as exc:
@registry.register_user
def testing_user():
pass
assert str(exc.value) == 'Entity must be a class'
with pytest.raises(entity_registry.RegistryError) as exc:
registry.register_user(ents.User.testing_create())
assert str(exc.value) == 'Entity must be a class'
def test_is_registered(self):
registry = entity_registry.EntityRegistry()
@registry.register_user
class TestingUser(object):
pass
@registry.register_permission
class TestingPermission(object):
pass
assert registry.is_registered('user') is True
assert registry.is_registered('permission') is True
assert registry.is_registered('bundle') is False
assert registry.is_registered('group') is False
class TestPermissionsConditions:
def setup_method(self):
ents.Permission.delete_cascaded()
ents.User.delete_cascaded()
def test_no_conditions(self):
with pytest.raises(ValueError):
utils.PermissionCondition()
def test_simple_string(self):
user = ents.User.testing_create(
permissions=[ents.Permission.testing_create(token='perm1')]
)
ents.Permission.testing_create(token='perm2')
assert utils.has_any('perm1').check(user) is True
assert utils.has_all('perm1').check(user) is True
assert utils.has_any('perm2').check(user) is False
assert utils.has_all('perm2').check(user) is False
def test_callable(self):
user1 = ents.User.testing_create(email='foo@bar.com')
user2 = ents.User.testing_create(email='abc@123.com')
def func(usr):
return usr.email.endswith('@bar.com')
assert utils.has_any(func).check(user1) is True
assert utils.has_all(func).check(user1) is True
assert utils.has_any(func).check(user2) is False
assert utils.has_all(func).check(user2) is False
def test_all(self):
user = ents.User.testing_create(
permissions=[
ents.Permission.testing_create(token='perm1'),
ents.Permission.testing_create(token='perm2'),
ents.Permission.testing_create(token='perm3'),
]
)
ents.Permission.testing_create(token='perm4')
assert utils.has_all('perm1').check(user) is True
assert utils.has_all('perm1', 'perm2').check(user) is True
assert utils.has_all('perm1', 'perm2', 'perm3').check(user) is True
assert utils.has_all('perm4').check(user) is False
assert utils.has_all('perm1', 'perm4').check(user) is False
assert utils.has_all('perm1', 'perm2', 'perm4').check(user) is False
def test_any(self):
user = ents.User.testing_create(
permissions=[ents.Permission.testing_create(token='perm1')]
)
ents.Permission.testing_create(token='perm2'),
ents.Permission.testing_create(token='perm3'),
ents.Permission.testing_create(token='perm4')
assert utils.has_any('perm1').check(user) is True
assert utils.has_any('perm1', 'perm2').check(user) is True
assert utils.has_any('perm1', 'perm2', 'perm3').check(user) is True
assert utils.has_any('perm2').check(user) is False
assert utils.has_any('perm2', 'perm3').check(user) is False
assert utils.has_any('perm2', 'perm3', 'perm4').check(user) is False
def test_nested(self):
user = ents.User.testing_create(
permissions=[
ents.Permission.testing_create(token='perm1'),
ents.Permission.testing_create(token='perm2'),
ents.Permission.testing_create(token='perm3'),
]
)
ents.Permission.testing_create(token='perm4')
condition = utils.has_any('perm4', utils.has_all('perm1', 'perm2'))
assert condition.check(user) is True
condition = utils.has_all(utils.has_any('perm1', 'perm2'), 'perm4')
assert condition.check(user) is False
condition = utils.has_all(utils.has_any('perm4', lambda _: True), 'perm1')
assert condition.check(user) is True
condition = utils.has_all(utils.has_any('perm4', lambda _: False), 'perm1')
assert condition.check(user) is False
"""class TestPerformance(object):
# check how long the SA events add to the process
def test_performance(self):
import time
start = time.time()
for _ in range(1000):
ents.User.testing_create()
ents.Group.testing_create()
ents.Bundle.testing_create()
assert False, time.time() - start
"""