quart-security 2.1.1__tar.gz → 2.2.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. {quart_security-2.1.1 → quart_security-2.2.1}/PKG-INFO +8 -3
  2. {quart_security-2.1.1 → quart_security-2.2.1}/README.md +7 -2
  3. {quart_security-2.1.1 → quart_security-2.2.1}/pyproject.toml +1 -1
  4. {quart_security-2.1.1 → quart_security-2.2.1}/quart_security/__init__.py +2 -1
  5. {quart_security-2.1.1 → quart_security-2.2.1}/quart_security/breach.py +4 -0
  6. {quart_security-2.1.1 → quart_security-2.2.1}/quart_security/decorators.py +17 -2
  7. {quart_security-2.1.1 → quart_security-2.2.1}/quart_security/password.py +32 -7
  8. {quart_security-2.1.1 → quart_security-2.2.1}/quart_security/utils.py +15 -0
  9. {quart_security-2.1.1 → quart_security-2.2.1}/quart_security/views.py +37 -17
  10. {quart_security-2.1.1 → quart_security-2.2.1}/LICENSE +0 -0
  11. {quart_security-2.1.1 → quart_security-2.2.1}/quart_security/core.py +0 -0
  12. {quart_security-2.1.1 → quart_security-2.2.1}/quart_security/datastore.py +0 -0
  13. {quart_security-2.1.1 → quart_security-2.2.1}/quart_security/email.py +0 -0
  14. {quart_security-2.1.1 → quart_security-2.2.1}/quart_security/forms.py +0 -0
  15. {quart_security-2.1.1 → quart_security-2.2.1}/quart_security/models.py +0 -0
  16. {quart_security-2.1.1 → quart_security-2.2.1}/quart_security/proxies.py +0 -0
  17. {quart_security-2.1.1 → quart_security-2.2.1}/quart_security/py.typed +0 -0
  18. {quart_security-2.1.1 → quart_security-2.2.1}/quart_security/signals.py +0 -0
  19. {quart_security-2.1.1 → quart_security-2.2.1}/quart_security/state.py +0 -0
  20. {quart_security-2.1.1 → quart_security-2.2.1}/quart_security/templates/security/_macros.html +0 -0
  21. {quart_security-2.1.1 → quart_security-2.2.1}/quart_security/templates/security/change_password.html +0 -0
  22. {quart_security-2.1.1 → quart_security-2.2.1}/quart_security/templates/security/confirm_email.html +0 -0
  23. {quart_security-2.1.1 → quart_security-2.2.1}/quart_security/templates/security/email/confirmation_instructions.txt +0 -0
  24. {quart_security-2.1.1 → quart_security-2.2.1}/quart_security/templates/security/email/register_conflict.txt +0 -0
  25. {quart_security-2.1.1 → quart_security-2.2.1}/quart_security/templates/security/email/reset_instructions.txt +0 -0
  26. {quart_security-2.1.1 → quart_security-2.2.1}/quart_security/templates/security/email/reset_notice.txt +0 -0
  27. {quart_security-2.1.1 → quart_security-2.2.1}/quart_security/templates/security/forgot_password.html +0 -0
  28. {quart_security-2.1.1 → quart_security-2.2.1}/quart_security/templates/security/login_user.html +0 -0
  29. {quart_security-2.1.1 → quart_security-2.2.1}/quart_security/templates/security/mf_recovery.html +0 -0
  30. {quart_security-2.1.1 → quart_security-2.2.1}/quart_security/templates/security/mf_recovery_codes.html +0 -0
  31. {quart_security-2.1.1 → quart_security-2.2.1}/quart_security/templates/security/register_user.html +0 -0
  32. {quart_security-2.1.1 → quart_security-2.2.1}/quart_security/templates/security/reset_password.html +0 -0
  33. {quart_security-2.1.1 → quart_security-2.2.1}/quart_security/templates/security/send_confirmation.html +0 -0
  34. {quart_security-2.1.1 → quart_security-2.2.1}/quart_security/templates/security/two_factor_select.html +0 -0
  35. {quart_security-2.1.1 → quart_security-2.2.1}/quart_security/templates/security/two_factor_setup.html +0 -0
  36. {quart_security-2.1.1 → quart_security-2.2.1}/quart_security/templates/security/two_factor_verify_code.html +0 -0
  37. {quart_security-2.1.1 → quart_security-2.2.1}/quart_security/templates/security/wan_register.html +0 -0
  38. {quart_security-2.1.1 → quart_security-2.2.1}/quart_security/templates/security/wan_signin.html +0 -0
  39. {quart_security-2.1.1 → quart_security-2.2.1}/quart_security/templates/security/wan_verify.html +0 -0
  40. {quart_security-2.1.1 → quart_security-2.2.1}/quart_security/totp.py +0 -0
  41. {quart_security-2.1.1 → quart_security-2.2.1}/quart_security/webauthn.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: quart-security
3
- Version: 2.1.1
3
+ Version: 2.2.1
4
4
  Summary: Native async auth for Quart
5
5
  Author: quart-security maintainers
6
6
  Requires-Python: >=3.11
@@ -143,6 +143,11 @@ These fields are required when login or MFA lockout is enabled. The built-in
143
143
  counter limits account-level guesses. Deploy an application or edge rate limiter
144
144
  for source IP and distributed abuse controls.
145
145
 
146
+ Emails are normalized with `normalize_email` (Unicode NFC, internationalized
147
+ domains decoded, lowercased) before every lookup and on registration; store
148
+ them the same way. Passwords are NFKD-normalized before hashing, so the same
149
+ password typed in composed or decomposed Unicode is one secret.
150
+
146
151
  The database must enforce unique normalized emails, `fs_uniquifier` values,
147
152
  WebAuthn user handles, and credential IDs. Use a stable primary key separate from
148
153
  `fs_uniquifier`: this value changes when security settings change.
@@ -174,7 +179,7 @@ Password reset and email confirmation:
174
179
  - `SECURITY_RESET_PASSWORD_WITHIN` (default: 1 hour)
175
180
  - `SECURITY_CONFIRM_EMAIL_WITHIN` (default: 1 day)
176
181
 
177
- Existing pbkdf2_sha512 and bcrypt hashes continue to verify after the argon2 default change. They are transparently rehashed to argon2id on the user's next successful login.
182
+ Existing pbkdf2_sha512 and bcrypt hashes continue to verify after the argon2 default change. bcrypt hashes are checked against the first 72 bytes of the password, as bcrypt always did. They are transparently rehashed to argon2id on the user's next successful login.
178
183
 
179
184
  Until then, a failed login for an account with a legacy hash takes a different time than one for an unknown email, which is checked against an argon2id dummy, so timing can reveal that the account exists. Apps that import hashes from another system should require a password reset rather than leave them in place.
180
185
 
@@ -205,7 +210,7 @@ Routing:
205
210
  - `SECURITY_POST_LOGIN_VIEW`
206
211
  - `SECURITY_POST_REGISTER_VIEW`
207
212
 
208
- A visit to `/login?next=/path` sends the user to `/path` after they sign in, through 2FA and passkey sign-in too. Only same-site paths are honored, the next visit to `/login` replaces the target, and a sign-in finishing more than 10 minutes after the form was shown ignores it.
213
+ A visit to `/login?next=/path` sends the user to `/path` after they sign in, through 2FA and passkey sign-in too. `auth_required` sends the page that was asked for. Only same-site paths are honored, the next visit to `/login` replaces the target, and a sign-in finishing more than 10 minutes after the form was shown ignores it.
209
214
 
210
215
  Registration answers the same way whether or not the email already has an account. For an existing email nothing is created and `user_register_conflict` fires with the existing user. On its own that is not enough: someone can register an email and try to sign in with the password they chose, which works only if the account is new. Turn on `SECURITY_CONFIRMABLE` to close that gap.
211
216
 
@@ -113,6 +113,11 @@ These fields are required when login or MFA lockout is enabled. The built-in
113
113
  counter limits account-level guesses. Deploy an application or edge rate limiter
114
114
  for source IP and distributed abuse controls.
115
115
 
116
+ Emails are normalized with `normalize_email` (Unicode NFC, internationalized
117
+ domains decoded, lowercased) before every lookup and on registration; store
118
+ them the same way. Passwords are NFKD-normalized before hashing, so the same
119
+ password typed in composed or decomposed Unicode is one secret.
120
+
116
121
  The database must enforce unique normalized emails, `fs_uniquifier` values,
117
122
  WebAuthn user handles, and credential IDs. Use a stable primary key separate from
118
123
  `fs_uniquifier`: this value changes when security settings change.
@@ -144,7 +149,7 @@ Password reset and email confirmation:
144
149
  - `SECURITY_RESET_PASSWORD_WITHIN` (default: 1 hour)
145
150
  - `SECURITY_CONFIRM_EMAIL_WITHIN` (default: 1 day)
146
151
 
147
- Existing pbkdf2_sha512 and bcrypt hashes continue to verify after the argon2 default change. They are transparently rehashed to argon2id on the user's next successful login.
152
+ Existing pbkdf2_sha512 and bcrypt hashes continue to verify after the argon2 default change. bcrypt hashes are checked against the first 72 bytes of the password, as bcrypt always did. They are transparently rehashed to argon2id on the user's next successful login.
148
153
 
149
154
  Until then, a failed login for an account with a legacy hash takes a different time than one for an unknown email, which is checked against an argon2id dummy, so timing can reveal that the account exists. Apps that import hashes from another system should require a password reset rather than leave them in place.
150
155
 
@@ -175,7 +180,7 @@ Routing:
175
180
  - `SECURITY_POST_LOGIN_VIEW`
176
181
  - `SECURITY_POST_REGISTER_VIEW`
177
182
 
178
- A visit to `/login?next=/path` sends the user to `/path` after they sign in, through 2FA and passkey sign-in too. Only same-site paths are honored, the next visit to `/login` replaces the target, and a sign-in finishing more than 10 minutes after the form was shown ignores it.
183
+ A visit to `/login?next=/path` sends the user to `/path` after they sign in, through 2FA and passkey sign-in too. `auth_required` sends the page that was asked for. Only same-site paths are honored, the next visit to `/login` replaces the target, and a sign-in finishing more than 10 minutes after the form was shown ignores it.
179
184
 
180
185
  Registration answers the same way whether or not the email already has an account. For an existing email nothing is created and `user_register_conflict` fires with the existing user. On its own that is not enough: someone can register an email and try to sign in with the password they chose, which works only if the account is new. Turn on `SECURITY_CONFIRMABLE` to close that gap.
181
186
 
@@ -4,7 +4,7 @@ build-backend = "flit_core.buildapi"
4
4
 
5
5
  [project]
6
6
  name = "quart-security"
7
- version = "2.1.1"
7
+ version = "2.2.1"
8
8
  description = "Native async auth for Quart"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.11"
@@ -20,7 +20,7 @@ from .signals import (
20
20
  user_registered,
21
21
  )
22
22
  from .state import SecurityState, SQLAlchemyStateStore
23
- from .utils import url_for_security
23
+ from .utils import normalize_email, url_for_security
24
24
 
25
25
  __all__ = [
26
26
  "Security",
@@ -43,4 +43,5 @@ __all__ = [
43
43
  "user_registered",
44
44
  "user_register_conflict",
45
45
  "url_for_security",
46
+ "normalize_email",
46
47
  ]
@@ -7,6 +7,8 @@ import logging
7
7
 
8
8
  import httpx2
9
9
 
10
+ from .password import normalize_password
11
+
10
12
  logger = logging.getLogger(__name__)
11
13
 
12
14
  _HIBP_URL = "https://api.pwnedpasswords.com/range/{prefix}"
@@ -24,6 +26,8 @@ async def password_is_breached(password: str, *, count_min: int = 1) -> bool | N
24
26
  False - password not found in response.
25
27
  None - network/HTTP error; caller should fail-open (allow the password).
26
28
  """
29
+ # Check the secret that gets hashed, not the typed form of it.
30
+ password = normalize_password(password)
27
31
  sha1 = (
28
32
  hashlib.sha1(password.encode("utf-8"), usedforsecurity=False)
29
33
  .hexdigest()
@@ -3,6 +3,7 @@
3
3
  import datetime
4
4
  import time
5
5
  from functools import wraps
6
+ from urllib.parse import quote
6
7
 
7
8
  from quart import abort, current_app, redirect, request, session
8
9
 
@@ -10,6 +11,15 @@ from .proxies import current_user
10
11
  from .utils import url_for_security
11
12
 
12
13
 
14
+ def _is_navigation():
15
+ # Only a page visit may pick where login goes next: an EventSource or XHR
16
+ # that outlived its session would otherwise hand its URL to the next login.
17
+ mode = request.headers.get("Sec-Fetch-Mode")
18
+ if mode and mode != "navigate":
19
+ return False
20
+ return "Accept" not in request.headers or request.accept_mimetypes.accept_html
21
+
22
+
13
23
  def auth_required(*methods, fresh=False):
14
24
  """Require an authenticated user for a route."""
15
25
 
@@ -21,9 +31,14 @@ def auth_required(*methods, fresh=False):
21
31
  @wraps(func)
22
32
  async def wrapper(*args, **kwargs):
23
33
  if not current_user.is_authenticated:
24
- if request.is_json:
34
+ if request.is_json or not _is_navigation():
25
35
  abort(401)
26
- return redirect(url_for_security("login", next=request.url))
36
+ # A path, not request.url: login only follows same-site paths.
37
+ # request.path is decoded; quote it so "%23" stays in the path.
38
+ target = quote(request.script_root + request.path)
39
+ if request.query_string:
40
+ target += "?" + request.query_string.decode()
41
+ return redirect(url_for_security("login", next=target))
27
42
  if fresh:
28
43
  freshness = current_app.config.get(
29
44
  "SECURITY_FRESHNESS", datetime.timedelta(minutes=60)
@@ -2,8 +2,10 @@
2
2
 
3
3
  import asyncio
4
4
  import secrets
5
+ import unicodedata
5
6
 
6
7
  from passlib.context import CryptContext
8
+ from passlib.exc import PasswordSizeError
7
9
  from quart import current_app
8
10
 
9
11
  # OWASP 2025 minimum argon2id parameters
@@ -50,19 +52,42 @@ def _password_config(app=None):
50
52
  return (app or current_app).extensions["quart_security_password"]
51
53
 
52
54
 
55
+ def normalize_password(password: str) -> str:
56
+ # The same password typed through different keyboards or pasted can arrive
57
+ # composed or decomposed; NFKD makes them one secret.
58
+ return unicodedata.normalize("NFKD", password)
59
+
60
+
61
+ def _secret(password: str, scheme: str | None) -> str | bytes:
62
+ # bcrypt only ever used the first 72 bytes; bcrypt 5 raises on more.
63
+ return password.encode()[:72] if scheme == "bcrypt" else password
64
+
65
+
53
66
  def hash_password(password: str, *, app=None) -> str:
54
67
  context, _salt = _password_config(app)
55
- return context.hash(password)
68
+ return context.hash(_secret(normalize_password(password), context.default_scheme()))
56
69
 
57
70
 
58
71
  def verify_password(password: str, password_hash: str, *, app=None) -> bool:
59
72
  context, salt = _password_config(app)
60
- if context.verify(password, password_hash):
61
- return True
62
- # Optional fallback for deployments that previously mixed in app salt.
73
+ scheme = context.identify(password_hash)
74
+ candidates = [normalize_password(password)]
75
+ if candidates[0] != password:
76
+ candidates.append(password) # hashed before passwords were normalized
63
77
  if salt:
64
- return context.verify(f"{password}{salt}", password_hash)
65
- return False
78
+ # Optional fallback for deployments that previously mixed in app salt.
79
+ candidates += [f"{c}{salt}" for c in candidates]
80
+ return any(
81
+ _verifies(context, _secret(c, scheme), password_hash) for c in candidates
82
+ )
83
+
84
+
85
+ def _verifies(context, secret, password_hash) -> bool:
86
+ try:
87
+ return context.verify(secret, password_hash)
88
+ except PasswordSizeError:
89
+ # NFKD can push a password that was hashed raw past passlib's limit.
90
+ return False
66
91
 
67
92
 
68
93
  def password_needs_rehash(password_hash: str, *, app=None) -> bool:
@@ -96,6 +121,6 @@ async def unknown_user_hash_async(*, app=None) -> str:
96
121
 
97
122
  def validate_password(password: str, min_length: int = 12) -> list[str]:
98
123
  errors: list[str] = []
99
- if len(password) < min_length:
124
+ if len(normalize_password(password)) < min_length:
100
125
  errors.append(f"Password must be at least {min_length} characters")
101
126
  return errors
@@ -4,7 +4,9 @@ from __future__ import annotations
4
4
 
5
5
  import datetime
6
6
  import inspect
7
+ import unicodedata
7
8
 
9
+ from email_validator import EmailNotValidError, validate_email
8
10
  from quart import url_for
9
11
 
10
12
 
@@ -20,6 +22,19 @@ async def maybe_await(value):
20
22
  return value
21
23
 
22
24
 
25
+ def normalize_email(value: str | None) -> str:
26
+ """One form per mailbox: lowercased, Unicode NFC, IDNA domains decoded.
27
+
28
+ Lowercasing first keeps it idempotent: lowering an NFC string can leave one
29
+ that is not NFC.
30
+ """
31
+ value = unicodedata.normalize("NFC", (value or "").strip().lower())
32
+ try:
33
+ return validate_email(value, check_deliverability=False).normalized
34
+ except EmailNotValidError:
35
+ return value # not an address; it can only fail to match one
36
+
37
+
23
38
  def naive_utcnow() -> datetime.datetime:
24
39
  """Return a naive UTC datetime while avoiding utcnow() deprecations."""
25
40
  return datetime.datetime.now(datetime.UTC).replace(tzinfo=None)
@@ -50,7 +50,7 @@ from .signals import (
50
50
  user_register_conflict,
51
51
  user_registered,
52
52
  )
53
- from .utils import maybe_await, naive_utcnow, url_for_security
53
+ from .utils import maybe_await, naive_utcnow, normalize_email, url_for_security
54
54
 
55
55
  security_bp = Blueprint("security", __name__, template_folder="templates")
56
56
 
@@ -59,10 +59,6 @@ def _is_post() -> bool:
59
59
  return request.method == "POST"
60
60
 
61
61
 
62
- def _normalize_email(value: str | None) -> str:
63
- return (value or "").strip().lower()
64
-
65
-
66
62
  def _resolve_redirect(config_key: str, fallback_endpoint: str) -> str:
67
63
  value = current_app.config.get(config_key)
68
64
  if isinstance(value, str) and value:
@@ -275,6 +271,20 @@ async def _password_errors(password: str) -> list[str]:
275
271
  return errors
276
272
 
277
273
 
274
+ def _needs_second_factor(user) -> bool:
275
+ return bool(
276
+ current_app.config.get("SECURITY_TWO_FACTOR")
277
+ and getattr(user, "tf_primary_method", None)
278
+ )
279
+
280
+
281
+ async def _start_second_factor(user):
282
+ session["tf_user_id"] = await _security.state_store.put(
283
+ {"user_id": user.get_id()}, ttl=300
284
+ )
285
+ return redirect(url_for_security("two_factor_token_validation"))
286
+
287
+
278
288
  def _awaiting_confirmation(user) -> bool:
279
289
  return bool(
280
290
  current_app.config.get("SECURITY_CONFIRMABLE")
@@ -494,7 +504,7 @@ async def login():
494
504
  session.pop("security_next", None)
495
505
 
496
506
  if _is_post() and form.validate():
497
- user = await _find_user(email=_normalize_email(form.email.data))
507
+ user = await _find_user(email=normalize_email(form.email.data))
498
508
 
499
509
  # A locked account fails like a wrong password, after the same work: a
500
510
  # distinct "locked" answer would only ever appear for real accounts.
@@ -525,13 +535,8 @@ async def login():
525
535
  user.password = await hash_password_async(form.password.data)
526
536
  await _commit()
527
537
 
528
- if current_app.config.get("SECURITY_TWO_FACTOR") and getattr(
529
- user, "tf_primary_method", None
530
- ):
531
- session["tf_user_id"] = await _security.state_store.put(
532
- {"user_id": user.get_id()}, ttl=300
533
- )
534
- return redirect(url_for_security("two_factor_token_validation"))
538
+ if _needs_second_factor(user):
539
+ return await _start_second_factor(user)
535
540
 
536
541
  await _reset_auth_failures(user)
537
542
  return await _complete_login(user)
@@ -562,7 +567,7 @@ async def register():
562
567
  await _enforce_csrf(getattr(form, "_submitted_csrf", None))
563
568
 
564
569
  if _is_post() and form.validate():
565
- email = _normalize_email(form.email.data)
570
+ email = normalize_email(form.email.data)
566
571
  # Password checks come first and an existing email gets the same answer as
567
572
  # a new one, after the same hashing work, so the form never reveals which
568
573
  # emails have an account.
@@ -655,7 +660,7 @@ async def forgot_password():
655
660
 
656
661
  if _is_post() and form.validate():
657
662
  raw, link = _new_link("reset_password")
658
- _defer(_reset_job, _normalize_email(form.email.data), raw, link)
663
+ _defer(_reset_job, normalize_email(form.email.data), raw, link)
659
664
  await flash(
660
665
  "If an account uses that email, a link to reset its password is on"
661
666
  " its way.",
@@ -775,7 +780,7 @@ async def send_confirmation():
775
780
 
776
781
  if _is_post() and form.validate():
777
782
  raw, link = _new_link("confirm_email")
778
- _defer(_send_confirmation_job, _normalize_email(form.email.data), raw, link)
783
+ _defer(_send_confirmation_job, normalize_email(form.email.data), raw, link)
779
784
  await flash(
780
785
  "If that email is waiting to be confirmed, a new link is on its way.",
781
786
  "info",
@@ -1384,7 +1389,12 @@ async def wan_signin_response():
1384
1389
  await flash("Unable to identify user from passkey.", "error")
1385
1390
  return redirect(url_for_security("wan_signin"))
1386
1391
 
1387
- if not getattr(user, "active", True):
1392
+ # Same gates as a password login; one message, as there.
1393
+ if (
1394
+ not getattr(user, "active", True)
1395
+ or _account_is_locked(user)
1396
+ or _awaiting_confirmation(user)
1397
+ ):
1388
1398
  await flash("Unable to find user for passkey sign-in.", "error")
1389
1399
  return redirect(url_for_security("wan_signin"))
1390
1400
  if user_handle and user_handle != user.fs_webauthn_user_handle:
@@ -1417,6 +1427,16 @@ async def wan_signin_response():
1417
1427
  if hasattr(stored_credential, "lastuse_datetime"):
1418
1428
  stored_credential.lastuse_datetime = naive_utcnow()
1419
1429
 
1430
+ # A passkey replaces the second factor only when it proved the user too
1431
+ # (user verification) and the app allows that.
1432
+ config = current_app.config
1433
+ if _needs_second_factor(user) and not (
1434
+ config.get("SECURITY_WAN_REQUIRE_USER_VERIFICATION", True)
1435
+ and config.get("SECURITY_WAN_ALLOW_AS_MULTI_FACTOR", True)
1436
+ ):
1437
+ await _commit()
1438
+ return await _start_second_factor(user)
1439
+
1420
1440
  return await _complete_login(user)
1421
1441
 
1422
1442
 
File without changes