diff options
| author | Dennis Fink | 2026-10-30 08:11:05 +0100 |
|---|---|---|
| committer | Dennis Fink | 2026-10-30 08:11:05 +0100 |
| commit | 9f093cf07a3531ee4b7d02c20151e21c141a93de (patch) | |
| tree | dc39b1586dd6599bd09e95f3dd463a0f64c2de3f | |
| parent | edd7c0c2220ba12c2a773f9ba1cf6e0e7a273856 (diff) | |
| download | webmentions-ssg-9f093cf07a3531ee4b7d02c20151e21c141a93de.tar.gz webmentions-ssg-9f093cf07a3531ee4b7d02c20151e21c141a93de.zip | |
fix(core): harden authentication flows
Reduce login abuse and username enumeration by rate limiting POST
attempts and always performing password verification, even for unknown
users.
Require authenticated, CSRF-protected POST requests for logout so
sessions cannot be terminated through cross-site or accidental GET
requests.
| -rw-r--r-- | tests/test_views.py | 212 | ||||
| -rw-r--r-- | webmentions_ssg/config.py | 2 | ||||
| -rw-r--r-- | webmentions_ssg/templates/base.html | 5 | ||||
| -rw-r--r-- | webmentions_ssg/views.py | 25 |
4 files changed, 226 insertions, 18 deletions
diff --git a/tests/test_views.py b/tests/test_views.py index ed944c9..f8dd375 100644 --- a/tests/test_views.py +++ b/tests/test_views.py @@ -486,19 +486,6 @@ def test_login_redirects_authenticated_user(app: Flask, client: FlaskClient) -> assert response.headers["Location"].endswith("/") -def test_logout_ends_session(app: Flask, client: FlaskClient) -> None: - log_in(app, client) - - response = client.get("/logout") - - assert response.status_code == 302 - assert response.headers["Location"].endswith("/") - - protected_response = client.get("/received") - assert protected_response.status_code == 302 - assert "/login" in protected_response.headers["Location"] - - def test_received_requires_login(client: FlaskClient) -> None: response = client.get("/received") @@ -932,3 +919,202 @@ def test_endpoint_reverifies_after_cooldown( assert stored.failure_reason is None verify.assert_called_once_with(identifier) + + +@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_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"] diff --git a/webmentions_ssg/config.py b/webmentions_ssg/config.py index 010e393..2661704 100644 --- a/webmentions_ssg/config.py +++ b/webmentions_ssg/config.py @@ -43,6 +43,8 @@ class DefaultConfig: ENDPOINT_GLOBAL_RATE_LIMIT = "1000/hour" ENDPOINT_REVERIFY_COOLDOWN_SECONDS = 600 + LOGIN_RATE_LIMIT = "5/minute;30/hour" + class DevelopmentConfig(DefaultConfig): DEBUG = True diff --git a/webmentions_ssg/templates/base.html b/webmentions_ssg/templates/base.html index fabfaaf..5cd521b 100644 --- a/webmentions_ssg/templates/base.html +++ b/webmentions_ssg/templates/base.html @@ -44,7 +44,10 @@ SPDX-License-Identifier: BSD-3-Clause href='{{ url_for("root.received") }}'>Received</a> <a class="nav-link{% if request.endpoint == 'root.sent' %} active{% endif %}" href='{{ url_for("root.sent") }}'>Sent</a> - <a class="nav-link" href="{{ url_for("root.logout") }}">Logout</a> + <form action="{{ url_for("root.logout") }}" method="post" class="m-0"> + <input type="hidden" name="csrf_token" value="{{ csrf_token() }}"> + <button type="submit" class="nav-link border-0 bg-transparent">Logout</button> + </form> </div> {% endif %} </div> diff --git a/webmentions_ssg/views.py b/webmentions_ssg/views.py index 7a97480..2ab02fa 100644 --- a/webmentions_ssg/views.py +++ b/webmentions_ssg/views.py @@ -4,6 +4,7 @@ """Provide routes for authentication and Webmention administration.""" +import secrets import uuid from datetime import UTC, datetime, timedelta from typing import Any, cast @@ -36,6 +37,9 @@ from .url_security import is_safe_next_url root_page = Blueprint("root", __name__) +DUMMY_USER = User(username=secrets.token_urlsafe()) +DUMMY_USER.password = secrets.token_urlsafe() + @root_page.route("/") def index() -> ResponseReturnValue: @@ -48,6 +52,11 @@ def index() -> ResponseReturnValue: @root_page.route("/login", methods=["GET", "POST"]) +@LIMITER.limit( + lambda: current_app.config["LOGIN_RATE_LIMIT"], + methods=["POST"], + error_message="Too many login attempts. Please try again later.", +) def login() -> ResponseReturnValue: """ Authenticate a user and start a login session. @@ -68,11 +77,18 @@ def login() -> ResponseReturnValue: sa.select(User).where(User.username == form.username.data) ) - password = form.password.data - if user is None or password is None or not user.check_password(password): + 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 + ): flash("Invalid username or password", "danger") return redirect(url_for("root.login")) - login_user(user) next_url = request.args.get("next") @@ -83,7 +99,8 @@ def login() -> ResponseReturnValue: return render_template("login.html", form=form) -@root_page.route("/logout") +@root_page.route("/logout", methods=("POST",)) +@login_required def logout() -> ResponseReturnValue: """ End the current user's login session. |
