| 1 |
""" |
| 2 |
test_basic |
| 3 |
~~~~~~~~~~~ |
| 4 |
|
| 5 |
Test common functionality |
| 6 |
|
| 7 |
:copyright: (c) 2019-2024 by J. Christopher Wagner (jwag). |
| 8 |
:license: MIT, see LICENSE for more details. |
| 9 |
""" |
| 10 |
|
| 11 |
import base64 |
| 12 |
from datetime import datetime, timedelta, timezone |
| 13 |
import json |
| 14 |
import re |
| 15 |
import pytest |
| 16 |
|
| 17 |
from flask import Blueprint, g |
| 18 |
|
| 19 |
from flask_security import uia_email_mapper |
| 20 |
from flask_security.decorators import auth_required |
| 21 |
from flask_principal import identity_loaded |
| 22 |
from freezegun import freeze_time |
| 23 |
|
| 24 |
from tests.conftest import v2_param |
| 25 |
from tests.test_utils import ( |
| 26 |
authenticate, |
| 27 |
capture_flashes, |
| 28 |
capture_queries, |
| 29 |
check_location, |
| 30 |
get_auth_token_version_3x, |
| 31 |
get_form_action, |
| 32 |
get_form_input_value, |
| 33 |
hash_password, |
| 34 |
init_app_with_options, |
| 35 |
is_authenticated, |
| 36 |
json_authenticate, |
| 37 |
logout, |
| 38 |
populate_data, |
| 39 |
verify_token, |
| 40 |
) |
| 41 |
|
| 42 |
|
| 43 |
def test_login_view(client): |
| 44 |
response = client.get("/login") |
| 45 |
assert b"<h1>Login</h1>" in response.data |
| 46 |
|
| 47 |
|
| 48 |
def test_authenticate(client): |
| 49 |
response = authenticate(client) |
| 50 |
assert response.status_code in [302, 303] |
| 51 |
response = authenticate(client, follow_redirects=True) |
| 52 |
assert b"Welcome [email protected]" in response.data |
| 53 |
|
| 54 |
|
| 55 |
@pytest.mark.settings(anonymous_user_disabled=True) |
| 56 |
def test_authenticate_no_anon(client): |
| 57 |
response = authenticate(client) |
| 58 |
assert response.status_code in [302, 303] |
| 59 |
response = authenticate(client, follow_redirects=True) |
| 60 |
assert b"Welcome [email protected]" in response.data |
| 61 |
|
| 62 |
|
| 63 |
def test_authenticate_with_next(client): |
| 64 |
data = dict(email="[email protected]", password="password") |
| 65 |
response = client.post("/login?next=/page1", data=data, follow_redirects=True) |
| 66 |
assert b"Page 1" in response.data |
| 67 |
|
| 68 |
|
| 69 |
def test_authenticate_with_next_bp(app, client): |
| 70 |
api = Blueprint("api", __name__) |
| 71 |
|
| 72 |
@api.route("/info") |
| 73 |
def info(): |
| 74 |
pass |
| 75 |
|
| 76 |
app.register_blueprint(api, url_prefix="/api") |
| 77 |
data = dict(email="[email protected]", password="password") |
| 78 |
response = client.post("/login?next=api.info", data=data, follow_redirects=False) |
| 79 |
assert response.status_code in [302, 303] |
| 80 |
assert "api/info" in response.location |
| 81 |
|
| 82 |
|
| 83 |
def test_authenticate_with_invalid_next(client, get_message): |
| 84 |
data = dict(email="[email protected]", password="password") |
| 85 |
response = client.post("/login?next=http://google.com", data=data) |
| 86 |
assert get_message("INVALID_REDIRECT") in response.data |
| 87 |
|
| 88 |
|
| 89 |
@pytest.mark.settings(flash_messages=False) |
| 90 |
def test_authenticate_with_invalid_next_json(client, get_message): |
| 91 |
data = dict(email="[email protected]", password="password") |
| 92 |
response = client.post("/login?next=http://google.com", json=data) |
| 93 |
assert response.json["response"]["errors"][0].encode() == get_message( |
| 94 |
"INVALID_REDIRECT" |
| 95 |
) |
| 96 |
|
| 97 |
|
| 98 |
def test_authenticate_with_invalid_malformed_next(client, get_message): |
| 99 |
data = dict(email="[email protected]", password="password") |
| 100 |
response = client.post("/login?next=http:///google.com", data=data) |
| 101 |
assert get_message("INVALID_REDIRECT") in response.data |
| 102 |
|
| 103 |
|
| 104 |
def test_unauthenticated(app, client, get_message): |
| 105 |
from flask_security import user_unauthenticated |
| 106 |
from flask import request |
| 107 |
|
| 108 |
recvd = [] |
| 109 |
|
| 110 |
@user_unauthenticated.connect_via(app) |
| 111 |
def un(myapp, **extra): |
| 112 |
assert request.path == "/profile" |
| 113 |
recvd.append("gotit") |
| 114 |
|
| 115 |
response = client.get("/profile", follow_redirects=False) |
| 116 |
assert len(recvd) == 1 |
| 117 |
assert response.location == "/login?next=/profile" |
| 118 |
|
| 119 |
|
| 120 |
@pytest.mark.flask_async() |
| 121 |
def test_unauthenticated_async(app, client, get_message): |
| 122 |
from flask_security import user_unauthenticated |
| 123 |
from flask import request |
| 124 |
|
| 125 |
recvd = [] |
| 126 |
|
| 127 |
@user_unauthenticated.connect_via(app) |
| 128 |
async def un(myapp, **extra): |
| 129 |
assert request.path == "/profile" |
| 130 |
recvd.append("gotit") |
| 131 |
|
| 132 |
response = client.get("/profile", follow_redirects=False) |
| 133 |
assert len(recvd) == 1 |
| 134 |
assert response.location == "/login?next=/profile" |
| 135 |
|
| 136 |
|
| 137 |
def test_login_template_next(client): |
| 138 |
# Test that our login template propagates next. |
| 139 |
response = client.get("/profile", follow_redirects=True) |
| 140 |
assert "?next=/profile" in response.request.url |
| 141 |
login_url = get_form_action(response) |
| 142 |
response = client.post( |
| 143 |
login_url, |
| 144 |
data=dict(email="[email protected]", password="password"), |
| 145 |
follow_redirects=True, |
| 146 |
) |
| 147 |
assert b"Profile Page" in response.data |
| 148 |
|
| 149 |
|
| 150 |
def test_authenticate_with_subdomain_next(app, client, get_message): |
| 151 |
app.config["SERVER_NAME"] = "lp.com" |
| 152 |
app.config["SECURITY_REDIRECT_ALLOW_SUBDOMAINS"] = True |
| 153 |
data = dict(email="[email protected]", password="password") |
| 154 |
response = client.post("/login?next=http://sub.lp.com", data=data) |
| 155 |
assert response.status_code in [302, 303] |
| 156 |
assert response.location == "http://sub.lp.com" |
| 157 |
|
| 158 |
|
| 159 |
@pytest.mark.settings(subdomain="auth") |
| 160 |
def test_authenticate_with_root_domain_next(app, client, get_message): |
| 161 |
# As of Flask 3.1 this must be explicitly set. |
| 162 |
app.subdomain_matching = True |
| 163 |
app.config["SERVER_NAME"] = "lp.com" |
| 164 |
app.config["SECURITY_REDIRECT_ALLOW_SUBDOMAINS"] = True |
| 165 |
data = dict(email="[email protected]", password="password") |
| 166 |
response = client.post("http://auth.lp.com/login?next=http://lp.com", data=data) |
| 167 |
assert response.status_code in [302, 303] |
| 168 |
assert response.location == "http://lp.com" |
| 169 |
|
| 170 |
|
| 171 |
def test_authenticate_with_invalid_subdomain_next(app, client, get_message): |
| 172 |
app.config["SERVER_NAME"] = "lp.com" |
| 173 |
app.config["SECURITY_REDIRECT_ALLOW_SUBDOMAINS"] = True |
| 174 |
data = dict(email="[email protected]", password="password") |
| 175 |
response = client.post("/login?next=http://sub.lp.net", data=data) |
| 176 |
assert get_message("INVALID_REDIRECT") in response.data |
| 177 |
|
| 178 |
|
| 179 |
def test_authenticate_with_subdomain_next_default_config(app, client, get_message): |
| 180 |
app.config["SERVER_NAME"] = "lp.com" |
| 181 |
data = dict(email="[email protected]", password="password") |
| 182 |
response = client.post("/login?next=http://sub.lp.com", data=data) |
| 183 |
assert get_message("INVALID_REDIRECT") in response.data |
| 184 |
|
| 185 |
|
| 186 |
@pytest.mark.settings( |
| 187 |
redirect_base_domain="bigidea.org", redirect_allowed_subdomains=["my.photo", "blog"] |
| 188 |
) |
| 189 |
def test_allow_subdomains(app, client, get_message): |
| 190 |
app.config["SERVER_NAME"] = "app.bigidea.org" |
| 191 |
data = dict(email="[email protected]", password="password") |
| 192 |
# not in subdomain allowed list |
| 193 |
response = client.post("/login?next=http://blog2.bigidea.org", data=data) |
| 194 |
assert get_message("INVALID_REDIRECT") in response.data |
| 195 |
|
| 196 |
response = client.post("/login?next=http://my.photo.bigidea.org/image", data=data) |
| 197 |
assert response.location == "http://my.photo.bigidea.org/image" |
| 198 |
|
| 199 |
|
| 200 |
@pytest.mark.settings( |
| 201 |
redirect_base_domain="bigidea.org", redirect_allowed_subdomains=[] |
| 202 |
) |
| 203 |
def test_redirect_allow_subdomains(app, client, get_message): |
| 204 |
app.config["SERVER_NAME"] = "bigidea.org" |
| 205 |
data = dict(email="[email protected]", password="password") |
| 206 |
response = client.post("/login?next=http://blog2.bigidea.org", data=data) |
| 207 |
assert get_message("INVALID_REDIRECT") in response.data |
| 208 |
response = client.post("/login?next=http://bigidea.org/imin", data=data) |
| 209 |
assert response.location == "http://bigidea.org/imin" |
| 210 |
|
| 211 |
|
| 212 |
@pytest.mark.settings( |
| 213 |
post_login_view="http://blog.bigidea.org/post_login", |
| 214 |
redirect_base_domain="bigidea.org", |
| 215 |
redirect_allowed_subdomains=["my.photo", "blog"], |
| 216 |
) |
| 217 |
def test_view_redirect(app, client, get_message): |
| 218 |
app.config["SERVER_NAME"] = "bigidea.org" |
| 219 |
data = dict(email="[email protected]", password="password") |
| 220 |
response = client.post("/login", data=data) |
| 221 |
assert response.location == "http://blog.bigidea.org/post_login" |
| 222 |
|
| 223 |
|
| 224 |
def test_authenticate_case_insensitive_email(app, client): |
| 225 |
response = authenticate(client, "[email protected]", follow_redirects=True) |
| 226 |
assert b"Welcome [email protected]" in response.data |
| 227 |
|
| 228 |
|
| 229 |
def test_authenticate_with_invalid_input(client, get_message): |
| 230 |
response = client.post( |
| 231 |
"/login", |
| 232 |
json=dict(password="password", email="[email protected]"), |
| 233 |
headers={"Content-Type": "application/json"}, |
| 234 |
) |
| 235 |
assert get_message("USER_DOES_NOT_EXIST") in response.data |
| 236 |
|
| 237 |
|
| 238 |
@pytest.mark.settings(post_login_view="/post_login") |
| 239 |
def test_get_already_authenticated(client): |
| 240 |
response = authenticate(client, follow_redirects=True) |
| 241 |
assert b"Welcome [email protected]" in response.data |
| 242 |
response = client.get("/login", follow_redirects=True) |
| 243 |
assert b"Post Login" in response.data |
| 244 |
|
| 245 |
# should still get extra goodies |
| 246 |
headers = {"Accept": "application/json", "Content-Type": "application/json"} |
| 247 |
response = client.get("/login", headers=headers) |
| 248 |
assert response.status_code == 200 |
| 249 |
|
| 250 |
jresponse = response.json["response"] |
| 251 |
assert all(a in jresponse for a in ["identity_attributes"]) |
| 252 |
assert "authentication_token" not in jresponse["user"] |
| 253 |
assert all(a in jresponse["user"] for a in ["email", "last_update"]) |
| 254 |
|
| 255 |
|
| 256 |
@pytest.mark.settings(post_login_view="/post_login") |
| 257 |
def test_get_already_authenticated_next(client): |
| 258 |
response = authenticate(client, follow_redirects=True) |
| 259 |
assert b"Welcome [email protected]" in response.data |
| 260 |
# This should NOT override post_login_view due to potential redirect loops. |
| 261 |
response = client.get("/login?next=/page1", follow_redirects=True) |
| 262 |
assert b"Post Login" in response.data |
| 263 |
|
| 264 |
|
| 265 |
@pytest.mark.settings(post_login_view="/post_login") |
| 266 |
def test_post_already_authenticated(client): |
| 267 |
response = authenticate(client, follow_redirects=True) |
| 268 |
assert b"Welcome [email protected]" in response.data |
| 269 |
data = dict(email="[email protected]", password="password") |
| 270 |
response = client.post("/login", data=data, follow_redirects=True) |
| 271 |
assert b"Post Login" in response.data |
| 272 |
# This should NOT override post_login_view due to potential redirect loops. |
| 273 |
response = client.post("/login?next=/page1", data=data, follow_redirects=True) |
| 274 |
assert b"Post Login" in response.data |
| 275 |
|
| 276 |
|
| 277 |
def test_login_form(client): |
| 278 |
response = client.post("/login", data={"email": "[email protected]"}) |
| 279 |
assert b"[email protected]" in response.data |
| 280 |
assert re.search(b'<input[^>]*type="email"[^>]*>', response.data) |
| 281 |
|
| 282 |
|
| 283 |
@pytest.mark.settings(username_enable=True) |
| 284 |
def test_login_form_username(client): |
| 285 |
# If USERNAME_ENABLE is set then login form should have a both an Email and |
| 286 |
# StringField |
| 287 |
response = client.get("/login") |
| 288 |
# Should be both email with Email type and username with autocomplete |
| 289 |
assert re.search(b'<input[^>]*type="email"[^>]*>', response.data) |
| 290 |
assert re.search(b'<input[^>]*autocomplete="username"[^>]*>', response.data) |
| 291 |
assert re.search(b'<input[^>]*autocomplete="current-password"[^>]*>', response.data) |
| 292 |
|
| 293 |
|
| 294 |
@pytest.mark.settings(username_enable=True, username_required=True) |
| 295 |
def test_login_form_username_required(app, client): |
| 296 |
# If username required - we should still be able to login with email alone |
| 297 |
# given default user_identity_attributes |
| 298 |
response = client.post( |
| 299 |
"/login", data=dict(email="[email protected]", password="password") |
| 300 |
) |
| 301 |
assert check_location(app, response.location, "/") |
| 302 |
|
| 303 |
|
| 304 |
@pytest.mark.confirmable() |
| 305 |
@pytest.mark.settings( |
| 306 |
return_generic_responses=True, requires_confirmation_error_view="/confirm" |
| 307 |
) |
| 308 |
def test_generic_response(app, client, get_message): |
| 309 |
response = client.post( |
| 310 |
"/login", data=dict(email="[email protected]", password="forgot") |
| 311 |
) |
| 312 |
assert get_message("GENERIC_AUTHN_FAILED") in response.data |
| 313 |
response = client.post("/login", data=dict(email="[email protected]", password="forgot")) |
| 314 |
assert get_message("GENERIC_AUTHN_FAILED") in response.data |
| 315 |
|
| 316 |
response = client.post( |
| 317 |
"/login", json=dict(email="[email protected]", password="forgot") |
| 318 |
) |
| 319 |
# make sure no field error key. |
| 320 |
assert list(response.json["response"]["field_errors"].keys()) == [""] |
| 321 |
assert len(response.json["response"]["field_errors"][""]) == 1 |
| 322 |
assert response.json["response"]["errors"][0].encode("utf-8") == get_message( |
| 323 |
"GENERIC_AUTHN_FAILED" |
| 324 |
) |
| 325 |
response = client.post("/login", json=dict(email="[email protected]", password="forgot")) |
| 326 |
assert response.json["response"]["errors"][0].encode("utf-8") == get_message( |
| 327 |
"GENERIC_AUTHN_FAILED" |
| 328 |
) |
| 329 |
|
| 330 |
# make sure don't get confirmation required |
| 331 |
with capture_flashes() as flashes: |
| 332 |
response = client.post( |
| 333 |
"/login", |
| 334 |
data=dict(email="[email protected]", password="password"), |
| 335 |
follow_redirects=False, |
| 336 |
) |
| 337 |
assert response.status_code == 200 |
| 338 |
assert len(flashes) == 0 |
| 339 |
|
| 340 |
|
| 341 |
@pytest.mark.parametrize("app", v2_param, indirect=True) |
| 342 |
@pytest.mark.registerable() |
| 343 |
@pytest.mark.settings(username_enable=True, return_generic_responses=True) |
| 344 |
def test_generic_response_username(app, client, get_message): |
| 345 |
data = dict( |
| 346 |
email="[email protected]", |
| 347 |
username="dude", |
| 348 |
password="awesome sunset", |
| 349 |
password_confirm="awesome sunset", |
| 350 |
) |
| 351 |
response = client.post("/register", json=data) |
| 352 |
assert response.headers["Content-Type"] == "application/json" |
| 353 |
assert response.status_code == 200 |
| 354 |
logout(client) |
| 355 |
|
| 356 |
response = client.post( |
| 357 |
"/login", |
| 358 |
data=dict( |
| 359 |
username="dude2", |
| 360 |
password="awesome sunset", |
| 361 |
password_confirm="awesome sunset", |
| 362 |
), |
| 363 |
) |
| 364 |
assert get_message("GENERIC_AUTHN_FAILED") in response.data |
| 365 |
|
| 366 |
response = client.post("/login", json=dict(username="dude2", password="forgot")) |
| 367 |
# make sure no field error key. |
| 368 |
assert list(response.json["response"]["field_errors"].keys()) == [""] |
| 369 |
assert len(response.json["response"]["field_errors"][""]) == 1 |
| 370 |
assert response.json["response"]["errors"][0].encode("utf-8") == get_message( |
| 371 |
"GENERIC_AUTHN_FAILED" |
| 372 |
) |
| 373 |
|
| 374 |
|
| 375 |
def test_unprovided_username(client, get_message): |
| 376 |
response = authenticate(client, "") |
| 377 |
assert get_message("USER_DOES_NOT_EXIST") in response.data |
| 378 |
|
| 379 |
|
| 380 |
def test_unprovided_password(client, get_message): |
| 381 |
response = authenticate(client, password="") |
| 382 |
assert get_message("PASSWORD_NOT_PROVIDED") in response.data |
| 383 |
|
| 384 |
|
| 385 |
def test_invalid_user(client, get_message): |
| 386 |
response = authenticate(client, email="[email protected]") |
| 387 |
assert get_message("USER_DOES_NOT_EXIST") in response.data |
| 388 |
|
| 389 |
|
| 390 |
def test_bad_password(client, get_message, signals): |
| 391 |
response = authenticate(client, password="bogus") |
| 392 |
assert get_message("INVALID_PASSWORD") in response.data |
| 393 |
assert signals["user_failed_authn"][0]["request_endpoint"] == "security.login" |
| 394 |
assert signals["user_failed_authn"][0]["user_email"] == "[email protected]" |
| 395 |
assert signals["user_failed_authn"][0]["auth_type"] == "password" |
| 396 |
assert not signals["user_failed_authn"][0]["tfa"] |
| 397 |
|
| 398 |
|
| 399 |
def test_inactive_user(client, get_message): |
| 400 |
response = authenticate(client, "[email protected]", "password") |
| 401 |
assert get_message("DISABLED_ACCOUNT") in response.data |
| 402 |
|
| 403 |
|
| 404 |
def test_inactive_forbids(app, client, get_message): |
| 405 |
"""Make sure that existing session doesn't work after |
| 406 |
user marked inactive |
| 407 |
""" |
| 408 |
response = authenticate(client, follow_redirects=True) |
| 409 |
assert response.status_code == 200 |
| 410 |
# make sure can access restricted page |
| 411 |
response = client.get("/profile", follow_redirects=True) |
| 412 |
assert b"Profile Page" in response.data |
| 413 |
|
| 414 |
# deactivate matt |
| 415 |
with app.test_request_context("/"): |
| 416 |
user = app.security.datastore.find_user(email="[email protected]") |
| 417 |
app.security.datastore.deactivate_user(user) |
| 418 |
app.security.datastore.commit() |
| 419 |
|
| 420 |
response = client.get("/profile", follow_redirects=False) |
| 421 |
print(response.data) |
| 422 |
# should be thrown back to login page. |
| 423 |
assert response.status_code in [302, 303] |
| 424 |
assert response.location == "/login?next=/profile" |
| 425 |
|
| 426 |
|
| 427 |
@pytest.mark.settings(unauthorized_view=None) |
| 428 |
def test_inactive_forbids_token(app, client_nc, get_message): |
| 429 |
"""Make sure that existing token doesn't work after |
| 430 |
user marked inactive |
| 431 |
""" |
| 432 |
response = json_authenticate(client_nc) |
| 433 |
assert response.status_code == 200 |
| 434 |
token = response.json["response"]["user"]["authentication_token"] |
| 435 |
headers = {"Authentication-Token": token} |
| 436 |
# make sure can access restricted page |
| 437 |
response = client_nc.get("/token", headers=headers) |
| 438 |
assert b"Token Authentication" in response.data |
| 439 |
|
| 440 |
# deactivate matt |
| 441 |
with app.test_request_context("/"): |
| 442 |
user = app.security.datastore.find_user(email="[email protected]") |
| 443 |
app.security.datastore.deactivate_user(user) |
| 444 |
app.security.datastore.commit() |
| 445 |
|
| 446 |
response = client_nc.get("/token", content_type="application/json", headers=headers) |
| 447 |
assert response.status_code == 401 |
| 448 |
|
| 449 |
|
| 450 |
def test_inactive_forbids_basic(app, client, get_message): |
| 451 |
"""Make sure that basic auth doesn't work if user deactivated""" |
| 452 |
|
| 453 |
# Should properly work. |
| 454 |
response = client.get( |
| 455 |
"/multi_auth", |
| 456 |
headers={ |
| 457 |
"Authorization": "Basic %s" |
| 458 |
% base64.b64encode(b"[email protected]:password").decode("utf-8") |
| 459 |
}, |
| 460 |
) |
| 461 |
assert b"Session, Token, Basic" in response.data |
| 462 |
|
| 463 |
# deactivate joe |
| 464 |
with app.test_request_context("/"): |
| 465 |
user = app.security.datastore.find_user(email="[email protected]") |
| 466 |
app.security.datastore.deactivate_user(user) |
| 467 |
app.security.datastore.commit() |
| 468 |
|
| 469 |
response = client.get( |
| 470 |
"/multi_auth", |
| 471 |
headers={ |
| 472 |
"Authorization": "Basic %s" |
| 473 |
% base64.b64encode(b"[email protected]:password").decode("utf-8") |
| 474 |
}, |
| 475 |
) |
| 476 |
assert get_message("UNAUTHENTICATED")[0] in response.data |
| 477 |
|
| 478 |
|
| 479 |
def test_unset_password(client, get_message): |
| 480 |
response = authenticate(client, "[email protected]", "password") |
| 481 |
assert get_message("INVALID_PASSWORD") in response.data |
| 482 |
response = authenticate(client, "[email protected]", "") |
| 483 |
assert get_message("PASSWORD_NOT_PROVIDED") in response.data |
| 484 |
|
| 485 |
|
| 486 |
def _locked(self, form_error): |
| 487 |
if self.email == "[email protected]": |
| 488 |
form_error.append("You are not allowed to do that") |
| 489 |
return True |
| 490 |
return False |
| 491 |
|
| 492 |
|
| 493 |
@pytest.mark.app_settings(TESTING_USER_INJECT=dict(is_locked=_locked)) |
| 494 |
def test_override_user_locked(app, client, get_message): |
| 495 |
data = dict(email="[email protected]", password="password") |
| 496 |
response = client.post("/login", json=data) |
| 497 |
assert response.status_code == 200 |
| 498 |
logout(client) |
| 499 |
|
| 500 |
data = dict(email="[email protected]", password="password") |
| 501 |
response = client.post("/login", json=data) |
| 502 |
assert response.status_code == 400 |
| 503 |
assert response.json["response"]["errors"] == ["You are not allowed to do that"] |
| 504 |
assert response.json["response"]["field_errors"]["email"] == [ |
| 505 |
"You are not allowed to do that" |
| 506 |
] |
| 507 |
|
| 508 |
|
| 509 |
@pytest.mark.app_settings(TESTING_USER_INJECT=dict(is_locked=_locked)) |
| 510 |
@pytest.mark.settings(return_generic_responses=True) |
| 511 |
def test_override_user_locked_gr(app, client, get_message): |
| 512 |
data = dict(email="[email protected]", password="password") |
| 513 |
response = client.post("/login", json=data) |
| 514 |
assert response.status_code == 400 |
| 515 |
assert response.json["response"]["errors"][0].encode("utf-8") == get_message( |
| 516 |
"GENERIC_AUTHN_FAILED" |
| 517 |
) |
| 518 |
assert "email" not in response.json["response"]["field_errors"] |
| 519 |
|
| 520 |
|
| 521 |
def test_logout(client): |
| 522 |
authenticate(client) |
| 523 |
response = logout(client, follow_redirects=True) |
| 524 |
assert b"Home Page" in response.data |
| 525 |
|
| 526 |
|
| 527 |
def test_logout_post(client): |
| 528 |
authenticate(client) |
| 529 |
response = client.post("/logout", content_type="application/json") |
| 530 |
assert response.status_code == 200 |
| 531 |
assert response.json["meta"]["code"] == 200 |
| 532 |
|
| 533 |
|
| 534 |
def test_logout_with_next_invalid(client, get_message): |
| 535 |
authenticate(client) |
| 536 |
response = client.get("/logout?next=http://google.com") |
| 537 |
assert "google.com" not in response.location |
| 538 |
|
| 539 |
|
| 540 |
def test_logout_with_next(client): |
| 541 |
authenticate(client) |
| 542 |
response = client.get("/logout?next=/page1", follow_redirects=True) |
| 543 |
assert b"Page 1" in response.data |
| 544 |
|
| 545 |
|
| 546 |
def test_missing_session_access(client, get_message): |
| 547 |
response = client.get("/profile", follow_redirects=True) |
| 548 |
assert get_message("UNAUTHENTICATED") in response.data |
| 549 |
|
| 550 |
|
| 551 |
def test_has_session_access(client): |
| 552 |
authenticate(client) |
| 553 |
response = client.get("/profile", follow_redirects=True) |
| 554 |
assert b"profile" in response.data |
| 555 |
|
| 556 |
|
| 557 |
def test_authorized_access(client): |
| 558 |
authenticate(client) |
| 559 |
response = client.get("/admin") |
| 560 |
assert b"Admin Page" in response.data |
| 561 |
|
| 562 |
|
| 563 |
def test_unauthorized_access(client, get_message): |
| 564 |
authenticate(client, "[email protected]") |
| 565 |
response = client.get("/admin", follow_redirects=True) |
| 566 |
assert response.status_code == 403 |
| 567 |
|
| 568 |
|
| 569 |
def test_unauthorized_callable_view(app, sqlalchemy_datastore, get_message): |
| 570 |
# Test various options using custom unauthorized view |
| 571 |
def unauthz_view(): |
| 572 |
from flask import request |
| 573 |
|
| 574 |
if request.path == "/admin": |
| 575 |
return None |
| 576 |
elif request.path == "/admin_perm": |
| 577 |
return "" |
| 578 |
elif request.path == "/admin_and_editor": |
| 579 |
return "/profile" |
| 580 |
elif request.path == "/simple": |
| 581 |
# N.B. security issue - app should verify this is local |
| 582 |
return request.referrer |
| 583 |
else: |
| 584 |
return "not_implemented" |
| 585 |
|
| 586 |
app.config["SECURITY_UNAUTHORIZED_VIEW"] = unauthz_view |
| 587 |
init_app_with_options(app, sqlalchemy_datastore) |
| 588 |
client = app.test_client() |
| 589 |
# activate tiya |
| 590 |
with app.test_request_context("/"): |
| 591 |
user = app.security.datastore.find_user(email="[email protected]") |
| 592 |
app.security.datastore.activate_user(user) |
| 593 |
app.security.datastore.commit() |
| 594 |
authenticate(client, "[email protected]") |
| 595 |
assert is_authenticated(client, get_message) |
| 596 |
|
| 597 |
response = client.get("/admin") |
| 598 |
assert response.status_code == 403 |
| 599 |
response = client.get("/admin_perm") |
| 600 |
assert response.status_code == 403 |
| 601 |
|
| 602 |
response = client.get("/admin_and_editor", follow_redirects=False) |
| 603 |
assert check_location(app, response.location, "/profile") |
| 604 |
response = client.get(response.location) |
| 605 |
assert response.data.count(get_message("UNAUTHORIZED")) == 1 |
| 606 |
|
| 607 |
response = client.get( |
| 608 |
"/simple", headers={"referer": "/myhome"}, follow_redirects=False |
| 609 |
) |
| 610 |
assert check_location(app, response.location, "/myhome") |
| 611 |
|
| 612 |
|
| 613 |
def test_unauthorized_url_view(app, sqlalchemy_datastore): |
| 614 |
# Test unknown endpoint basically results in redirect to the given string. |
| 615 |
app.config["SECURITY_UNAUTHORIZED_VIEW"] = ".myendpoint" |
| 616 |
init_app_with_options(app, sqlalchemy_datastore) |
| 617 |
client = app.test_client() |
| 618 |
authenticate(client, "[email protected]") |
| 619 |
response = client.get("/admin") |
| 620 |
assert response.status_code in [302, 303] |
| 621 |
check_location(app, response.location, ".myendpoint") |
| 622 |
|
| 623 |
|
| 624 |
@pytest.mark.settings(unauthorized_view="/unauthz") |
| 625 |
def test_roles_accepted(clients): |
| 626 |
# This specifically tests that we can pass a URL for unauthorized_view. |
| 627 |
for user in ("[email protected]", "[email protected]"): |
| 628 |
authenticate(clients, user) |
| 629 |
response = clients.get("/admin_or_editor") |
| 630 |
assert b"Admin or Editor Page" in response.data |
| 631 |
logout(clients) |
| 632 |
|
| 633 |
authenticate(clients, "[email protected]") |
| 634 |
response = clients.get("/admin_or_editor", follow_redirects=True) |
| 635 |
assert b"Unauthorized" in response.data |
| 636 |
|
| 637 |
|
| 638 |
@pytest.mark.settings(unauthorized_view="unauthz") |
| 639 |
def test_permissions_accepted(clients): |
| 640 |
for user in ("[email protected]", "[email protected]"): |
| 641 |
authenticate(clients, user) |
| 642 |
response = clients.get("/admin_perm") |
| 643 |
assert b"Admin Page with full-write or super" in response.data |
| 644 |
logout(clients) |
| 645 |
|
| 646 |
authenticate(clients, "[email protected]") |
| 647 |
response = clients.get("/admin_perm", follow_redirects=True) |
| 648 |
assert b"Unauthorized" in response.data |
| 649 |
|
| 650 |
|
| 651 |
@pytest.mark.settings(unauthorized_view="unauthz") |
| 652 |
def test_permissions_required(clients): |
| 653 |
for user in ["[email protected]"]: |
| 654 |
authenticate(clients, user) |
| 655 |
response = clients.get("/admin_perm_required") |
| 656 |
assert b"Admin Page required" in response.data |
| 657 |
logout(clients) |
| 658 |
|
| 659 |
authenticate(clients, "[email protected]") |
| 660 |
response = clients.get("/admin_perm_required", follow_redirects=True) |
| 661 |
assert b"Unauthorized" in response.data |
| 662 |
|
| 663 |
|
| 664 |
@pytest.mark.settings(unauthorized_view="unauthz") |
| 665 |
def test_unauthenticated_role_required(client, get_message): |
| 666 |
response = client.get("/admin", follow_redirects=True) |
| 667 |
assert get_message("UNAUTHORIZED") in response.data |
| 668 |
|
| 669 |
|
| 670 |
@pytest.mark.settings(unauthorized_view="unauthz") |
| 671 |
def test_multiple_role_required(clients): |
| 672 |
for user in ("[email protected]", "[email protected]"): |
| 673 |
authenticate(clients, user) |
| 674 |
response = clients.get("/admin_and_editor", follow_redirects=True) |
| 675 |
assert b"Unauthorized" in response.data |
| 676 |
clients.get("/logout") |
| 677 |
|
| 678 |
authenticate(clients, "[email protected]") |
| 679 |
response = clients.get("/admin_and_editor", follow_redirects=True) |
| 680 |
assert b"Admin and Editor Page" in response.data |
| 681 |
|
| 682 |
|
| 683 |
def test_ok_json_auth(client): |
| 684 |
response = json_authenticate(client) |
| 685 |
assert response.json["meta"]["code"] == 200 |
| 686 |
assert "authentication_token" in response.json["response"]["user"] |
| 687 |
|
| 688 |
|
| 689 |
def test_invalid_json_auth(client): |
| 690 |
response = json_authenticate(client, password="junk") |
| 691 |
assert b'"code": 400' in response.data |
| 692 |
|
| 693 |
|
| 694 |
def test_token_auth_via_querystring_valid_token(client): |
| 695 |
response = json_authenticate(client) |
| 696 |
token = response.json["response"]["user"]["authentication_token"] |
| 697 |
response = client.get("/token?auth_token=" + token) |
| 698 |
assert b"Token Authentication" in response.data |
| 699 |
|
| 700 |
|
| 701 |
def test_token_auth_via_header_valid_token(client): |
| 702 |
response = json_authenticate(client) |
| 703 |
token = response.json["response"]["user"]["authentication_token"] |
| 704 |
headers = {"Authentication-Token": token} |
| 705 |
response = client.get("/token", headers=headers) |
| 706 |
assert b"Token Authentication" in response.data |
| 707 |
|
| 708 |
|
| 709 |
def test_token_auth_via_querystring_invalid_token(client): |
| 710 |
response = client.get("/token?auth_token=X", headers={"Accept": "application/json"}) |
| 711 |
assert response.status_code == 401 |
| 712 |
|
| 713 |
|
| 714 |
def test_token_auth_via_header_invalid_token(client): |
| 715 |
response = client.get( |
| 716 |
"/token", headers={"Authentication-Token": "X", "Accept": "application/json"} |
| 717 |
) |
| 718 |
assert response.status_code == 401 |
| 719 |
|
| 720 |
|
| 721 |
def test_token_auth_invalid_for_session_auth(client): |
| 722 |
# when user is loaded from token data, session authentication should fail. |
| 723 |
response = json_authenticate(client) |
| 724 |
token = response.json["response"]["user"]["authentication_token"] |
| 725 |
# logout so session doesn't contain valid user details |
| 726 |
logout(client) |
| 727 |
headers = {"Authentication-Token": token, "Accept": "application/json"} |
| 728 |
response = client.get("/session", headers=headers) |
| 729 |
assert response.status_code == 401 |
| 730 |
|
| 731 |
|
| 732 |
def test_per_user_expired_token(app, client_nc): |
| 733 |
# Test expiry in auth_token using callable |
| 734 |
with freeze_time("2024-01-01"): |
| 735 |
|
| 736 |
def exp(user): |
| 737 |
assert user.email == "[email protected]" |
| 738 |
return int((datetime.now(timezone.utc) + timedelta(days=1)).timestamp()) |
| 739 |
|
| 740 |
app.config["SECURITY_TOKEN_EXPIRE_TIMESTAMP"] = exp |
| 741 |
|
| 742 |
response = json_authenticate(client_nc) |
| 743 |
token = response.json["response"]["user"]["authentication_token"] |
| 744 |
|
| 745 |
verify_token(client_nc, token, status=401) |
| 746 |
|
| 747 |
|
| 748 |
def test_per_user_not_expired_token(app, client_nc): |
| 749 |
# Test expiry in auth_token using callable |
| 750 |
def exp(user): |
| 751 |
assert user.email == "[email protected]" |
| 752 |
return int((datetime.now(timezone.utc) + timedelta(days=1)).timestamp()) |
| 753 |
|
| 754 |
app.config["SECURITY_TOKEN_EXPIRE_TIMESTAMP"] = exp |
| 755 |
|
| 756 |
response = json_authenticate(client_nc) |
| 757 |
token = response.json["response"]["user"]["authentication_token"] |
| 758 |
verify_token(client_nc, token) |
| 759 |
|
| 760 |
|
| 761 |
def test_garbled_auth_token(app, client_nc): |
| 762 |
# garble token |
| 763 |
def augment_auth_token(tdata): |
| 764 |
del tdata["exp"] |
| 765 |
|
| 766 |
app.config["TESTING_AUGMENT_AUTH_TOKEN"] = augment_auth_token |
| 767 |
response = json_authenticate(client_nc) |
| 768 |
token = response.json["response"]["user"]["authentication_token"] |
| 769 |
verify_token(client_nc, token, status=401) |
| 770 |
|
| 771 |
|
| 772 |
@pytest.mark.csrf(ignore_unauth=True, csrfprotect=True) |
| 773 |
def test_token_auth_csrf(client): |
| 774 |
response = json_authenticate(client) |
| 775 |
token = response.json["response"]["user"]["authentication_token"] |
| 776 |
csrf_token = response.json["response"]["csrf_token"] |
| 777 |
headers = {"Authentication-Token": token} |
| 778 |
response = client.post("/token", headers=headers) |
| 779 |
assert b"The CSRF token is missing" in response.data |
| 780 |
|
| 781 |
# test JSON version |
| 782 |
response = client.post("/token", headers=headers, content_type="application/json") |
| 783 |
assert response.status_code == 400 |
| 784 |
assert response.json["response"]["errors"][0] == "The CSRF token is missing." |
| 785 |
|
| 786 |
# now do it right |
| 787 |
headers["X-CSRF-Token"] = csrf_token |
| 788 |
response = client.post( |
| 789 |
"/token", |
| 790 |
headers=headers, |
| 791 |
) |
| 792 |
assert b"Token Authentication" in response.data |
| 793 |
|
| 794 |
|
| 795 |
def test_http_auth(client, get_message): |
| 796 |
# browsers expect 401 response with WWW-Authenticate header - which will prompt |
| 797 |
# them to pop up a login form. |
| 798 |
response = client.get("/http", headers={}) |
| 799 |
assert response.status_code == 401 |
| 800 |
assert get_message("UNAUTHENTICATED") in response.data |
| 801 |
assert "WWW-Authenticate" in response.headers |
| 802 |
assert 'Basic realm="Login Required"' == response.headers["WWW-Authenticate"] |
| 803 |
|
| 804 |
# Now provide correct credentials |
| 805 |
response = client.get( |
| 806 |
"/http", |
| 807 |
headers={ |
| 808 |
"Authorization": "Basic %s" |
| 809 |
% base64.b64encode(b"[email protected]:password").decode("utf-8") |
| 810 |
}, |
| 811 |
) |
| 812 |
assert b"HTTP Authentication" in response.data |
| 813 |
|
| 814 |
|
| 815 |
@pytest.mark.settings( |
| 816 |
USER_IDENTITY_ATTRIBUTES=[ |
| 817 |
{"email": {"mapper": uia_email_mapper}}, |
| 818 |
{"username": {"mapper": lambda x: x}}, |
| 819 |
] |
| 820 |
) |
| 821 |
def test_http_auth_username(client): |
| 822 |
response = client.get( |
| 823 |
"/http", |
| 824 |
headers={ |
| 825 |
"Authorization": "Basic %s" |
| 826 |
% base64.b64encode(b"jill:password").decode("utf-8") |
| 827 |
}, |
| 828 |
) |
| 829 |
assert b"HTTP Authentication" in response.data |
| 830 |
|
| 831 |
|
| 832 |
def test_http_auth_no_authorization(client): |
| 833 |
response = client.get( |
| 834 |
"/http_admin_required", |
| 835 |
headers={ |
| 836 |
"Authorization": "Basic %s" |
| 837 |
% base64.b64encode(b"[email protected]:password").decode("utf-8") |
| 838 |
}, |
| 839 |
) |
| 840 |
assert response.status_code == 403 |
| 841 |
|
| 842 |
|
| 843 |
def test_http_auth_no_authorization_json(client, get_message): |
| 844 |
response = client.get( |
| 845 |
"/http_admin_required", |
| 846 |
headers={ |
| 847 |
"accept": "application/json", |
| 848 |
"Authorization": "Basic %s" |
| 849 |
% base64.b64encode(b"[email protected]:password").decode("utf-8"), |
| 850 |
}, |
| 851 |
) |
| 852 |
assert response.status_code == 403 |
| 853 |
assert response.headers["Content-Type"] == "application/json" |
| 854 |
|
| 855 |
|
| 856 |
def test_http_auth_no_authentication(client, get_message): |
| 857 |
response = client.get("/http", headers={}) |
| 858 |
assert response.status_code == 401 |
| 859 |
assert get_message("UNAUTHENTICATED") in response.data |
| 860 |
assert "WWW-Authenticate" in response.headers |
| 861 |
assert 'Basic realm="Login Required"' == response.headers["WWW-Authenticate"] |
| 862 |
|
| 863 |
|
| 864 |
def test_http_auth_no_authentication_json(client, get_message): |
| 865 |
response = client.get("/http", headers={"accept": "application/json"}) |
| 866 |
assert response.status_code == 401 |
| 867 |
assert response.json["response"]["errors"][0].encode("utf-8") == get_message( |
| 868 |
"UNAUTHENTICATED" |
| 869 |
) |
| 870 |
assert response.headers["Content-Type"] == "application/json" |
| 871 |
|
| 872 |
|
| 873 |
def test_invalid_http_auth_invalid_username(client, get_message): |
| 874 |
response = client.get( |
| 875 |
"/http", |
| 876 |
headers={ |
| 877 |
"Authorization": "Basic %s" |
| 878 |
% base64.b64encode(b"bogus:bogus").decode("utf-8") |
| 879 |
}, |
| 880 |
) |
| 881 |
assert get_message("UNAUTHENTICATED") in response.data |
| 882 |
assert "WWW-Authenticate" in response.headers |
| 883 |
assert 'Basic realm="Login Required"' == response.headers["WWW-Authenticate"] |
| 884 |
|
| 885 |
|
| 886 |
def test_invalid_http_auth_invalid_username_json(client, get_message): |
| 887 |
# Even with JSON - Basic Auth required a WWW-Authenticate header response. |
| 888 |
response = client.get( |
| 889 |
"/http", |
| 890 |
headers={ |
| 891 |
"accept": "application/json", |
| 892 |
"Authorization": "Basic %s" |
| 893 |
% base64.b64encode(b"bogus:bogus").decode("utf-8"), |
| 894 |
}, |
| 895 |
) |
| 896 |
assert response.status_code == 401 |
| 897 |
assert response.json["response"]["errors"][0].encode("utf-8") == get_message( |
| 898 |
"UNAUTHENTICATED" |
| 899 |
) |
| 900 |
assert response.headers["Content-Type"] == "application/json" |
| 901 |
assert "WWW-Authenticate" in response.headers |
| 902 |
|
| 903 |
|
| 904 |
def test_invalid_http_auth_bad_password(client, get_message): |
| 905 |
response = client.get( |
| 906 |
"/http", |
| 907 |
headers={ |
| 908 |
"Authorization": "Basic %s" |
| 909 |
% base64.b64encode(b"[email protected]:bogus").decode("utf-8") |
| 910 |
}, |
| 911 |
) |
| 912 |
assert get_message("UNAUTHENTICATED") in response.data |
| 913 |
assert "WWW-Authenticate" in response.headers |
| 914 |
assert 'Basic realm="Login Required"' == response.headers["WWW-Authenticate"] |
| 915 |
|
| 916 |
|
| 917 |
def test_custom_http_auth_realm(client, get_message): |
| 918 |
response = client.get( |
| 919 |
"/http_custom_realm", |
| 920 |
headers={ |
| 921 |
"Authorization": "Basic %s" |
| 922 |
% base64.b64encode(b"[email protected]:bogus").decode("utf-8") |
| 923 |
}, |
| 924 |
) |
| 925 |
assert get_message("UNAUTHENTICATED") in response.data |
| 926 |
assert "WWW-Authenticate" in response.headers |
| 927 |
assert 'Basic realm="My Realm"' == response.headers["WWW-Authenticate"] |
| 928 |
|
| 929 |
|
| 930 |
@pytest.mark.csrf(csrfprotect=True) |
| 931 |
def test_http_auth_csrf(client, get_message): |
| 932 |
headers = { |
| 933 |
"Authorization": "Basic %s" |
| 934 |
% base64.b64encode(b"[email protected]:password").decode("utf-8") |
| 935 |
} |
| 936 |
response = client.post( |
| 937 |
"/http", |
| 938 |
headers=headers, |
| 939 |
) |
| 940 |
assert b"The CSRF token is missing" in response.data |
| 941 |
|
| 942 |
# test JSON version |
| 943 |
response = client.post("/http", headers=headers, content_type="application/json") |
| 944 |
assert response.status_code == 400 |
| 945 |
assert response.json["response"]["errors"][0] == "The CSRF token is missing." |
| 946 |
|
| 947 |
# grab a csrf_token |
| 948 |
response = client.get("/login") |
| 949 |
csrf_token = get_form_input_value(response, "csrf_token") |
| 950 |
headers["X-CSRF-Token"] = csrf_token |
| 951 |
response = client.post( |
| 952 |
"/http", |
| 953 |
headers=headers, |
| 954 |
) |
| 955 |
assert b"HTTP Authentication" in response.data |
| 956 |
|
| 957 |
|
| 958 |
def test_multi_auth_basic(client): |
| 959 |
response = client.get( |
| 960 |
"/multi_auth", |
| 961 |
headers={ |
| 962 |
"Authorization": "Basic %s" |
| 963 |
% base64.b64encode(b"[email protected]:password").decode("utf-8") |
| 964 |
}, |
| 965 |
) |
| 966 |
assert b"Basic" in response.data |
| 967 |
|
| 968 |
response = client.get("/multi_auth") |
| 969 |
# Default unauthn with basic is to return 401 with WWW-Authenticate Header |
| 970 |
# so that browser pops up a username/password dialog |
| 971 |
assert response.status_code == 401 |
| 972 |
assert "WWW-Authenticate" in response.headers |
| 973 |
|
| 974 |
|
| 975 |
def test_multi_auth_basic_invalid(client, get_message): |
| 976 |
response = client.get( |
| 977 |
"/multi_auth", |
| 978 |
headers={ |
| 979 |
"Authorization": "Basic %s" |
| 980 |
% base64.b64encode(b"bogus:bogus").decode("utf-8") |
| 981 |
}, |
| 982 |
) |
| 983 |
assert get_message("UNAUTHENTICATED") in response.data |
| 984 |
assert "WWW-Authenticate" in response.headers |
| 985 |
assert 'Basic realm="Login Required"' == response.headers["WWW-Authenticate"] |
| 986 |
|
| 987 |
response = client.get("/multi_auth") |
| 988 |
assert response.status_code == 401 |
| 989 |
|
| 990 |
|
| 991 |
def test_multi_auth_token(client): |
| 992 |
response = json_authenticate(client) |
| 993 |
token = response.json["response"]["user"]["authentication_token"] |
| 994 |
response = client.get("/multi_auth?auth_token=" + token) |
| 995 |
assert b"Token" in response.data |
| 996 |
|
| 997 |
|
| 998 |
def test_multi_auth_session(client): |
| 999 |
authenticate(client) |
| 1000 |
response = client.get("/multi_auth") |
| 1001 |
assert b"Session" in response.data |
| 1002 |
|
| 1003 |
|
| 1004 |
def test_authenticated_loop(client): |
| 1005 |
# If user is already authenticated say via session, and then hits an endpoint |
| 1006 |
# protected with @auth_token_required() - then they will be redirected to the login |
| 1007 |
# page which will simply note the current user is already logged in and redirect |
| 1008 |
# to POST_LOGIN_VIEW. Between 3.3.0 and 3.4.4 - this redirect would honor the 'next' |
| 1009 |
# parameter - thus redirecting back to the endpoint that caused the redirect in the |
| 1010 |
# first place - thus an infinite loop. |
| 1011 |
authenticate(client) |
| 1012 |
|
| 1013 |
response = client.get("/token", follow_redirects=True) |
| 1014 |
assert response.status_code == 200 |
| 1015 |
assert b"Home Page" in response.data |
| 1016 |
|
| 1017 |
|
| 1018 |
def test_user_deleted_during_session_reverts_to_anonymous_user(app, client): |
| 1019 |
authenticate(client) |
| 1020 |
|
| 1021 |
with app.test_request_context("/"): |
| 1022 |
user = app.security.datastore.find_user(email="[email protected]") |
| 1023 |
app.security.datastore.delete_user(user) |
| 1024 |
app.security.datastore.commit() |
| 1025 |
|
| 1026 |
response = client.get("/") |
| 1027 |
assert b"Hello [email protected]" not in response.data |
| 1028 |
|
| 1029 |
|
| 1030 |
def test_session_loads_identity(app, client): |
| 1031 |
@app.route("/identity_check") |
| 1032 |
@auth_required("session") |
| 1033 |
def id_check(): |
| 1034 |
if hasattr(g, "identity"): |
| 1035 |
identity = g.identity |
| 1036 |
assert hasattr(identity, "loader_called") |
| 1037 |
assert identity.loader_called |
| 1038 |
return "Success" |
| 1039 |
|
| 1040 |
json_authenticate(client) |
| 1041 |
|
| 1042 |
# add identity loader after authentication to only fire it for |
| 1043 |
# session-authentication next `get` call |
| 1044 |
@identity_loaded.connect_via(app) |
| 1045 |
def identity_loaded_check(sender, identity): |
| 1046 |
identity.loader_called = True |
| 1047 |
|
| 1048 |
response = client.get("/identity_check") |
| 1049 |
assert b"Success" == response.data |
| 1050 |
|
| 1051 |
|
| 1052 |
def test_remember_token(client): |
| 1053 |
response = authenticate(client, follow_redirects=False, remember=True) |
| 1054 |
client.delete_cookie("session") |
| 1055 |
assert not client.get_cookie("session") |
| 1056 |
assert client.get_cookie("remember_token") |
| 1057 |
response = client.get("/profile", follow_redirects=True) |
| 1058 |
assert b"Profile Page" in response.data |
| 1059 |
|
| 1060 |
|
| 1061 |
def test_request_loader_does_not_fail_with_invalid_token(client): |
| 1062 |
client.set_cookie("remember_token") |
| 1063 |
response = client.get("/") |
| 1064 |
assert b"BadSignature" not in response.data |
| 1065 |
|
| 1066 |
|
| 1067 |
def test_sending_auth_token_with_json(client): |
| 1068 |
response = json_authenticate(client) |
| 1069 |
token = response.json["response"]["user"]["authentication_token"] |
| 1070 |
data = '{"auth_token": "%s"}' % token |
| 1071 |
response = client.post( |
| 1072 |
"/token", data=data, headers={"Content-Type": "application/json"} |
| 1073 |
) |
| 1074 |
assert b"Token Authentication" in response.data |
| 1075 |
|
| 1076 |
|
| 1077 |
def test_json_not_dict(client): |
| 1078 |
response = client.post( |
| 1079 |
"/json", |
| 1080 |
data=json.dumps(["thing1", "thing2"]), |
| 1081 |
headers={"Content-Type": "application/json"}, |
| 1082 |
) |
| 1083 |
assert response.status_code == 200 |
| 1084 |
|
| 1085 |
|
| 1086 |
def test_login_info(client): |
| 1087 |
# Make sure we can get user info when logged in already. |
| 1088 |
|
| 1089 |
json_authenticate(client) |
| 1090 |
response = client.get("/login", headers={"Content-Type": "application/json"}) |
| 1091 |
assert response.status_code == 200 |
| 1092 |
assert response.cache_control.private |
| 1093 |
assert response.json["response"]["user"]["email"] == "[email protected]" |
| 1094 |
assert "last_update" in response.json["response"]["user"] |
| 1095 |
|
| 1096 |
response = client.get("/login", headers={"Accept": "application/json"}) |
| 1097 |
assert response.status_code == 200 |
| 1098 |
assert response.json["response"]["user"]["email"] == "[email protected]" |
| 1099 |
assert "last_update" in response.json["response"]["user"] |
| 1100 |
|
| 1101 |
|
| 1102 |
@pytest.mark.registerable() |
| 1103 |
@pytest.mark.settings(post_login_view="/anon_required") |
| 1104 |
def test_anon_required(client, get_message): |
| 1105 |
"""If logged in, should get 'anonymous_user_required' redirect""" |
| 1106 |
response = authenticate(client, follow_redirects=False) |
| 1107 |
response = client.get("/register") |
| 1108 |
assert "location" in response.headers |
| 1109 |
assert "/anon_required" in response.location |
| 1110 |
|
| 1111 |
|
| 1112 |
@pytest.mark.registerable() |
| 1113 |
@pytest.mark.settings(post_login_view="/anon_required") |
| 1114 |
def test_anon_required_json(client, get_message): |
| 1115 |
"""If logged in, should get 'anonymous_user_required' response""" |
| 1116 |
authenticate(client, follow_redirects=False) |
| 1117 |
response = client.get("/register", headers={"Accept": "application/json"}) |
| 1118 |
assert response.status_code == 400 |
| 1119 |
assert response.json["response"]["errors"][0].encode("utf-8") == get_message( |
| 1120 |
"ANONYMOUS_USER_REQUIRED" |
| 1121 |
) |
| 1122 |
|
| 1123 |
|
| 1124 |
def test_change_uniquifier(app, client_nc): |
| 1125 |
# make sure that existing token no longer works once we change the uniquifier |
| 1126 |
|
| 1127 |
response = json_authenticate(client_nc) |
| 1128 |
token = response.json["response"]["user"]["authentication_token"] |
| 1129 |
verify_token(client_nc, token) |
| 1130 |
|
| 1131 |
# now change uniquifier |
| 1132 |
with app.test_request_context("/"): |
| 1133 |
user = app.security.datastore.find_user(email="[email protected]") |
| 1134 |
app.security.datastore.reset_user_access(user) |
| 1135 |
app.security.datastore.commit() |
| 1136 |
|
| 1137 |
verify_token(client_nc, token, status=401) |
| 1138 |
|
| 1139 |
# get new token and verify it works |
| 1140 |
response = json_authenticate(client_nc) |
| 1141 |
token = response.json["response"]["user"]["authentication_token"] |
| 1142 |
verify_token(client_nc, token) |
| 1143 |
|
| 1144 |
|
| 1145 |
def test_verifying_token_from_version_3x(app, client): |
| 1146 |
""" |
| 1147 |
Check token generated with flask security 3.x, which has different form |
| 1148 |
than token from version 4.0.0, can be verified |
| 1149 |
""" |
| 1150 |
from .test_utils import get_auth_token_version_3x |
| 1151 |
|
| 1152 |
with app.test_request_context("/"): |
| 1153 |
user = app.security.datastore.find_user(email="[email protected]") |
| 1154 |
token = get_auth_token_version_3x(app, user) |
| 1155 |
|
| 1156 |
headers = {"Authentication-Token": token, "Accept": "application/json"} |
| 1157 |
response = client.get("/profile", headers=headers) |
| 1158 |
assert response.status_code == 200 |
| 1159 |
|
| 1160 |
|
| 1161 |
def test_verifying_token_from_version_4x(app, client): |
| 1162 |
from .test_utils import get_auth_token_version_4x |
| 1163 |
|
| 1164 |
with app.test_request_context("/"): |
| 1165 |
user = app.security.datastore.find_user(email="[email protected]") |
| 1166 |
token = get_auth_token_version_4x(app, user) |
| 1167 |
|
| 1168 |
headers = {"Authentication-Token": token, "Accept": "application/json"} |
| 1169 |
response = client.get("/profile", headers=headers) |
| 1170 |
assert response.status_code == 200 |
| 1171 |
|
| 1172 |
|
| 1173 |
def test_change_token_uniquifier(app): |
| 1174 |
pytest.importorskip("sqlalchemy") |
| 1175 |
pytest.importorskip("flask_sqlalchemy") |
| 1176 |
|
| 1177 |
# make sure that existing token no longer works once we change the token uniquifier |
| 1178 |
from sqlalchemy import Column, String |
| 1179 |
from flask_sqlalchemy import SQLAlchemy |
| 1180 |
from flask_security.models import fsqla_v2 as fsqla |
| 1181 |
from flask_security import Security, SQLAlchemyUserDatastore |
| 1182 |
|
| 1183 |
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///:memory:" |
| 1184 |
db = SQLAlchemy(app) |
| 1185 |
|
| 1186 |
fsqla.FsModels.set_db_info(db) |
| 1187 |
|
| 1188 |
class Role(db.Model, fsqla.FsRoleMixin): |
| 1189 |
pass |
| 1190 |
|
| 1191 |
class User(db.Model, fsqla.FsUserMixin): |
| 1192 |
fs_token_uniquifier = Column(String(64), unique=True, nullable=False) |
| 1193 |
|
| 1194 |
with app.app_context(): |
| 1195 |
db.create_all() |
| 1196 |
|
| 1197 |
ds = SQLAlchemyUserDatastore(db, User, Role) |
| 1198 |
app.security = Security(app, datastore=ds) |
| 1199 |
|
| 1200 |
with app.app_context(): |
| 1201 |
ds.create_user( |
| 1202 |
email="[email protected]", |
| 1203 |
password=hash_password("password"), |
| 1204 |
) |
| 1205 |
ds.commit() |
| 1206 |
|
| 1207 |
client_nc = app.test_client(use_cookies=False) |
| 1208 |
|
| 1209 |
response = json_authenticate(client_nc) |
| 1210 |
token = response.json["response"]["user"]["authentication_token"] |
| 1211 |
verify_token(client_nc, token) |
| 1212 |
|
| 1213 |
# now change uniquifier |
| 1214 |
with app.test_request_context("/"): |
| 1215 |
user = app.security.datastore.find_user(email="[email protected]") |
| 1216 |
app.security.datastore.reset_user_access(user) |
| 1217 |
app.security.datastore.commit() |
| 1218 |
|
| 1219 |
verify_token(client_nc, token, status=401) |
| 1220 |
|
| 1221 |
# get new token and verify it works |
| 1222 |
response = json_authenticate(client_nc) |
| 1223 |
token = response.json["response"]["user"]["authentication_token"] |
| 1224 |
verify_token(client_nc, token) |
| 1225 |
|
| 1226 |
with app.app_context(): |
| 1227 |
db.engine.dispose() |
| 1228 |
|
| 1229 |
|
| 1230 |
def test_null_token_uniquifier(app): |
| 1231 |
pytest.importorskip("sqlalchemy") |
| 1232 |
pytest.importorskip("flask_sqlalchemy") |
| 1233 |
|
| 1234 |
# If existing record has a null fs_token_uniquifier, should be set on first use. |
| 1235 |
from sqlalchemy import Column, String |
| 1236 |
from flask_sqlalchemy import SQLAlchemy |
| 1237 |
from flask_security.models import fsqla_v2 as fsqla |
| 1238 |
from flask_security import Security, SQLAlchemyUserDatastore |
| 1239 |
|
| 1240 |
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///:memory:" |
| 1241 |
db = SQLAlchemy(app) |
| 1242 |
|
| 1243 |
fsqla.FsModels.set_db_info(db) |
| 1244 |
|
| 1245 |
class Role(db.Model, fsqla.FsRoleMixin): |
| 1246 |
pass |
| 1247 |
|
| 1248 |
class User(db.Model, fsqla.FsUserMixin): |
| 1249 |
fs_token_uniquifier = Column(String(64), unique=True, nullable=True) |
| 1250 |
|
| 1251 |
with app.app_context(): |
| 1252 |
db.create_all() |
| 1253 |
|
| 1254 |
ds = SQLAlchemyUserDatastore(db, User, Role) |
| 1255 |
app.security = Security(app, datastore=ds) |
| 1256 |
|
| 1257 |
with app.app_context(): |
| 1258 |
ds.create_user( |
| 1259 |
email="[email protected]", |
| 1260 |
password=hash_password("password"), |
| 1261 |
) |
| 1262 |
ds.commit() |
| 1263 |
|
| 1264 |
# manually null out fs_token_uniquifier |
| 1265 |
user = ds.find_user(email="[email protected]") |
| 1266 |
user.fs_token_uniquifier = None |
| 1267 |
ds.put(user) |
| 1268 |
ds.commit() |
| 1269 |
|
| 1270 |
client_nc = app.test_client(use_cookies=False) |
| 1271 |
|
| 1272 |
response = json_authenticate(client_nc) |
| 1273 |
token = response.json["response"]["user"]["authentication_token"] |
| 1274 |
verify_token(client_nc, token) |
| 1275 |
|
| 1276 |
with app.app_context(): |
| 1277 |
db.engine.dispose() |
| 1278 |
|
| 1279 |
|
| 1280 |
def test_token_query(app, client_nc): |
| 1281 |
# Verify that when authenticating with auth token (and not session) |
| 1282 |
# that there is just one DB query to get user. |
| 1283 |
with capture_queries(app.security.datastore) as queries: |
| 1284 |
response = json_authenticate(client_nc) |
| 1285 |
assert len(queries) == 1 |
| 1286 |
token = response.json["response"]["user"]["authentication_token"] |
| 1287 |
response = client_nc.get( |
| 1288 |
"/token", |
| 1289 |
headers={"Content-Type": "application/json", "Authentication-Token": token}, |
| 1290 |
) |
| 1291 |
assert response.status_code == 200 |
| 1292 |
assert len(queries) == 2 |
| 1293 |
|
| 1294 |
|
| 1295 |
def test_session_query(in_app_context): |
| 1296 |
# Verify that when authenticating with auth token (but also sending session) |
| 1297 |
# that there are 2 DB queries to get user. |
| 1298 |
# This is since the session will load one - but auth_token_required needs to |
| 1299 |
# verify that the TOKEN is valid (and it is possible that the user_id in the |
| 1300 |
# session is different that the one in the token (huh?) |
| 1301 |
myapp = in_app_context |
| 1302 |
populate_data(myapp) |
| 1303 |
myclient = myapp.test_client() |
| 1304 |
|
| 1305 |
response = json_authenticate(myclient) |
| 1306 |
token = response.json["response"]["user"]["authentication_token"] |
| 1307 |
with capture_queries(myapp.security.datastore) as queries: |
| 1308 |
response = myclient.get( |
| 1309 |
"/token", |
| 1310 |
headers={"Content-Type": "application/json", "Authentication-Token": token}, |
| 1311 |
) |
| 1312 |
assert response.status_code == 200 |
| 1313 |
assert len(queries) == 2 |
| 1314 |
|
| 1315 |
|
| 1316 |
@pytest.mark.changeable() |
| 1317 |
def test_no_get_auth_token(app, client): |
| 1318 |
# Test that GETs don't return an auth token. This is a security issue since |
| 1319 |
# GETs aren't protected with CSRF |
| 1320 |
authenticate(client) |
| 1321 |
response = client.get( |
| 1322 |
"/login?include_auth_token", headers={"Content-Type": "application/json"} |
| 1323 |
) |
| 1324 |
assert "authentication_token" not in response.json["response"]["user"] |
| 1325 |
|
| 1326 |
data = dict( |
| 1327 |
password="password", |
| 1328 |
new_password="new strong password", |
| 1329 |
new_password_confirm="new strong password", |
| 1330 |
) |
| 1331 |
response = client.get( |
| 1332 |
"/change?include_auth_token", |
| 1333 |
json=data, |
| 1334 |
headers={"Content-Type": "application/json"}, |
| 1335 |
) |
| 1336 |
assert "authentication_token" not in response.json["response"]["user"] |
| 1337 |
|
| 1338 |
|
| 1339 |
def test_auth_token_decorator(app, client_nc): |
| 1340 |
""" |
| 1341 |
Test accessing endpoint decorated with auth_token_required |
| 1342 |
when using token generated by flask security 3.x algorithm |
| 1343 |
""" |
| 1344 |
with app.test_request_context("/"): |
| 1345 |
user = app.security.datastore.find_user(email="[email protected]") |
| 1346 |
token = get_auth_token_version_3x(app, user) |
| 1347 |
|
| 1348 |
response = client_nc.get( |
| 1349 |
"/token", |
| 1350 |
headers={"Content-Type": "application/json", "Authentication-Token": token}, |
| 1351 |
) |
| 1352 |
assert response.status_code == 200 |
| 1353 |
|
| 1354 |
|
| 1355 |
@pytest.mark.settings(cache_control={"no-store": True}) |
| 1356 |
def test_override_cache_control(app, client_nc): |
| 1357 |
response = json_authenticate(client_nc) |
| 1358 |
assert not response.cache_control.private |
| 1359 |
assert response.cache_control.no_store |
| 1360 |
|
| 1361 |
|
| 1362 |
@pytest.mark.settings(cache_control=None) |
| 1363 |
def test_no_cache_control(app, client_nc): |
| 1364 |
response = json_authenticate(client_nc) |
| 1365 |
assert "Cache-Control" not in response.headers |
| 1366 |
|
| 1367 |
|
| 1368 |
def test_cache_control_not_on_app_endpoints(app, client): |
| 1369 |
# SECURITY_CACHE_CONTROL applies to Flask-Security endpoints only - |
| 1370 |
# responses from application endpoints must not be touched. |
| 1371 |
response = client.get("/login") |
| 1372 |
assert response.cache_control.no_store |
| 1373 |
response = client.get("/") |
| 1374 |
assert "Cache-Control" not in response.headers |