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