-
Notifications
You must be signed in to change notification settings - Fork 152
/
test_common.py
1074 lines (831 loc) · 36.5 KB
/
test_common.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
"""
test_common
~~~~~~~~~~~
Test common functionality
:copyright: (c) 2019-2023 by J. Christopher Wagner (jwag).
:license: MIT, see LICENSE for more details.
"""
import base64
import json
import re
import pytest
from flask import Blueprint, g
from flask_security import uia_email_mapper
from flask_security.decorators import auth_required
from flask_principal import identity_loaded
from tests.test_utils import (
authenticate,
capture_flashes,
check_location,
get_auth_token_version_3x,
get_form_action,
get_num_queries,
hash_password,
json_authenticate,
logout,
populate_data,
verify_token,
)
def test_login_view(client):
response = client.get("/login")
assert b"<h1>Login</h1>" in response.data
def test_authenticate(client):
response = authenticate(client)
assert response.status_code == 302
response = authenticate(client, follow_redirects=True)
assert b"Welcome matt@lp.com" in response.data
def test_authenticate_with_next(client):
data = dict(email="matt@lp.com", password="password")
response = client.post("/login?next=/page1", data=data, follow_redirects=True)
assert b"Page 1" in response.data
def test_authenticate_with_next_bp(app, client):
api = Blueprint("api", __name__)
@api.route("/info")
def info():
pass
app.register_blueprint(api, url_prefix="/api")
data = dict(email="matt@lp.com", password="password")
response = client.post("/login?next=api.info", data=data, follow_redirects=False)
assert response.status_code == 302
assert "api/info" in response.location
def test_authenticate_with_invalid_next(client, get_message):
data = dict(email="matt@lp.com", password="password")
response = client.post("/login?next=http://google.com", data=data)
assert get_message("INVALID_REDIRECT") in response.data
def test_authenticate_with_invalid_malformed_next(client, get_message):
data = dict(email="matt@lp.com", password="password")
response = client.post("/login?next=http:///google.com", data=data)
assert get_message("INVALID_REDIRECT") in response.data
def test_login_template_next(client):
# Test that our login template propagates next.
response = client.get("/profile", follow_redirects=True)
assert "?next=/profile" in response.request.url
login_url = get_form_action(response)
response = client.post(
login_url,
data=dict(email="matt@lp.com", password="password"),
follow_redirects=True,
)
assert b"Profile Page" in response.data
def test_authenticate_with_subdomain_next(app, client, get_message):
app.config["SERVER_NAME"] = "lp.com"
app.config["SECURITY_REDIRECT_ALLOW_SUBDOMAINS"] = True
data = dict(email="matt@lp.com", password="password")
response = client.post("/login?next=http://sub.lp.com", data=data)
assert response.status_code == 302
def test_authenticate_with_root_domain_next(app, client, get_message):
app.config["SERVER_NAME"] = "lp.com"
app.config["SECURITY_SUBDOMAIN"] = "auth"
app.config["SECURITY_REDIRECT_ALLOW_SUBDOMAINS"] = True
data = dict(email="matt@lp.com", password="password")
response = client.post("/login?next=http://lp.com", data=data)
assert response.status_code == 302
def test_authenticate_with_invalid_subdomain_next(app, client, get_message):
app.config["SERVER_NAME"] = "lp.com"
app.config["SECURITY_REDIRECT_ALLOW_SUBDOMAINS"] = True
data = dict(email="matt@lp.com", password="password")
response = client.post("/login?next=http://sub.lp.net", data=data)
assert get_message("INVALID_REDIRECT") in response.data
def test_authenticate_with_subdomain_next_default_config(app, client, get_message):
app.config["SERVER_NAME"] = "lp.com"
data = dict(email="matt@lp.com", password="password")
response = client.post("/login?next=http://sub.lp.com", data=data)
assert get_message("INVALID_REDIRECT") in response.data
def test_authenticate_case_insensitive_email(app, client):
response = authenticate(client, "MATT@lp.com", follow_redirects=True)
assert b"Welcome matt@lp.com" in response.data
def test_authenticate_with_invalid_input(client, get_message):
response = client.post(
"/login",
json=dict(password="password"),
headers={"Content-Type": "application/json"},
)
assert get_message("USER_DOES_NOT_EXIST") in response.data
@pytest.mark.settings(post_login_view="/post_login")
def test_get_already_authenticated(client):
response = authenticate(client, follow_redirects=True)
assert b"Welcome matt@lp.com" in response.data
response = client.get("/login", follow_redirects=True)
assert b"Post Login" in response.data
@pytest.mark.settings(post_login_view="/post_login")
def test_get_already_authenticated_next(client):
response = authenticate(client, follow_redirects=True)
assert b"Welcome matt@lp.com" in response.data
# This should NOT override post_login_view due to potential redirect loops.
response = client.get("/login?next=/page1", follow_redirects=True)
assert b"Post Login" in response.data
@pytest.mark.settings(post_login_view="/post_login")
def test_post_already_authenticated(client):
response = authenticate(client, follow_redirects=True)
assert b"Welcome matt@lp.com" in response.data
data = dict(email="matt@lp.com", password="password")
response = client.post("/login", data=data, follow_redirects=True)
assert b"Post Login" in response.data
# This should NOT override post_login_view due to potential redirect loops.
response = client.post("/login?next=/page1", data=data, follow_redirects=True)
assert b"Post Login" in response.data
def test_login_form(client):
response = client.post("/login", data={"email": "matt@lp.com"})
assert b"matt@lp.com" in response.data
assert re.search(b'<input[^>]*type="email"[^>]*>', response.data)
@pytest.mark.settings(username_enable=True)
def test_login_form_username(client):
# If USERNAME_ENABLE is set then login form should have a both an Email and
# StringField
response = client.get("/login")
# Should be both email with Email type and username with autocomplete
assert re.search(b'<input[^>]*type="email"[^>]*>', response.data)
assert re.search(b'<input[^>]*autocomplete="username"[^>]*>', response.data)
assert re.search(b'<input[^>]*autocomplete="current-password"[^>]*>', response.data)
@pytest.mark.settings(username_enable=True, username_required=True)
def test_login_form_username_required(app, client):
# If username required - we should still be able to login with email alone
# given default user_identity_attributes
response = client.post(
"/login", data=dict(email="matt@lp.com", password="password")
)
assert check_location(app, response.location, "/")
@pytest.mark.confirmable()
@pytest.mark.settings(
return_generic_responses=True, requires_confirmation_error_view="/confirm"
)
def test_generic_response(app, client, get_message):
response = client.post(
"/login", data=dict(email="mattwho@lp.com", password="forgot")
)
assert get_message("GENERIC_AUTHN_FAILED") in response.data
response = client.post("/login", data=dict(email="matt@lp.com", password="forgot"))
assert get_message("GENERIC_AUTHN_FAILED") in response.data
response = client.post(
"/login", json=dict(email="mattwho@lp.com", password="forgot")
)
# make sure just 'null' key in errors.
assert list(response.json["response"]["field_errors"].keys()) == ["null"]
assert len(response.json["response"]["field_errors"]["null"]) == 1
assert response.json["response"]["errors"][0].encode("utf-8") == get_message(
"GENERIC_AUTHN_FAILED"
)
response = client.post("/login", json=dict(email="matt@lp.com", password="forgot"))
assert response.json["response"]["errors"][0].encode("utf-8") == get_message(
"GENERIC_AUTHN_FAILED"
)
# make sure don't get confirmation required
with capture_flashes() as flashes:
response = client.post(
"/login",
data=dict(email="mattwho@lp.com", password="password"),
follow_redirects=False,
)
assert response.status_code == 200
assert len(flashes) == 0
@pytest.mark.registerable()
@pytest.mark.settings(username_enable=True, return_generic_responses=True)
def test_generic_response_username(app, client, get_message):
data = dict(
email="dude@lp.com",
username="dude",
password="awesome sunset",
)
response = client.post("/register", json=data)
assert response.headers["Content-Type"] == "application/json"
assert response.status_code == 200
logout(client)
response = client.post(
"/login", data=dict(username="dude2", password="awesome sunset")
)
assert get_message("GENERIC_AUTHN_FAILED") in response.data
response = client.post("/login", json=dict(username="dude2", password="forgot"))
# make sure just 'null' key in errors.
assert list(response.json["response"]["field_errors"].keys()) == ["null"]
assert len(response.json["response"]["field_errors"]["null"]) == 1
assert response.json["response"]["errors"][0].encode("utf-8") == get_message(
"GENERIC_AUTHN_FAILED"
)
def test_unprovided_username(client, get_message):
response = authenticate(client, "")
assert get_message("USER_DOES_NOT_EXIST") in response.data
def test_unprovided_password(client, get_message):
response = authenticate(client, password="")
assert get_message("PASSWORD_NOT_PROVIDED") in response.data
def test_invalid_user(client, get_message):
response = authenticate(client, email="bogus@bogus.com")
assert get_message("USER_DOES_NOT_EXIST") in response.data
def test_bad_password(client, get_message):
response = authenticate(client, password="bogus")
assert get_message("INVALID_PASSWORD") in response.data
def test_inactive_user(client, get_message):
response = authenticate(client, "tiya@lp.com", "password")
assert get_message("DISABLED_ACCOUNT") in response.data
def test_inactive_forbids(app, client, get_message):
"""Make sure that existing session doesn't work after
user marked inactive
"""
response = authenticate(client, follow_redirects=True)
assert response.status_code == 200
# make sure can access restricted page
response = client.get("/profile", follow_redirects=True)
assert b"Profile Page" in response.data
# deactivate matt
with app.test_request_context("/"):
user = app.security.datastore.find_user(email="matt@lp.com")
app.security.datastore.deactivate_user(user)
app.security.datastore.commit()
response = client.get("/profile", follow_redirects=True)
# should be thrown back to login page.
assert response.status_code == 200
assert b"Please log in to access this page" in response.data
@pytest.mark.settings(unauthorized_view=None)
def test_inactive_forbids_token(app, client_nc, get_message):
"""Make sure that existing token doesn't work after
user marked inactive
"""
response = json_authenticate(client_nc)
assert response.status_code == 200
token = response.json["response"]["user"]["authentication_token"]
headers = {"Authentication-Token": token}
# make sure can access restricted page
response = client_nc.get("/token", headers=headers)
assert b"Token Authentication" in response.data
# deactivate matt
with app.test_request_context("/"):
user = app.security.datastore.find_user(email="matt@lp.com")
app.security.datastore.deactivate_user(user)
app.security.datastore.commit()
response = client_nc.get("/token", content_type="application/json", headers=headers)
assert response.status_code == 401
def test_inactive_forbids_basic(app, client, get_message):
"""Make sure that basic auth doesn't work if user deactivated"""
# Should properly work.
response = client.get(
"/multi_auth",
headers={
"Authorization": "Basic %s"
% base64.b64encode(b"joe@lp.com:password").decode("utf-8")
},
)
assert b"Session, Token, Basic" in response.data
# deactivate joe
with app.test_request_context("/"):
user = app.security.datastore.find_user(email="joe@lp.com")
app.security.datastore.deactivate_user(user)
app.security.datastore.commit()
response = client.get(
"/multi_auth",
headers={
"Authorization": "Basic %s"
% base64.b64encode(b"joe@lp.com:password").decode("utf-8")
},
)
assert b"You are not authenticated" in response.data
def test_unset_password(client, get_message):
response = authenticate(client, "jess@lp.com", "password")
assert get_message("INVALID_PASSWORD") in response.data
response = authenticate(client, "jess@lp.com", "")
assert get_message("PASSWORD_NOT_PROVIDED") in response.data
def test_logout(client):
authenticate(client)
response = logout(client, follow_redirects=True)
assert b"Home Page" in response.data
def test_logout_post(client):
authenticate(client)
response = client.post("/logout", content_type="application/json")
assert response.status_code == 200
assert response.json["meta"]["code"] == 200
def test_logout_with_next_invalid(client, get_message):
authenticate(client)
response = client.get("/logout?next=http://google.com")
assert "google.com" not in response.location
def test_logout_with_next(client):
authenticate(client)
response = client.get("/logout?next=/page1", follow_redirects=True)
assert b"Page 1" in response.data
def test_missing_session_access(client, get_message):
response = client.get("/profile", follow_redirects=True)
assert get_message("LOGIN") in response.data
def test_has_session_access(client):
authenticate(client)
response = client.get("/profile", follow_redirects=True)
assert b"profile" in response.data
def test_authorized_access(client):
authenticate(client)
response = client.get("/admin")
assert b"Admin Page" in response.data
def test_unauthorized_access(client, get_message):
authenticate(client, "joe@lp.com")
response = client.get("/admin", follow_redirects=True)
assert response.status_code == 403
@pytest.mark.settings(unauthorized_view=lambda: None)
def test_unauthorized_access_with_referrer(client, get_message):
authenticate(client, "joe@lp.com")
response = client.get("/admin", headers={"referer": "/admin"})
assert response.location != "/admin"
client.get(response.location)
response = client.get(
"/admin?a=b", headers={"referer": "http://localhost/admin?x=y"}
)
assert "/" in response.location
client.get(response.headers["Location"])
response = client.get(
"/admin", headers={"referer": "/admin"}, follow_redirects=True
)
assert response.data.count(get_message("UNAUTHORIZED")) == 1
# When referrer is from another path and unauthorized,
# we expect a temp redirect (302) to the referer
response = client.get("/admin?w=s", headers={"referer": "/profile"})
assert response.status_code == 302
assert "/profile" in response.location
@pytest.mark.settings(unauthorized_view="/unauthz")
def test_roles_accepted(clients):
# This specificaly tests that we can pass a URL for unauthorized_view.
for user in ("matt@lp.com", "joe@lp.com"):
authenticate(clients, user)
response = clients.get("/admin_or_editor")
assert b"Admin or Editor Page" in response.data
logout(clients)
authenticate(clients, "jill@lp.com")
response = clients.get("/admin_or_editor", follow_redirects=True)
assert b"Unauthorized" in response.data
@pytest.mark.settings(unauthorized_view="unauthz")
def test_permissions_accepted(clients):
for user in ("matt@lp.com", "joe@lp.com"):
authenticate(clients, user)
response = clients.get("/admin_perm")
assert b"Admin Page with full-write or super" in response.data
logout(clients)
authenticate(clients, "jill@lp.com")
response = clients.get("/admin_perm", follow_redirects=True)
assert b"Unauthorized" in response.data
@pytest.mark.settings(unauthorized_view="unauthz")
def test_permissions_required(clients):
for user in ["matt@lp.com"]:
authenticate(clients, user)
response = clients.get("/admin_perm_required")
assert b"Admin Page required" in response.data
logout(clients)
authenticate(clients, "joe@lp.com")
response = clients.get("/admin_perm_required", follow_redirects=True)
assert b"Unauthorized" in response.data
@pytest.mark.settings(unauthorized_view="unauthz")
def test_unauthenticated_role_required(client, get_message):
response = client.get("/admin", follow_redirects=True)
assert get_message("UNAUTHORIZED") in response.data
@pytest.mark.settings(unauthorized_view="unauthz")
def test_multiple_role_required(clients):
for user in ("matt@lp.com", "joe@lp.com"):
authenticate(clients, user)
response = clients.get("/admin_and_editor", follow_redirects=True)
assert b"Unauthorized" in response.data
clients.get("/logout")
authenticate(clients, "dave@lp.com")
response = clients.get("/admin_and_editor", follow_redirects=True)
assert b"Admin and Editor Page" in response.data
def test_ok_json_auth(client):
response = json_authenticate(client)
assert response.json["meta"]["code"] == 200
assert "authentication_token" in response.json["response"]["user"]
def test_invalid_json_auth(client):
response = json_authenticate(client, password="junk")
assert b'"code": 400' in response.data
def test_token_auth_via_querystring_valid_token(client):
response = json_authenticate(client)
token = response.json["response"]["user"]["authentication_token"]
response = client.get("/token?auth_token=" + token)
assert b"Token Authentication" in response.data
def test_token_auth_via_header_valid_token(client):
response = json_authenticate(client)
token = response.json["response"]["user"]["authentication_token"]
headers = {"Authentication-Token": token}
response = client.get("/token", headers=headers)
assert b"Token Authentication" in response.data
def test_token_auth_via_querystring_invalid_token(client):
response = client.get("/token?auth_token=X", headers={"Accept": "application/json"})
assert response.status_code == 401
def test_token_auth_via_header_invalid_token(client):
response = client.get(
"/token", headers={"Authentication-Token": "X", "Accept": "application/json"}
)
assert response.status_code == 401
def test_token_auth_invalid_for_session_auth(client):
# when user is loaded from token data, session authentication should fail.
response = json_authenticate(client)
token = response.json["response"]["user"]["authentication_token"]
# logout so session doesn't contain valid user details
logout(client)
headers = {"Authentication-Token": token, "Accept": "application/json"}
response = client.get("/session", headers=headers)
assert response.status_code == 401
def test_http_auth(client):
# browsers expect 401 response with WWW-Authenticate header - which will prompt
# them to pop up a login form.
response = client.get("/http", headers={})
assert response.status_code == 401
assert b"You are not authenticated" in response.data
assert "WWW-Authenticate" in response.headers
assert 'Basic realm="Login Required"' == response.headers["WWW-Authenticate"]
# Now provide correct credentials
response = client.get(
"/http",
headers={
"Authorization": "Basic %s"
% base64.b64encode(b"joe@lp.com:password").decode("utf-8")
},
)
assert b"HTTP Authentication" in response.data
@pytest.mark.settings(
USER_IDENTITY_ATTRIBUTES=[
{"email": {"mapper": uia_email_mapper}},
{"username": {"mapper": lambda x: x}},
]
)
def test_http_auth_username(client):
response = client.get(
"/http",
headers={
"Authorization": "Basic %s"
% base64.b64encode(b"jill:password").decode("utf-8")
},
)
assert b"HTTP Authentication" in response.data
def test_http_auth_no_authorization(client):
response = client.get(
"/http_admin_required",
headers={
"Authorization": "Basic %s"
% base64.b64encode(b"joe@lp.com:password").decode("utf-8")
},
)
assert response.status_code == 403
def test_http_auth_no_authorization_json(client, get_message):
response = client.get(
"/http_admin_required",
headers={
"accept": "application/json",
"Authorization": "Basic %s"
% base64.b64encode(b"joe@lp.com:password").decode("utf-8"),
},
)
assert response.status_code == 403
assert response.headers["Content-Type"] == "application/json"
@pytest.mark.settings(backwards_compat_unauthn=True)
def test_http_auth_no_authentication(client, get_message):
response = client.get("/http", headers={})
assert response.status_code == 401
assert b"<h1>Unauthorized</h1>" in response.data
assert "WWW-Authenticate" in response.headers
assert 'Basic realm="Login Required"' == response.headers["WWW-Authenticate"]
@pytest.mark.settings(backwards_compat_unauthn=False)
def test_http_auth_no_authentication_json(client, get_message):
response = client.get("/http", headers={"accept": "application/json"})
assert response.status_code == 401
assert response.json["response"]["errors"][0].encode("utf-8") == get_message(
"UNAUTHENTICATED"
)
assert response.headers["Content-Type"] == "application/json"
@pytest.mark.settings(backwards_compat_unauthn=True)
def test_invalid_http_auth_invalid_username(client):
response = client.get(
"/http",
headers={
"Authorization": "Basic %s"
% base64.b64encode(b"bogus:bogus").decode("utf-8")
},
)
assert b"<h1>Unauthorized</h1>" in response.data
assert "WWW-Authenticate" in response.headers
assert 'Basic realm="Login Required"' == response.headers["WWW-Authenticate"]
@pytest.mark.settings(backwards_compat_unauthn=False)
def test_invalid_http_auth_invalid_username_json(client, get_message):
# Even with JSON - Basic Auth required a WWW-Authenticate header response.
response = client.get(
"/http",
headers={
"accept": "application/json",
"Authorization": "Basic %s"
% base64.b64encode(b"bogus:bogus").decode("utf-8"),
},
)
assert response.status_code == 401
assert response.json["response"]["errors"][0].encode("utf-8") == get_message(
"UNAUTHENTICATED"
)
assert response.headers["Content-Type"] == "application/json"
assert "WWW-Authenticate" in response.headers
@pytest.mark.settings(backwards_compat_unauthn=True)
def test_invalid_http_auth_bad_password(client):
response = client.get(
"/http",
headers={
"Authorization": "Basic %s"
% base64.b64encode(b"joe@lp.com:bogus").decode("utf-8")
},
)
assert b"<h1>Unauthorized</h1>" in response.data
assert "WWW-Authenticate" in response.headers
assert 'Basic realm="Login Required"' == response.headers["WWW-Authenticate"]
@pytest.mark.settings(backwards_compat_unauthn=True)
def test_custom_http_auth_realm(client):
response = client.get(
"/http_custom_realm",
headers={
"Authorization": "Basic %s"
% base64.b64encode(b"joe@lp.com:bogus").decode("utf-8")
},
)
assert b"<h1>Unauthorized</h1>" in response.data
assert "WWW-Authenticate" in response.headers
assert 'Basic realm="My Realm"' == response.headers["WWW-Authenticate"]
def test_multi_auth_basic(client):
response = client.get(
"/multi_auth",
headers={
"Authorization": "Basic %s"
% base64.b64encode(b"joe@lp.com:password").decode("utf-8")
},
)
assert b"Basic" in response.data
response = client.get("/multi_auth")
# Default unauthn with basic is to return 401 with WWW-Authenticate Header
# so that browser pops up a username/password dialog
assert response.status_code == 401
assert "WWW-Authenticate" in response.headers
@pytest.mark.settings(backwards_compat_unauthn=True)
def test_multi_auth_basic_invalid(client):
response = client.get(
"/multi_auth",
headers={
"Authorization": "Basic %s"
% base64.b64encode(b"bogus:bogus").decode("utf-8")
},
)
assert b"<h1>Unauthorized</h1>" in response.data
assert "WWW-Authenticate" in response.headers
assert 'Basic realm="Login Required"' == response.headers["WWW-Authenticate"]
response = client.get("/multi_auth")
assert response.status_code == 401
def test_multi_auth_token(client):
response = json_authenticate(client)
token = response.json["response"]["user"]["authentication_token"]
response = client.get("/multi_auth?auth_token=" + token)
assert b"Token" in response.data
def test_multi_auth_session(client):
authenticate(client)
response = client.get("/multi_auth")
assert b"Session" in response.data
def test_authenticated_loop(client):
# If user is already authenticated say via session, and then hits an endpoint
# protected with @auth_token_required() - then they will be redirected to the login
# page which will simply note the current user is already logged in and redirect
# to POST_LOGIN_VIEW. Between 3.3.0 and 3.4.4 - this redirect would honor the 'next'
# parameter - thus redirecting back to the endpoint that caused the redirect in the
# first place - thus an infinite loop.
authenticate(client)
response = client.get("/token", follow_redirects=True)
assert response.status_code == 200
assert b"Home Page" in response.data
def test_user_deleted_during_session_reverts_to_anonymous_user(app, client):
authenticate(client)
with app.test_request_context("/"):
user = app.security.datastore.find_user(email="matt@lp.com")
app.security.datastore.delete_user(user)
app.security.datastore.commit()
response = client.get("/")
assert b"Hello matt@lp.com" not in response.data
def test_session_loads_identity(app, client):
@app.route("/identity_check")
@auth_required("session")
def id_check():
if hasattr(g, "identity"):
identity = g.identity
assert hasattr(identity, "loader_called")
assert identity.loader_called
return "Success"
json_authenticate(client)
# add identity loader after authentication to only fire it for
# session-authentication next `get` call
@identity_loaded.connect_via(app)
def identity_loaded_check(sender, identity):
identity.loader_called = True
response = client.get("/identity_check")
assert b"Success" == response.data
def test_remember_token(client):
response = authenticate(client, follow_redirects=False)
client.delete_cookie("session")
response = client.get("/profile")
assert b"profile" in response.data
def test_request_loader_does_not_fail_with_invalid_token(client):
client.set_cookie("remember_token")
response = client.get("/")
assert b"BadSignature" not in response.data
def test_sending_auth_token_with_json(client):
response = json_authenticate(client)
token = response.json["response"]["user"]["authentication_token"]
data = '{"auth_token": "%s"}' % token
response = client.post(
"/token", data=data, headers={"Content-Type": "application/json"}
)
assert b"Token Authentication" in response.data
def test_json_not_dict(client):
response = client.post(
"/json",
data=json.dumps(["thing1", "thing2"]),
headers={"Content-Type": "application/json"},
)
assert response.status_code == 200
def test_login_info(client):
# Make sure we can get user info when logged in already.
json_authenticate(client)
response = client.get("/login", headers={"Content-Type": "application/json"})
assert response.status_code == 200
assert response.json["response"]["user"]["email"] == "matt@lp.com"
assert "last_update" in response.json["response"]["user"]
response = client.get("/login", headers={"Accept": "application/json"})
assert response.status_code == 200
assert response.json["response"]["user"]["email"] == "matt@lp.com"
assert "last_update" in response.json["response"]["user"]
@pytest.mark.registerable()
@pytest.mark.settings(post_login_view="/anon_required")
def test_anon_required(client, get_message):
"""If logged in, should get 'anonymous_user_required' redirect"""
response = authenticate(client, follow_redirects=False)
response = client.get("/register")
assert "location" in response.headers
assert "/anon_required" in response.location
@pytest.mark.registerable()
@pytest.mark.settings(post_login_view="/anon_required")
def test_anon_required_json(client, get_message):
"""If logged in, should get 'anonymous_user_required' response"""
authenticate(client, follow_redirects=False)
response = client.get("/register", headers={"Accept": "application/json"})
assert response.status_code == 400
assert response.json["response"]["errors"][0].encode("utf-8") == get_message(
"ANONYMOUS_USER_REQUIRED"
)
def test_change_uniquifier(app, client_nc):
# make sure that existing token no longer works once we change the uniquifier
response = json_authenticate(client_nc)
token = response.json["response"]["user"]["authentication_token"]
verify_token(client_nc, token)
# now change uniquifier
with app.test_request_context("/"):
user = app.security.datastore.find_user(email="matt@lp.com")
app.security.datastore.reset_user_access(user)
app.security.datastore.commit()
verify_token(client_nc, token, status=401)
# get new token and verify it works
response = json_authenticate(client_nc)
token = response.json["response"]["user"]["authentication_token"]
verify_token(client_nc, token)
def test_verifying_token_from_version_3x(in_app_context):
"""
Check token generated with flask security 3.x, which has different form
than token from version 4.0.0, can be verified
"""
app = in_app_context
populate_data(app)
with app.test_request_context("/"):
user = app.security.datastore.find_user(email="matt@lp.com")
token = get_auth_token_version_3x(app, user)
data = app.security.remember_token_serializer.loads(
token, max_age=app.security.token_max_age
)
assert user.verify_auth_token(data) is True
def test_change_token_uniquifier(app):
pytest.importorskip("sqlalchemy")
# make sure that existing token no longer works once we change the token uniquifier
from sqlalchemy import Column, String
from flask_sqlalchemy import SQLAlchemy
from flask_security.models import fsqla_v2 as fsqla
from flask_security import Security, SQLAlchemyUserDatastore
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///:memory:"
db = SQLAlchemy(app)
fsqla.FsModels.set_db_info(db)
class Role(db.Model, fsqla.FsRoleMixin):
pass
class User(db.Model, fsqla.FsUserMixin):
fs_token_uniquifier = Column(String(64), unique=True, nullable=False)
with app.app_context():
db.create_all()
ds = SQLAlchemyUserDatastore(db, User, Role)
app.security = Security(app, datastore=ds)
with app.app_context():
ds.create_user(
email="matt@lp.com",
password=hash_password("password"),
)
ds.commit()
client_nc = app.test_client(use_cookies=False)
response = json_authenticate(client_nc)
token = response.json["response"]["user"]["authentication_token"]
verify_token(client_nc, token)
# now change uniquifier
with app.test_request_context("/"):
user = app.security.datastore.find_user(email="matt@lp.com")
app.security.datastore.reset_user_access(user)
app.security.datastore.commit()
verify_token(client_nc, token, status=401)
# get new token and verify it works
response = json_authenticate(client_nc)
token = response.json["response"]["user"]["authentication_token"]
verify_token(client_nc, token)
def test_null_token_uniquifier(app):
pytest.importorskip("sqlalchemy")
# If existing record has a null fs_token_uniquifier, should be set on first use.
from sqlalchemy import Column, String
from flask_sqlalchemy import SQLAlchemy
from flask_security.models import fsqla_v2 as fsqla
from flask_security import Security, SQLAlchemyUserDatastore
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///:memory:"
db = SQLAlchemy(app)
fsqla.FsModels.set_db_info(db)
class Role(db.Model, fsqla.FsRoleMixin):
pass
class User(db.Model, fsqla.FsUserMixin):
fs_token_uniquifier = Column(String(64), unique=True, nullable=True)
with app.app_context():
db.create_all()
ds = SQLAlchemyUserDatastore(db, User, Role)
app.security = Security(app, datastore=ds)
with app.app_context():
ds.create_user(
email="matt@lp.com",
password=hash_password("password"),
)
ds.commit()
# manually null out fs_token_uniquifier
user = ds.find_user(email="matt@lp.com")
user.fs_token_uniquifier = None
ds.put(user)
ds.commit()
client_nc = app.test_client(use_cookies=False)
response = json_authenticate(client_nc)
token = response.json["response"]["user"]["authentication_token"]
verify_token(client_nc, token)
def test_token_query(app, client_nc):
# Verify that when authenticating with auth token (and not session)
# that there is just one DB query to get user.
with app.app_context():
response = json_authenticate(client_nc)
token = response.json["response"]["user"]["authentication_token"]
assert get_num_queries(app.security.datastore) == 1