Debian Codegraph @

tests/test_misc.py

raw
1 """
2 test_misc
3 ~~~~~~~~~~~
4
5 Lots of tests
6
7 :copyright: (c) 2012 by Matt Wright.
8 :copyright: (c) 2019-2025 by J. Christopher Wagner (jwag).
9 :license: MIT, see LICENSE for more details.
10 """
11
12 from datetime import timedelta
13 import hashlib
14 from unittest import mock
15 import re
16 import os.path
17 import time
18 import typing as t
19
20 import pytest
21
22 from itsdangerous import BadTimeSignature
23 from wtforms.validators import DataRequired, Length
24
25 from tests.test_utils import (
26 authenticate,
27 capture_flashes,
28 capture_reset_password_requests,
29 check_location,
30 check_signals,
31 check_xlation,
32 get_csrf_token,
33 init_app_with_options,
34 json_authenticate,
35 logout,
36 populate_data,
37 reset_fresh,
38 get_form_input,
39 is_authenticated,
40 )
41 from tests.test_webauthn import HackWebauthnUtil, reg_2_keys
42
43 from flask import Flask, abort, request, Response
44 from flask_security import Security
45 from flask_security.forms import (
46 ChangePasswordForm,
47 ConfirmRegisterForm,
48 EmailField,
49 EmailValidation,
50 ForgotPasswordForm,
51 LoginForm,
52 PasswordField,
53 PasswordlessLoginForm,
54 RegisterForm,
55 RegisterFormV2,
56 RequiredLocalize,
57 ResetPasswordForm,
58 SendConfirmationForm,
59 StringField,
60 email_required,
61 valid_user_email,
62 )
63 from flask_security import auth_required, roles_required
64 from flask_security.utils import (
65 base_render_json,
66 encode_string,
67 json_error_response,
68 get_request_attr,
69 hash_data,
70 send_mail,
71 uia_email_mapper,
72 uia_phone_mapper,
73 verify_hash,
74 get_post_action_redirect,
75 )
76 from flask_security.core import _get_serializer
77
78 if t.TYPE_CHECKING: # pragma: no cover
79 from flask.testing import FlaskClient
80
81
82 @pytest.mark.recoverable()
83 def test_my_mail_util(app, sqlalchemy_datastore):
84 from flask_security import MailUtil
85
86 class MyMailUtil(MailUtil):
87 def send_mail(
88 self, template, subject, recipient, sender, body, html, user, **kwargs
89 ):
90 assert template == "reset_instructions"
91 assert subject == app.config["SECURITY_EMAIL_SUBJECT_PASSWORD_RESET"]
92 assert recipient == "[email protected]"
93 assert user.email == "[email protected]"
94 assert sender == "no-reply@localhost"
95 assert isinstance(sender, str)
96
97 init_app_with_options(
98 app, sqlalchemy_datastore, **{"security_args": {"mail_util_cls": MyMailUtil}}
99 )
100
101 client = app.test_client()
102 client.post("/reset", data=dict(email="[email protected]"))
103
104
105 def test_register_blueprint_flag(app, sqlalchemy_datastore):
106 app.security = Security(
107 app, datastore=sqlalchemy_datastore, register_blueprint=False
108 )
109 client = app.test_client()
110 response = client.get("/login")
111 assert response.status_code == 404
112
113
114 @pytest.mark.registerable()
115 @pytest.mark.recoverable()
116 @pytest.mark.changeable()
117 @pytest.mark.settings(
118 USER_IDENTITY_ATTRIBUTES=[
119 {"email": {"mapper": uia_email_mapper}},
120 {"username": {"mapper": lambda x: x}},
121 ]
122 )
123 @pytest.mark.filterwarnings(
124 "ignore:.*The RegisterForm is deprecated.*:DeprecationWarning"
125 )
126 def test_basic_custom_forms(app, sqlalchemy_datastore):
127 class MyLoginForm(LoginForm):
128 username = StringField("My Login Username Field")
129
130 class MyRegisterForm(RegisterForm):
131 email = EmailField("My Register Email Address Field")
132
133 class MyForgotPasswordForm(ForgotPasswordForm):
134 email = EmailField(
135 "My Forgot Email Address Field",
136 validators=[email_required, EmailValidation(verify=True), valid_user_email],
137 )
138
139 class MyResetPasswordForm(ResetPasswordForm):
140 password = StringField("My Reset Password Field")
141
142 class MyChangePasswordForm(ChangePasswordForm):
143 password = PasswordField("My Change Password Field")
144
145 app.security = Security(
146 app,
147 datastore=sqlalchemy_datastore,
148 login_form=MyLoginForm,
149 register_form=MyRegisterForm,
150 forgot_password_form=MyForgotPasswordForm,
151 reset_password_form=MyResetPasswordForm,
152 change_password_form=MyChangePasswordForm,
153 )
154
155 populate_data(app)
156 client = app.test_client()
157
158 response = client.get("/login")
159 assert b"My Login Username Field" in response.data
160
161 response = client.get("/register")
162 assert b"My Register Email Address Field" in response.data
163
164 response = client.get("/reset")
165 assert b"My Forgot Email Address Field" in response.data
166
167 with capture_reset_password_requests() as requests:
168 response = client.post("/reset", data=dict(email="[email protected]"))
169
170 token = requests[0]["token"]
171 response = client.get("/reset/" + token)
172 assert b"My Reset Password Field" in response.data
173
174 authenticate(client)
175
176 response = client.get("/change")
177 assert b"My Change Password Field" in response.data
178
179
180 @pytest.mark.registerable()
181 @pytest.mark.confirmable()
182 @pytest.mark.settings(use_register_v2=False)
183 @pytest.mark.filterwarnings("ignore:.*The ConfirmRegisterForm.*:DeprecationWarning")
184 def test_confirmable_custom_form(app, sqlalchemy_datastore):
185 class MyRegisterForm(ConfirmRegisterForm):
186 email = EmailField("My Register Email Address Field")
187
188 class MySendConfirmationForm(SendConfirmationForm):
189 email = EmailField("My Send Confirmation Email Address Field")
190
191 app.security = Security(
192 app,
193 datastore=sqlalchemy_datastore,
194 send_confirmation_form=MySendConfirmationForm,
195 confirm_register_form=MyRegisterForm,
196 )
197
198 client = app.test_client()
199
200 response = client.get("/register")
201 assert b"My Register Email Address Field" in response.data
202
203 response = client.get("/confirm")
204 assert b"My Send Confirmation Email Address Field" in response.data
205
206
207 def test_passwordless_custom_form(app, sqlalchemy_datastore):
208 app.config["SECURITY_PASSWORDLESS"] = True
209
210 class MyPasswordlessLoginForm(PasswordlessLoginForm):
211 email = EmailField("My Passwordless Email Address Field")
212
213 app.security = Security(
214 app,
215 datastore=sqlalchemy_datastore,
216 passwordless_login_form=MyPasswordlessLoginForm,
217 )
218
219 client = app.test_client()
220
221 response = client.get("/login")
222 assert b"My Passwordless Email Address Field" in response.data
223
224
225 @pytest.mark.parametrize("logout_methods", (["GET", "POST"], ["GET"], ["POST"]))
226 def test_logout_methods(app, sqlalchemy_datastore, logout_methods):
227 init_app_with_options(
228 app, sqlalchemy_datastore, **{"SECURITY_LOGOUT_METHODS": logout_methods}
229 )
230
231 client = app.test_client()
232
233 authenticate(client)
234
235 response = client.get("/logout", follow_redirects=True)
236
237 if "GET" in logout_methods:
238 assert response.status_code == 200
239
240 authenticate(client)
241
242 else:
243 assert response.status_code == 405 # method not allowed
244
245 response = client.post("/logout", follow_redirects=True)
246
247 if "POST" in logout_methods:
248 assert response.status_code == 200
249
250 else:
251 assert response.status_code == 405 # method not allowed
252
253
254 def test_logout_methods_none(app, sqlalchemy_datastore):
255 init_app_with_options(
256 app, sqlalchemy_datastore, **{"SECURITY_LOGOUT_METHODS": None}
257 )
258
259 client = app.test_client()
260
261 authenticate(client)
262
263 response = client.get("/logout", follow_redirects=True)
264
265 assert response.status_code == 404
266
267 response = client.post("/logout", follow_redirects=True)
268
269 assert response.status_code == 404
270
271
272 def test_passwordless_and_two_factor_configuration_mismatch(app, sqlalchemy_datastore):
273 with pytest.raises(ValueError):
274 init_app_with_options(
275 app,
276 sqlalchemy_datastore,
277 **{"SECURITY_TWO_FACTOR": True, "SECURITY_TWO_FACTOR_ENABLED_METHODS": []},
278 )
279
280
281 def test_flash_messages_off(app, sqlalchemy_datastore, get_message):
282 init_app_with_options(
283 app, sqlalchemy_datastore, **{"SECURITY_FLASH_MESSAGES": False}
284 )
285 client = app.test_client()
286 response = client.get("/profile")
287 assert get_message("LOGIN") not in response.data
288
289
290 def test_invalid_hash_scheme(app, sqlalchemy_datastore, get_message):
291 with pytest.raises(ValueError):
292 init_app_with_options(
293 app, sqlalchemy_datastore, **{"SECURITY_PASSWORD_HASH": "bogus"}
294 )
295
296
297 def test_change_hash_type(app, sqlalchemy_datastore):
298 init_app_with_options(
299 app,
300 sqlalchemy_datastore,
301 **{
302 "SECURITY_PASSWORD_HASH": "plaintext",
303 "SECURITY_PASSWORD_SALT": None,
304 "SECURITY_PASSWORD_SCHEMES": ["argon2", "plaintext"],
305 },
306 )
307
308 app.config["SECURITY_PASSWORD_HASH"] = "argon2"
309 app.config["SECURITY_PASSWORD_SALT"] = "salty"
310
311 app.security = Security(
312 app, datastore=sqlalchemy_datastore, register_blueprint=False
313 )
314
315 client = app.test_client()
316
317 response = client.post(
318 "/login", data=dict(email="[email protected]", password="password")
319 )
320 assert response.status_code in [302, 303]
321
322 response = client.get("/logout")
323
324 response = client.post(
325 "/login", data=dict(email="[email protected]", password="password")
326 )
327 assert response.status_code in [302, 303]
328
329
330 @pytest.mark.settings(hashing_schemes=["hex_md5"], deprecated_hashing_schemes=[])
331 @pytest.mark.parametrize("data", ["hellö", b"hello"])
332 def test_legacy_hash(in_app_context, data):
333 legacy_hash = hashlib.md5(encode_string(data)).hexdigest()
334 new_hash = hash_data(data)
335 assert legacy_hash == new_hash
336
337
338 def test_hash_data(in_app_context):
339 data = hash_data(b"hello")
340 assert isinstance(data, str)
341 data = hash_data("hellö")
342 assert isinstance(data, str)
343
344
345 def test_verify_hash(in_app_context):
346 data = hash_data("hellö")
347 assert verify_hash(data, "hellö") is True
348 assert verify_hash(data, "hello") is False
349
350 legacy_data = hashlib.md5(encode_string("hellö")).hexdigest()
351 assert verify_hash(legacy_data, "hellö") is True
352 assert verify_hash(legacy_data, "hello") is False
353
354
355 @pytest.mark.settings(
356 password_salt="öööööööööööööööööööööööööööööööööö", password_hash="bcrypt"
357 )
358 def test_password_unicode_password_salt(client):
359 response = authenticate(client)
360 assert response.status_code in [302, 303]
361 response = authenticate(client, follow_redirects=True)
362 assert b"Welcome [email protected]" in response.data
363
364
365 @pytest.mark.registerable()
366 def test_custom_forms_via_config(app, sqlalchemy_datastore):
367 class MyLoginForm(LoginForm):
368 email = StringField("My Login Email Address Field")
369
370 class MyRegisterForm(RegisterFormV2):
371 email = StringField("My Register Email Address Field")
372
373 app.config["SECURITY_LOGIN_FORM"] = MyLoginForm
374 app.config["SECURITY_REGISTER_FORM"] = MyRegisterForm
375
376 security = Security(datastore=sqlalchemy_datastore)
377 security.init_app(app)
378
379 client = app.test_client()
380 response = client.get("/login")
381 assert b"My Login Email Address Field" in response.data
382
383 response = client.get("/register")
384 assert b"My Register Email Address Field" in response.data
385
386
387 def test_custom_form_instantiator(app, client, get_message):
388 # Test application form instantiation.
389 # This is using the form factory pattern.
390 # Note in this case - Flask-Security doesn't even know the form class name.
391 from flask_security import FormInfo
392
393 class FormInstantiator:
394 def __init__(self, myservice):
395 self.myservice = myservice
396
397 def instantiator(self, form_name, form_cls, *args, **kwargs):
398 if form_name == "login_form":
399 return MyLoginForm(*args, service=self.myservice, **kwargs)
400 raise ValueError("Unknown Form")
401
402 class MyLoginForm(LoginForm):
403 def __init__(self, *args, service=None, **kwargs):
404 super().__init__(*args, **kwargs)
405 self.myservice = service
406
407 def validate(self, **kwargs: t.Any) -> bool:
408 if not super().validate(**kwargs): # pragma: no cover
409 return False
410 assert isinstance(self.email.errors, list)
411 if not self.myservice(self.email.data):
412 self.email.errors.append("Not happening")
413 return False
414 return True
415
416 def login_checker(email):
417 return True if email == "[email protected]" else False
418
419 fi = FormInstantiator(login_checker)
420 app.security.set_form_info("login_form", FormInfo(fi.instantiator))
421
422 response = authenticate(client, follow_redirects=True)
423 assert b"Welcome [email protected]" in response.data
424 logout(client)
425
426 # Try a normally legit user - but our service denies it
427 response = authenticate(client, email="[email protected]")
428 assert b"Not happening" in response.data
429
430
431 def test_custom_form_instantiator2(app, client, get_message):
432 # Test application form instantiation.
433 # This is using the form clone pattern.
434 # Note in this case - Flask-Security doesn't even know the form class name.
435 app.config["WTF_CSRF_ENABLED"] = True
436 from flask_security import FormInfo
437
438 class MyLoginForm(LoginForm):
439 def __init__(self, *args, service=None, **kwargs):
440 super().__init__(*args, **kwargs)
441 self.myservice = service
442
443 def instantiator(self, form_name, form_cls, *args, **kwargs):
444 return MyLoginForm(*args, service=self.myservice, **kwargs)
445
446 def validate(self, **kwargs: t.Any) -> bool:
447 if not super().validate(**kwargs): # pragma: no cover
448 return False
449 assert isinstance(self.email.errors, list)
450 if not self.myservice(self.email.data):
451 self.email.errors.append("Not happening")
452 return False
453 return True
454
455 def login_checker(email):
456 return True if email == "[email protected]" else False
457
458 with app.test_request_context():
459 fi = MyLoginForm(formdata=None, service=login_checker)
460 app.security.set_form_info("login_form", FormInfo(fi.instantiator))
461
462 csrf_token = get_csrf_token(client)
463 response = client.post(
464 "/login",
465 data=dict(email="[email protected]", password="password", csrf_token=csrf_token),
466 follow_redirects=True,
467 )
468 assert b"Welcome [email protected]" in response.data
469 logout(client)
470
471 # Try a normally legit user - but our service denies it
472 csrf_token = get_csrf_token(client)
473 response = client.post(
474 "/login",
475 data=dict(email="[email protected]", password="password", csrf_token=csrf_token),
476 )
477 assert b"Not happening" in response.data
478
479
480 def test_custom_form_setting(app, sqlalchemy_datastore):
481 from flask_security import FormInfo
482
483 security = Security(app=app, datastore=sqlalchemy_datastore)
484 with pytest.raises(ValueError) as vex:
485 security.set_form_info("mylogin_form", FormInfo())
486 assert "Unknown form name mylogin_form" == str(vex.value)
487 with pytest.raises(ValueError) as vex:
488 security.set_form_info("login_form", FormInfo())
489 assert "form class must be provided" in str(vex.value)
490
491
492 def test_form_required(app, sqlalchemy_datastore):
493 class MyLoginForm(LoginForm):
494 myfield = StringField("My Custom Field", validators=[RequiredLocalize()])
495
496 app.config["SECURITY_LOGIN_FORM"] = MyLoginForm
497
498 security = Security(datastore=sqlalchemy_datastore)
499 security.init_app(app)
500
501 client = app.test_client()
502
503 response = client.post("/login", content_type="application/json")
504 assert response.status_code == 400
505 assert b"myfield" in response.data
506
507
508 def test_form_required_local_message(app, sqlalchemy_datastore):
509 """Test having a local message (not xlatable and not part of MSG_ config."""
510
511 msg = "hi! did you forget me?"
512
513 class MyLoginForm(LoginForm):
514 myfield = StringField(
515 "My Custom Field", validators=[RequiredLocalize(message=msg)]
516 )
517
518 app.config["SECURITY_LOGIN_FORM"] = MyLoginForm
519
520 security = Security(datastore=sqlalchemy_datastore)
521 security.init_app(app)
522
523 client = app.test_client()
524
525 response = client.post("/login", content_type="application/json")
526 assert response.status_code == 400
527 assert b"myfield" in response.data
528 assert msg.encode("utf-8") in response.data
529 # WTforms 2.x incorrectly catches ValueError and sets that as the form error.
530 # Our config_value routine raises ValueError for missing config items..
531 assert b"Key" not in response.data
532
533
534 def test_without_babel(app, client):
535 # Test if babel modules exist but we don't init babel - things still work
536 app.config["BABEL_DEFAULT_LOCALE"] = "fr_FR"
537 response = client.get("/login")
538 assert response.status_code == 200
539
540
541 def test_no_email_sender(app, sqlalchemy_datastore, outbox):
542 """Verify that if SECURITY_EMAIL_SENDER is default
543 (which is a local proxy) that send_mail picks up MAIL_DEFAULT_SENDER.
544 """
545 app.config["MAIL_DEFAULT_SENDER"] = "[email protected]"
546
547 class TestUser:
548 def __init__(self, email):
549 self.email = email
550
551 security = Security()
552 security.init_app(app, sqlalchemy_datastore)
553
554 with app.app_context():
555 user = TestUser("[email protected]")
556 send_mail("Test Default Sender", user.email, "welcome", user=user)
557 assert 1 == len(outbox)
558 assert "[email protected]" == outbox[0].sender
559
560
561 def test_sender_tuple(app, sqlalchemy_datastore, outbox):
562 """Verify that if sender is a (name, address) tuple,
563 in the received email sender is properly formatted as "name <address>"
564 Flask-Mail takes tuples - Flask-Mailman takes them - however the
565 local-mem backend doesn't format them correctly (SMTP backend doesn't work either?)
566 """
567 app.config["MAIL_DEFAULT_SENDER"] = ("Test User", "[email protected]")
568
569 class TestUser:
570 def __init__(self, email):
571 self.email = email
572
573 security = Security()
574 security.init_app(app, sqlalchemy_datastore)
575
576 with app.app_context():
577 user = TestUser("[email protected]")
578 send_mail("Test Tuple Sender", user.email, "welcome", user=user)
579 assert 1 == len(outbox)
580 assert outbox[0].sender == "Test User <[email protected]>"
581
582
583 def test_send_mail_context(app, sqlalchemy_datastore, outbox):
584 """Test full context sent to MailUtil/send_mail"""
585 app.config["MAIL_DEFAULT_SENDER"] = "[email protected]"
586 app.security = Security()
587 app.security.init_app(app, sqlalchemy_datastore)
588
589 class TestUser:
590 def __init__(self, email):
591 self.email = email
592
593 @app.security.mail_context_processor
594 def mail():
595 return {"foo": "bar-mail"}
596
597 with app.app_context():
598 user = TestUser("[email protected]")
599 send_mail("Test Default Sender", user.email, "welcome", user=user)
600 assert 1 == len(outbox)
601 assert "[email protected]" == outbox[0].sender
602 matcher = re.match(
603 r".*ExtraContext:(\S+).*", outbox[0].body, re.IGNORECASE | re.DOTALL
604 )
605 assert matcher.group(1) == "bar-mail"
606
607
608 @pytest.mark.babel()
609 @pytest.mark.app_settings(babel_default_locale="fr_FR")
610 def test_xlation(app, client):
611 assert check_xlation(app, "fr_FR"), "You must run python setup.py compile_catalog"
612
613 response = client.get("/login")
614 assert b'<label for="password">Mot de passe</label>' in response.data
615 response = authenticate(client)
616 assert response.status_code in [302, 303]
617 response = authenticate(client, follow_redirects=True)
618 assert b"Bienvenue [email protected]" in response.data
619
620
621 @pytest.mark.babel()
622 @pytest.mark.app_settings(babel_default_locale="fr_FR")
623 def test_myxlation(app, sqlalchemy_datastore, pytestconfig):
624 # Test changing a single MSG and having an additional translation dir
625 # Flask-BabelEx doesn't support lists of directories..
626 pytest.importorskip("flask_babel")
627
628 i18n_dirname = [
629 "builtin",
630 os.path.join(pytestconfig.rootdir, "tests/translations"),
631 ]
632 init_app_with_options(
633 app, sqlalchemy_datastore, **{"SECURITY_I18N_DIRNAME": i18n_dirname}
634 )
635
636 assert check_xlation(app, "fr_FR"), "You must run python setup.py compile_catalog"
637
638 app.config["SECURITY_MSG_INVALID_PASSWORD"] = ("Password no-worky", "error")
639
640 client = app.test_client()
641 response = client.post("/login", data=dict(email="[email protected]", password="forgot"))
642 assert b"Passe - no-worky" in response.data
643
644
645 @pytest.mark.babel()
646 @pytest.mark.app_settings(babel_default_locale="fr_FR")
647 def test_myxlation_complete(app, sqlalchemy_datastore, pytestconfig):
648 # Test having own translations and not using builtin.
649 pytest.importorskip("flask_babel")
650 i18n_dirname = [
651 os.path.join(pytestconfig.rootdir, "tests/translations"),
652 ]
653 init_app_with_options(
654 app, sqlalchemy_datastore, **{"SECURITY_I18N_DIRNAME": i18n_dirname}
655 )
656
657 assert check_xlation(app, "fr_FR"), "You must run python setup.py compile_catalog"
658
659 app.config["SECURITY_MSG_INVALID_PASSWORD"] = ("Password no-worky", "error")
660
661 client = app.test_client()
662 response = client.post("/login", data=dict(email="[email protected]", password="forgot"))
663 assert b"Passe - no-worky" in response.data
664
665
666 @pytest.mark.babel()
667 @pytest.mark.app_settings(babel_default_locale="fr_FR")
668 def test_form_labels(app, sqlalchemy_datastore):
669 app.security = Security()
670 app.security.init_app(app, sqlalchemy_datastore)
671 assert check_xlation(app, "fr_FR"), "You must run python setup.py compile_catalog"
672
673 with app.test_request_context():
674 rform = RegisterForm()
675 assert str(rform.password.label.text) == "Mot de passe"
676 assert str(rform.password_confirm.label.text) == "Confirmer le mot de passe"
677 assert str(rform.email.label.text) == "Adresse email"
678 assert str(rform.submit.label.text) == "Inscription"
679
680 form = LoginForm()
681 assert str(form.password.label.text) == "Mot de passe"
682 assert str(form.remember.label.text) == "Se souvenir de moi"
683 assert str(form.email.label.text) == "Adresse email"
684 assert str(form.submit.label.text) == "Connexion"
685
686 form = ChangePasswordForm()
687 assert str(form.password.label.text) == "Mot de passe"
688 assert str(form.new_password.label.text) == "Nouveau mot de passe"
689 assert str(form.new_password_confirm.label.text) == "Confirmer le mot de passe"
690 assert str(form.submit.label.text) == "Changer le mot de passe"
691
692
693 @pytest.mark.babel()
694 @pytest.mark.app_settings(babel_default_locale="fr_FR")
695 def test_wtform_xlation(app, sqlalchemy_datastore):
696 # Make sure wtform xlations work
697 class MyLoginForm(LoginForm):
698 fixed_length = StringField(
699 "FixedLength", validators=[DataRequired(), Length(3, 3)]
700 )
701
702 app.security = Security()
703 app.security.init_app(app, datastore=sqlalchemy_datastore, login_form=MyLoginForm)
704 assert check_xlation(app, "fr_FR"), "You must run python setup.py compile_catalog"
705
706 client = app.test_client()
707 response = client.get("/login")
708 assert b'<label for="password">Mot de passe</label>' in response.data
709 data = dict(
710 email="[email protected]", password="", remember="y", fixed_length="waytoolong"
711 )
712 response = client.post(
713 "/login", json=data, headers={"Content-Type": "application/json"}
714 )
715 assert response.status_code == 400
716 flerror = response.json["response"]["field_errors"]["fixed_length"][0]
717 # This is completely dependent on WTforms translations....
718 assert (
719 flerror == "Le doit contenir exactement 3 caractères."
720 or flerror == "Le champ doit contenir exactement 3 caractères."
721 )
722
723
724 @pytest.mark.changeable()
725 @pytest.mark.babel()
726 def test_per_request_xlate(app, client):
727 from flask import request, session
728
729 babel = app.extensions["babel"]
730
731 def get_locale():
732 # For a given session - set lang based on first request.
733 # Honor explicit url request first
734 if "lang" not in session:
735 locale = request.args.get("lang", None)
736 if not locale:
737 locale = request.accept_languages.best
738 if locale:
739 session["lang"] = locale
740 return session.get("lang", None).replace("-", "_")
741
742 babel.locale_selector_func = get_locale
743 babel.locale_selector = get_locale # Flask-Babel >= 3.0.0
744
745 response = client.get("/login", headers=[("Accept-Language", "fr")])
746 assert b'<label for="password">Mot de passe</label>' in response.data
747 # make sure template contents get xlated (not just form).
748 assert b"<h1>Connexion</h1>" in response.data
749
750 data = dict(email="[email protected]", password="", remember="y")
751 response = client.post("/login", data=data, headers=[("Accept-Language", "fr")])
752 assert response.status_code == 200
753
754 # verify errors are xlated
755 assert b"Merci d&#39;indiquer un mot de passe" in response.data
756
757 # log in correctly - this should set locale in session
758 data = dict(email="[email protected]", password="password", remember="y")
759 response = client.post(
760 "/login", data=data, headers=[("Accept-Language", "fr")], follow_redirects=True
761 )
762 assert response.status_code == 200
763
764 # make sure further requests always get correct xlation w/o sending header
765 response = client.get("/change", follow_redirects=True)
766 assert response.status_code == 200
767 assert b"Nouveau mot de passe" in response.data
768 assert b"<h1>Changer le mot de passe</h1>" in response.data
769
770 # try JSON
771 response = client.post(
772 "/change",
773 json=dict(email="[email protected]"),
774 headers={"Content-Type": "application/json"},
775 )
776 assert response.status_code == 400
777 assert response.json["response"]["field_errors"]["new_password"] == [
778 "Merci d'indiquer un mot de passe"
779 ]
780
781
782 """
783 This cant work yet due to zxcvbn usage of gettext
784 def test_zxcvbn_xlate(app):
785 class TestUser(object):
786 def __init__(self, email):
787 self.email = email
788
789 app.config["BABEL_DEFAULT_LOCALE"] = "fr_FR"
790 app.security = Security()
791 app.security.init_app(app)
792 assert check_xlation(app, "fr_FR"), "You must run python setup.py compile_catalog"
793
794 with app.test_request_context():
795 user = TestUser("[email protected]")
796 pbad, pnorm = app.security.password_util.validate("simple", False, user=user)
797 print(pbad)
798 """
799
800
801 @pytest.mark.settings(password_check_breached="strict")
802 def test_breached(app, sqlalchemy_datastore):
803 # partial response from: https://api.pwnedpasswords.com/range/07003
804 pwned_response = b"AF5A73CD3CBCFDCD12B0B68CB7930F3E888:2\r\n\
805 AFD8AA47E6FD782ADDC11D89744769F7354:2\r\n\
806 B04334E179537C975D0B3C72DA2E5B68E44:15\r\n\
807 B118F58C2373FDF97ACF93BD3339684D1EB:2\r\n\
808 B1ED5D27429EDF77EFD84F4EA9BDA5013FB:4\r\n\
809 B25C03CFBE4CBF19E0F4889711C9A488E5D:2\r\n\
810 B3902FD808DCA504AAAD30F3C14BD3ACE7C:10"
811
812 app.security = Security()
813 app.security.init_app(app, sqlalchemy_datastore)
814 with app.test_request_context():
815 with mock.patch("urllib.request.urlopen") as mock_urlopen:
816 mock_urlopen.return_value.__enter__.return_value.read.return_value = (
817 pwned_response
818 )
819 pbad, pnorm = app.security.password_util.validate("flaskflask", False)
820 assert len(pbad) == 1
821 assert app.config["SECURITY_MSG_PASSWORD_BREACHED"][0] in pbad[0]
822
823
824 @pytest.mark.settings(
825 password_check_breached="strict",
826 password_breached_count=16,
827 password_complexity_checker="zxcvbn",
828 )
829 def test_breached_cnt(app, sqlalchemy_datastore):
830 # partial response from: https://api.pwnedpasswords.com/range/07003
831 pwned_response = b"AF5A73CD3CBCFDCD12B0B68CB7930F3E888:2\r\n\
832 AFD8AA47E6FD782ADDC11D89744769F7354:2\r\n\
833 B04334E179537C975D0B3C72DA2E5B68E44:15\r\n\
834 B118F58C2373FDF97ACF93BD3339684D1EB:2\r\n\
835 B1ED5D27429EDF77EFD84F4EA9BDA5013FB:4\r\n\
836 B25C03CFBE4CBF19E0F4889711C9A488E5D:2\r\n\
837 B3902FD808DCA504AAAD30F3C14BD3ACE7C:10"
838
839 app.security = Security()
840 app.security.init_app(app, sqlalchemy_datastore)
841 with app.test_request_context():
842 with mock.patch("urllib.request.urlopen") as mock_urlopen:
843 mock_urlopen.return_value.__enter__.return_value.read.return_value = (
844 pwned_response
845 )
846 pbad, pnorm = app.security.password_util.validate("flaskflask", True)
847 # Still weak password, just not pwned enough. Should fail complexity
848 assert len(pbad) == 1
849 assert "Repeats like" in pbad[0]
850
851
852 @pytest.mark.skip
853 @pytest.mark.settings(password_check_breached="strict")
854 def test_breached_real(app, sqlalchemy_datastore):
855 """Actually go out to internet.."""
856
857 app.security = Security()
858 app.security.init_app(app, sqlalchemy_datastore)
859 with app.test_request_context():
860 pbad, pnorm = app.security.password_util.validate("flaskflask", True)
861 assert len(pbad) == 1
862 assert app.config["SECURITY_MSG_PASSWORD_BREACHED"][0] in pbad[0]
863
864
865 def test_json_error_response_string():
866 """Unit test for correct response when a string is given."""
867 error_msg = "This is an error!"
868 response = json_error_response(errors=error_msg)
869 assert "field_errors" not in response
870 assert response["errors"][0] == error_msg
871
872
873 def test_json_error_response_dict():
874 """Unit test for correct response when a dict is given."""
875 error_msg = {
876 "e-mail": ["The e-mail address is already in the system."],
877 "name": ["The name is too long.", "Nice name"],
878 }
879 all_msgs = []
880 [all_msgs.extend(m) for m in error_msg.values()]
881 response = json_error_response(field_errors=error_msg)
882 assert "errors" in response
883 assert "field_errors" in response
884 assert all(m in response["errors"] for m in all_msgs)
885
886
887 def test_json_error_response_typeerror():
888 """Unit test for checking for error raising."""
889 error_msg = ("tuple",)
890 with pytest.raises(TypeError):
891 json_error_response(errors=error_msg)
892
893
894 def test_json_form_errors(app, client):
895 """Test wtforms form level errors are correctly sent via json"""
896 with app.test_request_context():
897 form = ChangePasswordForm()
898 form.validate()
899 form.form_errors.append("I am an error")
900 response = base_render_json(form)
901 error_list = response.json["response"]["errors"]
902 assert len(error_list) == 3
903 assert "I am an error" in error_list
904
905
906 def test_method_view(app, client):
907 # auth_required with flask method view
908 from flask.views import MethodView
909 from flask import render_template_string
910
911 class MyView(MethodView):
912 decorators = [auth_required("token", "session")]
913
914 def get(self):
915 return render_template_string("Hi view")
916
917 myview = MyView.as_view("myview")
918
919 app.add_url_rule("/myview", view_func=myview, methods=["GET"])
920
921 response = client.get("/myview", follow_redirects=False)
922 # should require login
923 assert response.status_code in [302, 303]
924 assert "/login" in response.location
925
926 authenticate(client)
927 response = client.get("/myview")
928 assert response.status_code == 200
929 assert b"Hi view" in response.data
930
931
932 def test_phone_util_override(app, sqlalchemy_datastore):
933 from flask_security import phone_util
934
935 class MyPhoneUtil(phone_util.PhoneUtil):
936 def validate_phone_number(self, input_data):
937 return "call-me"
938
939 def get_canonical_form(self, input_data):
940 return "very-canonical"
941
942 app.security = Security(phone_util_cls=MyPhoneUtil)
943 app.security.init_app(app, sqlalchemy_datastore)
944
945 with app.app_context():
946 assert uia_phone_mapper("55") == "very-canonical"
947
948
949 def test_authn_freshness(
950 app: "Flask", client: "FlaskClient", get_message: t.Callable[..., bytes]
951 ) -> None:
952 """Test freshness using default reauthn_handler"""
953
954 @auth_required(within=30, grace=0)
955 def myview():
956 return Response(status=200)
957
958 @auth_required(within=0.001, grace=0)
959 def myspecialview():
960 return Response(status=200)
961
962 app.add_url_rule("/myview", view_func=myview, methods=["GET"])
963 app.add_url_rule("/myspecialview", view_func=myspecialview, methods=["GET"])
964 authenticate(client)
965
966 # This should work and not be redirected
967 response = client.get("/myview", follow_redirects=False)
968 assert response.status_code == 200
969
970 # This should require additional authn and redirect to verify
971 time.sleep(0.1)
972 with capture_flashes() as flashes:
973 response = client.get("/myspecialview", follow_redirects=False)
974 assert response.status_code in [302, 303]
975 assert response.location == "/verify?next=/myspecialview"
976 assert flashes[0]["category"] == "error"
977 assert flashes[0]["message"].encode("utf-8") == get_message(
978 "REAUTHENTICATION_REQUIRED"
979 )
980
981 # Test json error response
982 response = client.get("/myspecialview", headers={"accept": "application/json"})
983 assert response.status_code == 401
984 assert response.json and response.json["response"]["errors"][0].encode(
985 "utf-8"
986 ) == get_message("REAUTHENTICATION_REQUIRED")
987
988
989 def test_authn_freshness_handler(app, client, get_message):
990 """Test with our own handler"""
991
992 @app.security.reauthn_handler
993 def my_reauthn(within, grace, headers=None):
994 assert within == timedelta(minutes=30) or timedelta(minutes=0.001)
995 if app.security._want_json(request):
996 payload = json_error_response(errors="Oh No")
997 return app.security._render_json(payload, 401, headers, None)
998 abort(500)
999
1000 @auth_required(within=30, grace=0)
1001 def myview():
1002 return Response(status=200)
1003
1004 @auth_required(within=0.001, grace=0)
1005 def myspecialview():
1006 return Response(status=200)
1007
1008 app.add_url_rule("/myview", view_func=myview, methods=["GET"])
1009 app.add_url_rule("/myspecialview", view_func=myspecialview, methods=["GET"])
1010 authenticate(client)
1011
1012 # This should work and not be redirected
1013 response = client.get("/myview", follow_redirects=False)
1014 assert response.status_code == 200
1015
1016 # This should require additional authn
1017 time.sleep(0.1)
1018 response = client.get("/myspecialview", follow_redirects=False)
1019 assert response.status_code == 500
1020
1021 # Test json error response
1022 response = client.get("/myspecialview", headers={"accept": "application/json"})
1023 assert response.status_code == 401
1024 assert response.json["response"]["errors"][0] == "Oh No"
1025
1026
1027 def test_authn_freshness_callable(app, client, get_message):
1028 @auth_required(within=lambda: timedelta(minutes=30))
1029 def myview():
1030 return Response(status=200)
1031
1032 app.add_url_rule("/myview", view_func=myview, methods=["GET"])
1033 authenticate(client)
1034
1035 # This should work and not be redirected
1036 response = client.get("/myview", follow_redirects=False)
1037 assert response.status_code == 200
1038
1039
1040 @pytest.mark.settings(url_prefix="/myprefix")
1041 def test_default_authn_bp(app, client):
1042 """Test default reauthn handler with blueprint prefix"""
1043
1044 @auth_required(within=1, grace=0)
1045 def myview():
1046 return Response(status=200)
1047
1048 app.add_url_rule("/myview", view_func=myview, methods=["GET"])
1049 authenticate(client, endpoint="/myprefix/login")
1050
1051 # This should require additional authn and redirect to verify
1052 reset_fresh(client, within=timedelta(minutes=1))
1053 response = client.get("/myview", follow_redirects=False)
1054 assert response.status_code in [302, 303]
1055 assert response.location == "/myprefix/verify?next=/myview"
1056
1057
1058 def test_authn_freshness_grace(app, client, get_message):
1059 # Test that grace override within.
1060 @auth_required(within=lambda: timedelta(minutes=30), grace=10)
1061 def myview():
1062 return Response(status=200)
1063
1064 @auth_required(within=0.001, grace=lambda: timedelta(minutes=10))
1065 def myspecialview():
1066 return Response(status=200)
1067
1068 app.add_url_rule("/myview", view_func=myview, methods=["GET"])
1069 app.add_url_rule("/myspecialview", view_func=myspecialview, methods=["GET"])
1070 authenticate(client)
1071
1072 # This should work and not be redirected
1073 response = client.get("/myview", follow_redirects=False)
1074 assert response.status_code == 200
1075
1076 # This should NOT require additional authn
1077 time.sleep(0.1)
1078 response = client.get("/myspecialview", follow_redirects=False)
1079 assert response.status_code == 200
1080
1081
1082 def test_authn_freshness_nc(app, client_nc, get_message):
1083 # By default, auth token carries the fs_paa time.
1084 @auth_required(within=30)
1085 def myview():
1086 return Response(status=200)
1087
1088 app.add_url_rule("/myview", view_func=myview, methods=["GET"])
1089
1090 response = json_authenticate(client_nc)
1091 token = response.json["response"]["user"]["authentication_token"]
1092 h = {"Authentication-Token": token}
1093
1094 # This should fail - should be a redirect
1095 response = client_nc.get("/myview", headers=h, follow_redirects=False)
1096 assert response.status_code == 200
1097
1098
1099 @pytest.mark.settings(freshness_allow_auth_token=False)
1100 def test_authn_freshness_nc_no(app, client_nc, get_message):
1101 # If don't send session cookie - then freshness always fails
1102 @auth_required(within=30)
1103 def myview():
1104 return Response(status=200)
1105
1106 app.add_url_rule("/myview", view_func=myview, methods=["GET"])
1107
1108 response = json_authenticate(client_nc)
1109 token = response.json["response"]["user"]["authentication_token"]
1110 h = {"Authentication-Token": token}
1111
1112 # This should fail - should be a redirect
1113 response = client_nc.get("/myview", headers=h, follow_redirects=False)
1114 assert response.status_code in [302, 303]
1115 assert response.location == "/verify?next=/myview"
1116
1117
1118 @pytest.mark.two_factor()
1119 @pytest.mark.settings(freshness=timedelta(minutes=-1), multi_factor_recovery_codes=True)
1120 def test_authn_freshness_nc_no_fresh(app, client_nc, get_message):
1121 # test disabling freshness when no session is sent.
1122 response = json_authenticate(client_nc)
1123 token = response.json["response"]["user"]["authentication_token"]
1124 h = {"Authentication-Token": token}
1125
1126 # This should work
1127 response = client_nc.get("/tf-setup", json={}, headers=h)
1128 assert response.status_code == 200
1129 assert not response.json["response"]["tf_required"]
1130
1131 response = client_nc.get("/mf-recovery-codes", json={}, headers=h)
1132 assert response.status_code == 200
1133 assert response.json["response"]["recovery_codes"] == []
1134
1135
1136 def test_verify_fresh(app, client, get_message):
1137 # Hit a fresh-required endpoint and walk through verify
1138 authenticate(client)
1139 reset_fresh(client, app.config["SECURITY_FRESHNESS"])
1140
1141 with capture_flashes() as flashes:
1142 response = client.get("/fresh", follow_redirects=True)
1143 assert b"Reauthenticate" in response.data
1144 assert flashes[0]["category"] == "error"
1145 assert flashes[0]["message"].encode("utf-8") == get_message(
1146 "REAUTHENTICATION_REQUIRED"
1147 )
1148 form_response = response.data.decode("utf-8")
1149 matcher = re.match(
1150 r'.*action="([^"]*)".*', form_response, re.IGNORECASE | re.DOTALL
1151 )
1152 verify_url = matcher.group(1)
1153
1154 reset_fresh(client, app.config["SECURITY_FRESHNESS"])
1155 response = client.get(verify_url)
1156 assert b"Reauthenticate" in response.data
1157
1158 response = client.post(
1159 verify_url, data=dict(password="not my password"), follow_redirects=False
1160 )
1161 assert b"Reauthenticate" in response.data
1162
1163 response = client.post(
1164 verify_url, data=dict(password="password"), follow_redirects=False
1165 )
1166 assert check_location(app, response.location, "/fresh")
1167
1168 # should be fine now
1169 response = client.get("/fresh", follow_redirects=True)
1170 assert b"Fresh Only" in response.data
1171
1172
1173 def test_verify_fresh_json(app, client, get_message, signals):
1174 # Hit a fresh-required endpoint and walk through verify
1175 authenticate(client)
1176 headers = {"Accept": "application/json", "Content-Type": "application/json"}
1177
1178 reset_fresh(client, app.config["SECURITY_FRESHNESS"])
1179 response = client.get("/fresh", headers=headers)
1180 assert response.status_code == 401
1181 assert response.json["response"]["reauth_required"]
1182 assert not response.json["response"]["oauth_enabled"]
1183 assert not response.json["response"]["oauth_providers"]
1184
1185 response = client.get("/verify")
1186 assert b"Reauthenticate" in response.data
1187
1188 response = client.post(
1189 "/verify", json=dict(password="not my password"), headers=headers
1190 )
1191 assert response.status_code == 400
1192 assert signals["user_failed_authn"][0]["request_endpoint"] == "security.verify"
1193 assert signals["user_failed_authn"][0]["user"].email == "[email protected]"
1194 assert signals["user_failed_authn"][0]["auth_type"] == "password"
1195 assert not signals["user_failed_authn"][0]["tfa"]
1196
1197 response = client.post("/verify", json=dict(password="password"), headers=headers)
1198 assert response.status_code == 200
1199
1200 # should be fine now
1201 response = client.get("/fresh", headers=headers)
1202 assert response.status_code == 200
1203 assert response.json["title"] == "Fresh Only"
1204 check_signals(signals, "user_failed_authn")
1205
1206
1207 @pytest.mark.changeable()
1208 def test_verify_pwd_json(app, client, get_message, signals):
1209 # Make sure verify accepts a normalized and original password.
1210 authenticate(client)
1211 headers = {"Accept": "application/json", "Content-Type": "application/json"}
1212 data = dict(
1213 password="password",
1214 new_password="new strong password\N{ROMAN NUMERAL ONE}",
1215 new_password_confirm="new strong password\N{ROMAN NUMERAL ONE}",
1216 )
1217 response = client.post(
1218 "/change",
1219 json=data,
1220 headers={"Content-Type": "application/json"},
1221 )
1222 assert response.status_code == 200
1223
1224 response = client.post(
1225 "/verify",
1226 json=dict(password="new strong password\N{ROMAN NUMERAL ONE}"),
1227 headers=headers,
1228 )
1229 assert response.status_code == 200
1230
1231 response = client.post(
1232 "/verify",
1233 json=dict(password="new strong password\N{LATIN CAPITAL LETTER I}"),
1234 headers=headers,
1235 )
1236 assert response.status_code == 200
1237 check_signals(signals, "password_changed")
1238
1239
1240 @pytest.mark.settings(verify_url="/auth/")
1241 def test_verify_next(app, client, get_message):
1242 authenticate(client)
1243 response = client.post(
1244 "/auth/?next=http://localhost/mynext",
1245 data=dict(password="password"),
1246 follow_redirects=False,
1247 )
1248 assert response.location == "http://localhost/mynext"
1249
1250
1251 @pytest.mark.webauthn(webauthn_util_cls=HackWebauthnUtil)
1252 def test_verify_wan(app, client, get_message):
1253 # test get correct options when requiring a reauthentication and have wan keys
1254 # setup.
1255 headers = {"Accept": "application/json", "Content-Type": "application/json"}
1256
1257 reg_2_keys(client)
1258
1259 reset_fresh(client, app.config["SECURITY_FRESHNESS"])
1260 response = client.get("/fresh", headers=headers)
1261 assert response.status_code == 401
1262 assert response.json["response"]["reauth_required"]
1263 assert response.json["response"]["has_webauthn_verify_credential"]
1264
1265 # the verify form should have the webauthn verify form attached
1266 response = client.get("verify")
1267 assert b'action="/wan-verify"' in response.data
1268
1269 app.config["SECURITY_WAN_ALLOW_AS_VERIFY"] = None
1270 response = client.get("/fresh", headers=headers)
1271 assert response.status_code == 401
1272 assert response.json["response"]["reauth_required"]
1273 assert not response.json["response"]["has_webauthn_verify_credential"]
1274
1275 # the verify form should NOT have the webauthn verify form attached
1276 response = client.get("verify")
1277 assert b'action="/wan-verify"' not in response.data
1278
1279
1280 def test_direct_decorator(app, client, get_message):
1281 """Test/show calling the auth_required decorator directly"""
1282 headers = {"Accept": "application/json", "Content-Type": "application/json"}
1283
1284 def myview():
1285 return roles_required("author")(domyview)()
1286
1287 def domyview():
1288 return Response(status=200)
1289
1290 app.add_url_rule("/myview", view_func=myview, methods=["GET"])
1291
1292 authenticate(client)
1293 response = client.get("/myview", headers=headers)
1294 assert response.status_code == 403
1295
1296 logout(client)
1297
1298 authenticate(client, email="[email protected]")
1299 response = client.get("/myview", headers=headers)
1300 assert response.status_code == 200
1301
1302
1303 def test_authn_via(app, client, get_message):
1304 """Test that we get correct fs_authn_via set in request"""
1305
1306 @auth_required(within=30, grace=0)
1307 def myview():
1308 assert get_request_attr("fs_authn_via") == "session"
1309 return Response(status=200)
1310
1311 app.add_url_rule("/myview", view_func=myview, methods=["GET"])
1312 authenticate(client)
1313
1314 # This should work and not be redirected
1315 response = client.get("/myview", follow_redirects=False)
1316 assert response.status_code == 200
1317
1318
1319 def test_post_security_with_application_root(app, sqlalchemy_datastore):
1320 init_app_with_options(app, sqlalchemy_datastore, **{"APPLICATION_ROOT": "/root"})
1321 client = app.test_client()
1322
1323 response = client.post(
1324 "/login", data=dict(email="[email protected]", password="password")
1325 )
1326 assert response.status_code in [302, 303]
1327 assert "/root" in response.location
1328
1329 response = client.get("/logout")
1330 assert response.status_code in [302, 303]
1331 assert "/root" in response.location
1332
1333
1334 def test_post_security_with_application_root_and_views(app, sqlalchemy_datastore):
1335 init_app_with_options(
1336 app,
1337 sqlalchemy_datastore,
1338 **{
1339 "APPLICATION_ROOT": "/root",
1340 "SECURITY_POST_LOGIN_VIEW": "/post_login",
1341 "SECURITY_POST_LOGOUT_VIEW": "/post_logout",
1342 },
1343 )
1344 client = app.test_client()
1345
1346 response = client.post(
1347 "/login", data=dict(email="[email protected]", password="password")
1348 )
1349 assert response.status_code in [302, 303]
1350 assert "/post_login" in response.location
1351
1352 response = client.get("/logout")
1353 assert response.status_code in [302, 303]
1354 assert "/post_logout" in response.location
1355
1356
1357 def test_open_redirect(app, client, get_message):
1358 """
1359 Test various possible URLs that urlsplit() shows as relative but
1360 many browsers will interpret as absolute - and thus have a
1361 open-redirect vulnerability.
1362 """
1363 test_urls = [
1364 ("\\\\\\github.com", "%5C%5C%5Cgithub.com"),
1365 (" //github.com", "%20//github.com"),
1366 (r"/\github.com", "/%5Cgithub.com"),
1367 (r"\/github.com", "%5C/github.com"),
1368 ("//github.com", ""),
1369 ("\t//github.com", "%09//github.com"),
1370 ]
1371 for nextloc in ["form", "query"]:
1372 for i, o in test_urls:
1373 if nextloc == "form":
1374 data = dict(email="[email protected]", password="password", next=i)
1375 response = client.post("/login", data=data, follow_redirects=False)
1376 else:
1377 data = dict(email="[email protected]", password="password")
1378 response = client.post(
1379 f"/login?next={i}", data=data, follow_redirects=False
1380 )
1381 if response.status_code in [302, 303]:
1382 # this means it passed form validation but should have been quoted
1383 assert check_location(app, response.location, o)
1384 elif response.status_code == 200:
1385 # should have failed form validation
1386 assert get_message("INVALID_REDIRECT") in response.data
1387 else:
1388 raise AssertionError("Bad response code")
1389 logout(client)
1390
1391
1392 @pytest.mark.settings(redirect_allow_subdomains=True)
1393 def test_open_redirect_subdomain(app, client, get_message):
1394 # As above - netloc is also susceptible to crazy escaping
1395 # The first URL below, if cut-n-pasted into Chrome will end up at amazon.com
1396 # The difference in response between in-form and query string is that
1397 # the query string is unescaped by Werkzeug but the form value isn't.
1398 app.config["SERVER_NAME"] = "lp.com"
1399 test_urls = [
1400 ("https://amazon.com\\.lp.com", "https://amazon.com%5C.lp.com", None),
1401 (
1402 "https://amazon.com%5C.lp.com",
1403 "https://amazon.com%255C.lp.com",
1404 "https://amazon.com%5C.lp.com",
1405 ),
1406 (
1407 "https://jwag:[email protected]\\.lp.com",
1408 "https://jwag:[email protected]%5C.lp.com",
1409 None,
1410 ),
1411 ]
1412 for nextloc in ["form", "query"]:
1413 for i, o, oq in test_urls:
1414 if nextloc == "form":
1415 data = dict(email="[email protected]", password="password", next=i)
1416 response = client.post("/login", data=data, follow_redirects=False)
1417 else:
1418 data = dict(email="[email protected]", password="password")
1419 response = client.post(
1420 f"/login?next={i}", data=data, follow_redirects=False
1421 )
1422 if response.status_code in [302, 303]:
1423 # this means it passed form validation but should have been quoted
1424 assert check_location(
1425 app, response.location, oq if oq and (nextloc == "query") else o
1426 )
1427 logout(client)
1428
1429
1430 def test_get_post_action_redirect(app, client):
1431 # test parts of get_post_action_redirect that are hard to get to via the client
1432 # e.g. port
1433 with app.test_request_context(base_url="https://lp.com:8080/"):
1434 r = get_post_action_redirect(
1435 "SECURITY_POST_LOGIN_VIEW", dict(next="https://lp.com:8080/myredirect")
1436 )
1437 assert r == "https://lp.com:8080/myredirect"
1438
1439
1440 def test_kwargs():
1441 import warnings
1442
1443 warnings.simplefilter("error")
1444 with pytest.raises(DeprecationWarning):
1445 Security(myownkwarg="hi")
1446
1447
1448 def test_nodatastore(app):
1449 with pytest.raises(ValueError):
1450 s = Security(app)
1451 s.init_app(app)
1452
1453
1454 @pytest.mark.filterwarnings("ignore:.*Replacing login_manager.*:DeprecationWarning")
1455 def test_reuse_security_object(sqlalchemy_datastore):
1456 # See: https://github.com/pallets-eco/flask-security/issues/518
1457 # Let folks re-use the Security object (mostly for testing).
1458 security = Security(datastore=sqlalchemy_datastore)
1459
1460 app = Flask(__name__)
1461 app.response_class = Response
1462 app.debug = True
1463 app.config["SECRET_KEY"] = "secret"
1464 app.config["TESTING"] = True
1465
1466 security.init_app(app)
1467 assert hasattr(app, "login_manager")
1468
1469 app = Flask(__name__)
1470 app.response_class = Response
1471 app.debug = True
1472 app.config["SECRET_KEY"] = "secret"
1473 app.config["TESTING"] = True
1474
1475 security.init_app(app)
1476 assert hasattr(app, "login_manager")
1477
1478
1479 @pytest.mark.settings(static_folder_url="/mystatic/fs")
1480 def test_static_url(app, sqlalchemy_datastore):
1481 from flask_security import url_for_security
1482 from flask import url_for
1483
1484 init_app_with_options(app, sqlalchemy_datastore)
1485 with app.test_request_context("http://localhost:5001/login"):
1486 static_url = url_for_security("static", filename="js/webauthn.js")
1487 assert static_url == "/mystatic/fs/js/webauthn.js"
1488
1489 static_url = url_for(".static", filename="js/webauthn.js")
1490 assert static_url == "/mystatic/fs/js/webauthn.js"
1491
1492
1493 def test_multi_app(app, sqlalchemy_datastore):
1494 # test that 2 different app with 2 different FS
1495 # with USERNAME_ENABLE which dynamically changes the class definition
1496 app = Flask(__name__)
1497 app.response_class = Response
1498 app.debug = True
1499 app.config["SECRET_KEY"] = "secret"
1500 app.config["TESTING"] = True
1501 app.config["SECURITY_USERNAME_ENABLE"] = True
1502
1503 security = Security(datastore=sqlalchemy_datastore)
1504 security.init_app(app)
1505 assert hasattr(security.forms["register_form"].cls, "username")
1506 assert "username" in security.user_identity_attributes[1].keys()
1507
1508 app = Flask(__name__)
1509 app.response_class = Response
1510 app.debug = True
1511 app.config["SECRET_KEY"] = "secret"
1512 app.config["TESTING"] = True
1513 app.config["SECURITY_USERNAME_ENABLE"] = True
1514
1515 security2 = Security(datastore=sqlalchemy_datastore)
1516 security2.init_app(app)
1517
1518 assert hasattr(security2.forms["register_form"].cls, "username")
1519 assert "username" in security2.user_identity_attributes[1].keys()
1520
1521
1522 @pytest.mark.registerable()
1523 def test_login_email_whatever(app, client, get_message):
1524 # login, by default, shouldn't verify email address is deliverable..
1525 # register etc can/should do that.
1526 app.config["SECURITY_EMAIL_VALIDATOR_ARGS"] = {"check_deliverability": True}
1527
1528 # register should fail since non-deliverable TLD
1529 data = dict(
1530 email="[email protected]",
1531 password="awesome sunset",
1532 )
1533 response = client.post("/register", json=data)
1534 assert response.status_code == 400
1535 assert response.json["response"]["errors"][0].encode("utf-8") == get_message(
1536 "INVALID_EMAIL_ADDRESS"
1537 )
1538
1539 # login should work since we are just checking for identity
1540 response = client.post(
1541 "/login", data=dict(email="[email protected]", password="password")
1542 )
1543 assert response.status_code in [302, 303]
1544 assert "/" in response.location
1545
1546
1547 @pytest.mark.skip
1548 def test_sqlalchemy_session_conn(request, app, tmpdir, realdburl):
1549 # test harness for checking connection mgmt by logging all connections
1550 from .conftest import sqlalchemy_session_setup
1551
1552 ds = sqlalchemy_session_setup(
1553 request, app, tmpdir, realdburl, echo_pool="debug", echo="debug"
1554 )
1555 init_app_with_options(app, ds)
1556 client = app.test_client()
1557
1558 client.post("/login", data=dict(email="[email protected]", password="password"))
1559
1560 client.post("/login", json=dict(noemail="[email protected]", password="password"))
1561 time.sleep(5)
1562
1563
1564 def test_login_required(app, client, get_message):
1565 # Test that @login_required calls our default_unauthn_handler
1566 from flask_login import login_required
1567
1568 @app.route("/loginreq")
1569 @login_required
1570 def login_req():
1571 pass
1572
1573 response = client.get("/loginreq", follow_redirects=False)
1574 assert response.location == "/login?next=/loginreq"
1575
1576 response = client.get("/loginreq", follow_redirects=True)
1577 assert get_message("UNAUTHENTICATED") in response.data
1578
1579
1580 def test_simplify_url():
1581 from flask_security.utils import simplify_url
1582
1583 s = simplify_url("https://localhost/profile", "https://localhost/login")
1584 assert s == "/login"
1585 s = simplify_url("https:/myhost/profile", "https://localhost/login")
1586 assert s == "https://localhost/login"
1587
1588
1589 @pytest.mark.parametrize(
1590 "verify_secret_key, verify_fallbacks, should_pass",
1591 [
1592 ("new_secret", [], False), # Should fail - only new key
1593 ("new_secret", ["old_secret"], True), # Should pass - has fallback
1594 ("old_secret", [], True), # Should pass - using original key
1595 ("wrong_secret", ["also_wrong"], False), # Should fail - no valid keys
1596 ],
1597 ids=["new-key-only", "with-fallback", "original-key", "wrong-keys"],
1598 )
1599 def test_secret_key_fallbacks(app, verify_secret_key, verify_fallbacks, should_pass):
1600 # Create token with original key
1601 app.config["SECRET_KEY"] = "old_secret"
1602 serializer = _get_serializer(app, "CONFIRM")
1603 token = serializer.dumps({"data": "test"})
1604
1605 # Attempt verification with different key configurations
1606 app.config["SECRET_KEY"] = verify_secret_key
1607 app.config["SECRET_KEY_FALLBACKS"] = verify_fallbacks
1608 serializer = _get_serializer(app, "CONFIRM")
1609
1610 if should_pass:
1611 data = serializer.loads(token)
1612 assert data["data"] == "test"
1613 else:
1614 with pytest.raises(BadTimeSignature):
1615 serializer.loads(token)
1616
1617
1618 @pytest.mark.settings(username_enable=True)
1619 def test_custom_login_form(app, sqlalchemy_datastore, get_message):
1620 # Test custom login form that deletes email and uses username only
1621 # Also test that if app leave 'email' in as a user identity attribute we
1622 # will ignore it
1623 class MyLoginForm(LoginForm):
1624 email = None
1625
1626 app.security = Security(
1627 app,
1628 datastore=sqlalchemy_datastore,
1629 login_form=MyLoginForm,
1630 )
1631
1632 populate_data(app)
1633 client = app.test_client()
1634
1635 response = client.get("/login", follow_redirects=False)
1636 assert not get_form_input(response, "email")
1637
1638 response = client.post(
1639 "/login", json=dict(email="[email protected]", password="password")
1640 )
1641 assert response.status_code == 400
1642 assert (
1643 get_message("USER_DOES_NOT_EXIST")
1644 == response.json["response"]["field_errors"][""][0].encode()
1645 )
1646
1647 response = client.post("/login", json=dict(username="jill", password="password"))
1648 assert response.status_code == 200
1649
1650
1651 @pytest.mark.settings(password_required=False)
1652 def test_password_required_setting(app, sqlalchemy_datastore):
1653 with pytest.raises(ValueError) as vex:
1654 Security(app=app, datastore=sqlalchemy_datastore)
1655 assert "SECURITY_PASSWORD_REQUIRED can only be" in str(vex.value)
1656
1657
1658 def test_null_user_id(app, client, get_message):
1659 # if DB not configured correctly - make sure we catch null fs_uniquifier
1660 json_authenticate(client)
1661 assert is_authenticated(client, get_message)
1662 with client.session_transaction() as sess:
1663 sess["_user_id"] = ""
1664 sess["user_id"] = ""
1665 assert not is_authenticated(client, get_message)
1666
1667
1668 @pytest.mark.settings(default_remember_me=True)
1669 def test_remember_login_form(app, client):
1670 # ensure form has the checkbox set if default set.
1671 response = client.get("/login")
1672 assert response.status_code == 200
1673 r = get_form_input(response, "remember")
1674 assert "checked" in r