aboutsummaryrefslogtreecommitdiff
path: root/tests
diff options
context:
space:
mode:
Diffstat (limited to 'tests')
-rw-r--r--tests/forms/test_user.py83
-rw-r--r--tests/test_init.py30
-rw-r--r--tests/views/test_user.py179
3 files changed, 284 insertions, 8 deletions
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 <me+coding@dennisfink.me>
+#
+# 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")