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 /tests/test_views.py | |
| 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.
Diffstat (limited to '')
| -rw-r--r-- | tests/test_views.py | 212 |
1 files changed, 199 insertions, 13 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"] |
