diff options
| author | Dennis Fink | 2026-11-13 19:22:33 +0100 |
|---|---|---|
| committer | Dennis Fink | 2026-11-13 19:22:33 +0100 |
| commit | 5c1eb15f00e20ece0a4ff8e7e1b4a5ab51e54232 (patch) | |
| tree | 04b442019424db67aa8ca23c5e652d12136f9fe7 | |
| parent | c421d269313d6623926954935a680fe4acb1dc86 (diff) | |
| download | webmentions-ssg-5c1eb15f00e20ece0a4ff8e7e1b4a5ab51e54232.tar.gz webmentions-ssg-5c1eb15f00e20ece0a4ff8e7e1b4a5ab51e54232.zip | |
refactor(core): simplify login password verification
Replace the module-level dummy user with a lazily cached password hash
so unknown usernames still perform a password check without hashing
during every import.
Use one linear verification path for existing, missing, and empty
passwords.
| -rw-r--r-- | tests/test_auth.py | 23 | ||||
| -rw-r--r-- | tests/views/test_session.py | 46 | ||||
| -rw-r--r-- | webmentions_ssg/auth.py | 9 | ||||
| -rw-r--r-- | webmentions_ssg/views/session.py | 16 |
4 files changed, 56 insertions, 38 deletions
diff --git a/tests/test_auth.py b/tests/test_auth.py index 34df8ce..e026e45 100644 --- a/tests/test_auth.py +++ b/tests/test_auth.py @@ -7,7 +7,7 @@ import pytest from flask import Flask -from webmentions_ssg import db +from webmentions_ssg import auth, db from webmentions_ssg.auth import AUTH, is_safe_next_url, load_user, validate_password from webmentions_ssg.models import User @@ -22,6 +22,27 @@ def test_user_loader_is_registered(app: Flask) -> None: assert AUTH._user_callback is load_user +def test_dummy_password_hash_is_lazily_cached( + monkeypatch: pytest.MonkeyPatch, +) -> None: + generated_passwords: list[str] = [] + + def fake_generate_password_hash(password: str) -> str: + generated_passwords.append(password) + return "dummy-hash" + + auth.dummy_password_hash.cache_clear() + try: + with monkeypatch.context() as patcher: + patcher.setattr(auth, "generate_password_hash", fake_generate_password_hash) + assert generated_passwords == [] + assert auth.dummy_password_hash() == "dummy-hash" + assert auth.dummy_password_hash() == "dummy-hash" + assert len(generated_passwords) == 1 + finally: + auth.dummy_password_hash.cache_clear() + + def test_load_user_returns_matching_user(app: Flask) -> None: with app.app_context(): user = User(username="account", password="secret") diff --git a/tests/views/test_session.py b/tests/views/test_session.py index 0c4de9f..d89f98e 100644 --- a/tests/views/test_session.py +++ b/tests/views/test_session.py @@ -140,51 +140,49 @@ def test_login_redirects_authenticated_user(app: Flask, client: FlaskClient) -> @pytest.mark.parametrize("username", ["admin", "unknown-user"]) +@pytest.mark.parametrize("password", ["wrong-password", None]) def test_login_always_checks_password( app: Flask, client: FlaskClient, views_module: ModuleType, monkeypatch: pytest.MonkeyPatch, username: str, + password: str | None, ) -> None: with app.app_context(): - db.session.add(User(username="admin", password="test")) + user = User(username="admin", password="test") + db.session.add(user) db.session.commit() + real_password_hash = user.password_hash mock_login_form( - views_module, - monkeypatch, - valid=True, - username=username, - password="wrong-password", + views_module, monkeypatch, valid=True, username=username, password=password ) - original_check_password = User.check_password - checked_users: list[User] = [] + original_check_password_hash = views_module.check_password_hash + checked_passwords: list[tuple[str, str]] = [] - def spy_check_password(self: User, password: str) -> bool: - checked_users.append(self) - return original_check_password(self, password) + def spy_check_password_hash(password_hash: str, password: str) -> bool: + checked_passwords.append((password_hash, password)) + return original_check_password_hash(password_hash, password) - monkeypatch.setattr(User, "check_password", spy_check_password) + monkeypatch.setattr(views_module, "check_password_hash", spy_check_password_hash) response = client.post("/login") assert response.status_code == 302 assert response.headers["Location"].endswith("/login") - assert len(checked_users) == 1 - - if username == "admin": - assert checked_users[0].username == "admin" - else: - assert checked_users[0] is views_module.DUMMY_USER + expected_hash = ( + real_password_hash if username == "admin" else views_module.dummy_password_hash() + ) + assert checked_passwords == [(expected_hash, password or "")] with client.session_transaction() as session: assert "_user_id" not in session assert ("danger", "Invalid username or password") in session["_flashes"] -def test_login_rejects_dummy_user_even_if_password_matches( +def test_login_rejects_unknown_user_even_if_password_matches( client: FlaskClient, views_module: ModuleType, monkeypatch: pytest.MonkeyPatch ) -> None: mock_login_form( @@ -195,19 +193,19 @@ def test_login_rejects_dummy_user_even_if_password_matches( password="anything", ) - checked_users: list[User] = [] + checked_passwords: list[tuple[str, str]] = [] - def mock_check_password(self: User, password: str) -> bool: - checked_users.append(self) + def mock_check_password_hash(password_hash: str, password: str) -> bool: + checked_passwords.append((password_hash, password)) return True - monkeypatch.setattr(User, "check_password", mock_check_password) + monkeypatch.setattr(views_module, "check_password_hash", mock_check_password_hash) response = client.post("/login") assert response.status_code == 302 assert response.headers["Location"].endswith("/login") - assert checked_users == [views_module.DUMMY_USER] + assert checked_passwords == [(views_module.dummy_password_hash(), "anything")] with client.session_transaction() as session: assert "_user_id" not in session diff --git a/webmentions_ssg/auth.py b/webmentions_ssg/auth.py index 6d4fe95..edfc858 100644 --- a/webmentions_ssg/auth.py +++ b/webmentions_ssg/auth.py @@ -6,12 +6,14 @@ import hashlib import secrets +from functools import cache from hmac import compare_digest from urllib.parse import urlsplit from flask import request from flask_limiter.util import get_remote_address from flask_login import LoginManager +from werkzeug.security import generate_password_hash from .extensions import db from .models import User @@ -23,8 +25,11 @@ AUTH.login_view = "root.login" # pyright: ignore[reportAttributeAccessIssue] MIN_PASSWORD_LENGTH = 8 -DUMMY_USER = User(username=secrets.token_urlsafe()) -DUMMY_USER.password = secrets.token_urlsafe() + +@cache +def dummy_password_hash() -> str: + """Lazily generate a reusable hash for unknown login usernames.""" + return generate_password_hash(secrets.token_urlsafe()) def validate_password(password: str) -> None: diff --git a/webmentions_ssg/views/session.py b/webmentions_ssg/views/session.py index b78fd13..870c967 100644 --- a/webmentions_ssg/views/session.py +++ b/webmentions_ssg/views/session.py @@ -8,9 +8,10 @@ import sqlalchemy as sa from flask import current_app, flash, redirect, render_template, request, url_for from flask.typing import ResponseReturnValue from flask_login import current_user, login_required, login_user, logout_user +from werkzeug.security import check_password_hash from .. import forms -from ..auth import DUMMY_USER, is_safe_next_url, login_username_limit_key +from ..auth import dummy_password_hash, is_safe_next_url, login_username_limit_key from ..extensions import db, limiter from ..models import User from .blueprint import root_page @@ -56,16 +57,9 @@ def login() -> ResponseReturnValue: sa.select(User).where(User.username == form.username.data) ) - user_exists = user is not None - - if user is None: - user = DUMMY_USER - - if ( - form.password.data is None - or not user.check_password(form.password.data) - or not user_exists - ): + password_hash = user.password_hash if user else dummy_password_hash() + password_ok = check_password_hash(password_hash, form.password.data or "") + if user is None or not password_ok: flash("Invalid username or password", "danger") return redirect(url_for("root.login")) login_user(user) |
