Debian Codegraph @

tests/test_utils.py

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