From acd1f42847786963fc4aaeed884c3091700c9e35 Mon Sep 17 00:00:00 2001 From: Dennis Fink Date: Tue, 17 Nov 2026 21:23:57 +0100 Subject: feat(core): add user account page Add an authenticated user page showing the current username and remote address, including guidance for validating reverse-proxy hop configuration. Allow users to change their own password through a CSRF-protected WTForms form while preserving the active session and invalidating other existing sessions. --- tests/forms/test_user.py | 83 +++++++++- tests/test_init.py | 30 +++- tests/views/test_user.py | 179 +++++++++++++++++++++ webmentions_ssg/forms/user.py | 37 ++++- .../ef8a9b6c2d41_received_status_history.py | 4 +- webmentions_ssg/templates/base.html | 2 + webmentions_ssg/templates/user.html | 35 ++++ webmentions_ssg/views/__init__.py | 12 +- webmentions_ssg/views/user.py | 39 +++++ 9 files changed, 406 insertions(+), 15 deletions(-) create mode 100644 tests/views/test_user.py create mode 100644 webmentions_ssg/templates/user.html create mode 100644 webmentions_ssg/views/user.py diff --git a/tests/forms/test_user.py b/tests/forms/test_user.py index 4b35a9a..216b0dc 100644 --- a/tests/forms/test_user.py +++ b/tests/forms/test_user.py @@ -6,7 +6,7 @@ import pytest from flask import Flask from werkzeug.datastructures import MultiDict -from webmentions_ssg.forms.user import LoginForm +from webmentions_ssg.forms.user import ChangePasswordForm, LoginForm @pytest.mark.parametrize( @@ -33,3 +33,84 @@ def test_login_form_accepts_credentials(app: Flask) -> None: meta={"csrf": False}, ) assert form.validate() + + +@pytest.mark.parametrize( + ("password", "error"), + [ + pytest.param("short", "at least 8 characters", id="too-short"), + pytest.param("valid\x00password", "control characters", id="control-character"), + ], +) +def test_change_password_form_uses_shared_password_policy( + app: Flask, password: str, error: str +) -> None: + with app.test_request_context("/user", method="POST"): + form = ChangePasswordForm( + formdata=MultiDict( + { + "current_password": "old password", + "new_password": password, + "confirm_password": password, + } + ), + meta={"csrf": False}, + ) + + assert not form.validate() + assert any(error in message for message in form.errors["new_password"]) + + +def test_change_password_form_rejects_mismatched_confirmation(app: Flask) -> None: + with app.test_request_context("/user", method="POST"): + form = ChangePasswordForm( + formdata=MultiDict( + { + "current_password": "old password", + "new_password": "new password", + "confirm_password": "different password", + } + ), + meta={"csrf": False}, + ) + + assert not form.validate() + assert "Passwords must match." in form.errors["confirm_password"] + + +@pytest.mark.parametrize( + "missing_field", ["current_password", "new_password", "confirm_password"] +) +def test_change_password_form_requires_all_fields( + app: Flask, missing_field: str +) -> None: + form_data = { + "current_password": "old password", + "new_password": "new password", + "confirm_password": "new password", + } + del form_data[missing_field] + with app.test_request_context("/user", method="POST"): + form = ChangePasswordForm(formdata=MultiDict(form_data), meta={"csrf": False}) + + assert not form.validate() + assert "This field is required." in form.errors[missing_field] + + +@pytest.mark.parametrize("password", [" ", "pāssword🐈"]) +def test_change_password_form_accepts_valid_unicode_and_whitespace_passwords( + app: Flask, password: str +) -> None: + with app.test_request_context("/user", method="POST"): + form = ChangePasswordForm( + formdata=MultiDict( + { + "current_password": "old password", + "new_password": password, + "confirm_password": password, + } + ), + meta={"csrf": False}, + ) + + assert form.validate() diff --git a/tests/test_init.py b/tests/test_init.py index cff42f9..8f2bbb7 100644 --- a/tests/test_init.py +++ b/tests/test_init.py @@ -56,7 +56,9 @@ def test_in_memory_sqlite_enforces_foreign_keys_without_wal(app: Flask) -> None: with app.app_context(): with db.engine.connect() as connection: assert connection.exec_driver_sql("PRAGMA foreign_keys").scalar() == 1 - assert connection.exec_driver_sql("PRAGMA journal_mode").scalar() == "memory" + assert ( + connection.exec_driver_sql("PRAGMA journal_mode").scalar() == "memory" + ) def test_file_sqlite_enables_wal_and_foreign_keys(tmp_path: Path) -> None: @@ -69,12 +71,16 @@ def test_file_sqlite_enables_wal_and_foreign_keys(tmp_path: Path) -> None: try: with db.engine.connect() as connection: assert connection.exec_driver_sql("PRAGMA foreign_keys").scalar() == 1 - assert connection.exec_driver_sql("PRAGMA journal_mode").scalar() == "wal" + assert ( + connection.exec_driver_sql("PRAGMA journal_mode").scalar() == "wal" + ) # Foreign-key enforcement must also apply to fresh pooled connections. db.engine.dispose() with db.engine.connect() as connection: assert connection.exec_driver_sql("PRAGMA foreign_keys").scalar() == 1 - assert connection.exec_driver_sql("PRAGMA journal_mode").scalar() == "wal" + assert ( + connection.exec_driver_sql("PRAGMA journal_mode").scalar() == "wal" + ) finally: db.engine.dispose() @@ -89,7 +95,9 @@ def test_sqlite_settings_apply_to_sqlite_binds(tmp_path: Path) -> None: try: with db.engines["archive"].connect() as connection: assert connection.exec_driver_sql("PRAGMA foreign_keys").scalar() == 1 - assert connection.exec_driver_sql("PRAGMA journal_mode").scalar() == "wal" + assert ( + connection.exec_driver_sql("PRAGMA journal_mode").scalar() == "wal" + ) finally: db.engines["archive"].dispose() db.engine.dispose() @@ -161,9 +169,15 @@ def test_in_memory_sqlite_skips_file_only_pragmas(tmp_path: Path) -> None: with app.app_context(): try: with db.engine.connect() as connection: - assert connection.exec_driver_sql("PRAGMA journal_mode").scalar() == "memory" + assert ( + connection.exec_driver_sql("PRAGMA journal_mode").scalar() + == "memory" + ) assert connection.exec_driver_sql("PRAGMA cache_size").scalar() == -4096 - assert connection.exec_driver_sql("PRAGMA wal_autocheckpoint").scalar() == 1000 + assert ( + connection.exec_driver_sql("PRAGMA wal_autocheckpoint").scalar() + == 1000 + ) finally: db.engine.dispose() @@ -178,7 +192,9 @@ def test_sqlite_pragma_settings_also_apply_to_binds(tmp_path: Path) -> None: with app.app_context(): try: with db.engines["archive"].connect() as connection: - assert connection.exec_driver_sql("PRAGMA busy_timeout").scalar() == 1234 + assert ( + connection.exec_driver_sql("PRAGMA busy_timeout").scalar() == 1234 + ) assert connection.exec_driver_sql("PRAGMA cache_size").scalar() == -2048 finally: db.engines["archive"].dispose() diff --git a/tests/views/test_user.py b/tests/views/test_user.py new file mode 100644 index 0000000..01db714 --- /dev/null +++ b/tests/views/test_user.py @@ -0,0 +1,179 @@ +# SPDX-FileCopyrightText: 2026 Dennis Fink +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Tests for the authenticated user page and password changes.""" + +import re +from http import HTTPStatus + +import pytest +from flask import Flask +from flask.testing import FlaskClient +from werkzeug.middleware.proxy_fix import ProxyFix + +from webmentions_ssg import db +from webmentions_ssg.models.user import User + +from .helpers import log_in + + +def password_data( + current: str = "test", + new: str = "a new longer password", + confirm: str | None = None, +) -> dict[str, str]: + return { + "current_password": current, + "new_password": new, + "confirm_password": new if confirm is None else confirm, + } + + +@pytest.mark.parametrize("method", ["get", "post"]) +def test_user_page_requires_login(client: FlaskClient, method: str) -> None: + response = getattr(client, method)("/user") + + assert response.status_code == HTTPStatus.FOUND + assert "/login?next=" in response.headers["Location"] + + +def test_user_page_shows_account_and_direct_remote_address( + app: Flask, client: FlaskClient +) -> None: + log_in(app, client) + + response = client.get( + "/user", + environ_overrides={"REMOTE_ADDR": "192.0.2.44"}, + headers={"X-Forwarded-For": "198.51.100.8"}, + ) + + assert response.status_code == HTTPStatus.OK + html = response.get_data(as_text=True) + assert "admin" in html + assert "192.0.2.44" in html + assert "198.51.100.8" not in html + assert "PROXY_FIX_TRUSTED_HOPS" in html + assert 'name="current_password"' in html + assert 'name="new_password"' in html + assert 'name="confirm_password"' in html + assert 'href="/user"' in html + + +def test_user_page_remote_address_respects_trusted_proxy( + app: Flask, client: FlaskClient +) -> None: + log_in(app, client) + app.config["PROXY_FIX_TRUSTED_HOPS"] = 1 + app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1) + + response = client.get( + "/user", + environ_overrides={"REMOTE_ADDR": "192.0.2.200"}, + headers={"X-Forwarded-For": "203.0.113.9, 198.51.100.27"}, + ) + + assert response.status_code == HTTPStatus.OK + html = response.get_data(as_text=True) + assert "198.51.100.27" in html + assert "203.0.113.9" not in html + assert "192.0.2.200" not in html + + +@pytest.mark.parametrize( + ("data", "message"), + [ + pytest.param( + password_data(current="wrong"), + "Current password is incorrect.", + id="wrong-current", + ), + pytest.param( + password_data(new="short"), "at least 8 characters", id="weak-new" + ), + pytest.param( + password_data(confirm="different"), "Passwords must match.", id="mismatch" + ), + pytest.param( + password_data(new="password\x7f"), "control characters", id="invalid-new" + ), + ], +) +def test_password_change_rejects_invalid_input( + app: Flask, client: FlaskClient, data: dict[str, str], message: str +) -> None: + log_in(app, client) + with client.session_transaction() as session: + old_session_id = session["_user_id"] + + response = client.post("/user", data=data) + + assert response.status_code == HTTPStatus.OK + assert message in response.get_data(as_text=True) + with client.session_transaction() as session: + assert session["_user_id"] == old_session_id + with app.app_context(): + user = db.session.get(User, 1) + assert user is not None + assert user.check_password("test") + assert not user.check_password(data["new_password"]) + + +def test_password_change_refreshes_own_session_and_revokes_other_sessions( + app: Flask, client: FlaskClient +) -> None: + log_in(app, client) + with client.session_transaction() as session: + old_session_id = session["_user_id"] + + other_client = app.test_client() + with other_client.session_transaction() as session: + session["_user_id"] = old_session_id + session["_fresh"] = True + assert other_client.get("/user").status_code == HTTPStatus.OK + + response = client.post("/user", data=password_data()) + + assert response.status_code == HTTPStatus.FOUND + assert response.headers["Location"] == "/user" + with client.session_transaction() as session: + assert session["_user_id"] != old_session_id + new_session_id = session["_user_id"] + + with app.app_context(): + user = db.session.get(User, 1) + assert user is not None + assert user.check_password("a new longer password") + assert not user.check_password("test") + assert user.get_id() == new_session_id + + page = client.get("/user") + assert page.status_code == HTTPStatus.OK + assert "Password changed successfully." in page.get_data(as_text=True) + assert other_client.get("/user").status_code == HTTPStatus.FOUND + + +def test_password_change_requires_csrf(app: Flask, client: FlaskClient) -> None: + app.config["WTF_CSRF_ENABLED"] = True + log_in(app, client) + + response = client.post("/user", data=password_data()) + assert response.status_code == HTTPStatus.BAD_REQUEST + + page = client.get("/user") + assert page.status_code == HTTPStatus.OK + match = re.search( + r'name="csrf_token"\s+value="([^"]+)"', page.get_data(as_text=True) + ) + assert match is not None + + response = client.post( + "/user", data={**password_data(), "csrf_token": match.group(1)} + ) + assert response.status_code == HTTPStatus.FOUND + + with app.app_context(): + user = db.session.get(User, 1) + assert user is not None + assert user.check_password("a new longer password") diff --git a/webmentions_ssg/forms/user.py b/webmentions_ssg/forms/user.py index 3bb6421..ae1736d 100644 --- a/webmentions_ssg/forms/user.py +++ b/webmentions_ssg/forms/user.py @@ -2,11 +2,13 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""User authentication forms.""" +"""User authentication and password-change forms.""" from flask_wtf import FlaskForm from wtforms import PasswordField, StringField, SubmitField -from wtforms.validators import InputRequired +from wtforms.validators import EqualTo, InputRequired, ValidationError + +from ..auth import validate_new_password class LoginForm(FlaskForm): @@ -15,3 +17,34 @@ class LoginForm(FlaskForm): username = StringField("Username", validators=[InputRequired()]) password = PasswordField("Password", validators=[InputRequired()]) submit = SubmitField("Sign In") + + +class ChangePasswordForm(FlaskForm): + """Verify the existing password and validate a replacement.""" + + current_password = PasswordField( + "Current password", + validators=[InputRequired()], + render_kw={"autocomplete": "current-password"}, + ) + new_password = PasswordField( + "New password", + validators=[InputRequired()], + render_kw={"autocomplete": "new-password"}, + ) + confirm_password = PasswordField( + "Confirm new password", + validators=[ + InputRequired(), + EqualTo("new_password", message="Passwords must match."), + ], + render_kw={"autocomplete": "new-password"}, + ) + submit = SubmitField("Change password") + + def validate_new_password(self, field: PasswordField) -> None: + """Apply the same password policy as the user-management CLI.""" + try: + validate_new_password(field.data or "") + except ValueError as exc: + raise ValidationError(str(exc)) from exc diff --git a/webmentions_ssg/migrations/versions/ef8a9b6c2d41_received_status_history.py b/webmentions_ssg/migrations/versions/ef8a9b6c2d41_received_status_history.py index db63011..92b8d25 100644 --- a/webmentions_ssg/migrations/versions/ef8a9b6c2d41_received_status_history.py +++ b/webmentions_ssg/migrations/versions/ef8a9b6c2d41_received_status_history.py @@ -40,9 +40,7 @@ def upgrade(): sa.Column("recovery_attempts", sa.Integer(), nullable=False), sa.Column("occurred_at", sa.DateTime(timezone=True), nullable=False), sa.ForeignKeyConstraint( - ["webmention_uuid"], - ["received_webmentions.uuid"], - ondelete="CASCADE", + ["webmention_uuid"], ["received_webmentions.uuid"], ondelete="CASCADE" ), ) op.create_index( diff --git a/webmentions_ssg/templates/base.html b/webmentions_ssg/templates/base.html index c7af077..4fffb38 100644 --- a/webmentions_ssg/templates/base.html +++ b/webmentions_ssg/templates/base.html @@ -49,6 +49,8 @@ SPDX-License-Identifier: BSD-3-Clause href="{{ url_for('webmentions.moderation') }}">Source rules Sent + User
diff --git a/webmentions_ssg/templates/user.html b/webmentions_ssg/templates/user.html new file mode 100644 index 0000000..ecd5ba9 --- /dev/null +++ b/webmentions_ssg/templates/user.html @@ -0,0 +1,35 @@ + +{% extends "base.html" %} + +{% set title = "User" %} +{% from "bootstrap5/form.html" import render_form %} + +{% block content %} +

User

+
+

Account

+
+
Username
+
+ {{ current_user.username }} +
+
Remote address
+
+ {{ remote_address or "Unavailable" }} +
+
+

+ The remote address is the client IP seen by the application for this request. + If it shows your reverse proxy instead, check the + PROXY_FIX_TRUSTED_HOPS configuration. +

+
+
+

Change password

+
{{ render_form(form) }}
+
+{% endblock %} diff --git a/webmentions_ssg/views/__init__.py b/webmentions_ssg/views/__init__.py index cdf024a..a4954b6 100644 --- a/webmentions_ssg/views/__init__.py +++ b/webmentions_ssg/views/__init__.py @@ -4,7 +4,15 @@ """Collect and expose the routes for the blueprint.""" -from . import endpoint, moderation, received, session, sources +from . import endpoint, moderation, received, session, sources, user from .blueprint import webmentions_bp -__all__ = ["endpoint", "moderation", "received", "session", "sources", "webmentions_bp"] +__all__ = [ + "endpoint", + "moderation", + "received", + "session", + "sources", + "user", + "webmentions_bp", +] diff --git a/webmentions_ssg/views/user.py b/webmentions_ssg/views/user.py new file mode 100644 index 0000000..4675ade --- /dev/null +++ b/webmentions_ssg/views/user.py @@ -0,0 +1,39 @@ +# SPDX-FileCopyrightText: 2026 Dennis Fink +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Authenticated user account page.""" + +from typing import cast + +from flask import flash, redirect, render_template, request, url_for +from flask.typing import ResponseReturnValue +from flask_login import current_user, login_required, login_user + +from ..extensions import db +from ..forms.user import ChangePasswordForm +from ..models.user import User +from .blueprint import webmentions_bp + + +@webmentions_bp.route("/user", methods=["GET", "POST"]) +@login_required +def user_page() -> ResponseReturnValue: + """Display account details and let the signed-in user change their password.""" + form = ChangePasswordForm() + + if form.validate_on_submit(): + user = cast(User, current_user._get_current_object()) + if not user.check_password(form.current_password.data or ""): + form.current_password.errors.append("Current password is incorrect.") + else: + user.password = form.new_password.data or "" + db.session.commit() + + # Password changes revoke all old session identifiers. Refresh this + # session with the new fingerprint so the user stays signed in. + login_user(user) + flash("Password changed successfully.", "success") + return redirect(url_for("webmentions.user_page")) + + return render_template("user.html", form=form, remote_address=request.remote_addr) -- cgit v1.3.1