forked from privacyidea/privacyidea
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_api_lib_policy.py
1345 lines (1182 loc) · 54.6 KB
/
test_api_lib_policy.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
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
This test file tests the api.lib.policy.py
The api.lib.policy.py depends on lib.policy and on flask!
"""
import json
from .base import (MyTestCase, PWFILE)
from privacyidea.lib.policy import (set_policy, delete_policy,
PolicyClass, SCOPE, ACTION, REMOTE_USER,
AUTOASSIGNVALUE)
from privacyidea.api.lib.prepolicy import (check_token_upload,
check_base_action, check_token_init,
check_max_token_user,
check_anonymous_user,
check_max_token_realm, set_realm,
init_tokenlabel, init_random_pin,
init_token_defaults,
encrypt_pin, check_otp_pin,
check_external, api_key_required,
mangle, is_remote_user_allowed,
required_email)
from privacyidea.api.lib.postpolicy import (check_serial, check_tokentype,
no_detail_on_success,
no_detail_on_fail, autoassign,
offline_info, sign_response,
get_webui_settings)
from privacyidea.lib.token import (init_token, get_tokens, remove_token,
set_realms, check_user_pass, unassign_token)
from privacyidea.lib.user import User
from flask import Response, Request, g, current_app
from werkzeug.test import EnvironBuilder
from privacyidea.lib.error import PolicyError, RegistrationError
from privacyidea.lib.machineresolver import save_resolver
from privacyidea.lib.machine import attach_token
from privacyidea.lib.auth import ROLE
import jwt
from datetime import datetime, timedelta
HOSTSFILE = "tests/testdata/hosts"
SSHKEY = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQDO1rx366cmSSs/89j" \
"/0u5aEiXa7bYArHn7zFNCBaVnDUiK9JDNkpWBj2ucbmOpDKWzH0Vl3in21E" \
"8BaRlq9AobASG0qlEqlnwrYwlH+vcYp6td4QBoh3sOelzhyrJFug9dnfe8o7" \
"0r3IL4HIbdQOdh1b8Ogi7aL01V/eVE9RgGfTNHUzuYRMUL3si4dtqbCsSjFZ" \
"6dN1nnVhos9cSphPr7pQEbq8xW0uxzOGrFDY9g1NSOleA8bOjsCT9k+3X4R7" \
"00iVGvpzWkKopcWrzXJDIa3yxylAMOM0c3uO9U3NLfRsucvcQ5Cs8S6ctM30" \
"8cua3t5WaBOsr3RyoXs+cHIPIkXnJHg03HsnWONaGxl8VPymC9s3P0zVwm2jMFx" \
"JD9WbBqep7Dwc5unxLOSKidKrnNflQiMyiIv+5dY5lhc0YTJdktC2Scse64ac2E" \
"7ldjG3bJuKSIWAz8Sd1km4ZJWWIx8NlpC9AfbHcgMyFUDniV1EtFIaSQLPspIk" \
"thzIMqPTpKblzdRZP37mPu/FpwfYG4S+F34dCmJ4BipslsVcqgCFJQHoAYAJc4N" \
"Dq5IRDQqXH2KybHpSLATnbSY7zjVD+evJeU994yTaXTFi5hBmd0aWTC+ph79mmE" \
"tu3dokA2YbLa7uWkAIXvX/HHauGLMTyCOpYi1BxN47c/kccxyNg" \
"jPw== corny@schnuck"
class PrePolicyDecoratorTestCase(MyTestCase):
def test_01_check_token_action(self):
g.logged_in_user = {"username": "admin1",
"role": "admin"}
builder = EnvironBuilder(method='POST',
data={'serial': "OATH123456"},
headers={})
env = builder.get_environ()
# Set the remote address so that we can filter for it
env["REMOTE_ADDR"] = "10.0.0.1"
g.client_ip = env["REMOTE_ADDR"]
req = Request(env)
req.all_data = {"serial": "SomeSerial"}
# Set a policy, that does allow the action
set_policy(name="pol1",
scope=SCOPE.ADMIN,
action="enable", client="10.0.0.0/8")
g.policy_object = PolicyClass()
# Action enable is cool
r = check_base_action(request=req, action="enable")
self.assertTrue(r)
# Another action - like "disable" - is not allowed
# An exception is
self.assertRaises(PolicyError,
check_base_action, req, "disable")
# Action delete is not allowed
self.assertRaises(PolicyError,
check_base_action, req, "delete")
# check action with a token realm
set_policy(name="pol1",
scope=SCOPE.ADMIN,
action="enable", client="10.0.0.0/8",
realm="realm1")
set_policy(name="pol2",
scope=SCOPE.ADMIN,
action="*", client="10.0.0.0/8",
realm="realm2")
g.policy_object = PolicyClass()
# set a polrealm1 and a polrealm2
# setup realm1
self.setUp_user_realms()
# setup realm2
self.setUp_user_realm2()
tokenobject = init_token({"serial": "POL001", "type": "hotp",
"otpkey": "1234567890123456"})
r = set_realms("POL001", [self.realm1])
tokenobject = init_token({"serial": "POL002", "type": "hotp",
"otpkey": "1234567890123456"})
r = set_realms("POL002", [self.realm2])
# Token in realm1 can not be deleted
req.all_data = {"serial": "POL001"}
self.assertRaises(PolicyError,
check_base_action, req, "delete")
# while token in realm2 can be deleted
req.all_data = {"serial": "POL002"}
r = check_base_action(req, action="delete")
self.assertTrue(r)
# A normal user can "disable", since no user policies are defined.
g.logged_in_user = {"username": "user1",
"role": "user"}
r = check_base_action(req, "disable")
self.assertTrue(r)
delete_policy("pol1")
delete_policy("pol2")
remove_token("POL001")
remove_token("POL002")
def test_01a_admin_realms(self):
admin1 = {"username": "admin1",
"role": "admin",
"realm": "realm1"}
admin2 = {"username": "admin1",
"role": "admin",
"realm": "realm2"}
set_policy(name="pol",
scope=SCOPE.ADMIN,
action="*", adminrealm="realm1")
g.policy_object = PolicyClass()
builder = EnvironBuilder(method='POST',
data={'serial': "OATH123456"},
headers={})
env = builder.get_environ()
# Set the remote address so that we can filter for it
env["REMOTE_ADDR"] = "10.0.0.1"
g.client_ip = env["REMOTE_ADDR"]
req = Request(env)
req.all_data = {}
# admin1 is allowed to do everything
g.logged_in_user = admin1
r = check_base_action(req, action="delete")
self.assertTrue(r)
# admin2 is not allowed.
g.logged_in_user = admin2
self.assertRaises(PolicyError, check_base_action, req, action="delete")
delete_policy("pol")
def test_02_check_token_init(self):
g.logged_in_user = {"username": "admin1",
"role": "admin"}
builder = EnvironBuilder(method='POST',
data={'serial': "OATH123456"},
headers={})
env = builder.get_environ()
# Set the remote address so that we can filter for it
env["REMOTE_ADDR"] = "10.0.0.1"
g.client_ip = env["REMOTE_ADDR"]
req = Request(env)
req.all_data = {"type": "totp"}
# Set a policy, that does allow the action
set_policy(name="pol1",
scope=SCOPE.ADMIN,
action="enrollTOTP, enrollHOTP",
client="10.0.0.0/8")
g.policy_object = PolicyClass()
# Enrolling TOTP is cool
r = check_token_init(req)
self.assertTrue(r)
# Another Token type can not be enrolled:
# An exception is raised
req.all_data = {"type": "motp"}
self.assertRaises(PolicyError,
check_token_init, req)
# A normal user can "enroll", since no user policies are defined.
g.logged_in_user = {"username": "user1",
"role": "user"}
r = check_token_init(req)
self.assertTrue(r)
# finally delete policy
delete_policy("pol1")
def test_03_check_token_upload(self):
g.logged_in_user = {"username": "admin1",
"role": "admin"}
builder = EnvironBuilder(method='POST',
data={'serial': "OATH123456"},
headers={})
env = builder.get_environ()
# Set the remote address so that we can filter for it
env["REMOTE_ADDR"] = "10.0.0.1"
g.client_ip = env["REMOTE_ADDR"]
req = Request(env)
req.all_data = {"filename": "token.xml"}
# Set a policy, that does allow the action
set_policy(name="pol1",
scope=SCOPE.ADMIN,
action="enrollTOTP, enrollHOTP, {0!s}".format(ACTION.IMPORT),
client="10.0.0.0/8")
g.policy_object = PolicyClass()
# Try to import tokens
r = check_token_upload(req)
self.assertTrue(r)
# The admin can not upload from another IP address
# An exception is raised
env["REMOTE_ADDR"] = "192.168.0.1"
g.client_ip = env["REMOTE_ADDR"]
req = Request(env)
req.all_data = {"filename": "token.xml"}
self.assertRaises(PolicyError,
check_token_upload, req)
# finally delete policy
delete_policy("pol1")
def test_04_check_max_token_user(self):
g.logged_in_user = {"username": "admin1",
"role": "admin"}
builder = EnvironBuilder(method='POST',
data={'serial': "OATH123456"},
headers={})
env = builder.get_environ()
# Set the remote address so that we can filter for it
env["REMOTE_ADDR"] = "10.0.0.1"
g.client_ip = env["REMOTE_ADDR"]
req = Request(env)
req.all_data = {"user": "cornelius",
"realm": self.realm1}
# Set a policy, that allows two tokens per user
set_policy(name="pol1",
scope=SCOPE.ENROLL,
action="{0!s}={1!s}".format(ACTION.MAXTOKENUSER, 2))
g.policy_object = PolicyClass()
# The user has one token, everything is fine.
self.setUp_user_realms()
tokenobject = init_token({"serial": "NEW001", "type": "hotp",
"otpkey": "1234567890123456"},
user=User(login="cornelius",
realm=self.realm1))
tokenobject_list = get_tokens(user=User(login="cornelius",
realm=self.realm1))
self.assertTrue(len(tokenobject_list) == 1)
self.assertTrue(check_max_token_user(req))
# Now the user gets his second token
tokenobject = init_token({"serial": "NEW002", "type": "hotp",
"otpkey": "1234567890123456"},
user=User(login="cornelius",
realm=self.realm1))
tokenobject_list = get_tokens(user=User(login="cornelius",
realm=self.realm1))
self.assertTrue(len(tokenobject_list) == 2)
# The user has two tokens. The check that will run in this case,
# before the user would be assigned the 3rd token, will raise a
# PolicyError
self.assertRaises(PolicyError,
check_max_token_user, req)
# The check for a token, that has no username in it, must not
# succeed. I.e. in the realm new tokens must be enrollable.
req.all_data = {}
self.assertTrue(check_max_token_user(req))
req.all_data = {"realm": self.realm1}
self.assertTrue(check_max_token_user(req))
# finally delete policy
delete_policy("pol1")
remove_token("NEW001")
remove_token("NEW002")
def test_05_check_max_token_realm(self):
g.logged_in_user = {"username": "admin1",
"role": "admin"}
builder = EnvironBuilder(method='POST',
data={'serial': "OATH123456"},
headers={})
env = builder.get_environ()
# Set the remote address so that we can filter for it
env["REMOTE_ADDR"] = "10.0.0.1"
g.client_ip = env["REMOTE_ADDR"]
req = Request(env)
req.all_data = {"realm": self.realm1}
# Set a policy, that allows two tokens per realm
set_policy(name="pol1",
scope=SCOPE.ENROLL,
action="max_token_per_realm=2",
realm=self.realm1)
g.policy_object = PolicyClass()
self.setUp_user_realms()
# Add the first token into the realm
tokenobject = init_token({"serial": "NEW001", "type": "hotp",
"otpkey": "1234567890123456"})
set_realms("NEW001", [self.realm1])
# check the realm, only one token is in it the policy condition will
# pass
tokenobject_list = get_tokens(realm=self.realm1)
self.assertTrue(len(tokenobject_list) == 1)
self.assertTrue(check_max_token_realm(req))
# add a second token to the realm
tokenobject = init_token({"serial": "NEW002", "type": "hotp",
"otpkey": "1234567890123456"})
set_realms("NEW002", [self.realm1])
tokenobject_list = get_tokens(realm=self.realm1)
self.assertTrue(len(tokenobject_list) == 2)
# request with a user object, not with a realm
req.all_data = {"user": "cornelius@{0!s}".format(self.realm1)}
# Now a new policy check will fail, since there are already two
# tokens in the realm
self.assertRaises(PolicyError,
check_max_token_realm, req)
# finally delete policy
delete_policy("pol1")
remove_token("NEW001")
remove_token("NEW002")
def test_06_set_realm(self):
g.logged_in_user = {"username": "admin1",
"role": "admin"}
builder = EnvironBuilder(method='POST',
data={'serial': "OATH123456"},
headers={})
env = builder.get_environ()
# Set the remote address so that we can filter for it
env["REMOTE_ADDR"] = "10.0.0.1"
g.client_ip = env["REMOTE_ADDR"]
req = Request(env)
# Set a policy, that allows two tokens per realm
set_policy(name="pol1",
scope=SCOPE.AUTHZ,
action="{0!s}={1!s}".format(ACTION.SETREALM, self.realm1),
realm="somerealm")
g.policy_object = PolicyClass()
# request, that matches the policy
req.all_data = {"realm": "somerealm"}
set_realm(req)
# Check, if the realm was modified to the realm specified in the policy
self.assertTrue(req.all_data.get("realm") == self.realm1)
# A request, that does not match the policy:
req.all_data = {"realm": "otherrealm"}
set_realm(req)
# Check, if the realm is still the same
self.assertEqual(req.all_data.get("realm"), "otherrealm")
# If there are several policies, which will produce different realms,
# we get an exception
set_policy(name="pol2",
scope=SCOPE.AUTHZ,
action="{0!s}={1!s}".format(ACTION.SETREALM, "ConflictRealm"),
realm="somerealm")
g.policy_object = PolicyClass()
# This request will trigger two policies with different realms to set
req.all_data = {"realm": "somerealm"}
self.assertRaises(PolicyError, set_realm, req)
# finally delete policy
delete_policy("pol1")
delete_policy("pol2")
def test_06_set_tokenlabel(self):
g.logged_in_user = {"username": "admin1",
"role": "admin"}
builder = EnvironBuilder(method='POST',
data={'serial': "OATH123456"},
headers={})
env = builder.get_environ()
# Set the remote address so that we can filter for it
env["REMOTE_ADDR"] = "10.0.0.1"
g.client_ip = env["REMOTE_ADDR"]
req = Request(env)
# Set a policy that defines the tokenlabel
set_policy(name="pol1",
scope=SCOPE.ENROLL,
action="{0!s}={1!s}".format(ACTION.TOKENLABEL, "<u>@<r>"))
set_policy(name="pol2",
scope=SCOPE.ENROLL,
action="{0!s}={1!s}".format(ACTION.TOKENISSUER, "myPI"))
g.policy_object = PolicyClass()
# request, that matches the policy
req.all_data = {
"user": "cornelius",
"realm": "home"}
init_tokenlabel(req)
# Check, if the tokenlabel was added
self.assertEqual(req.all_data.get("tokenlabel"), "<u>@<r>")
# Check, if the tokenissuer was added
self.assertEqual(req.all_data.get("tokenissuer"), "myPI")
# finally delete policy
delete_policy("pol1")
delete_policy("pol2")
def test_07_set_random_pin(self):
g.logged_in_user = {"username": "admin1",
"role": "admin"}
builder = EnvironBuilder(method='POST',
data={'serial': "OATH123456"},
headers={})
env = builder.get_environ()
# Set the remote address so that we can filter for it
env["REMOTE_ADDR"] = "10.0.0.1"
g.client_ip = env["REMOTE_ADDR"]
req = Request(env)
# Set a policy that defines the tokenlabel
set_policy(name="pol1",
scope=SCOPE.ENROLL,
action="{0!s}={1!s}".format(ACTION.OTPPINRANDOM, "12"))
set_policy(name="pinhandling",
scope=SCOPE.ENROLL,
action="{0!s}=privacyidea.lib.pinhandling.base.PinHandler".format(
ACTION.PINHANDLING))
g.policy_object = PolicyClass()
# request, that matches the policy
req.all_data = {
"user": "cornelius",
"realm": "home"}
init_random_pin(req)
# Check, if the tokenlabel was added
self.assertEqual(len(req.all_data.get("pin")), 12)
# finally delete policy
delete_policy("pol1")
delete_policy("pinhandling")
def test_08_encrypt_pin(self):
g.logged_in_user = {"username": "admin1",
"role": "admin"}
builder = EnvironBuilder(method='POST',
data={'serial': "OATH123456"},
headers={})
env = builder.get_environ()
# Set the remote address so that we can filter for it
env["REMOTE_ADDR"] = "10.0.0.1"
g.client_ip = env["REMOTE_ADDR"]
req = Request(env)
# Set a policy that defines the PIN to be encrypted
set_policy(name="pol1",
scope=SCOPE.ENROLL,
action=ACTION.ENCRYPTPIN)
g.policy_object = PolicyClass()
# request, that matches the policy
req.all_data = {
"user": "cornelius",
"realm": "home"}
encrypt_pin(req)
# Check, if the tokenlabel was added
self.assertEqual(req.all_data.get("encryptpin"), "True")
# finally delete policy
delete_policy("pol1")
def test_09_pin_policies(self):
g.logged_in_user = {"username": "user1",
"role": "user"}
builder = EnvironBuilder(method='POST',
data={'serial': "OATH123456"},
headers={})
env = builder.get_environ()
# Set the remote address so that we can filter for it
env["REMOTE_ADDR"] = "10.0.0.1"
g.client_ip = env["REMOTE_ADDR"]
req = Request(env)
# Set a policy that defines PIN policy
set_policy(name="pol1",
scope=SCOPE.USER,
action="{0!s}={1!s},{2!s}={3!s},{4!s}={5!s}".format(ACTION.OTPPINMAXLEN, "10",
ACTION.OTPPINMINLEN, "4",
ACTION.OTPPINCONTENTS, "cn"))
g.policy_object = PolicyClass()
req.all_data = {
"user": "cornelius",
"realm": "home"}
# The minimum OTP length is 4
self.assertRaises(PolicyError, check_otp_pin, req)
req.all_data = {
"user": "cornelius",
"realm": "home",
"pin": "12345566890012"}
# Fail maximum OTP length
self.assertRaises(PolicyError, check_otp_pin, req)
req.all_data = {
"user": "cornelius",
"realm": "home",
"pin": "123456"}
# Good OTP length, but missing character A-Z
self.assertRaises(PolicyError, check_otp_pin, req)
req.all_data = {
"user": "cornelius",
"realm": "home",
"pin": "abc123"}
# Good length and good contents
self.assertTrue(check_otp_pin(req))
# A token that does not use pins is ignored.
init_token({"type": "certificate",
"serial": "certificate"})
req.all_data = {"serial": "certificate",
"realm": "somerealm",
"user": "cornelius",
"pin": ""}
self.assertTrue(check_otp_pin(req))
init_token({"type": "sshkey",
"serial": "sshkey",
"sshkey": SSHKEY})
req.all_data = {"serial": "sshkey",
"realm": "somerealm",
"user": "cornelius",
"pin": ""}
self.assertTrue(check_otp_pin(req))
# finally delete policy
delete_policy("pol1")
def test_10_check_external(self):
g.logged_in_user = {"username": "user1",
"role": "user"}
builder = EnvironBuilder(method='POST',
data={'serial': "OATH123456"},
headers={})
env = builder.get_environ()
req = Request(env)
g.policy_object = PolicyClass()
req.all_data = {
"user": "cornelius",
"realm": "home"}
# Check success on no definition
r = check_external(req)
self.assertTrue(r)
# Check success with external function
current_app.config["PI_INIT_CHECK_HOOK"] = \
"privacyidea.api.lib.prepolicy.mock_success"
r = check_external(req)
self.assertTrue(r)
# Check exception with external function
current_app.config["PI_INIT_CHECK_HOOK"] = \
"privacyidea.api.lib.prepolicy.mock_fail"
self.assertRaises(Exception, check_external, req)
def test_11_api_key_required(self):
g.logged_in_user = {}
builder = EnvironBuilder(method='POST',
data={'serial': "OATH123456"},
headers={})
env = builder.get_environ()
# Set the remote address so that we can filter for it
env["REMOTE_ADDR"] = "10.0.0.1"
g.client_ip = env["REMOTE_ADDR"]
req = Request(env)
g.policy_object = PolicyClass()
# No policy and no Auth token
req.all_data = {}
r = api_key_required(req)
# The request was not modified
self.assertTrue(r)
# Set a policy, that allows two tokens per realm
set_policy(name="pol_api",
scope=SCOPE.AUTHZ,
action=ACTION.APIKEY)
g.policy_object = PolicyClass()
# A request with no API Key fails
self.assertRaises(PolicyError, api_key_required, req)
# A request with an API key succeeds
secret = current_app.config.get("SECRET_KEY")
token = jwt.encode({"role": ROLE.VALIDATE,
"exp": datetime.utcnow() + timedelta(hours=1)},
secret)
req.headers = {"Authorization": token}
r = api_key_required(req)
self.assertTrue(r)
# A request with a valid Admin Token does not succeed
token = jwt.encode({"role": ROLE.ADMIN,
"username": "admin",
"exp": datetime.utcnow() + timedelta(hours=1)},
secret)
req.headers = {"Authorization": token}
self.assertRaises(PolicyError, api_key_required, req)
delete_policy("pol_api")
def test_12_mangle(self):
g.logged_in_user = {"username": "admin1",
"role": "admin"}
builder = EnvironBuilder(method='POST',
data={'serial': "OATH123456"},
headers={})
env = builder.get_environ()
# Set the remote address so that we can filter for it
env["REMOTE_ADDR"] = "10.0.0.1"
g.client_ip = env["REMOTE_ADDR"]
req = Request(env)
# Set a mangle policy to change the username
# and only use the last 4 characters of the username
set_policy(name="mangle1",
scope=SCOPE.AUTH,
action="{0!s}=user/.*(.{{4}}$)/\\1/".format(ACTION.MANGLE))
g.policy_object = PolicyClass()
# request, that matches the policy
req.all_data = {"user": "Thiswillbesplit_user"}
mangle(req)
# Check if the user was modified
self.assertEqual(req.all_data.get("user"), "user")
# Set a mangle policy to remove blanks from realm name
set_policy(name="mangle2",
scope=SCOPE.AUTH,
action="{0!s}=realm/\\s//".format(ACTION.MANGLE))
g.policy_object = PolicyClass()
# request, that matches the policy
req.all_data = {"realm": "lower Realm"}
mangle(req)
# Check if the realm was modified
self.assertEqual(req.all_data.get("realm"), "lowerRealm")
# finally delete policy
delete_policy("mangle1")
delete_policy("mangle2")
def test_13_remote_user(self):
g.logged_in_user = {"username": "admin1",
"role": "admin"}
builder = EnvironBuilder(method='POST',
data={'serial': "OATH123456"},
headers={})
env = builder.get_environ()
# Set the remote address so that we can filter for it
env["REMOTE_ADDR"] = "10.0.0.1"
g.client_ip = env["REMOTE_ADDR"]
env["REMOTE_USER"] = "admin"
req = Request(env)
# A user, for whom the login via REMOTE_USER is allowed.
set_policy(name="ruser",
scope=SCOPE.WEBUI,
action="{0!s}={1!s}".format(ACTION.REMOTE_USER, REMOTE_USER.ACTIVE))
g.policy_object = PolicyClass()
r = is_remote_user_allowed(req)
self.assertEqual(r, [REMOTE_USER.ACTIVE])
# Login for the REMOTE_USER is not allowed.
# Only allowed for user "super", but REMOTE_USER=admin
set_policy(name="ruser",
scope=SCOPE.WEBUI,
action="{0!s}={1!s}".format(ACTION.REMOTE_USER, REMOTE_USER.ACTIVE),
user="super")
g.policy_object = PolicyClass()
r = is_remote_user_allowed(req)
self.assertEqual(r, [])
delete_policy("ruser")
def test_14_required_email(self):
g.logged_in_user = {"username": "admin1",
"role": "admin"}
builder = EnvironBuilder(method='POST',
data={'serial': "OATH123456"},
headers={})
env = builder.get_environ()
# Set the remote address so that we can filter for it
env["REMOTE_ADDR"] = "10.0.0.1"
g.client_ip = env["REMOTE_ADDR"]
req = Request(env)
# Set a mangle policy to change the username
# and only use the last 4 characters of the username
set_policy(name="email1",
scope=SCOPE.REGISTER,
action="{0!s}=/.*@mydomain\..*".format(ACTION.REQUIREDEMAIL))
g.policy_object = PolicyClass()
# request, that matches the policy
req.all_data = {"email": "[email protected]"}
# This emails is allowed
r = required_email(req)
self.assertTrue(r)
# This email is not allowed
req.all_data = {"email": "[email protected]"}
# This emails is allowed
self.assertRaises(RegistrationError, required_email, req)
delete_policy("email1")
g.policy_object = PolicyClass()
# Without a policy, this email can register
req.all_data = {"email": "[email protected]"}
# This emails is allowed
r = required_email(req)
self.assertTrue(r)
def test_15_reset_password(self):
builder = EnvironBuilder(method='POST',
data={'user': "cornelius",
"realm": self.realm1},
headers={})
env = builder.get_environ()
# Set the remote address so that we can filter for it
env["REMOTE_ADDR"] = "10.0.0.1"
g.client_ip = env["REMOTE_ADDR"]
req = Request(env)
# Set a mangle policy to change the username
# and only use the last 4 characters of the username
set_policy(name="recover",
scope=SCOPE.USER,
action="{0!s}".format(ACTION.RESYNC))
g.policy_object = PolicyClass()
req.all_data = {"user": "cornelius", "realm": self.realm1}
# There is a user policy without password reset, so an exception is
# raised
self.assertRaises(PolicyError, check_anonymous_user, req,
ACTION.PASSWORDRESET)
# The password reset is allowed
set_policy(name="recover",
scope=SCOPE.USER,
action="{0!s}".format(ACTION.PASSWORDRESET))
g.policy_object = PolicyClass()
r = check_anonymous_user(req, ACTION.PASSWORDRESET)
self.assertEqual(r, True)
def test_16_check_two_admins(self):
# We are checking two administrators
# adminA: all rights on all realms
# adminB: restricted rights on realmB
builder = EnvironBuilder(method='POST')
env = builder.get_environ()
# Set the remote address so that we can filter for it
req = Request(env)
req.all_data = {"name": "newpol",
"scope": SCOPE.WEBUI,
"action": ["loginmode=privacyIDEA"],
"active": True,
"client": [],
"realm": ["realmB"],
"resolver": ["resolverB"],
"time": "",
"user": []
}
set_policy("polAdminA", scope=SCOPE.ADMIN,
action="set, revoke, adduser, enrollSMS, policydelete, "
"policywrite, enrollTIQR, configdelete, machinelist, "
"enrollREMOTE, setpin, resync, unassign, tokenrealms,"
" enrollSPASS, auditlog, enrollPAPER, deleteuser, "
"enrollEMAIL, resolverdelete, enrollMOTP, enrollPW, "
"enrollHOTP, enrollQUESTION, enrollCERTIFICATE, "
"copytokenuser, configwrite, enrollTOTP, "
"enrollREGISTRATION, enrollYUBICO, resolverwrite, "
"updateuser, enable, enrollU2F, "
"manage_machine_tokens, getrandom, userlist, "
"getserial, radiusserver_write, system_documentation,"
" caconnectordelete, caconnectorwrite, disable, "
"mresolverdelete, copytokenpin, enrollRADIUS, "
"smtpserver_write, set_hsm_password, reset, "
"getchallenges, enroll4EYES, enrollYUBIKEY, "
"fetch_authentication_items, enrollDAPLUG, "
"mresolverwrite, losttoken, enrollSSHKEY, "
"importtokens, assign, delete",
user="adminA",
realm="realmA, realmB",
resolver="resolverA, resolverB",
)
set_policy("polAdminB", scope=SCOPE.ADMIN,
action="set, revoke, adduser, resync, unassign, "
"tokenrealms, deleteuser, enrollTOTP, "
"enrollREGISTRATION, updateuser, enable, userlist, "
"getserial, disable, reset, getchallenges, losttoken,"
" assign, delete ",
realm="realmB",
resolver="resolverB",
user="adminB")
g.policy_object = PolicyClass()
# Test AdminA
g.logged_in_user = {"username": "adminA",
"role": "admin",
"realm": ""}
r = check_base_action(req, action=ACTION.POLICYWRITE)
self.assertEqual(r, True)
# Test AdminB
g.logged_in_user = {"username": "adminB",
"role": "admin",
"realm": ""}
# AdminB is allowed to add user
r = check_base_action(req, action=ACTION.ADDUSER)
self.assertEqual(r, True)
# But admin b is not allowed to policywrite
self.assertRaises(PolicyError, check_base_action, req,
action=ACTION.POLICYWRITE)
# Test AdminC: is not allowed to do anything
g.logged_in_user = {"username": "adminC",
"role": "admin",
"realm": ""}
self.assertRaises(PolicyError, check_base_action, req,
action=ACTION.POLICYWRITE)
delete_policy("polAdminA")
delete_policy("polAdminB")
def test_17_add_user(self):
# Check if adding a user is restricted to the resolver
# adminA is allowed to add users to resolverA but not to resolverB
set_policy("userAdd", scope=SCOPE.ADMIN,
action="adduser",
user="adminA",
realm="realmA",
resolver="resolverA",
)
builder = EnvironBuilder(method='POST')
env = builder.get_environ()
# Set the remote address so that we can filter for it
req = Request(env)
req.all_data = {"user": "new_user",
"resolver": "resolverA"}
g.policy_object = PolicyClass()
g.logged_in_user = {"username": "adminA",
"role": "admin",
"realm": ""}
# User can be added
r = check_base_action(req, action=ACTION.ADDUSER)
self.assertEqual(r, True)
req.all_data = {"user": "new_user",
"resolver": "resolverB"}
# User can not be added in a different resolver
self.assertRaises(PolicyError, check_base_action, req,
action=ACTION.ADDUSER)
delete_policy("userAdd")
class PostPolicyDecoratorTestCase(MyTestCase):
def test_01_check_tokentype(self):
# http://werkzeug.pocoo.org/docs/0.10/test/#environment-building
builder = EnvironBuilder(method='POST',
data={'serial': "OATH123456"},
headers={})
env = builder.get_environ()
# Set the remote address so that we can filter for it
env["REMOTE_ADDR"] = "10.0.0.1"
g.client_ip = env["REMOTE_ADDR"]
req = Request(env)
# The response contains the token type SPASS
res = {"jsonrpc": "2.0",
"result": {"status": True,
"value": True},
"version": "privacyIDEA test",
"id": 1,
"detail": {"message": "matching 1 tokens",
"serial": "PISP0000AB00",
"type": "spass"}}
resp = Response(json.dumps(res))
# Set a policy, that does not allow the tokentype
set_policy(name="pol1",
scope=SCOPE.AUTHZ,
action="tokentype=hotp", client="10.0.0.0/8")
g.policy_object = PolicyClass()
# The token type SPASS is not allowed on this client, so an exception
# is raised.
self.assertRaises(PolicyError,
check_tokentype,
req, resp)
# A policy, that allows the token spass
# Set a policy, that does not allow the tokentype
set_policy(name="pol1",
scope=SCOPE.AUTHZ,
action="tokentype=spass", client="10.0.0.0/8")
g.policy_object = PolicyClass()
# The token type SPASS is not allowed on this client, so an exception
# is raised.
r = check_tokentype(req, resp)
jresult = json.loads(r.data)
self.assertTrue(jresult.get("result").get("value"))
def test_02_check_serial(self):
# http://werkzeug.pocoo.org/docs/0.10/test/#environment-building
builder = EnvironBuilder(method='POST',
data={'serial': "HOTP123435"},
headers={})
env = builder.get_environ()
# Set the remote address so that we can filter for it
env["REMOTE_ADDR"] = "10.0.0.1"
g.client_ip = env["REMOTE_ADDR"]
req = Request(env)
# The response contains the token type SPASS
res = {"jsonrpc": "2.0",
"result": {"status": True,
"value": True},
"version": "privacyIDEA test",
"id": 1,
"detail": {"message": "matching 1 tokens",
"serial": "HOTP123456",
"type": "hotp"}}
resp = Response(json.dumps(res))
# Set a policy, that does not allow the tokentype
set_policy(name="pol1",
scope=SCOPE.AUTHZ,
action="serial=TOTP", client="10.0.0.0/8")
g.policy_object = PolicyClass()
# The token serial HOTP is not allowed on this client, so an exception
# is raised.
self.assertRaises(PolicyError,
check_serial,
req, resp)
# A policy, that allows the token spass
# Set a policy, that does not allow the tokentype
set_policy(name="pol1",
scope=SCOPE.AUTHZ,
action="serial=HOTP", client="10.0.0.0/8")
g.policy_object = PolicyClass()
# The token type SPASS is not allowed on this client, so an exception
# is raised.
r = check_serial(req, resp)
jresult = json.loads(r.data)
self.assertTrue(jresult.get("result").get("value"))
def test_03_no_detail_on_success(self):
builder = EnvironBuilder(method='POST',
data={'serial': "HOTP123435"},
headers={})
env = builder.get_environ()
# Set the remote address so that we can filter for it
env["REMOTE_ADDR"] = "10.0.0.1"
g.client_ip = env["REMOTE_ADDR"]
req = Request(env)
# The response contains the token type SPASS
res = {"jsonrpc": "2.0",
"result": {"status": True,
"value": True},
"version": "privacyIDEA test",
"id": 1,
"detail": {"message": "matching 1 tokens",
"serial": "HOTP123456",
"type": "hotp"}}
resp = Response(json.dumps(res))
# Set a policy, that does not allow the detail on success