aboutsummaryrefslogtreecommitdiff
path: root/tests/views/test_session.py
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--tests/views/test_session.py431
1 files changed, 431 insertions, 0 deletions
diff --git a/tests/views/test_session.py b/tests/views/test_session.py
new file mode 100644
index 0000000..6a96032
--- /dev/null
+++ b/tests/views/test_session.py
@@ -0,0 +1,431 @@
+# SPDX-FileCopyrightText: 2026 Dennis Fink <me+coding@dennisfink.me>
+#
+# SPDX-License-Identifier: BSD-3-Clause
+
+from types import ModuleType
+
+import pytest
+from flask import Flask
+from flask.testing import FlaskClient
+
+from webmentions_ssg import DATABASE as db
+from webmentions_ssg.models import User
+
+from .helpers import log_in, mock_login_form
+
+
+@pytest.fixture
+def views_module(app: Flask) -> ModuleType:
+ _ = app
+ from webmentions_ssg.views import session as module
+
+ return module
+
+
+def test_login_renders_form(client: FlaskClient) -> None:
+ response = client.get("/login")
+
+ assert response.status_code == 200
+ assert "login" in response.get_data(as_text=True).lower()
+
+
+@pytest.mark.parametrize("password", ("wrong-password", None))
+def test_login_rejects_invalid_credentials(
+ app: Flask,
+ client: FlaskClient,
+ views_module: ModuleType,
+ monkeypatch: pytest.MonkeyPatch,
+ password: str | None,
+) -> None:
+ with app.app_context():
+ db.session.add(User(username="admin", password="test"))
+ db.session.commit()
+
+ mock_login_form(
+ views_module, monkeypatch, valid=True, username="admin", password=password
+ )
+
+ response = client.post("/login")
+
+ assert response.status_code == 302
+ assert response.headers["Location"].endswith("/login")
+
+ with client.session_transaction() as session:
+ assert "_user_id" not in session
+ assert ("danger", "Invalid username or password") in session["_flashes"]
+
+
+@pytest.mark.parametrize(
+ "next_url",
+ [
+ pytest.param("/", id="root"),
+ pytest.param("/received", id="local-path"),
+ pytest.param("/received?page=2", id="query-string"),
+ pytest.param("/received#details", id="fragment"),
+ ],
+)
+def test_login_redirects_to_local_next_page(
+ app: Flask,
+ client: FlaskClient,
+ views_module: ModuleType,
+ monkeypatch: pytest.MonkeyPatch,
+ next_url: str,
+) -> None:
+ with app.app_context():
+ user = User(username="admin", password="test")
+ db.session.add(user)
+ db.session.commit()
+ user_id = user.get_id()
+
+ mock_login_form(views_module, monkeypatch, valid=True)
+
+ response = client.post("/login", query_string={"next": next_url})
+
+ assert response.status_code == 302
+ assert response.headers["Location"] == next_url
+
+ with client.session_transaction() as session:
+ assert session["_user_id"] == str(user_id)
+
+
+@pytest.mark.parametrize(
+ "next_url",
+ [
+ pytest.param(None, id="missing"),
+ pytest.param("", id="empty"),
+ pytest.param("received", id="relative-path"),
+ pytest.param("https://evil.example/phishing", id="absolute-https"),
+ pytest.param("http://evil.example", id="absolute-http"),
+ pytest.param("javascript:alert(1)", id="non-http-scheme"),
+ pytest.param("//evil.example/phishing", id="scheme-relative"),
+ pytest.param("///evil.example/phishing", id="triple-slash"),
+ pytest.param("////evil.example", id="four-slashes"),
+ pytest.param(r"/\evil.example", id="slash-backslash-host"),
+ pytest.param(r"/received\evil.example", id="backslash-in-path"),
+ pytest.param(r"\/evil.example", id="backslash-slash-host"),
+ ],
+)
+def test_login_rejects_unsafe_next_page(
+ app: Flask,
+ client: FlaskClient,
+ views_module: ModuleType,
+ monkeypatch: pytest.MonkeyPatch,
+ next_url: str | None,
+) -> None:
+ with app.app_context():
+ user = User(username="admin", password="test")
+ db.session.add(user)
+ db.session.commit()
+ user_id = user.get_id()
+
+ mock_login_form(views_module, monkeypatch, valid=True)
+
+ query_string = {} if next_url is None else {"next": next_url}
+ response = client.post("/login", query_string=query_string)
+
+ assert response.status_code == 302
+ assert response.headers["Location"] == "/"
+
+ with client.session_transaction() as session:
+ assert session["_user_id"] == str(user_id)
+
+
+def test_login_redirects_authenticated_user(app: Flask, client: FlaskClient) -> None:
+ log_in(app, client)
+
+ response = client.get("/login")
+
+ assert response.status_code == 302
+ assert response.headers["Location"].endswith("/")
+
+
+@pytest.mark.parametrize("username", ["admin", "unknown-user"])
+def test_login_always_checks_password(
+ app: Flask,
+ client: FlaskClient,
+ views_module: ModuleType,
+ monkeypatch: pytest.MonkeyPatch,
+ username: str,
+) -> None:
+ with app.app_context():
+ db.session.add(User(username="admin", password="test"))
+ db.session.commit()
+
+ mock_login_form(
+ views_module,
+ monkeypatch,
+ valid=True,
+ username=username,
+ password="wrong-password",
+ )
+
+ original_check_password = User.check_password
+ checked_users: list[User] = []
+
+ def spy_check_password(self: User, password: str) -> bool:
+ checked_users.append(self)
+ return original_check_password(self, password)
+
+ monkeypatch.setattr(User, "check_password", spy_check_password)
+
+ 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
+
+ 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(
+ client: FlaskClient, views_module: ModuleType, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ mock_login_form(
+ views_module,
+ monkeypatch,
+ valid=True,
+ username="unknown-user",
+ password="anything",
+ )
+
+ checked_users: list[User] = []
+
+ def mock_check_password(self: User, password: str) -> bool:
+ checked_users.append(self)
+ return True
+
+ monkeypatch.setattr(User, "check_password", mock_check_password)
+
+ response = client.post("/login")
+
+ assert response.status_code == 302
+ assert response.headers["Location"].endswith("/login")
+ assert checked_users == [views_module.DUMMY_USER]
+
+ with client.session_transaction() as session:
+ assert "_user_id" not in session
+
+
+def test_login_rate_limit_is_independent_per_ip(
+ app: Flask,
+ client: FlaskClient,
+ views_module: ModuleType,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ app.config["LOGIN_RATE_LIMIT"] = "1/minute"
+
+ mock_login_form(
+ views_module,
+ monkeypatch,
+ valid=True,
+ username="unknown-user",
+ password="wrong-password",
+ )
+
+ def attempt(ip: str) -> int:
+ response = client.post("/login", environ_overrides={"REMOTE_ADDR": ip})
+ return response.status_code
+
+ assert attempt("192.0.2.10") == 302
+ assert attempt("192.0.2.10") == 429
+
+ # Another IP still has its own allowance.
+ assert attempt("192.0.2.11") == 302
+ assert attempt("192.0.2.11") == 429
+
+
+def test_login_rate_limit_uses_forwarded_client_ip_when_proxy_is_trusted(
+ app: Flask,
+ client: FlaskClient,
+ views_module: ModuleType,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from werkzeug.middleware.proxy_fix import ProxyFix
+
+ app.config["LOGIN_RATE_LIMIT"] = "1/minute"
+ app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1)
+ mock_login_form(
+ views_module,
+ monkeypatch,
+ valid=True,
+ username="unknown-user",
+ password="wrong-password",
+ )
+
+ def attempt(client_ip: str) -> int:
+ response = client.post(
+ "/login",
+ environ_overrides={"REMOTE_ADDR": "192.0.2.200"},
+ headers={"X-Forwarded-For": client_ip},
+ )
+ return response.status_code
+
+ assert attempt("198.51.100.11") == 302
+ # A forged earlier X-Forwarded-For entry cannot change the client bucket.
+ assert attempt("203.0.113.99, 198.51.100.11") == 429
+ assert attempt("198.51.100.12") == 302
+
+
+def test_login_username_limit_throttles_across_ips(
+ app: Flask,
+ client: FlaskClient,
+ views_module: ModuleType,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ app.config["LOGIN_RATE_LIMIT"] = "100/minute"
+ app.config["LOGIN_USERNAME_RATE_LIMIT"] = "2/minute"
+
+ with monkeypatch.context() as patcher:
+ mock_login_form(
+ views_module,
+ patcher,
+ valid=True,
+ username="unknown-user",
+ password="wrong-password",
+ )
+
+ def attempt(ip: str, username: str) -> int:
+ return client.post(
+ "/login",
+ data={"username": username, "password": "wrong-password"},
+ environ_overrides={"REMOTE_ADDR": ip},
+ ).status_code
+
+ assert attempt("192.0.2.10", "Admin") == 302
+ assert attempt("192.0.2.11", " admin ") == 302
+ assert attempt("192.0.2.12", "ADMIN") == 429
+ # An unrelated username is not locked by attempts against Admin.
+ assert attempt("192.0.2.12", "another-user") == 302
+
+ # Restore the real form: the POST-only limits must not block a GET,
+ # even from the client IP that submitted the throttled attempt.
+ response = client.get("/login", environ_overrides={"REMOTE_ADDR": "192.0.2.12"})
+ assert response.status_code == 200
+
+
+def test_login_missing_username_uses_per_ip_bucket(
+ app: Flask,
+ client: FlaskClient,
+ views_module: ModuleType,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ app.config["LOGIN_RATE_LIMIT"] = "100/minute"
+ app.config["LOGIN_USERNAME_RATE_LIMIT"] = "1/minute"
+ mock_login_form(
+ views_module,
+ monkeypatch,
+ valid=True,
+ username="unknown-user",
+ password="wrong-password",
+ )
+
+ def attempt(ip: str) -> int:
+ return client.post("/login", environ_overrides={"REMOTE_ADDR": ip}).status_code
+
+ assert attempt("192.0.2.10") == 302
+ assert attempt("192.0.2.10") == 429
+ assert attempt("192.0.2.11") == 302
+
+
+def test_login_rate_limits_requests_per_ip(
+ app: Flask,
+ client: FlaskClient,
+ views_module: ModuleType,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ app.config["LOGIN_RATE_LIMIT"] = "2/minute"
+
+ with monkeypatch.context() as patcher:
+ form = mock_login_form(
+ views_module,
+ patcher,
+ valid=True,
+ username="unknown-user",
+ password="wrong-password",
+ )
+
+ responses = [
+ client.post("/login", environ_overrides={"REMOTE_ADDR": "192.0.2.10"})
+ for _ in range(3)
+ ]
+
+ assert [response.status_code for response in responses] == [302, 302, 429]
+ assert form.validate_on_submit.call_count == 2
+ assert "Too many login attempts" in responses[-1].get_data(as_text=True)
+
+ # The real LoginForm is restored here.
+ # GET requests must remain accessible after throttling.
+ response = client.get("/login", environ_overrides={"REMOTE_ADDR": "192.0.2.10"})
+ assert response.status_code == 200
+
+ with client.session_transaction() as session:
+ assert "_user_id" not in session
+
+
+def test_logout_rejects_get(app: Flask, client: FlaskClient) -> None:
+ log_in(app, client)
+
+ response = client.get("/logout")
+
+ assert response.status_code == 405
+
+ with client.session_transaction() as session:
+ assert "_user_id" in session
+
+
+@pytest.mark.parametrize(
+ "data",
+ [
+ pytest.param({}, id="missing"),
+ pytest.param({"csrf_token": "invalid"}, id="invalid"),
+ ],
+)
+def test_logout_rejects_invalid_csrf(
+ app: Flask, client: FlaskClient, data: dict[str, str]
+) -> None:
+ app.config["WTF_CSRF_ENABLED"] = True
+ log_in(app, client)
+
+ response = client.post("/logout", data=data)
+
+ assert response.status_code == 400
+
+ with client.session_transaction() as session:
+ assert "_user_id" in session
+
+
+def test_logout_ends_session(app: Flask, client: FlaskClient) -> None:
+ import re
+
+ app.config["WTF_CSRF_ENABLED"] = True
+ log_in(app, client)
+
+ page = client.get("/received")
+ assert page.status_code == 200
+
+ html = page.get_data(as_text=True)
+
+ assert 'action="/logout"' in html
+ assert 'method="post"' in html
+
+ match = re.search(r'name="csrf_token"\s+value="([^"]+)"', html)
+ assert match is not None
+
+ response = client.post("/logout", data={"csrf_token": match.group(1)})
+
+ assert response.status_code == 302
+ assert response.headers["Location"].endswith("/")
+
+ with client.session_transaction() as session:
+ assert "_user_id" not in session
+
+ protected_response = client.get("/received")
+ assert protected_response.status_code == 302
+ assert "/login" in protected_response.headers["Location"]