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