| 1 |
""" |
| 2 |
test_utils |
| 3 |
~~~~~~~~~~ |
| 4 |
|
| 5 |
Test utils |
| 6 |
|
| 7 |
:copyright: (c) 2019-2026 by J. Christopher Wagner (jwag). |
| 8 |
:license: MIT, see LICENSE for more details. |
| 9 |
""" |
| 10 |
|
| 11 |
from __future__ import annotations |
| 12 |
|
| 13 |
from contextlib import contextmanager |
| 14 |
import re |
| 15 |
import time |
| 16 |
|
| 17 |
from flask.json.tag import TaggedJSONSerializer |
| 18 |
from flask.signals import message_flashed |
| 19 |
|
| 20 |
from flask_security import ( |
| 21 |
Security, |
| 22 |
SmsSenderBaseClass, |
| 23 |
SmsSenderFactory, |
| 24 |
UserMixin, |
| 25 |
) |
| 26 |
from flask_security.signals import ( |
| 27 |
login_instructions_sent, |
| 28 |
reset_password_instructions_sent, |
| 29 |
tf_security_token_sent, |
| 30 |
user_registered, |
| 31 |
us_security_token_sent, |
| 32 |
) |
| 33 |
from flask_security.utils import hash_data, hash_password |
| 34 |
|
| 35 |
from itsdangerous import BadSignature, SignatureExpired, URLSafeTimedSerializer |
| 36 |
from werkzeug.http import parse_cookie |
| 37 |
|
| 38 |
_missing = object |
| 39 |
|
| 40 |
|
| 41 |
def authenticate( |
| 42 |
client, |
| 43 |
email="[email protected]", |
| 44 |
password="password", |
| 45 |
endpoint=None, |
| 46 |
csrf=False, |
| 47 |
remember=False, |
| 48 |
**kwargs, |
| 49 |
): |
| 50 |
data = dict(email=email, password=password) |
| 51 |
if csrf: |
| 52 |
response = client.get(endpoint or "/login") |
| 53 |
data["csrf_token"] = get_form_input_value(response, "csrf_token") |
| 54 |
if remember: |
| 55 |
data["remember"] = "y" |
| 56 |
return client.post(endpoint or "/login", data=data, **kwargs) |
| 57 |
|
| 58 |
|
| 59 |
def json_authenticate(client, email="[email protected]", password="password", endpoint=None): |
| 60 |
data = dict(email=email, password=password) |
| 61 |
|
| 62 |
# Get auth token always |
| 63 |
ep = endpoint or "/login?include_auth_token" |
| 64 |
return client.post(ep, content_type="application/json", json=data) |
| 65 |
|
| 66 |
|
| 67 |
def is_authenticated(client, get_message, auth_token=None): |
| 68 |
# Return True is 'client' is authenticated. |
| 69 |
# Return False if not |
| 70 |
# Raise ValueError not certain... |
| 71 |
headers = {"accept": "application/json"} |
| 72 |
if auth_token: |
| 73 |
headers["Authentication-Token"] = auth_token |
| 74 |
response = client.get("/profile", headers=headers) |
| 75 |
if response.status_code == 200: |
| 76 |
return True |
| 77 |
if response.status_code == 401 and response.json["response"]["errors"][0].encode( |
| 78 |
"utf-8" |
| 79 |
) == get_message("UNAUTHENTICATED"): |
| 80 |
return False |
| 81 |
raise ValueError("Failed to figure out if authenticated") |
| 82 |
|
| 83 |
|
| 84 |
def check_location(app, location, expected_base): |
| 85 |
# verify response location. Historically this can be absolute or relative based |
| 86 |
# on configuration. As of 5.4 and Werkzeug 2.1 it is always relative |
| 87 |
return location == expected_base |
| 88 |
|
| 89 |
|
| 90 |
def verify_token(client_nc, token, status=None): |
| 91 |
# Use passed auth token in API that requires auth and verify status. |
| 92 |
# Pass in a client_nc to get valid results. |
| 93 |
response = client_nc.get( |
| 94 |
"/token", |
| 95 |
headers={"Content-Type": "application/json", "Authentication-Token": token}, |
| 96 |
) |
| 97 |
# /token is an application endpoint - SECURITY_CACHE_CONTROL must not |
| 98 |
# be applied to it (see issue #1263). |
| 99 |
assert "Cache-Control" not in response.headers |
| 100 |
if status: |
| 101 |
assert response.status_code == status |
| 102 |
else: |
| 103 |
assert b"Token Authentication" in response.data |
| 104 |
|
| 105 |
|
| 106 |
def logout(client, endpoint=None, **kwargs): |
| 107 |
return client.get(endpoint or "/logout", **kwargs) |
| 108 |
|
| 109 |
|
| 110 |
def json_logout(client, token, endpoint=None): |
| 111 |
return client.post( |
| 112 |
endpoint or "/logout", |
| 113 |
headers={ |
| 114 |
"Content-Type": "application/json", |
| 115 |
"Accept": "application/json", |
| 116 |
"Authentication-Token": token, |
| 117 |
}, |
| 118 |
) |
| 119 |
|
| 120 |
|
| 121 |
def get_csrf_token(client): |
| 122 |
response = client.get( |
| 123 |
"/login", |
| 124 |
data={}, |
| 125 |
headers={"Accept": "application/json"}, |
| 126 |
) |
| 127 |
return response.json["response"]["csrf_token"] |
| 128 |
|
| 129 |
|
| 130 |
def get_session(response): |
| 131 |
"""Return session cookie contents. |
| 132 |
This a base64 encoded json. |
| 133 |
Returns a dict |
| 134 |
""" |
| 135 |
|
| 136 |
# Alas seems like if there are multiple set-cookie headers - we are on our own |
| 137 |
for index, h in enumerate(response.headers): |
| 138 |
if h[0] == "Set-Cookie": |
| 139 |
cookie = parse_cookie(response.headers[index][1]) |
| 140 |
encoded_cookie = cookie.get("session", None) |
| 141 |
if encoded_cookie: |
| 142 |
serializer = URLSafeTimedSerializer( |
| 143 |
"secret", serializer=TaggedJSONSerializer() |
| 144 |
) |
| 145 |
val = serializer.loads_unsafe(encoded_cookie) |
| 146 |
return val[1] |
| 147 |
|
| 148 |
|
| 149 |
def setup_tf_sms(client, url_prefix=None, csrf_token=None): |
| 150 |
# Simple setup of SMS as a second factor and return the sender so caller |
| 151 |
# can get codes. |
| 152 |
SmsSenderFactory.senders["test"] = SmsTestSender |
| 153 |
sms_sender = SmsSenderFactory.createSender("test") |
| 154 |
data = dict(setup="sms", phone="+442083661188", csrf_token=csrf_token) |
| 155 |
response = client.post("/".join(filter(None, (url_prefix, "tf-setup"))), json=data) |
| 156 |
assert sms_sender.get_count() == 1 |
| 157 |
code = sms_sender.messages[0].split()[-1] |
| 158 |
response = client.post( |
| 159 |
"/".join(filter(None, (url_prefix, "tf-validate"))), |
| 160 |
json=dict(code=code, csrf_token=csrf_token), |
| 161 |
) |
| 162 |
assert response.status_code == 200 |
| 163 |
return sms_sender |
| 164 |
|
| 165 |
|
| 166 |
def get_existing_session(client): |
| 167 |
cookie = client.get_cookie("session") |
| 168 |
if cookie: |
| 169 |
serializer = URLSafeTimedSerializer("secret", serializer=TaggedJSONSerializer()) |
| 170 |
val = serializer.loads_unsafe(cookie.value) |
| 171 |
return val[1] |
| 172 |
return None |
| 173 |
|
| 174 |
|
| 175 |
def reset_fresh(client, within): |
| 176 |
# Assumes client authenticated. |
| 177 |
# Upon return the NEXT request if protected with a freshness check |
| 178 |
# will require a fresh authentication. |
| 179 |
with client.session_transaction() as sess: |
| 180 |
old_paa = sess["fs_paa"] - within.total_seconds() - 100 |
| 181 |
sess["fs_paa"] = old_paa |
| 182 |
sess.pop("fs_gexp", None) |
| 183 |
return old_paa |
| 184 |
|
| 185 |
|
| 186 |
def reset_fresh_auth_token(app, within, email="[email protected]"): |
| 187 |
# Assumes client authenticated. |
| 188 |
# Returns a new auth token that will force the NEXT request, |
| 189 |
# if protected with a freshness check to require a fresh authentication |
| 190 |
with app.test_request_context("/"): |
| 191 |
user = app.security.datastore.find_user(email=email) |
| 192 |
tdata = dict(ver=str(5)) |
| 193 |
if hasattr(user, "fs_token_uniquifier"): |
| 194 |
tdata["uid"] = str(user.fs_token_uniquifier) |
| 195 |
else: |
| 196 |
tdata["uid"] = str(user.fs_uniquifier) |
| 197 |
tdata["fs_paa"] = time.time() - within.total_seconds() - 100 |
| 198 |
tdata["exp"] = int(app.config.get("SECURITY_TOKEN_EXPIRE_TIMESTAMP")(user)) |
| 199 |
return app.security.remember_token_serializer.dumps(tdata) |
| 200 |
|
| 201 |
|
| 202 |
def get_form_action(response, ordinal=0): |
| 203 |
# Return the URL that the form WOULD post to - this is useful to check |
| 204 |
# how our templates actually work (e.g. propagation of 'next') |
| 205 |
matcher = re.findall( |
| 206 |
r'(?:<form action|formaction)="(\S*)"', |
| 207 |
response.data.decode("utf-8"), |
| 208 |
re.IGNORECASE | re.DOTALL, |
| 209 |
) |
| 210 |
return matcher[ordinal] |
| 211 |
|
| 212 |
|
| 213 |
def _parse_form_input(response, rex): |
| 214 |
matcher = re.findall( |
| 215 |
rex, |
| 216 |
response.data.decode("utf-8"), |
| 217 |
re.IGNORECASE | re.DOTALL, |
| 218 |
) |
| 219 |
if matcher: |
| 220 |
return matcher[0] |
| 221 |
return None |
| 222 |
|
| 223 |
|
| 224 |
def get_form_input(response, field_id): |
| 225 |
# return entire input field for field with the id == field_id or None if not found |
| 226 |
return _parse_form_input(response, f'<input ([^>]*id="{field_id}"[^>]*)">') |
| 227 |
|
| 228 |
|
| 229 |
def get_form_input_value(response, field_id): |
| 230 |
# return 'value' of field with the id == field_id or None if not found |
| 231 |
return _parse_form_input( |
| 232 |
response, f'<input [^>]*id="{field_id}"[^>]*value="([^"]*)">' |
| 233 |
) |
| 234 |
|
| 235 |
|
| 236 |
def check_xlation(app, locale): |
| 237 |
"""Return True if locale is loaded""" |
| 238 |
with app.test_request_context(): |
| 239 |
domain = app.security.i18n_domain |
| 240 |
xlations = domain.get_translations() |
| 241 |
if not xlations: |
| 242 |
return False |
| 243 |
# Flask-Babel doesn't populate _info as Flask-BabelEx did - so look in first |
| 244 |
# string which is catalog info. |
| 245 |
matcher = re.search(r"Language:\s*(\w+)", xlations._catalog[""]) |
| 246 |
return matcher.group(1) == locale |
| 247 |
|
| 248 |
|
| 249 |
def create_roles(ds): |
| 250 |
roles = [ |
| 251 |
("admin", ["full-read", "full-write", "super"]), |
| 252 |
("editor", ["full-read", "full-write"]), |
| 253 |
("author", ["full-read", "my-write"]), |
| 254 |
("simple", None), |
| 255 |
] |
| 256 |
for role in roles: |
| 257 |
if hasattr(ds.role_model, "permissions") and role[1]: |
| 258 |
ds.create_role(name=role[0], permissions=role[1]) |
| 259 |
else: |
| 260 |
ds.create_role(name=role[0]) |
| 261 |
ds.commit() |
| 262 |
|
| 263 |
|
| 264 |
def create_users(app, ds, count=None): |
| 265 |
users = [ |
| 266 |
("[email protected]", "matt", "password", ["admin"], True, 123456, None), |
| 267 |
("[email protected]", "joe", "password", ["editor"], True, 234567, None), |
| 268 |
("[email protected]", "dave", "password", ["admin", "editor"], True, 345678, None), |
| 269 |
("[email protected]", "jill", "password", ["author"], True, 456789, None), |
| 270 |
("[email protected]", "tiya", "password", [], False, 567890, None), |
| 271 |
("[email protected]", "gene", "password", ["simple"], True, 889900, None), |
| 272 |
("[email protected]", "jess", None, [], True, 678901, None), |
| 273 |
("[email protected]", "gal", "password", ["admin"], True, 112233, "sms"), |
| 274 |
("[email protected]", "gal2", "password", ["admin"], True, 223311, "authenticator"), |
| 275 |
("[email protected]", "gal3", "password", ["admin"], True, 331122, "email"), |
| 276 |
] |
| 277 |
count = count or len(users) |
| 278 |
|
| 279 |
for u in users[:count]: |
| 280 |
pw = u[2] |
| 281 |
if pw is not None: |
| 282 |
pw = hash_password(pw) |
| 283 |
roles = [ds.find_or_create_role(rn) for rn in u[3]] |
| 284 |
ds.commit() |
| 285 |
totp_secret = None |
| 286 |
if app.config.get("SECURITY_TWO_FACTOR", None) and u[6]: |
| 287 |
totp_secret = app.security._totp_factory.generate_totp_secret() |
| 288 |
user = ds.create_user( |
| 289 |
email=u[0], |
| 290 |
username=u[1], |
| 291 |
password=pw, |
| 292 |
active=u[4], |
| 293 |
security_number=u[5], |
| 294 |
tf_primary_method=u[6], |
| 295 |
tf_totp_secret=totp_secret, |
| 296 |
) |
| 297 |
ds.commit() |
| 298 |
for role in roles: |
| 299 |
ds.add_role_to_user(user, role) |
| 300 |
ds.commit() |
| 301 |
|
| 302 |
|
| 303 |
def populate_data(app, user_count=None): |
| 304 |
ds = app.security.datastore |
| 305 |
with app.app_context(): |
| 306 |
create_roles(ds) |
| 307 |
create_users(app, ds, user_count) |
| 308 |
|
| 309 |
|
| 310 |
def init_app_with_options(app, datastore, **options): |
| 311 |
security_args = options.pop("security_args", {}) |
| 312 |
app.config.update(**options) |
| 313 |
app.security = Security(app, datastore=datastore, **security_args) |
| 314 |
populate_data(app) |
| 315 |
|
| 316 |
|
| 317 |
@contextmanager |
| 318 |
def capture_queries(datastore): |
| 319 |
from sqlalchemy import event |
| 320 |
|
| 321 |
queries = [] |
| 322 |
|
| 323 |
@event.listens_for(datastore.db.session, "do_orm_execute") |
| 324 |
def _do_orm_execute(orm_execute_state): |
| 325 |
queries.append(orm_execute_state) |
| 326 |
|
| 327 |
yield queries |
| 328 |
|
| 329 |
|
| 330 |
class SmsTestSender(SmsSenderBaseClass): |
| 331 |
messages: list[str] = [] |
| 332 |
count = 0 |
| 333 |
|
| 334 |
# This looks strange because we need class variables since test need to access a |
| 335 |
# sender but the actual sender is instantiated low down in SMS code. |
| 336 |
def __init__(self): |
| 337 |
super().__init__() |
| 338 |
SmsTestSender.count = 0 |
| 339 |
SmsTestSender.messages = [] |
| 340 |
|
| 341 |
def send_sms(self, from_number, to_number, msg): |
| 342 |
SmsTestSender.messages.append(msg) |
| 343 |
SmsTestSender.count += 1 |
| 344 |
return |
| 345 |
|
| 346 |
def get_count(self): |
| 347 |
return SmsTestSender.count |
| 348 |
|
| 349 |
|
| 350 |
class SmsBadSender(SmsSenderBaseClass): |
| 351 |
def send_sms(self, from_number, to_number, msg): |
| 352 |
raise ValueError(f"Unknown number: {to_number}") |
| 353 |
|
| 354 |
|
| 355 |
@contextmanager |
| 356 |
def capture_passwordless_login_requests(): |
| 357 |
login_requests = [] |
| 358 |
|
| 359 |
def _on(app, **data): |
| 360 |
login_requests.append(data) |
| 361 |
|
| 362 |
login_instructions_sent.connect(_on) |
| 363 |
|
| 364 |
try: |
| 365 |
yield login_requests |
| 366 |
finally: |
| 367 |
login_instructions_sent.disconnect(_on) |
| 368 |
|
| 369 |
|
| 370 |
@contextmanager |
| 371 |
def capture_registrations(): |
| 372 |
"""Testing utility for capturing registrations.""" |
| 373 |
registrations = [] |
| 374 |
|
| 375 |
def _on(app, **data): |
| 376 |
data["email"] = data["user"].email |
| 377 |
registrations.append(data) |
| 378 |
|
| 379 |
user_registered.connect(_on) |
| 380 |
|
| 381 |
try: |
| 382 |
yield registrations |
| 383 |
finally: |
| 384 |
user_registered.disconnect(_on) |
| 385 |
|
| 386 |
|
| 387 |
@contextmanager |
| 388 |
def capture_reset_password_requests(): |
| 389 |
"""Testing utility for capturing password reset requests.""" |
| 390 |
reset_requests = [] |
| 391 |
|
| 392 |
def _on(app, **data): |
| 393 |
reset_requests.append(data) |
| 394 |
|
| 395 |
reset_password_instructions_sent.connect(_on) |
| 396 |
|
| 397 |
try: |
| 398 |
yield reset_requests |
| 399 |
finally: |
| 400 |
reset_password_instructions_sent.disconnect(_on) |
| 401 |
|
| 402 |
|
| 403 |
def check_signals( |
| 404 |
signals: dict, |
| 405 |
expected: str | list | dict[str, int] | None = None, |
| 406 |
ignore: str | list[str] | None = None, |
| 407 |
) -> None: |
| 408 |
# Check if test received expected # of signals. |
| 409 |
# Expected can be a string (signal name), list of strings or |
| 410 |
# dict of signal name to expected count. |
| 411 |
# Use with the signals fixture |
| 412 |
if not expected: |
| 413 |
expected = dict() |
| 414 |
elif isinstance(expected, str): |
| 415 |
expected = {expected: 1} |
| 416 |
elif isinstance(expected, list): |
| 417 |
expected = {sig: 1 for sig in expected} |
| 418 |
if not ignore: |
| 419 |
ignore = ["user_authenticated"] # this is too common in tests to worry about |
| 420 |
elif isinstance(ignore, str): |
| 421 |
ignore = [ignore] |
| 422 |
for sig in signals: |
| 423 |
if sig not in ignore: |
| 424 |
expected_calls = expected.get(sig, 0) |
| 425 |
actual_calls = len(signals[sig]) |
| 426 |
assert ( |
| 427 |
expected_calls == actual_calls |
| 428 |
), f"Expected {expected_calls} calls to {sig} but got {actual_calls}" |
| 429 |
|
| 430 |
|
| 431 |
@contextmanager |
| 432 |
def capture_flashes(): |
| 433 |
"""Testing utility for capturing flashes.""" |
| 434 |
flashes = [] |
| 435 |
|
| 436 |
def _on(app, **data): |
| 437 |
flashes.append(data) |
| 438 |
|
| 439 |
message_flashed.connect(_on) |
| 440 |
|
| 441 |
try: |
| 442 |
yield flashes |
| 443 |
finally: |
| 444 |
message_flashed.disconnect(_on) |
| 445 |
|
| 446 |
|
| 447 |
@contextmanager |
| 448 |
def capture_send_code_requests(): |
| 449 |
# Easy way to get token/code required for code logins |
| 450 |
# either second factor or us_signin |
| 451 |
login_requests = [] |
| 452 |
|
| 453 |
def _on(app, **data): |
| 454 |
assert all(v in data for v in ["user", "method", "login_token"]) |
| 455 |
assert isinstance(data["user"], UserMixin) |
| 456 |
login_requests.append(data) |
| 457 |
|
| 458 |
us_security_token_sent.connect(_on) |
| 459 |
tf_security_token_sent.connect(_on) |
| 460 |
|
| 461 |
try: |
| 462 |
yield login_requests |
| 463 |
finally: |
| 464 |
us_security_token_sent.disconnect(_on) |
| 465 |
tf_security_token_sent.disconnect(_on) |
| 466 |
|
| 467 |
|
| 468 |
def get_auth_token_version_3x(app, user): |
| 469 |
""" |
| 470 |
Copy of algorithm that generated user token in version 3.x |
| 471 |
""" |
| 472 |
data = [str(user.id), hash_data(user.password)] |
| 473 |
if hasattr(user, "fs_uniquifier"): |
| 474 |
data.append(user.fs_uniquifier) |
| 475 |
return app.security.remember_token_serializer.dumps(data) |
| 476 |
|
| 477 |
|
| 478 |
def get_auth_token_version_4x(app, user): |
| 479 |
"""Copy of algorithm that generated user token in version 4.x- 5.4""" |
| 480 |
data = [str(user.fs_uniquifier)] |
| 481 |
return app.security.remember_token_serializer.dumps(data) |
| 482 |
|
| 483 |
|
| 484 |
class FakeSerializer: |
| 485 |
def __init__(self, age=None, invalid=False): |
| 486 |
self.age = age |
| 487 |
self.invalid = invalid |
| 488 |
|
| 489 |
def loads(self, token, max_age): |
| 490 |
if self.age: |
| 491 |
assert max_age == self.age |
| 492 |
raise SignatureExpired("expired") |
| 493 |
if self.invalid: |
| 494 |
raise BadSignature("bad") |
| 495 |
|
| 496 |
def loads_unsafe(self, token): |
| 497 |
return None, None |
| 498 |
|
| 499 |
def dumps(self, state): |
| 500 |
return "heres your state" |
| 501 |
|
| 502 |
|
| 503 |
def convert_bool_option(v): |
| 504 |
# Used for command line options to convert string to bool |
| 505 |
if str(v).lower() in ["true"]: |
| 506 |
return True |
| 507 |
elif str(v).lower() in ["false"]: |
| 508 |
return False |
| 509 |
return v |