| 1 |
""" |
| 2 |
test_two_factor |
| 3 |
~~~~~~~~~~~~~~~~~ |
| 4 |
|
| 5 |
two_factor tests |
| 6 |
|
| 7 |
:copyright: (c) 2019-2026 by J. Christopher Wagner (jwag). |
| 8 |
:license: MIT, see LICENSE for more details. |
| 9 |
""" |
| 10 |
|
| 11 |
from datetime import date, timedelta |
| 12 |
import re |
| 13 |
|
| 14 |
from freezegun import freeze_time |
| 15 |
import markupsafe |
| 16 |
from passlib.totp import TOTP |
| 17 |
import pytest |
| 18 |
from flask_principal import identity_changed |
| 19 |
from flask_security import ( |
| 20 |
SQLAlchemyUserDatastore, |
| 21 |
SmsSenderFactory, |
| 22 |
reset_password_instructions_sent, |
| 23 |
tf_profile_changed, |
| 24 |
uia_email_mapper, |
| 25 |
) |
| 26 |
from tests.test_utils import ( |
| 27 |
SmsBadSender, |
| 28 |
SmsTestSender, |
| 29 |
authenticate, |
| 30 |
capture_flashes, |
| 31 |
capture_send_code_requests, |
| 32 |
check_location, |
| 33 |
check_xlation, |
| 34 |
get_form_action, |
| 35 |
get_form_input_value, |
| 36 |
get_session, |
| 37 |
is_authenticated, |
| 38 |
json_authenticate, |
| 39 |
logout, |
| 40 |
check_signals, |
| 41 |
) |
| 42 |
|
| 43 |
pytestmark = pytest.mark.two_factor() |
| 44 |
|
| 45 |
|
| 46 |
SmsSenderFactory.senders["test"] = SmsTestSender |
| 47 |
SmsSenderFactory.senders["bad"] = SmsBadSender |
| 48 |
|
| 49 |
|
| 50 |
def tf_authenticate(app, client, json=False, validate=True, remember=False): |
| 51 |
"""Login/Authenticate using two factor. |
| 52 |
This is the equivalent of utils:authenticate |
| 53 |
""" |
| 54 |
prev_sms = app.config["SECURITY_SMS_SERVICE"] |
| 55 |
app.config["SECURITY_SMS_SERVICE"] = "test" |
| 56 |
sms_sender = SmsSenderFactory.createSender("test") |
| 57 |
json_data = dict(email="[email protected]", password="password", remember=remember) |
| 58 |
response = client.post( |
| 59 |
"/login", json=json_data, headers={"Content-Type": "application/json"} |
| 60 |
) |
| 61 |
|
| 62 |
assert b'"code": 200' in response.data |
| 63 |
app.config["SECURITY_SMS_SERVICE"] = prev_sms |
| 64 |
|
| 65 |
if validate: |
| 66 |
code = sms_sender.messages[0].split()[-1] |
| 67 |
if json: |
| 68 |
response = client.post( |
| 69 |
"/tf-validate", |
| 70 |
json=dict(code=code), |
| 71 |
) |
| 72 |
assert response.status_code == 200 |
| 73 |
else: |
| 74 |
response = client.post( |
| 75 |
"/tf-validate", data=dict(code=code), follow_redirects=True |
| 76 |
) |
| 77 |
assert response.status_code == 200 |
| 78 |
|
| 79 |
|
| 80 |
def tf_in_session(session): |
| 81 |
return any( |
| 82 |
k in session |
| 83 |
for k in [ |
| 84 |
"tf_state", |
| 85 |
"tf_primary_method", |
| 86 |
"tf_user_id", |
| 87 |
"tf_remember_login", |
| 88 |
"tf_totp_secret", |
| 89 |
"tf_select", |
| 90 |
] |
| 91 |
) |
| 92 |
|
| 93 |
|
| 94 |
@pytest.mark.settings(two_factor_always_validate=False) |
| 95 |
def test_always_validate(app, client, get_message): |
| 96 |
tf_authenticate(app, client, remember=True) |
| 97 |
assert client.get_cookie("tf_validity") |
| 98 |
|
| 99 |
logout(client) |
| 100 |
|
| 101 |
data = dict(email="[email protected]", password="password") |
| 102 |
response = client.post("/login", data=data, follow_redirects=True) |
| 103 |
assert b"Welcome [email protected]" in response.data |
| 104 |
assert response.status_code == 200 |
| 105 |
|
| 106 |
logout(client) |
| 107 |
data = dict(email="[email protected]", password="password") |
| 108 |
response = client.post("/login", data=data, follow_redirects=True) |
| 109 |
assert b"Please enter your authentication code" in response.data |
| 110 |
|
| 111 |
# make sure the cookie doesn't affect the JSON request |
| 112 |
client.delete_cookie("tf_validity") |
| 113 |
# Test JSON (this authenticates [email protected]) |
| 114 |
tf_authenticate(app, client, json=True, remember=True) |
| 115 |
logout(client) |
| 116 |
|
| 117 |
data = dict(email="[email protected]", password="password") |
| 118 |
response = client.post( |
| 119 |
"/login", |
| 120 |
json=data, |
| 121 |
follow_redirects=True, |
| 122 |
) |
| 123 |
assert response.status_code == 200 |
| 124 |
# verify logged in |
| 125 |
is_authenticated(client, get_message) |
| 126 |
logout(client) |
| 127 |
|
| 128 |
data["email"] = "[email protected]" |
| 129 |
response = client.post( |
| 130 |
"/login", |
| 131 |
json=data, |
| 132 |
follow_redirects=True, |
| 133 |
) |
| 134 |
assert response.status_code == 200 |
| 135 |
assert response.json["response"]["tf_required"] |
| 136 |
assert response.json["response"]["tf_state"] == "ready" |
| 137 |
assert response.json["response"]["tf_primary_method"] == "authenticator" |
| 138 |
|
| 139 |
|
| 140 |
@pytest.mark.settings(two_factor_always_validate=False) |
| 141 |
def test_do_not_remember_tf_validity(app, client): |
| 142 |
tf_authenticate(app, client) |
| 143 |
logout(client) |
| 144 |
|
| 145 |
data = dict(email="[email protected]", password="password") |
| 146 |
response = client.post("/login", data=data, follow_redirects=True) |
| 147 |
assert b"Please enter your authentication code" in response.data |
| 148 |
|
| 149 |
# Test JSON |
| 150 |
tf_authenticate(app, client, json=True) |
| 151 |
logout(client) |
| 152 |
assert not client.get_cookie("tf_validity") |
| 153 |
|
| 154 |
data = dict(email="[email protected]", password="password") |
| 155 |
response = client.post( |
| 156 |
"/login", |
| 157 |
json=data, |
| 158 |
follow_redirects=True, |
| 159 |
headers={"Content-Type": "application/json"}, |
| 160 |
) |
| 161 |
|
| 162 |
assert response.status_code == 200 |
| 163 |
assert response.json["response"]["tf_required"] |
| 164 |
assert response.json["response"]["tf_state"] == "ready" |
| 165 |
assert response.json["response"]["tf_primary_method"] == "sms" |
| 166 |
|
| 167 |
|
| 168 |
@pytest.mark.settings( |
| 169 |
two_factor_always_validate=False, two_factor_login_validity="-1 minutes" |
| 170 |
) |
| 171 |
def test_tf_expired_cookie(app, client): |
| 172 |
tf_authenticate(app, client, remember=True) |
| 173 |
logout(client) |
| 174 |
|
| 175 |
data = dict(email="[email protected]", password="password") |
| 176 |
response = client.post("/login", data=data, follow_redirects=True) |
| 177 |
|
| 178 |
assert b"Please enter your authentication code" in response.data |
| 179 |
|
| 180 |
# Test JSON |
| 181 |
tf_authenticate(app, client, json=True, remember=True) |
| 182 |
logout(client) |
| 183 |
data = dict(email="[email protected]", password="password") |
| 184 |
response = client.post( |
| 185 |
"/login", |
| 186 |
json=data, |
| 187 |
follow_redirects=True, |
| 188 |
headers={"Content-Type": "application/json"}, |
| 189 |
) |
| 190 |
assert response.status_code == 200 |
| 191 |
assert response.json["response"]["tf_required"] |
| 192 |
assert response.json["response"]["tf_state"] == "ready" |
| 193 |
assert response.json["response"]["tf_primary_method"] == "sms" |
| 194 |
|
| 195 |
|
| 196 |
@pytest.mark.settings(two_factor_always_validate=False) |
| 197 |
def test_change_uniquifier_invalidates_cookie(app, client): |
| 198 |
tf_authenticate(app, client, remember=True) |
| 199 |
logout(client) |
| 200 |
with app.app_context(): |
| 201 |
user = app.security.datastore.find_user(email="[email protected]") |
| 202 |
app.security.datastore.set_uniquifier(user) |
| 203 |
app.security.datastore.commit() |
| 204 |
|
| 205 |
data = dict(email="[email protected]", password="password") |
| 206 |
response = client.post("/login", data=data, follow_redirects=True) |
| 207 |
|
| 208 |
assert b"Please enter your authentication code" in response.data |
| 209 |
|
| 210 |
client.delete_cookie("tf_validity") |
| 211 |
# Test JSON |
| 212 |
tf_authenticate(app, client, json=True, remember=True) |
| 213 |
logout(client) |
| 214 |
with app.app_context(): |
| 215 |
user = app.security.datastore.find_user(email="[email protected]") |
| 216 |
app.security.datastore.set_uniquifier(user) |
| 217 |
app.security.datastore.commit() |
| 218 |
data = dict(email="[email protected]", password="password") |
| 219 |
response = client.post( |
| 220 |
"/login", |
| 221 |
json=data, |
| 222 |
follow_redirects=True, |
| 223 |
headers={"Content-Type": "application/json"}, |
| 224 |
) |
| 225 |
assert response.status_code == 200 |
| 226 |
assert response.json["response"]["tf_required"] |
| 227 |
assert response.json["response"]["tf_state"] == "ready" |
| 228 |
assert response.json["response"]["tf_primary_method"] == "sms" |
| 229 |
|
| 230 |
|
| 231 |
@pytest.mark.settings(two_factor_always_validate=False, two_factor_required=True) |
| 232 |
def test_tf_reset_invalidates_cookie(app, client): |
| 233 |
tf_authenticate(app, client, remember=True) |
| 234 |
logout(client) |
| 235 |
with app.app_context(): |
| 236 |
user = app.security.datastore.find_user(email="[email protected]") |
| 237 |
app.security.datastore.reset_user_access(user) |
| 238 |
app.security.datastore.commit() |
| 239 |
|
| 240 |
data = dict(email="[email protected]", password="password") |
| 241 |
response = client.post("/login", data=data, follow_redirects=True) |
| 242 |
|
| 243 |
assert b"Two-Factor authentication adds an extra layer of security" in response.data |
| 244 |
|
| 245 |
client.delete_cookie("tf_validity") |
| 246 |
# Test JSON |
| 247 |
tf_authenticate(app, client, json=True, remember=True, validate=False) |
| 248 |
logout(client) |
| 249 |
with app.app_context(): |
| 250 |
user = app.security.datastore.find_user(email="[email protected]") |
| 251 |
app.security.datastore.reset_user_access(user) |
| 252 |
app.security.datastore.commit() |
| 253 |
data = dict(email="[email protected]", password="password") |
| 254 |
response = client.post( |
| 255 |
"/login", |
| 256 |
json=data, |
| 257 |
follow_redirects=True, |
| 258 |
headers={"Content-Type": "application/json"}, |
| 259 |
) |
| 260 |
assert response.status_code == 200 |
| 261 |
assert response.json["response"]["tf_required"] |
| 262 |
assert response.json["response"]["tf_state"] == "setup_from_login" |
| 263 |
|
| 264 |
|
| 265 |
@pytest.mark.settings(two_factor_required=True) |
| 266 |
def test_two_factor_two_factor_setup_anonymous(app, client, get_message): |
| 267 |
# trying to pick method without doing earlier stage |
| 268 |
data = dict(setup="email") |
| 269 |
|
| 270 |
with capture_flashes() as flashes: |
| 271 |
response = client.post("/tf-setup", data=data) |
| 272 |
assert response.status_code in [302, 303] |
| 273 |
assert flashes[0]["category"] == "error" |
| 274 |
assert flashes[0]["message"].encode("utf-8") == get_message( |
| 275 |
"TWO_FACTOR_PERMISSION_DENIED" |
| 276 |
) |
| 277 |
|
| 278 |
|
| 279 |
@pytest.mark.settings(two_factor_required=True, url_prefix="/api") |
| 280 |
def test_two_factor_illegal_state(app, client, get_message): |
| 281 |
# trying to pick method without doing earlier stage |
| 282 |
data = dict(setup="email") |
| 283 |
|
| 284 |
with capture_flashes() as flashes: |
| 285 |
response = client.post("/api/tf-setup", data=data) |
| 286 |
assert response.status_code in [302, 303] |
| 287 |
assert "/api/login" in response.location |
| 288 |
assert flashes[0]["category"] == "error" |
| 289 |
assert flashes[0]["message"].encode("utf-8") == get_message( |
| 290 |
"TWO_FACTOR_PERMISSION_DENIED" |
| 291 |
) |
| 292 |
|
| 293 |
# try validate code |
| 294 |
response = client.post( |
| 295 |
"/api/tf-validate", data=dict(code=b"333"), follow_redirects=False |
| 296 |
) |
| 297 |
assert response.status_code in [302, 303] |
| 298 |
assert "/api/login" in response.location |
| 299 |
|
| 300 |
# try rescue |
| 301 |
response = client.post( |
| 302 |
"/api/tf-rescue", data=dict(help_setup="lost_device"), follow_redirects=False |
| 303 |
) |
| 304 |
assert response.status_code in [302, 303] |
| 305 |
assert "/api/login" in response.location |
| 306 |
|
| 307 |
|
| 308 |
@pytest.mark.settings(two_factor_required=True) |
| 309 |
def test_two_factor_flag(app, clients, get_message, outbox, signals): |
| 310 |
# trying to verify code without going through two-factor |
| 311 |
# first login function |
| 312 |
client = clients |
| 313 |
wrong_code = b"000000" |
| 314 |
response = client.post( |
| 315 |
"/tf-validate", data=dict(code=wrong_code), follow_redirects=True |
| 316 |
) |
| 317 |
|
| 318 |
message = b"You currently do not have permissions to access this page" |
| 319 |
assert message in response.data |
| 320 |
|
| 321 |
# Test login using invalid email |
| 322 |
data = dict(email="[email protected]", password="password") |
| 323 |
response = client.post("/login", data=data, follow_redirects=True) |
| 324 |
assert b"Specified user does not exist" in response.data |
| 325 |
response = client.post( |
| 326 |
"/login", |
| 327 |
json=data, |
| 328 |
headers={"Content-Type": "application/json"}, |
| 329 |
follow_redirects=True, |
| 330 |
) |
| 331 |
assert b"Specified user does not exist" in response.data |
| 332 |
|
| 333 |
# Test login using valid email and invalid password |
| 334 |
data = dict(email="[email protected]", password="wrong_pass") |
| 335 |
response = client.post("/login", data=data, follow_redirects=True) |
| 336 |
assert b"Invalid password" in response.data |
| 337 |
response = client.post( |
| 338 |
"/login", |
| 339 |
json=data, |
| 340 |
headers={"Content-Type": "application/json"}, |
| 341 |
follow_redirects=True, |
| 342 |
) |
| 343 |
assert b"Invalid password" in response.data |
| 344 |
|
| 345 |
# Test two-factor authentication first login |
| 346 |
data = dict(email="[email protected]", password="password") |
| 347 |
response = client.post("/login", data=data, follow_redirects=True) |
| 348 |
message = b"Two-Factor authentication adds an extra layer of security" |
| 349 |
assert message in response.data |
| 350 |
response = client.post( |
| 351 |
"/tf-setup", data=dict(setup="not_a_method"), follow_redirects=True |
| 352 |
) |
| 353 |
assert b"Marked method is not valid" in response.data |
| 354 |
with client.session_transaction() as session: |
| 355 |
assert session["tf_state"] == "setup_from_login" |
| 356 |
|
| 357 |
# try non-existing setup on setup page (using json) |
| 358 |
data = dict(setup="not_a_method") |
| 359 |
response = client.post( |
| 360 |
"/tf-setup", |
| 361 |
json=data, |
| 362 |
headers={"Content-Type": "application/json"}, |
| 363 |
follow_redirects=True, |
| 364 |
) |
| 365 |
assert response.status_code == 400 |
| 366 |
assert ( |
| 367 |
response.json["response"]["field_errors"]["setup"][0] |
| 368 |
== "Marked method is not valid" |
| 369 |
) |
| 370 |
|
| 371 |
data = dict(setup="email") |
| 372 |
response = client.post( |
| 373 |
"/tf-setup", |
| 374 |
json=data, |
| 375 |
headers={"Content-Type": "application/json"}, |
| 376 |
follow_redirects=True, |
| 377 |
) |
| 378 |
|
| 379 |
# Test for sms in process of valid login |
| 380 |
sms_sender = SmsSenderFactory.createSender("test") |
| 381 |
data = dict(email="[email protected]", password="password") |
| 382 |
response = client.post( |
| 383 |
"/login", |
| 384 |
json=data, |
| 385 |
headers={"Content-Type": "application/json"}, |
| 386 |
follow_redirects=True, |
| 387 |
) |
| 388 |
assert b'"code": 200' in response.data |
| 389 |
assert sms_sender.get_count() == 1 |
| 390 |
session = get_session(response) |
| 391 |
assert session["tf_state"] == "ready" |
| 392 |
|
| 393 |
code = sms_sender.messages[0].split()[-1] |
| 394 |
# submit bad token to two_factor_token_validation |
| 395 |
response = client.post("/tf-validate", data=dict(code=wrong_code)) |
| 396 |
assert get_message("TWO_FACTOR_INVALID_TOKEN") in response.data |
| 397 |
assert ( |
| 398 |
signals["user_failed_authn"][2]["request_endpoint"] |
| 399 |
== "security.two_factor_token_validation" |
| 400 |
) |
| 401 |
assert signals["user_failed_authn"][2]["user"].email == "[email protected]" |
| 402 |
assert signals["user_failed_authn"][2]["auth_type"] == "code" |
| 403 |
assert signals["user_failed_authn"][2]["tfa"] |
| 404 |
|
| 405 |
# submit right token and show appropriate response |
| 406 |
response = client.post("/tf-validate", data=dict(code=code), follow_redirects=True) |
| 407 |
assert get_message("TWO_FACTOR_LOGIN_SUCCESSFUL") in response.data |
| 408 |
|
| 409 |
# Upon completion, session cookie shouldn't have any two factor stuff in it. |
| 410 |
assert not tf_in_session(get_session(response)) |
| 411 |
|
| 412 |
# Test change two_factor view from sms to mail |
| 413 |
setup_data = dict(setup="email") |
| 414 |
response = client.post("/tf-setup", data=setup_data, follow_redirects=True) |
| 415 |
msg = b"Enter code to complete setup" |
| 416 |
assert msg in response.data |
| 417 |
|
| 418 |
# Fetch token validate form |
| 419 |
response = client.get("/tf-validate") |
| 420 |
assert response.status_code == 200 |
| 421 |
# make sure two_factor_verify_code_form is set |
| 422 |
assert b'name="code"' in response.data |
| 423 |
|
| 424 |
code = outbox[1].body.split()[-1] |
| 425 |
# submit right token and show appropriate response |
| 426 |
response = client.post("/tf-validate", data=dict(code=code), follow_redirects=True) |
| 427 |
assert b"You successfully changed your two-factor method" in response.data |
| 428 |
|
| 429 |
# Test change two_factor password confirmation view to authenticator |
| 430 |
# Setup authenticator |
| 431 |
setup_data = dict(setup="authenticator") |
| 432 |
response = client.post("/tf-setup", data=setup_data, follow_redirects=True) |
| 433 |
assert b"Open an authenticator app on your device" in response.data |
| 434 |
# verify png QRcode is present |
| 435 |
assert b"data:image/svg+xml;base64," in response.data |
| 436 |
|
| 437 |
# parse out key |
| 438 |
rd = response.data.decode("utf-8") |
| 439 |
matcher = re.match(r".*((?:\S{4}-){7}\S{4}).*", rd, re.DOTALL) |
| 440 |
totp_secret = matcher.group(1) |
| 441 |
|
| 442 |
# Generate token from passed totp_secret and confirm setup |
| 443 |
totp = TOTP(totp_secret) |
| 444 |
code = totp.generate().token |
| 445 |
response = client.post("/tf-validate", data=dict(code=code), follow_redirects=True) |
| 446 |
assert b"You successfully changed your two-factor method" in response.data |
| 447 |
|
| 448 |
logout(client) |
| 449 |
|
| 450 |
# Test login with remember_token |
| 451 |
assert not client.get_cookie("remember_token") |
| 452 |
data = dict(email="[email protected]", password="password", remember=True) |
| 453 |
response = client.post( |
| 454 |
"/login", |
| 455 |
json=data, |
| 456 |
headers={"Content-Type": "application/json"}, |
| 457 |
follow_redirects=True, |
| 458 |
) |
| 459 |
|
| 460 |
# Generate token from passed totp_secret |
| 461 |
code = totp.generate().token |
| 462 |
response = client.post("/tf-validate", data=dict(code=code), follow_redirects=True) |
| 463 |
assert get_message("TWO_FACTOR_LOGIN_SUCCESSFUL") in response.data |
| 464 |
|
| 465 |
# Verify that the remember token is properly set |
| 466 |
assert client.get_cookie("remember_token") |
| 467 |
|
| 468 |
response = logout(client) |
| 469 |
# Verify that logout clears session info |
| 470 |
assert not tf_in_session(get_session(response)) |
| 471 |
|
| 472 |
# Test two-factor authentication first login |
| 473 |
data = dict(email="[email protected]", password="password") |
| 474 |
response = client.post("/login", data=data, follow_redirects=True) |
| 475 |
message = b"Two-Factor authentication adds an extra layer of security" |
| 476 |
assert message in response.data |
| 477 |
|
| 478 |
# check availability of qrcode when this option is not picked |
| 479 |
assert b"data:image/png;base64," not in response.data |
| 480 |
|
| 481 |
# check availability of qrcode page when this option is picked |
| 482 |
setup_data = dict(setup="authenticator") |
| 483 |
response = client.post("/tf-setup", data=setup_data, follow_redirects=True) |
| 484 |
assert b"Open an authenticator app on your device" in response.data |
| 485 |
assert b"data:image/svg+xml;base64," in response.data |
| 486 |
|
| 487 |
# check appearance of setup page when sms picked and phone number entered |
| 488 |
sms_sender = SmsSenderFactory.createSender("test") |
| 489 |
data = dict(setup="sms", phone="+442083661177") |
| 490 |
response = client.post("/tf-setup", data=data, follow_redirects=True) |
| 491 |
assert b"Enter code to complete setup" in response.data |
| 492 |
assert sms_sender.get_count() == 1 |
| 493 |
code = sms_sender.messages[0].split()[-1] |
| 494 |
|
| 495 |
response = client.post("/tf-validate", data=dict(code=code), follow_redirects=True) |
| 496 |
assert get_message("TWO_FACTOR_LOGIN_SUCCESSFUL") in response.data |
| 497 |
assert not tf_in_session(get_session(response)) |
| 498 |
|
| 499 |
logout(client) |
| 500 |
|
| 501 |
# check when two_factor_rescue function should not appear |
| 502 |
rescue_data_json = dict(help_setup="lost_device") |
| 503 |
response = client.post( |
| 504 |
"/tf-rescue", |
| 505 |
json=rescue_data_json, |
| 506 |
headers={"Content-Type": "application/json"}, |
| 507 |
) |
| 508 |
assert b'"code": 400' in response.data |
| 509 |
|
| 510 |
# check when two_factor_rescue function should appear |
| 511 |
data = dict(email="[email protected]", password="password") |
| 512 |
response = client.post("/login", data=data, follow_redirects=True) |
| 513 |
assert b"Please enter your authentication code" in response.data |
| 514 |
rescue_data = dict(help_setup="email") |
| 515 |
response = client.post("/tf-rescue", data=rescue_data, follow_redirects=True) |
| 516 |
message = b"The code for authentication was sent to your email address" |
| 517 |
assert message in response.data |
| 518 |
rescue_data = dict(help_setup="help") |
| 519 |
response = client.post("/tf-rescue", data=rescue_data, follow_redirects=True) |
| 520 |
message = b"An email was sent to us in order to reset your application account" |
| 521 |
assert message in response.data |
| 522 |
|
| 523 |
|
| 524 |
@pytest.mark.settings(two_factor_rescue_email=False) |
| 525 |
def test_no_rescue_email(app, client): |
| 526 |
headers = {"Accept": "application/json", "Content-Type": "application/json"} |
| 527 |
|
| 528 |
response = client.post( |
| 529 |
"/login", json=dict(email="[email protected]", password="password") |
| 530 |
) |
| 531 |
assert response.json["response"]["tf_required"] |
| 532 |
|
| 533 |
response = client.get("/tf-rescue", headers=headers) |
| 534 |
options = response.json["response"]["recovery_options"] |
| 535 |
assert len(options.keys()) == 1 |
| 536 |
assert "help" in options.keys() |
| 537 |
|
| 538 |
# make sure that even if post using email - we get an error |
| 539 |
response = client.post("/tf-rescue", json=dict(help_setup="email")) |
| 540 |
assert response.status_code == 400 |
| 541 |
assert ( |
| 542 |
response.json["response"]["field_errors"]["help_setup"][0] |
| 543 |
== "Not a valid choice." |
| 544 |
) |
| 545 |
|
| 546 |
|
| 547 |
@pytest.mark.settings(two_factor_required=True) |
| 548 |
def test_setup_bad_phone(app, client, get_message): |
| 549 |
data = dict(email="[email protected]", password="password") |
| 550 |
response = client.post("/login", data=data, follow_redirects=True) |
| 551 |
message = b"Two-Factor authentication adds an extra layer of security" |
| 552 |
assert message in response.data |
| 553 |
|
| 554 |
sms_sender = SmsSenderFactory.createSender("test") |
| 555 |
data = dict(setup="sms", phone="555-1212") |
| 556 |
response = client.post("/tf-setup", data=data, follow_redirects=True) |
| 557 |
assert b"Phone number not valid" in response.data |
| 558 |
assert sms_sender.get_count() == 0 |
| 559 |
|
| 560 |
# require phone number with SMS |
| 561 |
data = dict(setup="sms") |
| 562 |
response = client.post("/tf-setup", data=data, follow_redirects=True) |
| 563 |
assert b"Phone number not valid" in response.data |
| 564 |
assert sms_sender.get_count() == 0 |
| 565 |
|
| 566 |
# Now setup good phone |
| 567 |
response = client.post( |
| 568 |
"/tf-setup", data=dict(setup="sms", phone="650-555-1212"), follow_redirects=True |
| 569 |
) |
| 570 |
assert sms_sender.get_count() == 1 |
| 571 |
code = sms_sender.messages[0].split()[-1] |
| 572 |
# shouldn't get authenticator stuff when setting up SMS |
| 573 |
assert b"data:image/png;base64," not in response.data |
| 574 |
|
| 575 |
response = client.post("/tf-validate", data=dict(code=code), follow_redirects=True) |
| 576 |
assert get_message("TWO_FACTOR_LOGIN_SUCCESSFUL") in response.data |
| 577 |
assert not tf_in_session(get_session(response)) |
| 578 |
|
| 579 |
headers = {"Accept": "application/json", "Content-Type": "application/json"} |
| 580 |
response = client.get("/tf-setup", headers=headers) |
| 581 |
# N.B. right now for tfa - we don't canonicalize phone number (since user |
| 582 |
# never has to type it in). |
| 583 |
assert response.json["response"]["tf_phone_number"] == "650-555-1212" |
| 584 |
|
| 585 |
|
| 586 |
@pytest.mark.settings(two_factor_required=True) |
| 587 |
def test_json(app, client, signals): |
| 588 |
""" |
| 589 |
Test login/setup using JSON. |
| 590 |
""" |
| 591 |
headers = {"Accept": "application/json", "Content-Type": "application/json"} |
| 592 |
|
| 593 |
# Login with someone already setup. |
| 594 |
sms_sender = SmsSenderFactory.createSender("test") |
| 595 |
data = dict(email="[email protected]", password="password") |
| 596 |
response = client.post("/login", json=data, headers=headers) |
| 597 |
assert response.status_code == 200 |
| 598 |
assert response.json["response"]["tf_required"] |
| 599 |
assert response.json["response"]["tf_state"] == "ready" |
| 600 |
assert response.json["response"]["tf_primary_method"] == "sms" |
| 601 |
|
| 602 |
# Verify SMS sent |
| 603 |
assert sms_sender.get_count() == 1 |
| 604 |
code = sms_sender.messages[0].split()[-1] |
| 605 |
assert signals["tf_security_token_sent"][0]["token"] == code |
| 606 |
assert signals["tf_security_token_sent"][0]["method"] == "sms" |
| 607 |
response = client.post("/tf-validate", json=dict(code=code)) |
| 608 |
assert response.status_code == 200 |
| 609 |
assert signals["tf_code_confirmed"][0]["user_email"] == "[email protected]" |
| 610 |
# verify logged in |
| 611 |
response = client.get("/profile", follow_redirects=False) |
| 612 |
assert response.status_code == 200 |
| 613 |
logout(client) |
| 614 |
|
| 615 |
# Test that user not yet setup for 2FA gets correct response. |
| 616 |
data = dict(email="[email protected]", password="password") |
| 617 |
response = client.post("/login", json=data) |
| 618 |
assert response.json["response"]["tf_required"] |
| 619 |
assert response.json["response"]["tf_state"] == "setup_from_login" |
| 620 |
|
| 621 |
# Start setup process. |
| 622 |
response = client.get("/tf-setup", headers=headers) |
| 623 |
assert response.json["response"]["tf_required"] |
| 624 |
assert "sms" in response.json["response"]["tf_available_methods"] |
| 625 |
|
| 626 |
# Now try to setup |
| 627 |
data = dict(setup="sms", phone="+442083661177") |
| 628 |
response = client.post("/tf-setup", json=data) |
| 629 |
assert response.status_code == 200 |
| 630 |
assert response.json["response"]["tf_state"] == "validating_profile" |
| 631 |
assert response.json["response"]["tf_primary_method"] == "sms" |
| 632 |
code = sms_sender.messages[0].split()[-1] |
| 633 |
assert signals["tf_security_token_sent"][1]["token"] == code |
| 634 |
response = client.post("/tf-validate", json=dict(code=code), headers=headers) |
| 635 |
assert response.status_code == 200 |
| 636 |
assert "csrf_token" in response.json["response"] |
| 637 |
assert response.json["response"]["user"]["email"] == "[email protected]" |
| 638 |
|
| 639 |
logout(client) |
| 640 |
|
| 641 |
# Verify tf is now setup and can directly get code |
| 642 |
data = dict(email="[email protected]", password="password") |
| 643 |
response = client.post("/login", json=data) |
| 644 |
assert response.json["response"]["tf_required"] |
| 645 |
assert response.json["response"]["tf_state"] == "ready" |
| 646 |
|
| 647 |
# send bad code |
| 648 |
response = client.post("/tf-validate", json=dict(code="whatsup")) |
| 649 |
assert response.status_code == 400 |
| 650 |
assert response.json["response"]["field_errors"]["code"][0] == "Invalid code" |
| 651 |
assert response.json["response"]["errors"][0] == "Invalid code" |
| 652 |
assert ( |
| 653 |
signals["user_failed_authn"][0]["request_endpoint"] |
| 654 |
== "security.two_factor_token_validation" |
| 655 |
) |
| 656 |
assert signals["user_failed_authn"][0]["user"].email == "[email protected]" |
| 657 |
assert signals["user_failed_authn"][0]["auth_type"] == "code" |
| 658 |
assert signals["user_failed_authn"][0]["tfa"] |
| 659 |
|
| 660 |
# Do a GET - should get recovery options |
| 661 |
response = client.get("/tf-validate", headers=headers) |
| 662 |
options = response.json["response"]["recovery_options"] |
| 663 |
assert "email" in options.keys() |
| 664 |
assert "/tf-rescue" in options["email"] |
| 665 |
|
| 666 |
# now send correct code |
| 667 |
code = sms_sender.messages[0].split()[-1] |
| 668 |
response = client.post("/tf-validate", json=dict(code=code)) |
| 669 |
assert response.status_code == 200 |
| 670 |
# verify logged in |
| 671 |
response = client.get("/profile", follow_redirects=False) |
| 672 |
assert response.status_code == 200 |
| 673 |
|
| 674 |
# tf-setup should provide existing info |
| 675 |
response = client.get("/tf-setup", headers=headers) |
| 676 |
assert response.json["response"]["tf_required"] |
| 677 |
assert "sms" in response.json["response"]["tf_available_methods"] |
| 678 |
assert "disable" not in response.json["response"]["tf_available_methods"] |
| 679 |
assert response.json["response"]["tf_primary_method"] == "sms" |
| 680 |
assert response.json["response"]["tf_phone_number"] == "+442083661177" |
| 681 |
assert not tf_in_session(get_session(response)) |
| 682 |
check_signals( |
| 683 |
signals, |
| 684 |
{"user_failed_authn": 1, "tf_security_token_sent": 3, "tf_code_confirmed": 3}, |
| 685 |
) |
| 686 |
|
| 687 |
|
| 688 |
@pytest.mark.settings(two_factor_rescue_mail="[email protected]") |
| 689 |
def test_rescue_json(app, client, outbox): |
| 690 |
# it's an error if not primary authenticated |
| 691 |
rescue_data_json = dict(help_setup="help") |
| 692 |
response = client.post( |
| 693 |
"/tf-rescue", |
| 694 |
json=rescue_data_json, |
| 695 |
) |
| 696 |
assert response.status_code == 400 |
| 697 |
|
| 698 |
# check when two_factor_rescue function should appear |
| 699 |
data = dict(email="[email protected]", password="password") |
| 700 |
response = client.post("/login", json=data) |
| 701 |
assert response.json["response"]["tf_required"] |
| 702 |
|
| 703 |
rescue_data = dict(help_setup="email") |
| 704 |
response = client.post("/tf-rescue", json=rescue_data) |
| 705 |
assert response.status_code == 200 |
| 706 |
|
| 707 |
assert outbox[0].recipients == ["[email protected]"] |
| 708 |
assert outbox[0].sender == "no-reply@localhost" |
| 709 |
assert outbox[0].subject == "Two-Factor Login" |
| 710 |
matcher = re.match(r".*code: ([0-9]+).*", outbox[0].body, re.IGNORECASE | re.DOTALL) |
| 711 |
response = client.post("/tf-validate", json=dict(code=matcher.group(1))) |
| 712 |
assert response.status_code == 200 |
| 713 |
logout(client) |
| 714 |
|
| 715 |
# Try rescue with no email (should send email to admin) |
| 716 |
client.post("/login", json=data) |
| 717 |
rescue_data = dict(help_setup="help") |
| 718 |
response = client.post("/tf-rescue", json=rescue_data) |
| 719 |
assert response.status_code == 200 |
| 720 |
|
| 721 |
assert outbox[1].recipients == ["[email protected]"] |
| 722 |
assert outbox[1].sender == "no-reply@localhost" |
| 723 |
assert outbox[1].subject == "Two-Factor Rescue" |
| 724 |
assert "[email protected]" in outbox[1].body |
| 725 |
|
| 726 |
|
| 727 |
@pytest.mark.settings(two_factor_required=True) |
| 728 |
def test_json_auth_token(app, client): |
| 729 |
""" |
| 730 |
Test getting auth_token with two-factor |
| 731 |
""" |
| 732 |
headers = {"Accept": "application/json", "Content-Type": "application/json"} |
| 733 |
|
| 734 |
# Login with someone already setup. |
| 735 |
sms_sender = SmsSenderFactory.createSender("test") |
| 736 |
data = dict(email="[email protected]", password="password") |
| 737 |
response = client.post("/login", json=data, headers=headers) |
| 738 |
assert response.status_code == 200 |
| 739 |
assert response.json["response"]["tf_required"] |
| 740 |
|
| 741 |
# Verify SMS sent |
| 742 |
assert sms_sender.get_count() == 1 |
| 743 |
code = sms_sender.messages[0].split()[-1] |
| 744 |
response = client.post("/tf-validate?include_auth_token", json=dict(code=code)) |
| 745 |
assert response.status_code == 200 |
| 746 |
token = response.json["response"]["user"]["authentication_token"] |
| 747 |
headers = {"Authentication-Token": token} |
| 748 |
# make sure can access restricted page |
| 749 |
response = client.get("/token", headers=headers) |
| 750 |
assert b"Token Authentication" in response.data |
| 751 |
|
| 752 |
|
| 753 |
@pytest.mark.settings(two_factor_required=True) |
| 754 |
def test_no_opt_out(app, client, get_message): |
| 755 |
# Test if 2FA required, can't opt-out. |
| 756 |
sms_sender = SmsSenderFactory.createSender("test") |
| 757 |
response = client.post( |
| 758 |
"/login", |
| 759 |
data=dict(email="[email protected]", password="password"), |
| 760 |
follow_redirects=True, |
| 761 |
) |
| 762 |
assert sms_sender.get_count() == 1 |
| 763 |
code = sms_sender.messages[0].split()[-1] |
| 764 |
|
| 765 |
# submit right token and show appropriate response |
| 766 |
response = client.post("/tf-validate", data=dict(code=code), follow_redirects=True) |
| 767 |
assert get_message("TWO_FACTOR_LOGIN_SUCCESSFUL") in response.data |
| 768 |
|
| 769 |
response = client.get("/tf-setup", follow_redirects=True) |
| 770 |
assert b"Disable two factor" not in response.data |
| 771 |
assert b"Currently setup two-factor method: SMS" in response.data |
| 772 |
|
| 773 |
# Try to opt-out |
| 774 |
data = dict(setup="disable") |
| 775 |
response = client.post("/tf-setup", data=data, follow_redirects=True) |
| 776 |
assert response.status_code == 200 |
| 777 |
assert b"Marked method is not valid" in response.data |
| 778 |
|
| 779 |
|
| 780 |
@pytest.mark.settings( |
| 781 |
two_factor_setup_url="/custom-setup", two_factor_rescue_url="/custom-rescue" |
| 782 |
) |
| 783 |
def test_custom_urls(client): |
| 784 |
response = client.get("/tf-setup") |
| 785 |
assert response.status_code == 404 |
| 786 |
response = client.get("/custom-setup") |
| 787 |
assert response.status_code in [302, 303] |
| 788 |
response = client.get("/custom-rescue") |
| 789 |
assert response.status_code in [302, 303] |
| 790 |
|
| 791 |
|
| 792 |
def test_evil_validate(app, client): |
| 793 |
""" |
| 794 |
Test logged in, and randomly try to validate a token |
| 795 |
""" |
| 796 |
signalled_identity = [] |
| 797 |
|
| 798 |
@identity_changed.connect_via(app) |
| 799 |
def on_identity_changed(app, identity): |
| 800 |
signalled_identity.append(identity.id) |
| 801 |
|
| 802 |
response = authenticate(client, "[email protected]") |
| 803 |
session = get_session(response) |
| 804 |
assert "tf_state" not in session |
| 805 |
with app.app_context(): |
| 806 |
user = app.security.datastore.find_user(email="[email protected]") |
| 807 |
assert signalled_identity[0] == user.fs_uniquifier |
| 808 |
del signalled_identity[:] |
| 809 |
|
| 810 |
# try to validate |
| 811 |
response = client.post("/tf-validate", data=dict(code="?"), follow_redirects=True) |
| 812 |
# This should log us out since it thinks we are evil |
| 813 |
assert not signalled_identity[0] |
| 814 |
del signalled_identity[:] |
| 815 |
|
| 816 |
|
| 817 |
def test_opt_in(app, client, get_message): |
| 818 |
""" |
| 819 |
Test entire lifecycle of user not having 2FA - setting it up, then deciding |
| 820 |
to turn it back off |
| 821 |
All using forms based API |
| 822 |
""" |
| 823 |
|
| 824 |
signalled_identity = [] |
| 825 |
|
| 826 |
@identity_changed.connect_via(app) |
| 827 |
def on_identity_changed(app, identity): |
| 828 |
signalled_identity.append(identity.id) |
| 829 |
|
| 830 |
response = authenticate(client, "[email protected]") |
| 831 |
session = get_session(response) |
| 832 |
assert "tf_state" not in session |
| 833 |
with app.app_context(): |
| 834 |
user = app.security.datastore.find_user(email="[email protected]") |
| 835 |
assert signalled_identity[0] == user.fs_uniquifier |
| 836 |
del signalled_identity[:] |
| 837 |
|
| 838 |
# opt-in for SMS 2FA |
| 839 |
sms_sender = SmsSenderFactory.createSender("test") |
| 840 |
data = dict(setup="sms", phone="+442083661177") |
| 841 |
response = client.post("/tf-setup", data=data, follow_redirects=True) |
| 842 |
assert b"Enter code to complete setup" in response.data |
| 843 |
assert sms_sender.get_count() == 1 |
| 844 |
code = sms_sender.messages[0].split()[-1] |
| 845 |
|
| 846 |
# Validate token - this should complete 2FA setup |
| 847 |
response = client.post("/tf-validate", data=dict(code=code), follow_redirects=True) |
| 848 |
assert b"You successfully changed" in response.data |
| 849 |
assert check_location(app, response.history[0].location, "/tf-setup") |
| 850 |
|
| 851 |
# Upon completion, session cookie shouldnt have any two factor stuff in it. |
| 852 |
session = get_session(response) |
| 853 |
assert not tf_in_session(session) |
| 854 |
|
| 855 |
# Log out |
| 856 |
logout(client) |
| 857 |
assert not signalled_identity[0] |
| 858 |
del signalled_identity[:] |
| 859 |
|
| 860 |
# Login now should require 2FA with sms |
| 861 |
sms_sender = SmsSenderFactory.createSender("test") |
| 862 |
response = authenticate(client, "[email protected]") |
| 863 |
session = get_session(response) |
| 864 |
assert session["tf_state"] == "ready" |
| 865 |
assert len(signalled_identity) == 0 |
| 866 |
|
| 867 |
assert sms_sender.get_count() == 1 |
| 868 |
code = sms_sender.messages[0].split()[-1] |
| 869 |
response = client.post("/tf-validate", data=dict(code=code), follow_redirects=True) |
| 870 |
assert get_message("TWO_FACTOR_LOGIN_SUCCESSFUL") in response.data |
| 871 |
# Verify now logged in |
| 872 |
with app.app_context(): |
| 873 |
user = app.security.datastore.find_user(email="[email protected]") |
| 874 |
assert signalled_identity[0] == user.fs_uniquifier |
| 875 |
del signalled_identity[:] |
| 876 |
|
| 877 |
# Now opt back out. |
| 878 |
data = dict(setup="disable") |
| 879 |
response = client.post("/tf-setup", data=data, follow_redirects=True) |
| 880 |
assert b"You successfully disabled two-factor authorization." in response.data |
| 881 |
|
| 882 |
# Log out |
| 883 |
logout(client) |
| 884 |
assert not signalled_identity[0] |
| 885 |
del signalled_identity[:] |
| 886 |
|
| 887 |
# Should be able to log in with just user/pass |
| 888 |
response = authenticate(client, "[email protected]") |
| 889 |
session = get_session(response) |
| 890 |
assert "tf_state" not in session |
| 891 |
with app.app_context(): |
| 892 |
user = app.security.datastore.find_user(email="[email protected]") |
| 893 |
assert signalled_identity[0] == user.fs_uniquifier |
| 894 |
|
| 895 |
|
| 896 |
def test_opt_in_nc(app, client_nc, get_message, signals): |
| 897 |
""" |
| 898 |
Test tf-setup without cookies |
| 899 |
""" |
| 900 |
response = json_authenticate(client_nc, "[email protected]") |
| 901 |
assert response.status_code == 200 |
| 902 |
token = response.json["response"]["user"]["authentication_token"] |
| 903 |
headers = {"Authentication-Token": token, "Accept": "application/json"} |
| 904 |
|
| 905 |
sms_sender = SmsSenderFactory.createSender("test") |
| 906 |
data = dict(setup="sms", phone="+442083661177") |
| 907 |
response = client_nc.post("/tf-setup", json=data, headers=headers) |
| 908 |
assert response.status_code == 200 |
| 909 |
state_token = response.json["response"]["tf_state_token"] |
| 910 |
assert sms_sender.get_count() == 1 |
| 911 |
code = sms_sender.messages[0].split()[-1] |
| 912 |
|
| 913 |
# send bad token |
| 914 |
response = client_nc.post( |
| 915 |
"/tf-setup/not-a-token", json=dict(code=code), headers=headers |
| 916 |
) |
| 917 |
assert response.status_code == 400 |
| 918 |
assert response.json["response"]["errors"][0].encode("utf-8") == get_message( |
| 919 |
"API_ERROR" |
| 920 |
) |
| 921 |
|
| 922 |
# send bad code |
| 923 |
response = client_nc.post( |
| 924 |
f"/tf-setup/{state_token}", json=dict(code=12345), headers=headers |
| 925 |
) |
| 926 |
assert response.status_code == 400 |
| 927 |
assert response.json["response"]["errors"][0].encode("utf-8") == get_message( |
| 928 |
"TWO_FACTOR_INVALID_TOKEN" |
| 929 |
) |
| 930 |
# setup shouldn't trigger this. |
| 931 |
assert len(signals["user_failed_authn"]) == 0 |
| 932 |
|
| 933 |
# Validate token - this should complete 2FA setup |
| 934 |
@tf_profile_changed.connect_via(app) |
| 935 |
def pc(sender, user, method, **kwargs): |
| 936 |
assert method == "sms" |
| 937 |
assert user.tf_phone_number == "+442083661177" |
| 938 |
|
| 939 |
response = client_nc.post( |
| 940 |
f"/tf-setup/{state_token}", json=dict(code=code), headers=headers |
| 941 |
) |
| 942 |
assert response.status_code == 200 |
| 943 |
|
| 944 |
response = client_nc.get("/tf-setup", headers=headers) |
| 945 |
assert response.json["response"]["tf_method"] == "sms" |
| 946 |
assert response.json["response"]["tf_phone_number"] == "+442083661177" |
| 947 |
|
| 948 |
|
| 949 |
def test_opt_in_nc_expired(app, client_nc, get_message): |
| 950 |
""" |
| 951 |
Test tf-setup without cookies - expired token |
| 952 |
""" |
| 953 |
with freeze_time( |
| 954 |
date.today() + timedelta(days=-1) |
| 955 |
): # older than TWO_FACTOR_SETUP_WITHIN |
| 956 |
response = json_authenticate(client_nc, "[email protected]") |
| 957 |
assert response.status_code == 200 |
| 958 |
token = response.json["response"]["user"]["authentication_token"] |
| 959 |
headers = {"Authentication-Token": token, "Accept": "application/json"} |
| 960 |
|
| 961 |
sms_sender = SmsSenderFactory.createSender("test") |
| 962 |
data = dict(setup="sms", phone="+442083661177") |
| 963 |
response = client_nc.post("/tf-setup", json=data, headers=headers) |
| 964 |
assert response.status_code == 200 |
| 965 |
state_token = response.json["response"]["tf_state_token"] |
| 966 |
assert sms_sender.get_count() == 1 |
| 967 |
code = sms_sender.messages[0].split()[-1] |
| 968 |
|
| 969 |
# Validate token - this should complete 2FA setup |
| 970 |
response = client_nc.post( |
| 971 |
f"/tf-setup/{state_token}", json=dict(code=code), headers=headers |
| 972 |
) |
| 973 |
assert response.status_code == 400 |
| 974 |
assert response.json["response"]["errors"][0].encode("utf-8") == get_message( |
| 975 |
"TWO_FACTOR_SETUP_EXPIRED", |
| 976 |
within=app.config["SECURITY_TWO_FACTOR_SETUP_WITHIN"], |
| 977 |
) |
| 978 |
|
| 979 |
|
| 980 |
def test_opt_in_state_token(app, client, get_message, signals): |
| 981 |
""" |
| 982 |
Test using forms and new state_token approach (rather than sessions to store |
| 983 |
intermediate state) |
| 984 |
""" |
| 985 |
authenticate(client, "[email protected]") |
| 986 |
|
| 987 |
# opt-in for SMS 2FA |
| 988 |
sms_sender = SmsSenderFactory.createSender("test") |
| 989 |
data = dict(setup="sms", phone="+442083661177") |
| 990 |
response = client.post("/tf-setup", data=data, follow_redirects=True) |
| 991 |
assert b"Enter code to complete setup" in response.data |
| 992 |
assert sms_sender.get_count() == 1 |
| 993 |
code = sms_sender.messages[0].split()[-1] |
| 994 |
verify_url = get_form_action(response, 1) # this will be with state_token |
| 995 |
|
| 996 |
# send in bad token |
| 997 |
response = client.post( |
| 998 |
"/tf-setup/not-a-token", data=dict(code=code), follow_redirects=True |
| 999 |
) |
| 1000 |
assert check_location(app, response.history[0].location, "/tf-setup") |
| 1001 |
assert get_message("API_ERROR") in response.data |
| 1002 |
|
| 1003 |
# send in bad code |
| 1004 |
response = client.post(verify_url, data=dict(code=12345), follow_redirects=True) |
| 1005 |
assert check_location(app, response.history[0].location, "/tf-setup") |
| 1006 |
assert get_message("TWO_FACTOR_INVALID_TOKEN") in response.data |
| 1007 |
# setup shouldn't trigger this. |
| 1008 |
assert len(signals["user_failed_authn"]) == 0 |
| 1009 |
|
| 1010 |
# Validate token - this should complete 2FA setup |
| 1011 |
response = client.post(verify_url, data=dict(code=code), follow_redirects=True) |
| 1012 |
assert b"You successfully changed" in response.data |
| 1013 |
assert check_location(app, response.history[0].location, "/tf-setup") |
| 1014 |
|
| 1015 |
# Upon completion, session cookie shouldn't have any two factor stuff in it. |
| 1016 |
session = get_session(response) |
| 1017 |
assert not tf_in_session(session) |
| 1018 |
|
| 1019 |
response = client.get("/tf-setup") |
| 1020 |
assert b"Disable two-factor" in response.data |
| 1021 |
assert b"Currently setup two-factor method: SMS" in response.data |
| 1022 |
|
| 1023 |
|
| 1024 |
def test_opt_out_json(app, client, get_message): |
| 1025 |
headers = {"Accept": "application/json", "Content-Type": "application/json"} |
| 1026 |
|
| 1027 |
tf_authenticate(app, client) |
| 1028 |
response = client.get("tf-setup", headers=headers) |
| 1029 |
assert "disable" in response.json["response"]["tf_available_methods"] |
| 1030 |
|
| 1031 |
response = client.post("tf-setup", json=dict(setup="disable"), headers=headers) |
| 1032 |
assert response.status_code == 200 |
| 1033 |
logout(client) |
| 1034 |
|
| 1035 |
# Should be able to log in with just user/pass |
| 1036 |
response = authenticate(client, "[email protected]") |
| 1037 |
session = get_session(response) |
| 1038 |
assert "tf_state" not in session |
| 1039 |
# verify logged in |
| 1040 |
assert is_authenticated(client, get_message) |
| 1041 |
response = client.get("tf-setup", headers=headers) |
| 1042 |
assert "disable" not in response.json["response"]["tf_available_methods"] |
| 1043 |
|
| 1044 |
|
| 1045 |
@pytest.mark.filterwarnings("ignore") |
| 1046 |
@pytest.mark.recoverable() |
| 1047 |
@pytest.mark.settings(two_factor_required=True, auto_login_after_reset=True) |
| 1048 |
def test_recoverable(app, client, get_message): |
| 1049 |
# make sure 'forgot password' doesn't bypass 2FA. |
| 1050 |
# '[email protected]' already setup for SMS |
| 1051 |
|
| 1052 |
rtokens = [] |
| 1053 |
sms_sender = SmsSenderFactory.createSender("test") |
| 1054 |
|
| 1055 |
@reset_password_instructions_sent.connect_via(app) |
| 1056 |
def on_instructions_sent(sapp, **kwargs): |
| 1057 |
rtokens.append(kwargs["token"]) |
| 1058 |
|
| 1059 |
client.post("/reset", data=dict(email="[email protected]"), follow_redirects=True) |
| 1060 |
response = client.post( |
| 1061 |
"/reset/" + rtokens[0], |
| 1062 |
data={"password": "awesome sunset", "password_confirm": "awesome sunset"}, |
| 1063 |
follow_redirects=True, |
| 1064 |
) |
| 1065 |
# Should have redirected us to the 2FA login page |
| 1066 |
assert b"Please enter your authentication code" in response.data |
| 1067 |
|
| 1068 |
# we shouldn't be logged in |
| 1069 |
response = client.get("/profile", follow_redirects=False) |
| 1070 |
assert response.status_code in [302, 303] |
| 1071 |
|
| 1072 |
# Grab code that was sent |
| 1073 |
assert sms_sender.get_count() == 1 |
| 1074 |
code = sms_sender.messages[0].split()[-1] |
| 1075 |
response = client.post("/tf-validate", data=dict(code=code), follow_redirects=True) |
| 1076 |
assert get_message("TWO_FACTOR_LOGIN_SUCCESSFUL") in response.data |
| 1077 |
|
| 1078 |
# verify we are logged in |
| 1079 |
response = client.get("/profile", follow_redirects=False) |
| 1080 |
assert response.status_code == 200 |
| 1081 |
|
| 1082 |
|
| 1083 |
@pytest.mark.settings(two_factor_required=True) |
| 1084 |
def test_admin_setup_reset(app, client, get_message): |
| 1085 |
# Verify can use administrative datastore method to setup SMS |
| 1086 |
# and that administrative reset removes access. |
| 1087 |
sms_sender = SmsSenderFactory.createSender("test") |
| 1088 |
|
| 1089 |
data = dict(email="[email protected]", password="password") |
| 1090 |
response = client.post( |
| 1091 |
"/login", json=data, headers={"Content-Type": "application/json"} |
| 1092 |
) |
| 1093 |
assert response.json["response"]["tf_required"] |
| 1094 |
|
| 1095 |
# we shouldn't be logged in |
| 1096 |
response = client.get("/profile", follow_redirects=False) |
| 1097 |
assert response.status_code in [302, 303] |
| 1098 |
assert response.location == "/login?next=/profile" |
| 1099 |
|
| 1100 |
# Use admin to setup gene's SMS/phone. |
| 1101 |
with app.app_context(): |
| 1102 |
user = app.security.datastore.find_user(email="[email protected]") |
| 1103 |
totp_secret = app.security._totp_factory.generate_totp_secret() |
| 1104 |
app.security.datastore.tf_set(user, "sms", totp_secret, phone="+442083661177") |
| 1105 |
app.security.datastore.commit() |
| 1106 |
|
| 1107 |
response = authenticate(client, "[email protected]") |
| 1108 |
session = get_session(response) |
| 1109 |
assert session["tf_state"] == "ready" |
| 1110 |
|
| 1111 |
# Grab code that was sent |
| 1112 |
assert sms_sender.get_count() == 1 |
| 1113 |
code = sms_sender.messages[0].split()[-1] |
| 1114 |
response = client.post("/tf-validate", data=dict(code=code), follow_redirects=True) |
| 1115 |
assert get_message("TWO_FACTOR_LOGIN_SUCCESSFUL") in response.data |
| 1116 |
|
| 1117 |
# verify we are logged in |
| 1118 |
response = client.get("/profile", follow_redirects=False) |
| 1119 |
assert response.status_code == 200 |
| 1120 |
|
| 1121 |
# logout |
| 1122 |
logout(client) |
| 1123 |
|
| 1124 |
# use administrative reset method |
| 1125 |
with app.app_context(): |
| 1126 |
user = app.security.datastore.find_user(email="[email protected]") |
| 1127 |
app.security.datastore.reset_user_access(user) |
| 1128 |
app.security.datastore.commit() |
| 1129 |
|
| 1130 |
data = dict(email="[email protected]", password="password") |
| 1131 |
response = client.post( |
| 1132 |
"/login", json=data, headers={"Content-Type": "application/json"} |
| 1133 |
) |
| 1134 |
assert response.json["response"]["tf_required"] |
| 1135 |
assert response.json["response"]["tf_state"] == "setup_from_login" |
| 1136 |
|
| 1137 |
# we shouldn't be logged in |
| 1138 |
response = client.get("/profile", follow_redirects=False) |
| 1139 |
assert response.status_code in [302, 303] |
| 1140 |
|
| 1141 |
|
| 1142 |
@pytest.mark.settings(two_factor_required=True) |
| 1143 |
def test_datastore(app, clients, get_message): |
| 1144 |
# Test that user record is properly set after proper 2FA setup. |
| 1145 |
client = clients |
| 1146 |
sms_sender = SmsSenderFactory.createSender("test") |
| 1147 |
data = dict(email="[email protected]", password="password") |
| 1148 |
response = client.post( |
| 1149 |
"/login", json=data, headers={"Content-Type": "application/json"} |
| 1150 |
) |
| 1151 |
assert response.json["meta"]["code"] == 200 |
| 1152 |
session = get_session(response) |
| 1153 |
assert session["tf_state"] == "setup_from_login" |
| 1154 |
|
| 1155 |
# setup |
| 1156 |
data = dict(setup="sms", phone="+442083661177") |
| 1157 |
response = client.post( |
| 1158 |
"/tf-setup", json=data, headers={"Content-Type": "application/json"} |
| 1159 |
) |
| 1160 |
|
| 1161 |
assert sms_sender.get_count() == 1 |
| 1162 |
session = get_session(response) |
| 1163 |
assert session["tf_state"] == "validating_profile" |
| 1164 |
assert session["tf_primary_method"] == "sms" |
| 1165 |
|
| 1166 |
code = sms_sender.messages[0].split()[-1] |
| 1167 |
|
| 1168 |
# submit token and show appropriate response |
| 1169 |
response = client.post("/tf-validate", data=dict(code=code), follow_redirects=True) |
| 1170 |
assert get_message("TWO_FACTOR_LOGIN_SUCCESSFUL") in response.data |
| 1171 |
session = get_session(response) |
| 1172 |
# Verify that successful login clears session info |
| 1173 |
assert not tf_in_session(session) |
| 1174 |
|
| 1175 |
with app.app_context(): |
| 1176 |
user = app.security.datastore.find_user(email="[email protected]") |
| 1177 |
assert user.tf_primary_method == "sms" |
| 1178 |
assert user.tf_phone_number == "+442083661177" |
| 1179 |
assert "enckey" in user.tf_totp_secret |
| 1180 |
|
| 1181 |
|
| 1182 |
def test_totp_secret_generation(app, client): |
| 1183 |
""" |
| 1184 |
Test the totp secret generation upon changing method to make sure |
| 1185 |
it stays the same after the process is completed |
| 1186 |
""" |
| 1187 |
|
| 1188 |
# Properly log in jill for this test |
| 1189 |
signalled_identity = [] |
| 1190 |
|
| 1191 |
@identity_changed.connect_via(app) |
| 1192 |
def on_identity_changed(app, identity): |
| 1193 |
signalled_identity.append(identity.id) |
| 1194 |
|
| 1195 |
response = authenticate(client, "[email protected]") |
| 1196 |
session = get_session(response) |
| 1197 |
assert "tf_state" not in session |
| 1198 |
with app.app_context(): |
| 1199 |
user = app.security.datastore.find_user(email="[email protected]") |
| 1200 |
assert signalled_identity[0] == user.fs_uniquifier |
| 1201 |
assert not user.tf_totp_secret |
| 1202 |
del signalled_identity[:] |
| 1203 |
|
| 1204 |
sms_sender = SmsSenderFactory.createSender("test") |
| 1205 |
data = dict(setup="sms", phone="+442083661188") |
| 1206 |
response = client.post("/tf-setup", data=data, follow_redirects=True) |
| 1207 |
assert b"Enter code to complete setup" in response.data |
| 1208 |
assert sms_sender.get_count() == 1 |
| 1209 |
code = sms_sender.messages[0].split()[-1] |
| 1210 |
|
| 1211 |
# Retrieve the currently generated totp secret for later comparison |
| 1212 |
session = get_session(response) |
| 1213 |
generated_secret = session["tf_totp_secret"] |
| 1214 |
assert "enckey" in generated_secret |
| 1215 |
|
| 1216 |
# Validate token - this should complete 2FA setup |
| 1217 |
response = client.post("/tf-validate", data=dict(code=code), follow_redirects=True) |
| 1218 |
assert b"You successfully changed" in response.data |
| 1219 |
|
| 1220 |
# Retrieve the final totp secret and make sure it matches the previous one |
| 1221 |
with app.app_context(): |
| 1222 |
user = app.security.datastore.find_user(email="[email protected]") |
| 1223 |
assert generated_secret == user.tf_totp_secret |
| 1224 |
|
| 1225 |
# Finally opt back out and check that tf_totp_secret is None |
| 1226 |
data = dict(setup="disable") |
| 1227 |
response = client.post("/tf-setup", data=data, follow_redirects=True) |
| 1228 |
assert b"You successfully disabled two-factor authorization." in response.data |
| 1229 |
with app.app_context(): |
| 1230 |
user = app.security.datastore.find_user(email="[email protected]") |
| 1231 |
assert user.tf_totp_secret is None |
| 1232 |
|
| 1233 |
# Log out |
| 1234 |
logout(client) |
| 1235 |
assert not signalled_identity[0] |
| 1236 |
del signalled_identity[:] |
| 1237 |
|
| 1238 |
|
| 1239 |
@pytest.mark.settings(two_factor_enabled_methods=["authenticator"]) |
| 1240 |
def test_just_authenticator(app, client): |
| 1241 |
authenticate(client, email="[email protected]") |
| 1242 |
|
| 1243 |
response = client.get("/tf-setup", follow_redirects=True) |
| 1244 |
assert b"Set up using SMS" not in response.data |
| 1245 |
|
| 1246 |
data = dict(setup="authenticator") |
| 1247 |
response = client.post("/tf-setup", data=data, follow_redirects=True) |
| 1248 |
assert b"Submit Code" in response.data |
| 1249 |
|
| 1250 |
# test json |
| 1251 |
response = client.post("/tf-setup", json=data) |
| 1252 |
assert response.status_code == 200 |
| 1253 |
|
| 1254 |
|
| 1255 |
@pytest.mark.settings( |
| 1256 |
USER_IDENTITY_ATTRIBUTES=[ |
| 1257 |
{"username": {"mapper": lambda x: "@" not in x}}, |
| 1258 |
{"email": {"mapper": uia_email_mapper}}, |
| 1259 |
] |
| 1260 |
) |
| 1261 |
def test_authr_identity(app, client): |
| 1262 |
# Setup authenticator |
| 1263 |
headers = {"Accept": "application/json", "Content-Type": "application/json"} |
| 1264 |
authenticate(client, email="[email protected]") |
| 1265 |
|
| 1266 |
setup_data = dict(setup="authenticator") |
| 1267 |
response = client.post("/tf-setup", json=setup_data, headers=headers) |
| 1268 |
jr = response.json["response"] |
| 1269 |
assert jr["tf_authr_issuer"] == "tests" |
| 1270 |
assert jr["tf_authr_username"] == "jill" |
| 1271 |
assert jr["tf_state"] == "validating_profile" |
| 1272 |
assert len(jr["tf_authr_b32key"]) % 8 == 0 and re.match( |
| 1273 |
r"^[A-Z2-7]+=*$", jr["tf_authr_b32key"] |
| 1274 |
) |
| 1275 |
assert "tf_authr_key" in response.json["response"] |
| 1276 |
assert ( |
| 1277 |
jr["tf_authr_uri"] |
| 1278 |
== f"otpauth://totp/tests:jill?secret={jr['tf_authr_b32key']}&issuer=tests" |
| 1279 |
) |
| 1280 |
|
| 1281 |
|
| 1282 |
@pytest.mark.settings( |
| 1283 |
USER_IDENTITY_ATTRIBUTES=[ |
| 1284 |
{"security_number": {"mapper": lambda x: x.isdigit()}}, |
| 1285 |
{"email": {"mapper": uia_email_mapper}}, |
| 1286 |
] |
| 1287 |
) |
| 1288 |
def test_authr_identity_num(app, client): |
| 1289 |
# Test that response to setup has 'security_number' as the 'username' |
| 1290 |
# since it is listed first. |
| 1291 |
headers = {"Accept": "application/json", "Content-Type": "application/json"} |
| 1292 |
authenticate(client, email="[email protected]") |
| 1293 |
|
| 1294 |
setup_data = dict(setup="authenticator") |
| 1295 |
response = client.post("/tf-setup", json=setup_data, headers=headers) |
| 1296 |
assert response.json["response"]["tf_authr_username"] == "456789" |
| 1297 |
assert "tf_authr_key" in response.json["response"] |
| 1298 |
|
| 1299 |
|
| 1300 |
@pytest.mark.settings( |
| 1301 |
USER_IDENTITY_ATTRIBUTES=[ |
| 1302 |
{"email": {"mapper": uia_email_mapper}}, |
| 1303 |
{"username": {"mapper": lambda x: x}}, |
| 1304 |
] |
| 1305 |
) |
| 1306 |
def test_email_salutation(app, client, outbox): |
| 1307 |
authenticate(client, email="[email protected]") |
| 1308 |
response = client.post("/tf-setup", data=dict(setup="email"), follow_redirects=True) |
| 1309 |
msg = b"Enter code to complete setup" |
| 1310 |
assert msg in response.data |
| 1311 |
|
| 1312 |
assert "[email protected]" in outbox[0].recipients |
| 1313 |
assert "[email protected]" in outbox[0].body |
| 1314 |
assert "[email protected]" in outbox[0].alts["html"] |
| 1315 |
|
| 1316 |
|
| 1317 |
@pytest.mark.settings( |
| 1318 |
USER_IDENTITY_ATTRIBUTES=[ |
| 1319 |
{"username": {"mapper": lambda x: "@" not in x}}, |
| 1320 |
{"email": {"mapper": uia_email_mapper}}, |
| 1321 |
] |
| 1322 |
) |
| 1323 |
def test_username_salutation(app, client, outbox): |
| 1324 |
authenticate(client, email="[email protected]") |
| 1325 |
response = client.post("/tf-setup", data=dict(setup="email"), follow_redirects=True) |
| 1326 |
msg = b"Enter code to complete setup" |
| 1327 |
assert msg in response.data |
| 1328 |
|
| 1329 |
assert "[email protected]" in outbox[0].recipients |
| 1330 |
assert "[email protected]" not in outbox[0].body |
| 1331 |
assert "[email protected]" not in outbox[0].alts["html"] |
| 1332 |
assert "jill" in outbox[0].body |
| 1333 |
|
| 1334 |
|
| 1335 |
@pytest.mark.settings(sms_service="bad") |
| 1336 |
def test_bad_sender(app, client, get_message): |
| 1337 |
# If SMS sender fails - make sure propagated |
| 1338 |
# Test form, json, x signin, setup |
| 1339 |
headers = {"Accept": "application/json", "Content-Type": "application/json"} |
| 1340 |
|
| 1341 |
# test normal, already setup up login. |
| 1342 |
with capture_flashes() as flashes: |
| 1343 |
data = {"email": "[email protected]", "password": "password"} |
| 1344 |
response = client.post("login", data=data, follow_redirects=False) |
| 1345 |
assert response.status_code in [302, 303] |
| 1346 |
assert "/login" in response.location |
| 1347 |
assert get_message("FAILED_TO_SEND_CODE") in flashes[0]["message"].encode("utf-8") |
| 1348 |
|
| 1349 |
# test w/ JSON |
| 1350 |
data = dict(email="[email protected]", password="password") |
| 1351 |
response = client.post("login", json=data, headers=headers) |
| 1352 |
assert response.status_code == 500 |
| 1353 |
assert response.json["response"]["errors"][0].encode("utf-8") == get_message( |
| 1354 |
"FAILED_TO_SEND_CODE" |
| 1355 |
) |
| 1356 |
|
| 1357 |
# Now test setup |
| 1358 |
tf_authenticate(app, client) |
| 1359 |
data = dict(setup="sms", phone="+442083661188") |
| 1360 |
response = client.post("tf-setup", data=data) |
| 1361 |
assert get_message("FAILED_TO_SEND_CODE") in response.data |
| 1362 |
|
| 1363 |
response = client.post("tf-setup", json=data, headers=headers) |
| 1364 |
assert response.status_code == 500 |
| 1365 |
assert response.json["response"]["errors"][0].encode("utf-8") == get_message( |
| 1366 |
"FAILED_TO_SEND_CODE" |
| 1367 |
) |
| 1368 |
|
| 1369 |
|
| 1370 |
cresponse = [None, "That didnt work out as we planned", "Failed Again"] |
| 1371 |
|
| 1372 |
|
| 1373 |
def _tf_send_code(self, method, totp_secret, phone_number): |
| 1374 |
return self.code_response.pop(0) |
| 1375 |
|
| 1376 |
|
| 1377 |
@pytest.mark.app_settings( |
| 1378 |
TESTING_USER_INJECT=dict( |
| 1379 |
tf_send_security_token=_tf_send_code, code_response=cresponse |
| 1380 |
) |
| 1381 |
) |
| 1382 |
def test_replace_send_code(app, client, get_message): |
| 1383 |
data = dict(email="[email protected]", password="password") |
| 1384 |
response = client.post("/login", data=data, follow_redirects=True) |
| 1385 |
assert b"Please enter your authentication code" in response.data |
| 1386 |
rescue_data = dict(help_setup="email") |
| 1387 |
response = client.post("/tf-rescue", data=rescue_data, follow_redirects=True) |
| 1388 |
assert b"That didnt work out as we planned" in response.data |
| 1389 |
|
| 1390 |
# Test JSON |
| 1391 |
headers = {"Accept": "application/json", "Content-Type": "application/json"} |
| 1392 |
response = client.post("/tf-rescue", json=rescue_data, headers=headers) |
| 1393 |
assert response.status_code == 500 |
| 1394 |
assert response.json["response"]["field_errors"]["help_setup"][0] == "Failed Again" |
| 1395 |
|
| 1396 |
|
| 1397 |
def test_propagate_next(app, client): |
| 1398 |
# verify we propagate the ?next param all the way through a two-factor login |
| 1399 |
with capture_send_code_requests() as codes: |
| 1400 |
data = dict(email="[email protected]", password="password") |
| 1401 |
response = client.post("/login?next=/im-in", data=data, follow_redirects=True) |
| 1402 |
assert "?next=/im-in" in response.request.url |
| 1403 |
# grab URL from form to show that our template propagates ?next |
| 1404 |
verify_url = get_form_action(response) |
| 1405 |
response = client.post( |
| 1406 |
verify_url, data=dict(code=codes[0]["login_token"]), follow_redirects=False |
| 1407 |
) |
| 1408 |
assert "/im-in" in response.location |
| 1409 |
logout(client) |
| 1410 |
|
| 1411 |
# do it with next in the form |
| 1412 |
data = dict(email="[email protected]", password="password", next="/im-in") |
| 1413 |
response = client.post("/login", data=data, follow_redirects=True) |
| 1414 |
assert "?next=/im-in" in response.request.url |
| 1415 |
# grab URL from form to show that our template propagates ?next |
| 1416 |
verify_url = get_form_action(response) |
| 1417 |
response = client.post( |
| 1418 |
verify_url, data=dict(code=codes[1]["login_token"]), follow_redirects=False |
| 1419 |
) |
| 1420 |
assert "/im-in" in response.location |
| 1421 |
|
| 1422 |
|
| 1423 |
@pytest.mark.settings(freshness=timedelta(minutes=0)) |
| 1424 |
def test_verify(app, client, get_message): |
| 1425 |
# Test setup when reauthenticate required |
| 1426 |
authenticate(client) |
| 1427 |
response = client.get("tf-setup", follow_redirects=False) |
| 1428 |
assert check_location(app, response.location, "/verify?next=/tf-setup") |
| 1429 |
logout(client) |
| 1430 |
|
| 1431 |
# Now try again - follow redirects to get to verify form |
| 1432 |
# This call should require re-verify |
| 1433 |
authenticate(client) |
| 1434 |
response = client.get("tf-setup", follow_redirects=True) |
| 1435 |
assert get_message("REAUTHENTICATION_REQUIRED") in response.data |
| 1436 |
verify_password_url = get_form_action(response) |
| 1437 |
|
| 1438 |
# Send wrong password |
| 1439 |
response = client.post( |
| 1440 |
verify_password_url, |
| 1441 |
data=dict(password="iforgot"), |
| 1442 |
follow_redirects=True, |
| 1443 |
) |
| 1444 |
assert response.status_code == 200 |
| 1445 |
assert get_message("INVALID_PASSWORD") in response.data |
| 1446 |
|
| 1447 |
# Verify with correct password |
| 1448 |
with capture_flashes() as flashes: |
| 1449 |
response = client.post( |
| 1450 |
verify_password_url, |
| 1451 |
data=dict(password="password"), |
| 1452 |
follow_redirects=False, |
| 1453 |
) |
| 1454 |
assert response.status_code in [302, 303] |
| 1455 |
assert check_location(app, response.location, "/tf-setup") |
| 1456 |
|
| 1457 |
assert get_message("REAUTHENTICATION_SUCCESSFUL") == flashes[0]["message"].encode( |
| 1458 |
"utf-8" |
| 1459 |
) |
| 1460 |
|
| 1461 |
|
| 1462 |
def test_verify_json(app, client, get_message): |
| 1463 |
# Test setup when reauthenticate required |
| 1464 |
# N.B. with freshness=0 we never set a grace period and should never be able to |
| 1465 |
# get to /tf-setup |
| 1466 |
authenticate(client) |
| 1467 |
headers = {"Accept": "application/json", "Content-Type": "application/json"} |
| 1468 |
|
| 1469 |
app.config["SECURITY_FRESHNESS"] = timedelta(minutes=0) |
| 1470 |
response = client.get("tf-setup", headers=headers) |
| 1471 |
assert response.status_code == 401 |
| 1472 |
assert response.json["response"]["reauth_required"] |
| 1473 |
|
| 1474 |
response = client.post("verify", json=dict(password="notmine"), headers=headers) |
| 1475 |
assert response.status_code == 400 |
| 1476 |
assert response.json["response"]["errors"][0].encode("utf-8") == get_message( |
| 1477 |
"INVALID_PASSWORD" |
| 1478 |
) |
| 1479 |
|
| 1480 |
response = client.post("verify", json=dict(password="password"), headers=headers) |
| 1481 |
assert response.status_code == 200 |
| 1482 |
|
| 1483 |
app.config["SECURITY_FRESHNESS"] = timedelta(minutes=60) |
| 1484 |
response = client.get("tf-setup", headers=headers) |
| 1485 |
assert response.status_code == 200 |
| 1486 |
|
| 1487 |
|
| 1488 |
@pytest.mark.settings(freshness=timedelta(minutes=-1)) |
| 1489 |
def test_setup_nofresh(app, client, get_message): |
| 1490 |
authenticate(client) |
| 1491 |
response = client.get("tf-setup", follow_redirects=False) |
| 1492 |
assert response.status_code == 200 |
| 1493 |
|
| 1494 |
|
| 1495 |
@pytest.mark.settings(two_factor_enabled_methods=["email"]) |
| 1496 |
def test_no_sms(app, get_message, outbox): |
| 1497 |
pytest.importorskip("sqlalchemy") |
| 1498 |
pytest.importorskip("flask_sqlalchemy") |
| 1499 |
|
| 1500 |
# Make sure that don't require tf_phone_number if SMS isn't an option. |
| 1501 |
from sqlalchemy import ( |
| 1502 |
Boolean, |
| 1503 |
Column, |
| 1504 |
Integer, |
| 1505 |
String, |
| 1506 |
) |
| 1507 |
from sqlalchemy.orm import relationship, backref |
| 1508 |
from flask_sqlalchemy import SQLAlchemy |
| 1509 |
from flask_security.models import fsqla_v2 as fsqla |
| 1510 |
from flask_security import Security, UserMixin, hash_password |
| 1511 |
|
| 1512 |
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///:memory:" |
| 1513 |
db = SQLAlchemy(app) |
| 1514 |
|
| 1515 |
fsqla.FsModels.set_db_info(db) |
| 1516 |
|
| 1517 |
class Role(db.Model, fsqla.FsRoleMixin): |
| 1518 |
pass |
| 1519 |
|
| 1520 |
class User(db.Model, UserMixin): |
| 1521 |
id = Column(Integer, primary_key=True) |
| 1522 |
email = Column(String(255), unique=True, nullable=False) |
| 1523 |
password = Column(String(255), nullable=False) |
| 1524 |
active = Column(Boolean(), nullable=False) |
| 1525 |
|
| 1526 |
# Faster token checking |
| 1527 |
fs_uniquifier = Column(String(64), unique=True, nullable=False) |
| 1528 |
|
| 1529 |
# 2FA |
| 1530 |
tf_primary_method = Column(String(64), nullable=True) |
| 1531 |
tf_totp_secret = Column(String(255), nullable=True) |
| 1532 |
|
| 1533 |
roles = relationship( |
| 1534 |
"Role", secondary="roles_users", backref=backref("users", lazy="dynamic") |
| 1535 |
) |
| 1536 |
|
| 1537 |
with app.app_context(): |
| 1538 |
db.create_all() |
| 1539 |
|
| 1540 |
ds = SQLAlchemyUserDatastore(db, User, Role) |
| 1541 |
app.security = Security(app, datastore=ds) |
| 1542 |
|
| 1543 |
with app.app_context(): |
| 1544 |
ds.create_user( |
| 1545 |
email="[email protected]", |
| 1546 |
password=hash_password("password"), |
| 1547 |
) |
| 1548 |
ds.commit() |
| 1549 |
|
| 1550 |
client = app.test_client() |
| 1551 |
data = dict(email="[email protected]", password="password") |
| 1552 |
client.post("/login", data=data, follow_redirects=True) |
| 1553 |
|
| 1554 |
response = client.post("/tf-setup", data=dict(setup="email"), follow_redirects=True) |
| 1555 |
msg = b"Enter code to complete setup" |
| 1556 |
assert msg in response.data |
| 1557 |
|
| 1558 |
code = outbox[0].body.split()[-1] |
| 1559 |
# submit right token and show appropriate response |
| 1560 |
response = client.post("/tf-validate", data=dict(code=code), follow_redirects=True) |
| 1561 |
assert b"You successfully changed your two-factor method" in response.data |
| 1562 |
|
| 1563 |
with app.app_context(): |
| 1564 |
db.engine.dispose() |
| 1565 |
|
| 1566 |
|
| 1567 |
@pytest.mark.settings(two_factor_post_setup_view="/post_setup_view") |
| 1568 |
def test_post_setup_redirect(app, client): |
| 1569 |
authenticate(client, "[email protected]") |
| 1570 |
|
| 1571 |
sms_sender = SmsSenderFactory.createSender("test") |
| 1572 |
data = dict(setup="sms", phone="+442083661177") |
| 1573 |
response = client.post("/tf-setup", data=data, follow_redirects=True) |
| 1574 |
assert b"Enter code to complete setup" in response.data |
| 1575 |
assert sms_sender.get_count() == 1 |
| 1576 |
code = sms_sender.messages[0].split()[-1] |
| 1577 |
|
| 1578 |
# Validate token - this should complete 2FA setup |
| 1579 |
response = client.post("/tf-validate", data=dict(code=code), follow_redirects=False) |
| 1580 |
assert check_location(app, response.location, "/post_setup_view") |
| 1581 |
|
| 1582 |
|
| 1583 |
@pytest.mark.app_settings(babel_default_locale="fr_FR") |
| 1584 |
@pytest.mark.babel() |
| 1585 |
def test_xlation(app, client, get_message_local): |
| 1586 |
# Test method translation |
| 1587 |
assert check_xlation(app, "fr_FR"), "You must run python setup.py compile_catalog" |
| 1588 |
|
| 1589 |
# login as gal2 which has 'authenticator' set up |
| 1590 |
response = authenticate(client, email="[email protected]", follow_redirects=True) |
| 1591 |
with app.test_request_context(): |
| 1592 |
existing = ( |
| 1593 |
"Veuillez saisir votre code d'authentification généré via: authentificateur" |
| 1594 |
) |
| 1595 |
assert markupsafe.escape(existing).encode() in response.data |
| 1596 |
with app.app_context(): |
| 1597 |
# generate 'code' as authenticator would and complete authentication |
| 1598 |
user = app.security.datastore.find_user(email="[email protected]") |
| 1599 |
code = app.security._totp_factory.generate_totp_password(user.tf_totp_secret) |
| 1600 |
client.post("/tf-validate", data=dict(code=code), follow_redirects=True) |
| 1601 |
response = client.get("/tf-setup", follow_redirects=True) |
| 1602 |
with app.test_request_context(): |
| 1603 |
existing = "Méthode à deux facteurs actuellement configurée : authentificateur" |
| 1604 |
assert markupsafe.escape(existing).encode() in response.data |
| 1605 |
|
| 1606 |
|
| 1607 |
@pytest.mark.csrf(ignore_unauth=True) |
| 1608 |
@pytest.mark.settings(two_factor_post_setup_view="/post_setup_view") |
| 1609 |
def test_setup_csrf(app, client): |
| 1610 |
# Verify /tf-setup properly handles CSRF and template relays CSRF errors |
| 1611 |
tf_authenticate(app, client) |
| 1612 |
response = client.get("tf-setup") |
| 1613 |
assert b"Disable" in response.data |
| 1614 |
csrf_token = get_form_input_value(response, "csrf_token") |
| 1615 |
|
| 1616 |
response = client.post("tf-setup", data=dict(setup="disable")) |
| 1617 |
assert b"The CSRF token is missing" in response.data |
| 1618 |
|
| 1619 |
response = client.post( |
| 1620 |
"tf-setup", data=dict(setup="disable", csrf_token=csrf_token) |
| 1621 |
) |
| 1622 |
assert check_location(app, response.location, "/post_setup_view") |
| 1623 |
|
| 1624 |
|
| 1625 |
@pytest.mark.csrf(ignore_unauth=True, csrfprotect=True) |
| 1626 |
def test_setup_csrf_header(app, client): |
| 1627 |
# Test that can setup using csrf token in header |
| 1628 |
tf_authenticate(app, client) |
| 1629 |
response = client.get("tf-setup", json=dict()) |
| 1630 |
csrf_token = response.json["response"]["csrf_token"] |
| 1631 |
|
| 1632 |
response = client.post("tf-setup", json=dict(setup="disable")) |
| 1633 |
assert response.status_code == 400 |
| 1634 |
assert response.json["response"]["errors"][0] == "The CSRF token is missing." |
| 1635 |
|
| 1636 |
response = client.post( |
| 1637 |
"tf-setup", json=dict(setup="disable"), headers={"X-CSRF-Token": csrf_token} |
| 1638 |
) |
| 1639 |
assert response.status_code == 200 |
| 1640 |
|
| 1641 |
|
| 1642 |
@pytest.mark.csrf(csrfprotect=True) |
| 1643 |
@pytest.mark.settings(CSRF_COOKIE_NAME="XSRF-Token") |
| 1644 |
def test_csrf_2fa_login_cookie(app, client): |
| 1645 |
# Use XSRF-Token cookie for entire login sequence |
| 1646 |
sms_sender = SmsSenderFactory.createSender("test") |
| 1647 |
response = client.get( |
| 1648 |
"/login", data={}, headers={"Content-Type": "application/json"} |
| 1649 |
) |
| 1650 |
assert client.get_cookie("XSRF-Token") |
| 1651 |
csrf_token = response.json["response"]["csrf_token"] |
| 1652 |
assert csrf_token == client.get_cookie("XSRF-Token").value |
| 1653 |
|
| 1654 |
response = client.post( |
| 1655 |
"/login", |
| 1656 |
json=dict(email="[email protected]", password="password"), |
| 1657 |
headers={ |
| 1658 |
"Content-Type": "application/json", |
| 1659 |
"X-CSRF-Token": client.get_cookie("XSRF-Token").value, |
| 1660 |
}, |
| 1661 |
) |
| 1662 |
assert b'"code": 200' in response.data |
| 1663 |
session = get_session(response) |
| 1664 |
assert session["tf_state"] == "ready" |
| 1665 |
|
| 1666 |
assert sms_sender.get_count() == 1 |
| 1667 |
code = sms_sender.messages[0].split()[-1] |
| 1668 |
|
| 1669 |
response = client.post( |
| 1670 |
"/tf-validate", |
| 1671 |
json=dict(code=code), |
| 1672 |
headers={ |
| 1673 |
"Content-Type": "application/json", |
| 1674 |
"X-CSRF-Token": client.get_cookie("XSRF-Token").value, |
| 1675 |
}, |
| 1676 |
) |
| 1677 |
assert response.status_code == 200 |
| 1678 |
|
| 1679 |
# verify original session csrf_token still works. |
| 1680 |
response = client.post( |
| 1681 |
"/json_auth", |
| 1682 |
json=dict(label="label"), |
| 1683 |
headers={"Content-Type": "application/json", "X-CSRF-Token": csrf_token}, |
| 1684 |
) |
| 1685 |
assert response.status_code == 200 |
| 1686 |
|
| 1687 |
# use XSRF_Cookie to send in csrf_token |
| 1688 |
response = client.post( |
| 1689 |
"/json_auth", |
| 1690 |
json=dict(label="label"), |
| 1691 |
headers={ |
| 1692 |
"Content-Type": "application/json", |
| 1693 |
"X-CSRF-Token": client.get_cookie("XSRF-Token").value, |
| 1694 |
}, |
| 1695 |
) |
| 1696 |
assert response.status_code == 200 |
| 1697 |
assert response.json["label"] == "label" |
| 1698 |
|
| 1699 |
|
| 1700 |
@pytest.mark.csrf(ignore_unauth=True, csrfprotect=True) |
| 1701 |
@pytest.mark.settings(CSRF_COOKIE_NAME="XSRF-Token") |
| 1702 |
def test_csrf_2fa_nounauth_cookie(app, client): |
| 1703 |
# use CSRF cookie when ignoring unauth endpoints |
| 1704 |
sms_sender = SmsSenderFactory.createSender("test") |
| 1705 |
response = client.post( |
| 1706 |
"/login", |
| 1707 |
json=dict(email="[email protected]", password="password"), |
| 1708 |
headers={"Content-Type": "application/json"}, |
| 1709 |
) |
| 1710 |
|
| 1711 |
code = sms_sender.messages[0].split()[-1] |
| 1712 |
response = client.post( |
| 1713 |
"/tf-validate", |
| 1714 |
json=dict(code=code), |
| 1715 |
headers={"Content-Type": "application/json"}, |
| 1716 |
) |
| 1717 |
assert response.status_code == 200 |
| 1718 |
|
| 1719 |
response = client.post( |
| 1720 |
"/json_auth", |
| 1721 |
json=dict(label="label"), |
| 1722 |
headers={ |
| 1723 |
"Content-Type": "application/json", |
| 1724 |
"X-CSRF-Token": client.get_cookie("XSRF-Token").value, |
| 1725 |
}, |
| 1726 |
) |
| 1727 |
assert response.status_code == 200 |
| 1728 |
assert response.json["label"] == "label" |
| 1729 |
|
| 1730 |
|
| 1731 |
def _tf_required(self, tf_setup_methods, tf_fresh): |
| 1732 |
if self.email == "[email protected]": |
| 1733 |
return False, tf_setup_methods |
| 1734 |
return True, tf_setup_methods |
| 1735 |
|
| 1736 |
|
| 1737 |
@pytest.mark.app_settings(TESTING_USER_INJECT=dict(check_tf_required=_tf_required)) |
| 1738 |
@pytest.mark.settings(two_factor_required=True) |
| 1739 |
def test_override_tf_required(app, client, get_message): |
| 1740 |
data = dict(email="[email protected]", password="password") |
| 1741 |
response = client.post("/login", json=data) |
| 1742 |
assert response.status_code == 200 |
| 1743 |
assert response.json["response"]["tf_required"] |
| 1744 |
|
| 1745 |
data = dict(email="[email protected]", password="password") |
| 1746 |
response = client.post("/login", json=data) |
| 1747 |
assert response.status_code == 200 |
| 1748 |
assert not response.json["response"]["tf_required"] |
| 1749 |
|
| 1750 |
|
| 1751 |
def _tf_required_admin(self, tf_setup_methods, tf_fresh): |
| 1752 |
if self.has_role("admin"): |
| 1753 |
return True, tf_setup_methods |
| 1754 |
return False, tf_setup_methods |
| 1755 |
|
| 1756 |
|
| 1757 |
@pytest.mark.app_settings( |
| 1758 |
TESTING_USER_INJECT=dict(check_tf_required=_tf_required_admin) |
| 1759 |
) |
| 1760 |
def test_override_tf_required_admin(app, client, get_message): |
| 1761 |
# jill is an 'author' so shouldn't require TF |
| 1762 |
data = dict(email="[email protected]", password="password") |
| 1763 |
response = client.post("/login", json=data) |
| 1764 |
assert response.status_code == 200 |
| 1765 |
assert not response.json["response"]["tf_required"] |
| 1766 |
client.post("/logout") |
| 1767 |
|
| 1768 |
# gal is an admin so should require TF |
| 1769 |
data = dict(email="[email protected]", password="password") |
| 1770 |
response = client.post("/login", json=data) |
| 1771 |
assert response.status_code == 200 |
| 1772 |
assert response.json["response"]["tf_required"] |