""" test_utils ~~~~~~~~~~ Test utils :copyright: (c) 2019-2026 by J. Christopher Wagner (jwag). :license: MIT, see LICENSE for more details. """ from __future__ import annotations from contextlib import contextmanager import re import time from flask.json.tag import TaggedJSONSerializer from flask.signals import message_flashed from flask_security import ( Security, SmsSenderBaseClass, SmsSenderFactory, UserMixin, ) from flask_security.signals import ( login_instructions_sent, reset_password_instructions_sent, tf_security_token_sent, user_registered, us_security_token_sent, ) from flask_security.utils import hash_data, hash_password from itsdangerous import BadSignature, SignatureExpired, URLSafeTimedSerializer from werkzeug.http import parse_cookie _missing = object def authenticate( client, email="matt@lp.com", password="password", endpoint=None, csrf=False, remember=False, **kwargs, ): data = dict(email=email, password=password) if csrf: response = client.get(endpoint or "/login") data["csrf_token"] = get_form_input_value(response, "csrf_token") if remember: data["remember"] = "y" return client.post(endpoint or "/login", data=data, **kwargs) def json_authenticate(client, email="matt@lp.com", password="password", endpoint=None): data = dict(email=email, password=password) # Get auth token always ep = endpoint or "/login?include_auth_token" return client.post(ep, content_type="application/json", json=data) def is_authenticated(client, get_message, auth_token=None): # Return True is 'client' is authenticated. # Return False if not # Raise ValueError not certain... headers = {"accept": "application/json"} if auth_token: headers["Authentication-Token"] = auth_token response = client.get("/profile", headers=headers) if response.status_code == 200: return True if response.status_code == 401 and response.json["response"]["errors"][0].encode( "utf-8" ) == get_message("UNAUTHENTICATED"): return False raise ValueError("Failed to figure out if authenticated") def check_location(app, location, expected_base): # verify response location. Historically this can be absolute or relative based # on configuration. As of 5.4 and Werkzeug 2.1 it is always relative return location == expected_base def verify_token(client_nc, token, status=None): # Use passed auth token in API that requires auth and verify status. # Pass in a client_nc to get valid results. response = client_nc.get( "/token", headers={"Content-Type": "application/json", "Authentication-Token": token}, ) # /token is an application endpoint - SECURITY_CACHE_CONTROL must not # be applied to it (see issue #1263). assert "Cache-Control" not in response.headers if status: assert response.status_code == status else: assert b"Token Authentication" in response.data def logout(client, endpoint=None, **kwargs): return client.get(endpoint or "/logout", **kwargs) def json_logout(client, token, endpoint=None): return client.post( endpoint or "/logout", headers={ "Content-Type": "application/json", "Accept": "application/json", "Authentication-Token": token, }, ) def get_csrf_token(client): response = client.get( "/login", data={}, headers={"Accept": "application/json"}, ) return response.json["response"]["csrf_token"] def get_session(response): """Return session cookie contents. This a base64 encoded json. Returns a dict """ # Alas seems like if there are multiple set-cookie headers - we are on our own for index, h in enumerate(response.headers): if h[0] == "Set-Cookie": cookie = parse_cookie(response.headers[index][1]) encoded_cookie = cookie.get("session", None) if encoded_cookie: serializer = URLSafeTimedSerializer( "secret", serializer=TaggedJSONSerializer() ) val = serializer.loads_unsafe(encoded_cookie) return val[1] def setup_tf_sms(client, url_prefix=None, csrf_token=None): # Simple setup of SMS as a second factor and return the sender so caller # can get codes. SmsSenderFactory.senders["test"] = SmsTestSender sms_sender = SmsSenderFactory.createSender("test") data = dict(setup="sms", phone="+442083661188", csrf_token=csrf_token) response = client.post("/".join(filter(None, (url_prefix, "tf-setup"))), json=data) assert sms_sender.get_count() == 1 code = sms_sender.messages[0].split()[-1] response = client.post( "/".join(filter(None, (url_prefix, "tf-validate"))), json=dict(code=code, csrf_token=csrf_token), ) assert response.status_code == 200 return sms_sender def get_existing_session(client): cookie = client.get_cookie("session") if cookie: serializer = URLSafeTimedSerializer("secret", serializer=TaggedJSONSerializer()) val = serializer.loads_unsafe(cookie.value) return val[1] return None def reset_fresh(client, within): # Assumes client authenticated. # Upon return the NEXT request if protected with a freshness check # will require a fresh authentication. with client.session_transaction() as sess: old_paa = sess["fs_paa"] - within.total_seconds() - 100 sess["fs_paa"] = old_paa sess.pop("fs_gexp", None) return old_paa def reset_fresh_auth_token(app, within, email="matt@lp.com"): # Assumes client authenticated. # Returns a new auth token that will force the NEXT request, # if protected with a freshness check to require a fresh authentication with app.test_request_context("/"): user = app.security.datastore.find_user(email=email) tdata = dict(ver=str(5)) if hasattr(user, "fs_token_uniquifier"): tdata["uid"] = str(user.fs_token_uniquifier) else: tdata["uid"] = str(user.fs_uniquifier) tdata["fs_paa"] = time.time() - within.total_seconds() - 100 tdata["exp"] = int(app.config.get("SECURITY_TOKEN_EXPIRE_TIMESTAMP")(user)) return app.security.remember_token_serializer.dumps(tdata) def get_form_action(response, ordinal=0): # Return the URL that the form WOULD post to - this is useful to check # how our templates actually work (e.g. propagation of 'next') matcher = re.findall( r'(?: