Debian Codegraph @

tests/conftest.py

raw
1 """
2 conftest
3 ~~~~~~~~
4
5 Test fixtures and what not
6
7 :copyright: (c) 2017 by CERN.
8 :copyright: (c) 2019-2026 by J. Christopher Wagner (jwag).
9 :license: MIT, see LICENSE for more details.
10 """
11
12 from __future__ import annotations
13
14 from collections.abc import Mapping
15 import sqlite3
16 import gc
17 import os
18 import tempfile
19 import time
20 import typing as t
21 import sys
22 from urllib.parse import urlsplit
23
24 from passlib.ifc import PasswordHash
25 from passlib.registry import register_crypt_handler
26 import pytest
27 from flask import Flask, Response, jsonify, render_template
28 from flask import request as flask_request
29 from flask_mail import Mail
30 from flask_wtf import CSRFProtect
31
32 try:
33 from sqlalchemy.orm import Mapped
34 except ImportError:
35 pass
36
37 from flask_security import (
38 FSQLALiteUserDatastore,
39 MongoEngineUserDatastore,
40 PeeweeUserDatastore,
41 RoleMixin,
42 Security,
43 SQLAlchemySessionUserDatastore,
44 SQLAlchemyUserDatastore,
45 UserMixin,
46 WebAuthnMixin,
47 auth_required,
48 auth_token_required,
49 http_auth_required,
50 get_request_attr,
51 roles_accepted,
52 roles_required,
53 permissions_accepted,
54 permissions_required,
55 uia_email_mapper,
56 RefreshTrackerMixin,
57 )
58 from flask_security.utils import localize_callback
59
60 from tests.test_utils import convert_bool_option, populate_data
61
62 # enable testing both register form options
63 v2_param = [
64 pytest.param(dict(use_register_v2=True), id="use_register_v2-True"),
65 pytest.param(dict(use_register_v2=False), id="use_register_v2-False"),
66 ]
67
68
69 class Nomixin:
70 pass
71
72
73 class FastHash(PasswordHash):
74 """Our own 'hasher'. For testing
75 we want a fast hash, but a real one such that the provided password
76 and hash aren't the same (which is what happens when using plaintext).
77 """
78
79 name = "fasthash"
80 setting_kwds = ()
81 context_kwds = ()
82
83 @classmethod
84 def hash(cls, secret, **kwds):
85 return f"$fh$1${secret}"
86
87 @classmethod
88 def verify(cls, secret, stored_hash, **context_kwds):
89 new_hash = f"$fh$1${secret}"
90 return new_hash == stored_hash
91
92 @classmethod
93 def identify(cls, stored_hash):
94 return stored_hash.startswith("$fh$1$")
95
96 @classmethod
97 def using(cls, relaxed=False, **settings):
98 return type("fasthash2", (cls,), {})
99
100
101 # python 3.13 is strict about not closing sqlite3 db connections.
102 def find_sqlite_connections():
103 connections = []
104 for obj in gc.get_objects():
105 if isinstance(obj, sqlite3.Connection):
106 connections.append(obj)
107 return connections
108
109
110 @pytest.fixture()
111 def app(request, pytestconfig):
112 # assert not find_sqlite_connections() # hopefully find tests that don't clean up
113 app = Flask(__name__)
114 app.response_class = Response
115 app.debug = True
116 app.config["SECRET_KEY"] = "secret"
117 app.config["TESTING"] = True
118 app.config["LOGIN_DISABLED"] = False
119 app.config["WTF_CSRF_ENABLED"] = False
120 # Our test emails/domain isn't necessarily valid
121 app.config["SECURITY_EMAIL_VALIDATOR_ARGS"] = {"check_deliverability": False}
122 app.config["SECURITY_TOTP_SECRETS"] = {
123 "1": "TjQ9Qa31VOrfEzuPy4VHQWPCTmRzCnFzMKLxXYiZu9B"
124 }
125 app.config["SECURITY_TOTP_ISSUER"] = "tests"
126 app.config["SECURITY_SMS_SERVICE"] = "test"
127 app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
128
129 app.config["SECURITY_PASSWORD_SALT"] = "salty"
130 app.config["SECURITY_CONFIRM_SALT"] = "confirm-salty"
131 # Make this fasthash for most tests - reduces unit test time by 50%
132 app.config["SECURITY_PASSWORD_SCHEMES"] = ["fasthash", "argon2", "bcrypt"]
133 app.config["SECURITY_PASSWORD_HASH"] = "fasthash"
134 app.config["SECURITY_PASSWORD_SINGLE_HASH"] = True
135 register_crypt_handler(FastHash)
136 # Make this hex_md5 for token tests
137 app.config["SECURITY_HASHING_SCHEMES"] = ["hex_md5"]
138 app.config["SECURITY_DEPRECATED_HASHING_SCHEMES"] = []
139 app.fs_constructor_args = (
140 dict()
141 ) # allow marks to set items for Security constructor
142
143 for opt in [
144 "changeable",
145 "change_email",
146 "change_username",
147 "confirmable",
148 "passwordless",
149 "recoverable",
150 "registerable",
151 "refresh_token",
152 "trackable",
153 "two_factor",
154 "unified_signin",
155 "username_recovery",
156 "webauthn",
157 ]:
158 app.config["SECURITY_" + opt.upper()] = opt in request.keywords
159
160 marker_getter = request.node.get_closest_marker
161
162 # Import webauthn, or skip test if webauthn isn't installed
163 webauthn_test = marker_getter("webauthn")
164 if webauthn_test is not None:
165 pytest.importorskip("webauthn")
166 app.fs_constructor_args.update(**webauthn_test.kwargs)
167
168 oauthlib_test = marker_getter("oauth")
169 if oauthlib_test is not None:
170 pytest.importorskip("authlib")
171
172 mfa_test = marker_getter("two_factor") or marker_getter("unified_signin")
173 if mfa_test is not None:
174 pytest.importorskip("cryptography")
175
176 flask_async_test = marker_getter("flask_async")
177 if flask_async_test is not None:
178 pytest.importorskip("asgiref") # from flask[async]
179
180 # allow parameterized tests to set security config variables
181 if hasattr(request, "param") and isinstance(request.param, Mapping):
182 for key, value in request.param.items():
183 app.config["SECURITY_" + key.upper()] = value
184
185 # Override config settings as requested for this test
186 settings = marker_getter("settings")
187 if settings is not None:
188 for key, value in settings.kwargs.items():
189 app.config["SECURITY_" + key.upper()] = value
190 settings = marker_getter("app_settings")
191 if settings is not None:
192 for key, value in settings.kwargs.items():
193 app.config[key.upper()] = value
194
195 # allow pytest command line to override everything
196 if request.config.option.setting:
197 for s in request.config.option.setting:
198 key, value = s.split("=")
199 app.config[key.upper()] = convert_bool_option(value)
200
201 app.mail = Mail(app) # type: ignore
202
203 # use babel marker to signify tests that need babel extension.
204 babel = marker_getter("babel")
205 if babel:
206 pytest.importorskip("flask_babel")
207 from flask_babel import Babel
208
209 if locale := babel.kwargs.get("babel_default_locale", None):
210 app.config["BABEL_DEFAULT_LOCALE"] = locale
211 if babel.kwargs.get("test_xlations", None):
212 i18n_dirname = [
213 os.path.join(pytestconfig.rootdir, "tests/translations"),
214 ]
215 app.config["SECURITY_I18N_DIRNAME"] = i18n_dirname
216 Babel(app)
217
218 csrf = marker_getter("csrf")
219 if csrf is not None:
220 # without any keys/arguments - this is the default config
221 # Note that WTF_CSRF_CHECK_DEFAULT = True means Flask_wtf will
222 # run a CSRF check as part of @before_request - before we see it.
223 # Above we set WTF_CSRF_ENABLED to False. With this marker
224 # we want the 'default' config.
225 del app.config["WTF_CSRF_ENABLED"]
226 if "ignore_unauth" in csrf.kwargs.keys():
227 app.config["WTF_CSRF_CHECK_DEFAULT"] = False
228 app.config["SECURITY_CSRF_IGNORE_UNAUTH_ENDPOINTS"] = True
229 if "csrfprotect" in csrf.kwargs.keys():
230 # This is needed when passing CSRF in header or non-form input
231 app.config["WTF_CSRF_CHECK_DEFAULT"] = False
232 CSRFProtect(app)
233
234 @app.route("/")
235 def index():
236 return render_template("index.html", content="Home Page")
237
238 @app.route("/profile")
239 @auth_required()
240 def profile():
241 if hasattr(app, "security"):
242 if app.security._want_json(flask_request):
243 return jsonify(message="profile")
244
245 return render_template("index.html", content="Profile Page")
246
247 @app.route("/post_login")
248 @auth_required()
249 def post_login():
250 return render_template("index.html", content="Post Login")
251
252 @app.route("/http", methods=["GET", "POST"])
253 @http_auth_required
254 def http():
255 return "HTTP Authentication"
256
257 @app.route("/http_admin_required")
258 @http_auth_required
259 @permissions_required("admin")
260 def http_admin_required():
261 assert get_request_attr("fs_authn_via") == "basic"
262 return "HTTP Authentication"
263
264 @app.route("/http_custom_realm")
265 @http_auth_required("My Realm")
266 def http_custom_realm():
267 assert get_request_attr("fs_authn_via") == "basic"
268 return render_template("index.html", content="HTTP Authentication")
269
270 @app.route("/session")
271 @auth_required("session")
272 def session():
273 return "Session Authentication"
274
275 @app.route("/token", methods=["GET", "POST"])
276 @auth_token_required
277 def token():
278 assert get_request_attr("fs_authn_via") == "token"
279 return render_template("index.html", content="Token Authentication")
280
281 @app.route("/multi_auth")
282 @auth_required("session", "token", "basic")
283 def multi_auth():
284 return render_template("index.html", content="Session, Token, Basic auth")
285
286 @app.route("/post_logout")
287 def post_logout():
288 return render_template("index.html", content="Post Logout")
289
290 @app.route("/post_register")
291 def post_register():
292 return render_template("index.html", content="Post Register")
293
294 @app.route("/post_confirm")
295 def post_confirm():
296 return render_template("index.html", content="Post Confirm")
297
298 @app.route("/post_reset")
299 def post_reset():
300 return render_template("index.html", content="Post Reset")
301
302 @app.route("/post_change_username")
303 def post_change_username():
304 return render_template("index.html", content="Post Change Username")
305
306 @app.route("/admin")
307 @roles_required("admin")
308 def admin():
309 assert get_request_attr("fs_authn_via") == "session"
310 return render_template("index.html", content="Admin Page")
311
312 @app.route("/admin_and_editor")
313 @roles_required("admin", "editor")
314 def admin_and_editor():
315 return render_template("index.html", content="Admin and Editor Page")
316
317 @app.route("/admin_or_editor")
318 @roles_accepted("admin", "editor")
319 def admin_or_editor():
320 return render_template("index.html", content="Admin or Editor Page")
321
322 @app.route("/simple")
323 @roles_accepted("simple")
324 def simple():
325 return render_template("index.html", content="SimplePage")
326
327 @app.route("/admin_perm")
328 @permissions_accepted("full-write", "super")
329 def admin_perm():
330 return render_template(
331 "index.html", content="Admin Page with full-write or super"
332 )
333
334 @app.route("/admin_perm_required")
335 @permissions_required("full-write", "super")
336 def admin_perm_required():
337 return render_template("index.html", content="Admin Page required")
338
339 @app.route("/page1")
340 def page_1():
341 return "Page 1"
342
343 @app.route("/json", methods=["GET", "POST"])
344 def echo_json():
345 return jsonify(flask_request.get_json())
346
347 @app.route("/json_auth", methods=["POST"])
348 @auth_required()
349 def echo_jsonauth():
350 return jsonify(flask_request.get_json())
351
352 @app.route("/unauthz", methods=["GET", "POST"])
353 def unauthz():
354 return render_template("index.html", content="Unauthorized")
355
356 @app.route("/fresh", methods=["GET", "POST"])
357 @auth_required(within=60)
358 def fresh():
359 if app.security._want_json(flask_request):
360 return jsonify(title="Fresh Only")
361 else:
362 return render_template("index.html", content="Fresh Only")
363
364 def revert_forms():
365 # Some forms/tests have dynamic fields - be sure to revert them.
366 if hasattr(app, "security"):
367 for form_name in [
368 "login_form",
369 "register_form",
370 "confirm_register_form",
371 "change_username_form",
372 ]:
373 if hasattr(app.security.forms[form_name].cls, "username"):
374 del app.security.forms[form_name].cls.username
375
376 from flask_security import RegisterFormV2
377 from flask_security.forms import PasswordConfirmFormMixin, NewPasswordFormMixin
378
379 for attr in ["username"]:
380 if hasattr(RegisterFormV2, attr):
381 delattr(RegisterFormV2, attr)
382 RegisterFormV2.password_confirm = PasswordConfirmFormMixin.password_confirm
383 RegisterFormV2.password = NewPasswordFormMixin.password
384
385 request.addfinalizer(revert_forms)
386 yield app
387
388
389 @pytest.fixture()
390 def outbox(app):
391 with app.mail.record_messages() as outbox:
392 yield outbox
393
394
395 @pytest.fixture()
396 def mongoengine_datastore(app, tmpdir, realmongodburl):
397 ds, td = mongoengine_setup(app, tmpdir, realmongodburl)
398 yield ds
399 td()
400
401
402 def mongoengine_setup(app, tmpdir, realmongodburl):
403 # To run against a realdb: mongod --dbpath <somewhere>
404 import pymongo
405 import mongomock
406 from mongoengine import Document, connect
407 from mongoengine.fields import (
408 BinaryField,
409 BooleanField,
410 DateTimeField,
411 IntField,
412 ListField,
413 ReferenceField,
414 StringField,
415 )
416 from mongoengine import PULL, CASCADE, disconnect_all
417
418 db_name = "flask_security_test"
419 db_host = realmongodburl if realmongodburl else "mongodb://localhost"
420 db_client_class = pymongo.MongoClient if realmongodburl else mongomock.MongoClient
421 db = connect(
422 alias=db_name,
423 db=db_name,
424 host=db_host,
425 port=27017,
426 mongo_client_class=db_client_class,
427 )
428
429 class Role(Document, RoleMixin):
430 name = StringField(required=True, unique=True, max_length=80)
431 description = StringField(max_length=255)
432 permissions = ListField(required=False)
433 meta = {"db_alias": db_name}
434
435 class WebAuthn(Document, WebAuthnMixin):
436 credential_id = BinaryField(primary_key=True, max_bytes=1024, required=True)
437 public_key = BinaryField(required=True)
438 sign_count = IntField(default=0)
439 transports = ListField(required=False)
440 backup_state = BooleanField(required=True)
441 device_type = StringField(max_length=64, required=True)
442
443 # a JSON string as returned from registration
444 extensions = StringField(max_length=255)
445 lastuse_datetime = DateTimeField(required=True)
446 # name is provided by user - we make sure it is unique per user
447 name = StringField(max_length=64, required=True)
448 usage = StringField(max_length=64, required=True)
449 # we need to be able to look up a user from a credential_id
450 user = ReferenceField("User")
451 meta = {"db_alias": db_name}
452
453 def get_user_mapping(self) -> dict[str, str]:
454 """
455 Return the mapping from webauthn back to User
456 """
457 return dict(id=self.user.id)
458
459 class FsRefreshTracker(Document, RefreshTrackerMixin):
460 """Refresh Token Tracker"""
461
462 refresh_family = StringField(max_length=64, required=True)
463 gen = IntField(default=1)
464 expires_at = DateTimeField(required=True)
465 revoked_at = DateTimeField(required=False)
466 last_used_at = DateTimeField(required=True)
467 name = StringField(max_length=64)
468 user = ReferenceField("User")
469
470 meta = {"db_alias": db_name}
471
472 class User(Document, UserMixin):
473 email = StringField(unique=True, max_length=255)
474 fs_uniquifier = StringField(unique=True, max_length=64, required=True)
475 fs_webauthn_user_handle = StringField(unique=True, max_length=64)
476 username = StringField(unique=True, required=False, sparse=True, max_length=255)
477 password = StringField(required=False, max_length=255)
478 security_number = IntField(unique=True, required=False, sparse=True)
479 last_login_at = DateTimeField()
480 current_login_at = DateTimeField()
481 tf_primary_method = StringField(max_length=255)
482 tf_totp_secret = StringField(max_length=255)
483 tf_phone_number = StringField(max_length=255)
484 mf_recovery_codes = ListField(required=False)
485 us_totp_secrets = StringField()
486 us_phone_number = StringField(
487 max_length=255, unique=True, required=False, sparse=True
488 )
489 last_login_ip = StringField(max_length=100)
490 current_login_ip = StringField(max_length=100)
491 login_count = IntField()
492 active = BooleanField(default=True)
493 confirmed_at = DateTimeField()
494 roles = ListField(ReferenceField(Role), default=[])
495 webauthn = ListField(
496 ReferenceField(WebAuthn, reverse_delete_rule=PULL), default=[]
497 )
498 refresh_trackers = ListField(
499 ReferenceField(FsRefreshTracker, reverse_delete_rule=PULL), default=[]
500 )
501 meta = {"db_alias": db_name}
502
503 def get_security_payload(self):
504 return {"email": str(self.email)}
505
506 User.register_delete_rule(WebAuthn, "user", CASCADE)
507 User.register_delete_rule(FsRefreshTracker, "user", CASCADE)
508
509 def tear_down():
510 with app.app_context():
511 User.drop_collection()
512 Role.drop_collection()
513 WebAuthn.drop_collection()
514 db.drop_database(db_name)
515 disconnect_all()
516
517 return (
518 MongoEngineUserDatastore(db, User, Role, WebAuthn, FsRefreshTracker),
519 tear_down,
520 )
521
522
523 @pytest.fixture()
524 def sqlalchemy_datastore(app, tmpdir, realdburl):
525 ds, td = sqlalchemy_setup(app, tmpdir, realdburl)
526 yield ds
527 td()
528
529
530 def sqlalchemy_setup(app, tmpdir, realdburl):
531 pytest.importorskip("flask_sqlalchemy")
532 from flask_sqlalchemy import SQLAlchemy
533 from sqlalchemy import Column, Integer
534 from flask_security.models import fsqla_v4 as fsqla
535
536 if realdburl:
537 db_url, db_info = _setup_realdb(realdburl)
538 app.config["SQLALCHEMY_DATABASE_URI"] = db_url
539 else:
540 app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///:memory:"
541
542 # In Flask-SQLAlchemy >= 3.0.0 queries are no longer logged automatically,
543 # even in debug or testing mode.
544 app.config["SQLALCHEMY_RECORD_QUERIES"] = True
545
546 db = SQLAlchemy(app)
547
548 fsqla.FsModels.set_db_info(db)
549
550 class Role(db.Model, fsqla.FsRoleMixin):
551 pass
552
553 class WebAuthn(db.Model, fsqla.FsWebAuthnMixin):
554 pass
555
556 class FsRefreshTracker(db.Model, fsqla.FsRefreshTrackerMixin):
557 pass
558
559 class User(
560 db.Model, fsqla.FsUserMixin, app.config.get("TESTING_USER_MIXIN", Nomixin)
561 ):
562 security_number = Column(Integer, unique=True)
563
564 def __init__(self, *args, **kwargs):
565 from flask import current_app
566
567 super().__init__(*args, **kwargs)
568 inject = current_app.config.get("TESTING_USER_INJECT") or dict()
569 for k, v in inject.items():
570 setattr(User, k, v)
571
572 def get_security_payload(self):
573 # Make sure we still properly hook up to flask's JSON extension
574 # which handles datetime
575 return {"email": str(self.email), "last_update": self.update_datetime}
576
577 def augment_auth_token(self, tdata):
578 # for testing - if TESTING_AUGMENT_AUTH_TOKEN is set - call that
579 from flask import current_app
580
581 if cb := current_app.config.get("TESTING_AUGMENT_AUTH_TOKEN"):
582 cb(tdata)
583
584 with app.app_context():
585 db.create_all()
586
587 def tear_down():
588 with app.app_context():
589 if realdburl:
590 db.drop_all()
591 db.engine.dispose() # make sure Flask-SQLAlchemy connections are closed
592 _teardown_realdb(db_info)
593 engine = db.engine
594 engine.dispose()
595
596 return (
597 SQLAlchemyUserDatastore(db, User, Role, WebAuthn, FsRefreshTracker),
598 tear_down,
599 )
600
601
602 @pytest.fixture()
603 def fsqlalite_datastore(app, tmpdir, realdburl):
604 ds, td = fsqlalite_setup(app, tmpdir, realdburl)
605 yield ds
606 td()
607
608
609 @pytest.fixture()
610 def fsqlalite_min_datastore(app, tmpdir, realdburl):
611 pytest.importorskip("flask_sqlalchemy_lite")
612 from sqlalchemy.orm import declared_attr, mapped_column, relationship
613 from sqlalchemy import String
614
615 class FsMinUserMixin(UserMixin):
616 # flask_security basic fields
617 id: Mapped[int] = mapped_column(primary_key=True) # type: ignore
618 email: Mapped[str] = mapped_column(String(255), unique=True) # type: ignore
619 password: Mapped[str | None] = mapped_column(String(255)) # type: ignore
620 active: Mapped[bool] = mapped_column() # type: ignore
621 fs_uniquifier: Mapped[str] = mapped_column( # type: ignore
622 String(64), unique=True
623 )
624
625 @declared_attr
626 def roles(cls):
627 # The first arg is a class name, the backref is a column name
628 return relationship(
629 "Role",
630 secondary="roles_users",
631 back_populates="users",
632 )
633
634 ds, td = fsqlalite_setup(
635 app,
636 tmpdir,
637 realdburl,
638 usermixin=FsMinUserMixin,
639 use_webauthn=False,
640 use_fs_tracker=False,
641 )
642 yield ds
643 td()
644
645
646 def fsqlalite_setup(
647 app, tmpdir, realdburl, usermixin=None, use_webauthn=True, use_fs_tracker=True
648 ):
649 pytest.importorskip("flask_sqlalchemy_lite")
650 from flask_sqlalchemy_lite import SQLAlchemy
651 from sqlalchemy.orm import DeclarativeBase, mapped_column
652 from flask_security.models import sqla_v2 as sqla
653
654 if not usermixin:
655 usermixin = sqla.FsUserMixin
656 if realdburl:
657 db_url, db_info = _setup_realdb(realdburl)
658 else:
659 db_url = "sqlite:///:memory:"
660 app.config |= {
661 "SQLALCHEMY_ENGINES": {
662 "default": {"url": db_url, "pool_pre_ping": True},
663 },
664 }
665 db = SQLAlchemy(app)
666
667 class Model(DeclarativeBase):
668 pass
669
670 sqla.FsModels.set_db_info(base_model=Model)
671
672 class Role(Model, sqla.FsRoleMixin):
673 __tablename__ = "role"
674
675 if use_webauthn:
676
677 class WebAuthn(Model, sqla.FsWebAuthnMixin):
678 __tablename__ = "webauthn"
679
680 if use_fs_tracker:
681
682 class FsRefreshTracker(Model, sqla.FsRefreshTrackerMixin):
683 __tablename__ = "fs_refresh_tracker"
684
685 class User(Model, usermixin, app.config.get("TESTING_USER_MIXIN", Nomixin)):
686 __tablename__ = "user"
687 security_number: Mapped[t.Optional[int]] = mapped_column( # type: ignore
688 unique=True
689 )
690
691 def get_security_payload(self) -> dict[str, t.Any]:
692 # Make sure we still properly hook up to flask's JSON extension
693 # which handles datetime
694 return {"email": str(self.email), "last_update": self.update_datetime}
695
696 with app.app_context():
697 Model.metadata.create_all(db.engine)
698
699 def tear_down():
700 with app.app_context():
701 Model.metadata.drop_all(db.engine)
702 engine = db.engine
703 engine.dispose()
704 if realdburl:
705 _teardown_realdb(db_info)
706
707 return (
708 FSQLALiteUserDatastore(
709 db,
710 User,
711 Role,
712 WebAuthn if use_webauthn else None,
713 FsRefreshTracker if use_fs_tracker else None,
714 ),
715 tear_down,
716 )
717
718
719 @pytest.fixture()
720 def sqlalchemy_session_datastore(app, tmpdir, realdburl):
721 if sys.version_info < (3, 10):
722 pytest.skip("requires python3.10 or higher")
723 ds, td = sqlalchemy_session_setup(app, tmpdir, realdburl)
724 yield ds
725 td()
726
727
728 def sqlalchemy_session_setup(app, tmpdir, realdburl, **engine_kwargs):
729 """
730 Note that we test having a different user id column name here.
731 """
732 pytest.importorskip("sqlalchemy")
733 from sqlalchemy import create_engine
734 from sqlalchemy.orm import (
735 mapped_column,
736 scoped_session,
737 sessionmaker,
738 declarative_base,
739 )
740 from sqlalchemy.ext.declarative import declared_attr
741 from sqlalchemy import (
742 Column,
743 Integer,
744 ForeignKey,
745 )
746 from flask_security.models import sqla_v2 as sqla
747
748 if realdburl:
749 db_url, db_info = _setup_realdb(realdburl)
750 engine = db_info["engine"]
751 else:
752 db_url = "sqlite:///:memory:"
753 engine = create_engine(db_url, **engine_kwargs)
754
755 db_session = scoped_session(
756 sessionmaker(autocommit=False, autoflush=False, bind=engine)
757 )
758 app.teardown_appcontext(lambda exc: db_session.close())
759 Base = declarative_base()
760 # Note that in this case we don't call set_db_info since we are using
761 # normal table names AND we need our own RolesUsers table since we modified the
762 # PK names.
763
764 class WebAuthn(Base, sqla.FsWebAuthnMixin):
765 __tablename__ = "webauthn"
766
767 @declared_attr
768 def user_id(self) -> Mapped[int]:
769 return mapped_column(ForeignKey("user.myuserid", ondelete="CASCADE"))
770
771 def get_user_mapping(self) -> dict[str, t.Any]:
772 """
773 Return the filter needed by find_user() to get the user
774 associated with this webauthn credential.
775 """
776 return dict(myuserid=self.user_id)
777
778 class FsRefreshTracker(Base, sqla.FsRefreshTrackerMixin):
779 __tablename__ = "fs_refresh_tracker"
780
781 @declared_attr
782 def user_id(self) -> Mapped[int]:
783 return mapped_column(ForeignKey("user.myuserid", ondelete="CASCADE"))
784
785 class RolesUsers(Base):
786 __tablename__ = "roles_users"
787 id = Column(Integer(), primary_key=True)
788 user_id = Column("user_id", Integer(), ForeignKey("user.myuserid"))
789 role_id = Column("role_id", Integer(), ForeignKey("role.myroleid"))
790
791 class Role(Base, sqla.FsRoleMixin):
792 __tablename__ = "role"
793 myroleid: Mapped[int] = mapped_column(primary_key=True) # type: ignore
794 id: Mapped[int] = mapped_column(nullable=True) # type: ignore
795
796 class User(Base, sqla.FsUserMixin, app.config.get("TESTING_USER_MIXIN", Nomixin)):
797 __tablename__ = "user"
798 myuserid: Mapped[int] = mapped_column(primary_key=True) # type: ignore
799 id: Mapped[int] = mapped_column(nullable=True) # type: ignore
800 security_number: Mapped[t.Optional[int]] = mapped_column( # type: ignore
801 unique=True
802 )
803
804 def get_security_payload(self):
805 # Make sure we still properly hook up to flask's JSON extension
806 # which handles datetime
807 return {"email": str(self.email), "last_update": self.update_datetime}
808
809 with app.app_context():
810 Base.metadata.create_all(bind=engine)
811
812 def tear_down():
813 with app.app_context():
814 Base.metadata.drop_all(bind=engine)
815 engine.dispose()
816 if realdburl:
817 _teardown_realdb(db_info)
818
819 return (
820 SQLAlchemySessionUserDatastore(
821 db_session, User, Role, WebAuthn, FsRefreshTracker
822 ),
823 tear_down,
824 )
825
826
827 @pytest.fixture()
828 def peewee_datastore(app, tmpdir, realdburl):
829 ds, td = peewee_setup(app, tmpdir, realdburl)
830 yield ds
831 td()
832
833
834 def peewee_setup(app, tmpdir, realdburl):
835 pytest.importorskip("peewee")
836 from peewee import (
837 TextField,
838 DateTimeField,
839 Field,
840 IntegerField,
841 BooleanField,
842 BlobField,
843 ForeignKeyField,
844 CharField,
845 )
846 from playhouse.flask_utils import FlaskDB
847
848 if realdburl:
849 engine_mapper = {
850 "postgresql": "peewee.PostgresqlDatabase",
851 "mysql": "peewee.MySQLDatabase",
852 }
853 db_url, db_info = _setup_realdb(realdburl)
854 pieces = urlsplit(db_url)
855 db_config = {
856 "name": pieces.path[1:],
857 "engine": engine_mapper[pieces.scheme.split("+")[0]],
858 "user": pieces.username,
859 "password": pieces.password,
860 "host": pieces.hostname,
861 "port": pieces.port,
862 }
863 else:
864 f, path = tempfile.mkstemp(
865 prefix="flask-security-test-db", suffix=".db", dir=str(tmpdir)
866 )
867 db_config = {"name": path, "engine": "peewee.SqliteDatabase"}
868
869 app.config["DATABASE"] = db_config
870
871 db = FlaskDB(app)
872
873 class AsaList(Field):
874 field_type = "text"
875
876 def db_value(self, value):
877 try:
878 return ",".join(value)
879 except TypeError:
880 return value
881
882 def python_value(self, value):
883 if value:
884 return value.split(",")
885 return []
886
887 class Role(RoleMixin, db.Model):
888 name = CharField(unique=True, max_length=80)
889 description = TextField(null=True)
890 permissions = AsaList(null=True)
891
892 class User(UserMixin, db.Model):
893 email = TextField(unique=True, null=False)
894 fs_uniquifier = TextField(unique=True, null=False)
895 fs_webauthn_user_handle = TextField(unique=True, null=True)
896 username = TextField(unique=True, null=True)
897 security_number = IntegerField(null=True)
898 password = TextField(null=True)
899 last_login_at = DateTimeField(null=True)
900 current_login_at = DateTimeField(null=True)
901 tf_primary_method = TextField(null=True)
902 tf_totp_secret = TextField(null=True)
903 tf_phone_number = TextField(null=True)
904 mf_recovery_codes = AsaList(null=True)
905 us_totp_secrets = TextField(null=True)
906 us_phone_number = TextField(null=True, unique=True)
907 last_login_ip = TextField(null=True)
908 current_login_ip = TextField(null=True)
909 login_count = IntegerField(null=True)
910 active = BooleanField(default=True)
911 confirmed_at = DateTimeField(null=True)
912
913 def get_security_payload(self):
914 return {"email": str(self.email)}
915
916 class WebAuthn(WebAuthnMixin, db.Model):
917 credential_id = BlobField(unique=True, null=False, index=True)
918 public_key = BlobField(null=False)
919 sign_count = IntegerField(default=0)
920 transports = AsaList(null=True)
921
922 # a JSON string as returned from registration
923 extensions = TextField(null=True)
924 lastuse_datetime = DateTimeField(null=False)
925 # name is provided by user - we make sure is unique per user
926 name = TextField(null=False)
927 usage = TextField(null=False)
928 backup_state = BooleanField()
929 device_type = TextField(null=False)
930
931 # This creates a real column called user_id
932 user = ForeignKeyField(User, backref="webauthn")
933
934 class FsRefreshTracker(RefreshTrackerMixin, db.Model):
935 """Refresh Token Tracker"""
936
937 refresh_family = TextField(unique=True, null=False)
938 gen = IntegerField(default=1)
939 expires_at = DateTimeField(null=False)
940 revoked_at = DateTimeField(null=True)
941 last_used_at = DateTimeField(null=False)
942 name = TextField(null=False)
943 user = ForeignKeyField(User, backref="refresh_trackers")
944
945 class UserRoles(db.Model):
946 """Peewee does not have built-in many-to-many support, so we have to
947 create this mapping class to link users to roles."""
948
949 user = ForeignKeyField(User, backref="roles")
950 role = ForeignKeyField(Role, backref="users")
951 name = property(lambda self: self.role.name)
952 description = property(lambda self: self.role.description)
953
954 def get_permissions(self):
955 return self.role.get_permissions()
956
957 with app.app_context():
958 for Model in (Role, User, UserRoles, WebAuthn, FsRefreshTracker):
959 Model.drop_table()
960 Model.create_table()
961
962 def tear_down():
963 if realdburl:
964 db.close_db(None)
965 _teardown_realdb(db_info)
966 else:
967 db.close_db(None)
968 os.close(f)
969 os.remove(path)
970
971 return (
972 PeeweeUserDatastore(db, User, Role, UserRoles, WebAuthn, FsRefreshTracker),
973 tear_down,
974 )
975
976
977 @pytest.fixture()
978 def client(request, app, sqlalchemy_datastore):
979 app.security = Security(
980 app, datastore=sqlalchemy_datastore, **app.fs_constructor_args
981 )
982 populate_data(app)
983 return app.test_client(use_cookies=not app.config.get("TESTING_NO_COOKIES", False))
984
985
986 @pytest.fixture()
987 def client_nc(request, app, sqlalchemy_datastore):
988 # useful for testing token auth.
989 # No Cookies for You!
990 app.security = Security(app, datastore=sqlalchemy_datastore)
991 populate_data(app)
992 return app.test_client(use_cookies=False)
993
994
995 @pytest.fixture()
996 def signals():
997 """Tracks signal calls for testing purposes.
998
999 This sets up a receiver for all signals and tracks the data
1000 """
1001 from flask_security import signals
1002 import inspect
1003 import blinker
1004
1005 signal_calls = dict()
1006 def_signals = inspect.getmembers(
1007 signals, lambda v: isinstance(v, blinker.NamedSignal)
1008 )
1009
1010 for name, sig in def_signals:
1011 sc = signal_calls[name] = []
1012
1013 def _on(app, _sc=sc, **kwargs):
1014 assert isinstance(app, Flask)
1015 kwargs["request_endpoint"] = (
1016 flask_request.endpoint if flask_request else None
1017 )
1018 # user argument is an ORM structure so may not be available in a test
1019 # outside of the request - capture value(s) here
1020 user = kwargs.get("user", None)
1021 if user:
1022 assert isinstance(kwargs["user"], UserMixin)
1023 kwargs["user_email"] = user.email
1024 _sc.append(kwargs)
1025
1026 sig.connect(_on, weak=False)
1027 return signal_calls
1028
1029
1030 @pytest.fixture(
1031 params=[
1032 "cl-fsqlalchemy",
1033 "cl-sqla-session",
1034 "cl-mongo",
1035 "cl-peewee",
1036 "cl-fsqlalite",
1037 ]
1038 )
1039 def clients(request, app, tmpdir, realdburl, realmongodburl):
1040 if request.param == "cl-fsqlalchemy":
1041 ds, td = sqlalchemy_setup(app, tmpdir, realdburl)
1042 elif request.param == "cl-sqla-session":
1043 if sys.version_info < (3, 10):
1044 pytest.skip("requires python3.10 or higher")
1045 ds, td = sqlalchemy_session_setup(app, tmpdir, realdburl)
1046 elif request.param == "cl-mongo":
1047 ds, td = mongoengine_setup(app, tmpdir, realmongodburl)
1048 elif request.param == "cl-peewee":
1049 ds, td = peewee_setup(app, tmpdir, realdburl)
1050 elif request.param == "cl-fsqlalite":
1051 ds, td = fsqlalite_setup(app, tmpdir, realdburl)
1052
1053 app.security = Security(app, datastore=ds, **app.fs_constructor_args)
1054 populate_data(app)
1055 if request.param == "cl-peewee":
1056 # peewee is insistent on a single connection?
1057 ds.db.close_db(None)
1058 yield app.test_client(use_cookies=not app.config.get("TESTING_NO_COOKIES", False))
1059 td()
1060
1061
1062 @pytest.fixture()
1063 def in_app_context(request, app, sqlalchemy_datastore):
1064 app.security = Security(
1065 app, datastore=sqlalchemy_datastore, **app.fs_constructor_args
1066 )
1067 with app.app_context():
1068 yield app
1069
1070
1071 @pytest.fixture()
1072 def get_message(app: Flask) -> t.Callable[..., bytes]:
1073 def fn(key, **kwargs):
1074 rv = app.config["SECURITY_MSG_" + key][0] % kwargs
1075 return rv.encode("utf-8")
1076
1077 return fn
1078
1079
1080 @pytest.fixture()
1081 def get_message_local(app):
1082 def fn(key, **kwargs):
1083 return localize_callback(app.config["SECURITY_MSG_" + key][0], **kwargs)
1084
1085 return fn
1086
1087
1088 @pytest.fixture(
1089 params=[
1090 "sqlalchemy",
1091 "sqlalchemy-session",
1092 "mongoengine",
1093 "peewee",
1094 "fsqlalite",
1095 ]
1096 )
1097 def datastore(request, app, tmpdir, realdburl, realmongodburl):
1098 if request.param == "sqlalchemy":
1099 ds, td = sqlalchemy_setup(app, tmpdir, realdburl)
1100 elif request.param == "sqlalchemy-session":
1101 ds, td = sqlalchemy_session_setup(app, tmpdir, realdburl)
1102 elif request.param == "mongoengine":
1103 ds, td = mongoengine_setup(app, tmpdir, realmongodburl)
1104 elif request.param == "peewee":
1105 ds, td = peewee_setup(app, tmpdir, realdburl)
1106 elif request.param == "fsqlalite":
1107 ds, td = fsqlalite_setup(app, tmpdir, realdburl)
1108 yield ds
1109 td()
1110
1111
1112 @pytest.fixture()
1113 def script_info(app, datastore):
1114 from flask.cli import ScriptInfo
1115
1116 def create_app():
1117 uia = [
1118 {"email": {"mapper": uia_email_mapper}},
1119 {"us_phone_number": {"mapper": lambda x: x}},
1120 ]
1121
1122 app.config.update(**{"SECURITY_USER_IDENTITY_ATTRIBUTES": uia})
1123 app.security = Security(app, datastore=datastore)
1124 return app
1125
1126 return ScriptInfo(create_app=create_app)
1127
1128
1129 @pytest.fixture()
1130 def script_info_min(app, fsqlalite_min_datastore):
1131 from flask.cli import ScriptInfo
1132
1133 def create_app():
1134 app.security = Security(app, datastore=fsqlalite_min_datastore)
1135 return app
1136
1137 return ScriptInfo(create_app=create_app)
1138
1139
1140 def pytest_addoption(parser):
1141 parser.addoption(
1142 "--realdburl",
1143 action="store",
1144 default=None,
1145 help="""Set url for using real database for testing.
1146 For postgres: 'postgresql://user:password@host/')""",
1147 )
1148 parser.addoption(
1149 "--realmongodburl",
1150 action="store",
1151 default=None,
1152 help="""Set url for using real mongo database for testing.
1153 e.g. 'localhost'""",
1154 )
1155 parser.addoption(
1156 "--setting",
1157 default=None,
1158 action="append",
1159 help="""Set one or more SECURITY_ settings from command line.
1160 e.g. --setting anonymous_user_enable=False""",
1161 )
1162
1163
1164 @pytest.fixture(scope="session")
1165 def realdburl(request):
1166 """
1167 Support running datastore tests against a real DB.
1168 For example psycopg2 is very strict about types in queries
1169 compared to sqlite
1170 To use postgres you need to of course run a postgres instance on localhost
1171 then pass in an extra arg to pytest:
1172 --realdburl postgresql://<user>@localhost/
1173 For mysql same - just download and add a root password.
1174 --realdburl "mysql+pymysql://root:<password>@localhost/"
1175 """
1176 return request.config.option.realdburl
1177
1178
1179 @pytest.fixture(scope="session")
1180 def realmongodburl(request):
1181 """
1182 Support running datastore tests against a real Mongo DB.
1183 --realmongodburl "localhost"
1184
1185 """
1186 return request.config.option.realmongodburl
1187
1188
1189 def _setup_realdb(realdburl):
1190 """
1191 Called when we want to run unit tests against a real DB.
1192 This is useful since different DB drivers are pickier about queries etc.
1193 (such as pyscopg2 and postgres)
1194 """
1195 from sqlalchemy import create_engine
1196 from sqlalchemy_utils import database_exists, create_database
1197
1198 db_name = "flask_security_test_%s" % str(time.time()).replace(".", "_")
1199
1200 db_uri = realdburl + db_name
1201 engine = create_engine(db_uri)
1202 if not database_exists(engine.url):
1203 create_database(engine.url)
1204 print("Setting up real DB at " + db_uri)
1205 return db_uri, {"engine": engine}
1206
1207
1208 def _teardown_realdb(db_info):
1209 from sqlalchemy_utils import drop_database
1210
1211 drop_database(db_info["engine"].url)
1212
1213
1214 @pytest.fixture()
1215 def humanizer(request):
1216 pytest.importorskip("humanize")
1217 import humanize
1218
1219 if getattr(request, "param", None):
1220 humanize.i18n.activate(request.param)
1221 yield 1
1222 humanize.i18n.deactivate()
1223 else:
1224 yield 0