diff --git a/shelfmark/core/self_user_routes.py b/shelfmark/core/self_user_routes.py index 83e0124c..a3f88f70 100644 --- a/shelfmark/core/self_user_routes.py +++ b/shelfmark/core/self_user_routes.py @@ -1,11 +1,12 @@ """Self-service user account routes.""" import sqlite3 +from dataclasses import dataclass from functools import wraps from typing import TYPE_CHECKING, Any from flask import Flask, Response, g, jsonify, request, session -from werkzeug.security import generate_password_hash +from werkzeug.security import check_password_hash, generate_password_hash from shelfmark.core.admin_settings_routes import ( build_user_notification_test_response, @@ -37,6 +38,20 @@ if TYPE_CHECKING: logger = setup_logger(__name__) MIN_PASSWORD_LENGTH = 4 + + +@dataclass(frozen=True) +class PasswordAttemptLimiter: + """The login lockout, lent to the password change so it cannot be used to guess a password. + + ``record_failure`` returns True when the account is now locked. + """ + + is_locked: Callable[[str], bool] + record_failure: Callable[[str], bool] + clear: Callable[[str], None] + + _VISIBLE_SELF_SETTINGS_SECTIONS_KEY = "VISIBLE_SELF_SETTINGS_SECTIONS" _SELF_SETTINGS_SECTION_DELIVERY = "delivery" _SELF_SETTINGS_SECTION_SEARCH = "search" @@ -177,7 +192,49 @@ def _get_allowed_self_settings_keys(visible_sections: list[str]) -> set[str]: return allowed_keys -def register_self_user_routes(app: Flask, user_db: UserDB) -> None: +def _check_current_password( + user: Mapping[str, Any], + current_password: object, + attempts: PasswordAttemptLimiter | None, +) -> tuple[Response, int] | None: + """An error response unless ``current_password`` is the user's password. + + A wrong guess counts toward the same lockout as a failed login. + """ + username = str(user.get("username") or "") + if attempts is not None and attempts.is_locked(username): + return jsonify( + { + "error": "Too many failed attempts", + "message": "This account is locked for a while after too many wrong passwords.", + } + ), 429 + stored_hash = user.get("password_hash") + if ( + not isinstance(current_password, str) + or not current_password + or not isinstance(stored_hash, str) + or not check_password_hash(stored_hash, current_password) + ): + if attempts is not None: + attempts.record_failure(username) + return jsonify( + { + "error": "Current password is incorrect", + "message": "Enter your current password to set a new one.", + } + ), 400 + if attempts is not None: + attempts.clear(username) + return None + + +def register_self_user_routes( + app: Flask, + user_db: UserDB, + *, + password_attempts: PasswordAttemptLimiter | None = None, +) -> None: """Register self-service user endpoints.""" def _require_authenticated_user( @@ -303,6 +360,8 @@ def register_self_user_routes(app: Flask, user_db: UserDB) -> None: password = data.get("password", "") password_hash: str | None = None if password: + if not isinstance(password, str): + return jsonify({"error": "Password must be a string"}), 400 if not capabilities["canSetPassword"]: return jsonify( { @@ -314,6 +373,11 @@ def register_self_user_routes(app: Flask, user_db: UserDB) -> None: return jsonify( {"error": f"Password must be at least {MIN_PASSWORD_LENGTH} characters"} ), 400 + current_error = _check_current_password( + user, data.get("current_password"), password_attempts + ) + if current_error is not None: + return current_error password_hash = generate_password_hash(password) user_fields: dict[str, Any] = {} diff --git a/shelfmark/main.py b/shelfmark/main.py index 422cc244..e48aa20a 100644 --- a/shelfmark/main.py +++ b/shelfmark/main.py @@ -214,11 +214,23 @@ try: import_module("shelfmark.config.users_settings") from shelfmark.core.admin_routes import register_admin_routes from shelfmark.core.oidc_routes import register_oidc_routes - from shelfmark.core.self_user_routes import register_self_user_routes + from shelfmark.core.self_user_routes import ( + PasswordAttemptLimiter, + register_self_user_routes, + ) register_oidc_routes(app, user_db) register_admin_routes(app, user_db) - register_self_user_routes(app, user_db) + register_self_user_routes( + app, + user_db, + # Looked up when called: the lockout helpers are defined further down this module. + password_attempts=PasswordAttemptLimiter( + is_locked=lambda username: is_account_locked(username), # noqa: PLW0108 + record_failure=lambda username: record_failed_login(username, get_client_ip()), + clear=lambda username: clear_failed_logins(username), # noqa: PLW0108 + ), + ) except (sqlite3.OperationalError, OSError) as e: logger.warning( "User database initialization failed: %s. Multi-user authentication features will be disabled. Ensure CONFIG_DIR (%s) exists and is writable.", diff --git a/src/frontend/src/components/settings/SelfSettingsModal.tsx b/src/frontend/src/components/settings/SelfSettingsModal.tsx index 138546b9..7d59d06c 100644 --- a/src/frontend/src/components/settings/SelfSettingsModal.tsx +++ b/src/frontend/src/components/settings/SelfSettingsModal.tsx @@ -33,7 +33,11 @@ interface SelfSettingsModalProps { const MIN_PASSWORD_LENGTH = 4; -const getPasswordError = (password: string, passwordConfirm: string): string | null => { +const getPasswordError = ( + password: string, + passwordConfirm: string, + currentPassword: string, +): string | null => { if (!password && !passwordConfirm) { return null; } @@ -43,6 +47,9 @@ const getPasswordError = (password: string, passwordConfirm: string): string | n if (password.length < MIN_PASSWORD_LENGTH) { return `Password must be at least ${MIN_PASSWORD_LENGTH} characters`; } + if (!currentPassword) { + return 'Current password is required'; + } return password === passwordConfirm ? null : 'Passwords do not match'; }; @@ -121,6 +128,7 @@ const SelfSettingsModalSession = ({ const [editPassword, setEditPassword] = useState(''); const [editPasswordConfirm, setEditPasswordConfirm] = useState(''); + const [editCurrentPassword, setEditCurrentPassword] = useState(''); const [themeValue, setThemeValue] = useState(getStoredThemePreference()); @@ -157,6 +165,7 @@ const SelfSettingsModalSession = ({ }); setEditPassword(''); setEditPasswordConfirm(''); + setEditCurrentPassword(''); } catch (error) { setLoadError(getErrorMessage(error, 'Failed to load account settings')); } finally { @@ -185,7 +194,7 @@ const SelfSettingsModalSession = ({ ); const hasPasswordChanges = editPassword.length > 0 || editPasswordConfirm.length > 0; - const passwordError = getPasswordError(editPassword, editPasswordConfirm); + const passwordError = getPasswordError(editPassword, editPasswordConfirm, editCurrentPassword); const hasChanges = hasSettingsChanges || hasProfileChanges || hasPasswordChanges; const handleTestNotificationRoutes = useCallback((routes: Array>) => { @@ -205,6 +214,7 @@ const SelfSettingsModalSession = ({ email?: string | null; display_name?: string | null; password?: string; + current_password?: string; settings?: Record; } = {}; @@ -219,6 +229,7 @@ const SelfSettingsModalSession = ({ } if (editingUser.edit_capabilities.canSetPassword && editPassword) { payload.password = editPassword; + payload.current_password = editCurrentPassword; } if (hasSettingsChanges) { payload.settings = currentSettingsPayload; @@ -249,6 +260,7 @@ const SelfSettingsModalSession = ({ originalUser, passwordError, editPassword, + editCurrentPassword, ]); if (!isOpen && !isClosing) { @@ -359,6 +371,8 @@ const SelfSettingsModalSession = ({ onEditPasswordChange={setEditPassword} editPasswordConfirm={editPasswordConfirm} onEditPasswordConfirmChange={setEditPasswordConfirm} + editCurrentPassword={editCurrentPassword} + onEditCurrentPasswordChange={setEditCurrentPassword} preferencesPlacement="after" preferencesPanel={{ hideTitle: true, diff --git a/src/frontend/src/components/settings/users/UserCard.tsx b/src/frontend/src/components/settings/users/UserCard.tsx index d6fde5c2..d49976d9 100644 --- a/src/frontend/src/components/settings/users/UserCard.tsx +++ b/src/frontend/src/components/settings/users/UserCard.tsx @@ -446,6 +446,9 @@ interface UserEditFieldsProps { onEditPasswordChange: (value: string) => void; editPasswordConfirm: string; onEditPasswordConfirmChange: (value: string) => void; + /** Self-service only: the current password, asked for when a new one is typed. */ + editCurrentPassword?: string; + onEditCurrentPasswordChange?: (value: string) => void; onDelete?: () => void; onConfirmDelete?: () => void; onCancelDelete?: () => void; @@ -464,6 +467,8 @@ const UserEditFields = ({ onEditPasswordChange, editPasswordConfirm, onEditPasswordConfirmChange, + editCurrentPassword = '', + onEditCurrentPasswordChange, onDelete, onConfirmDelete, onCancelDelete, @@ -480,6 +485,13 @@ const UserEditFields = ({ 'Display name', ); const emailField = createTextField('email', 'Email', user.email || '', 'user@example.com'); + const currentPasswordField = createPasswordField( + 'current_password', + 'Current Password', + editCurrentPassword, + 'Required to set a new password', + true, + ); const newPasswordField = createPasswordField( 'new_password', 'New Password', @@ -530,6 +542,14 @@ const UserEditFields = ({ <> {renderPasswordField(newPasswordField, editPassword, onEditPasswordChange)} + {editPassword && + onEditCurrentPasswordChange && + renderPasswordField( + currentPasswordField, + editCurrentPassword, + onEditCurrentPasswordChange, + )} + {editPassword && renderPasswordField( confirmPasswordField, @@ -604,6 +624,8 @@ export const UserAccountCardContent = ({ onEditPasswordChange, editPasswordConfirm, onEditPasswordConfirmChange, + editCurrentPassword, + onEditCurrentPasswordChange, onDelete, onConfirmDelete, onCancelDelete, @@ -634,6 +656,8 @@ export const UserAccountCardContent = ({ onEditPasswordChange={onEditPasswordChange} editPasswordConfirm={editPasswordConfirm} onEditPasswordConfirmChange={onEditPasswordConfirmChange} + editCurrentPassword={editCurrentPassword} + onEditCurrentPasswordChange={onEditCurrentPasswordChange} onDelete={onDelete} onConfirmDelete={onConfirmDelete} onCancelDelete={onCancelDelete} diff --git a/src/frontend/src/services/api.ts b/src/frontend/src/services/api.ts index e621d86b..77f55bec 100644 --- a/src/frontend/src/services/api.ts +++ b/src/frontend/src/services/api.ts @@ -1066,6 +1066,7 @@ export const getSelfUserEditContext = async (): Promise => export const updateSelfUser = async ( data: Partial> & { password?: string; + current_password?: string; settings?: Record; }, ): Promise => { diff --git a/tests/core/test_self_user_routes.py b/tests/core/test_self_user_routes.py index c03ba5b2..0c95bf70 100644 --- a/tests/core/test_self_user_routes.py +++ b/tests/core/test_self_user_routes.py @@ -7,8 +7,9 @@ from unittest.mock import patch import pytest from flask import Flask +from werkzeug.security import check_password_hash, generate_password_hash -from shelfmark.core.self_user_routes import register_self_user_routes +from shelfmark.core.self_user_routes import PasswordAttemptLimiter, register_self_user_routes from shelfmark.core.user_db import UserDB @@ -245,10 +246,11 @@ def test_users_me_update_rejects_oidc_email_change(app, user_db): def test_users_me_update_keeps_password_and_profile_when_settings_rejected(app, user_db): + old_hash = generate_password_hash("oldpass99") user = user_db.create_user( username="alice", display_name="Alice Old", - password_hash="old_hash", + password_hash=old_hash, ) client = _authed_client_for_user(app, user) @@ -261,6 +263,7 @@ def test_users_me_update_keeps_password_and_profile_when_settings_rejected(app, "/api/users/me", json={ "password": "newpass99", + "current_password": "oldpass99", "display_name": "Alice New", "settings": { "USER_NOTIFICATION_ROUTES": [ @@ -274,15 +277,16 @@ def test_users_me_update_keeps_password_and_profile_when_settings_rejected(app, assert resp.json["error"] == "Some settings are admin-only" stored = user_db.get_user(user_id=user["id"]) - assert stored["password_hash"] == "old_hash" + assert stored["password_hash"] == old_hash assert stored["display_name"] == "Alice Old" def test_users_me_update_applies_password_profile_and_settings_together(app, user_db): + old_hash = generate_password_hash("oldpass99") user = user_db.create_user( username="alice", display_name="Alice Old", - password_hash="old_hash", + password_hash=old_hash, ) client = _authed_client_for_user(app, user) @@ -295,6 +299,7 @@ def test_users_me_update_applies_password_profile_and_settings_together(app, use "/api/users/me", json={ "password": "newpass99", + "current_password": "oldpass99", "display_name": "Alice New", "settings": {"DESTINATION": "/books/alice"}, }, @@ -303,6 +308,147 @@ def test_users_me_update_applies_password_profile_and_settings_together(app, use assert resp.status_code == 200 stored = user_db.get_user(user_id=user["id"]) - assert stored["password_hash"] != "old_hash" + assert stored["password_hash"] != old_hash + assert check_password_hash(stored["password_hash"], "newpass99") assert stored["display_name"] == "Alice New" assert user_db.get_user_settings(user["id"])["DESTINATION"] == "/books/alice" + + +def _put_password(client, payload): + with patch("shelfmark.core.self_user_routes.load_active_auth_mode", return_value="builtin"): + return client.put("/api/users/me", json=payload) + + +def _user_with_password(user_db, password="oldpass99"): + return user_db.create_user(username="alice", password_hash=generate_password_hash(password)) + + +def _stored_password_still(user_db, user, password): + return check_password_hash(user_db.get_user(user_id=user["id"])["password_hash"], password) + + +def test_a_new_password_needs_the_current_one(app, user_db): + user = _user_with_password(user_db) + client = _authed_client_for_user(app, user) + + resp = _put_password(client, {"password": "newpass99"}) + + assert resp.status_code == 400 + assert resp.json["error"] == "Current password is incorrect" + assert _stored_password_still(user_db, user, "oldpass99") + + +def test_a_wrong_current_password_changes_nothing(app, user_db): + user = _user_with_password(user_db) + client = _authed_client_for_user(app, user) + + resp = _put_password(client, {"password": "newpass99", "current_password": "guess"}) + + assert resp.status_code == 400 + assert _stored_password_still(user_db, user, "oldpass99") + assert not _stored_password_still(user_db, user, "newpass99") + + +def test_the_right_current_password_sets_the_new_one(app, user_db): + user = _user_with_password(user_db) + client = _authed_client_for_user(app, user) + + resp = _put_password(client, {"password": "newpass99", "current_password": "oldpass99"}) + + assert resp.status_code == 200 + assert _stored_password_still(user_db, user, "newpass99") + assert not _stored_password_still(user_db, user, "oldpass99") + + +@pytest.mark.parametrize("password", [12345, ["newpass99"], {"a": 1}, True]) +def test_a_password_that_is_not_a_string_is_refused(app, user_db, password): + user = _user_with_password(user_db) + client = _authed_client_for_user(app, user) + + resp = _put_password(client, {"password": password, "current_password": "oldpass99"}) + + assert resp.status_code == 400 + assert _stored_password_still(user_db, user, "oldpass99") + + +@pytest.mark.parametrize("current", [12345, ["oldpass99"], None, ""]) +def test_a_current_password_that_is_not_a_string_is_refused(app, user_db, current): + user = _user_with_password(user_db) + client = _authed_client_for_user(app, user) + + resp = _put_password(client, {"password": "newpass99", "current_password": current}) + + assert resp.status_code == 400 + assert _stored_password_still(user_db, user, "oldpass99") + + +def test_a_profile_change_without_a_password_needs_no_current_password(app, user_db): + user = _user_with_password(user_db) + client = _authed_client_for_user(app, user) + + resp = _put_password(client, {"display_name": "Alice"}) + + assert resp.status_code == 200 + assert _stored_password_still(user_db, user, "oldpass99") + + +class _Attempts: + """Stands in for the login lockout and remembers what it was asked.""" + + def __init__(self, locked=False): + self.locked = locked + self.failures = [] + self.cleared = [] + + def limiter(self): + return PasswordAttemptLimiter( + is_locked=lambda username: self.locked, + record_failure=lambda username: self.failures.append(username) or False, + clear=self.cleared.append, + ) + + +@pytest.fixture +def limited_app(user_db): + def _make(attempts): + test_app = Flask(__name__) + test_app.config["SECRET_KEY"] = "test-secret" + test_app.config["TESTING"] = True + register_self_user_routes(test_app, user_db, password_attempts=attempts.limiter()) + return test_app + + return _make + + +def test_a_wrong_current_password_counts_toward_the_login_lockout(limited_app, user_db): + attempts = _Attempts() + user = _user_with_password(user_db) + client = _authed_client_for_user(limited_app(attempts), user) + + _put_password(client, {"password": "newpass99", "current_password": "guess"}) + + assert attempts.failures == ["alice"] + assert attempts.cleared == [] + + +def test_a_locked_account_cannot_try_a_current_password(limited_app, user_db): + attempts = _Attempts(locked=True) + user = _user_with_password(user_db) + client = _authed_client_for_user(limited_app(attempts), user) + + resp = _put_password(client, {"password": "newpass99", "current_password": "oldpass99"}) + + assert resp.status_code == 429 + assert _stored_password_still(user_db, user, "oldpass99") + assert attempts.failures == [] + + +def test_the_right_current_password_clears_the_failures(limited_app, user_db): + attempts = _Attempts() + user = _user_with_password(user_db) + client = _authed_client_for_user(limited_app(attempts), user) + + resp = _put_password(client, {"password": "newpass99", "current_password": "oldpass99"}) + + assert resp.status_code == 200 + assert attempts.cleared == ["alice"]