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