diff options
| author | Dennis Fink | 2026-10-31 19:33:49 +0100 |
|---|---|---|
| committer | Dennis Fink | 2026-10-31 19:33:49 +0100 |
| commit | 3a3284abe23e143cbb638877f47958c82afa3367 (patch) | |
| tree | 5409bb940d252756f502d545cc145b382f06a3a0 /tests | |
| parent | 40bdba0f2aa132f47326d2591e83039249ae2121 (diff) | |
| download | webmentions-ssg-3a3284abe23e143cbb638877f47958c82afa3367.tar.gz webmentions-ssg-3a3284abe23e143cbb638877f47958c82afa3367.zip | |
fix(core): harden login rate limiting behind proxies
Trust forwarded client addresses only for an explicitly configured
number of reverse-proxy hops so per-IP limits cannot be bypassed or
collapsed in proxied deployments.
Add a separate hashed per-username login limit across IPs to reduce
distributed credential-guessing attempts without storing raw usernames
in limiter keys.
Diffstat (limited to 'tests')
| -rw-r--r-- | tests/test_config.py | 84 | ||||
| -rw-r--r-- | tests/test_views.py | 119 |
2 files changed, 203 insertions, 0 deletions
diff --git a/tests/test_config.py b/tests/test_config.py index aae7cce..c483ee7 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -6,6 +6,9 @@ from pathlib import Path +from flask import request +from flask_limiter.util import get_remote_address + import pytest from wtforms import Field, ValidationError from wtforms.form import BaseForm @@ -288,3 +291,84 @@ def test_invalid_resource_limits_fail_at_startup( setattr(InvalidResourceLimit, key, value) with pytest.raises(ValueError, match=key): create_app(InvalidResourceLimit) + + +def test_proxy_fix_disabled_by_default(tmp_path: Path) -> None: + class DirectConfig(TestingConfig): + LOG_FILE = str(tmp_path / "direct.log") + + app = create_app(DirectConfig) + + @app.get("/_proxy-check") + def proxy_check() -> dict[str, str]: + return { + "ip": get_remote_address(), + "scheme": request.scheme, + "host": request.host, + } + + response = app.test_client().get( + "/_proxy-check", + environ_overrides={"REMOTE_ADDR": "192.0.2.50"}, + headers={ + "X-Forwarded-For": "198.51.100.99", + "X-Forwarded-Proto": "https", + "X-Forwarded-Host": "attacker.example", + }, + ) + assert response.json == {"ip": "192.0.2.50", "scheme": "http", "host": "localhost"} + + +def test_proxy_fix_trusts_only_configured_proxy_hops(tmp_path: Path) -> None: + class TwoProxyConfig(TestingConfig): + LOG_FILE = str(tmp_path / "proxy.log") + PROXY_FIX_TRUSTED_HOPS = 2 + + app = create_app(TwoProxyConfig) + + @app.get("/_proxy-check") + def proxy_check() -> dict[str, str]: + return { + "ip": get_remote_address(), + "scheme": request.scheme, + "host": request.host, + } + + response = app.test_client().get( + "/_proxy-check", + environ_overrides={"REMOTE_ADDR": "192.0.2.50"}, + headers={ + "X-Forwarded-For": "198.51.100.99, 203.0.113.4, 192.0.2.10", + "X-Forwarded-Proto": "http, https", + "X-Forwarded-Host": "attacker.example", + }, + ) + assert response.json == {"ip": "203.0.113.4", "scheme": "http", "host": "localhost"} + + +@pytest.mark.parametrize("hops", [-1, True, False, None, "1", 1.5]) +def test_invalid_proxy_fix_hop_counts_fail_at_startup( + tmp_path: Path, hops: object +) -> None: + class InvalidProxyConfig(TestingConfig): + LOG_FILE = str(tmp_path / "invalid-proxy.log") + PROXY_FIX_TRUSTED_HOPS = hops + + with pytest.raises(ValueError, match="PROXY_FIX_TRUSTED_HOPS"): + create_app(InvalidProxyConfig) + + +def test_proxy_fix_can_be_configured_via_environment( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + config_path = tmp_path / "development.cfg" + config_path.write_text("# proxy configuration supplied by environment\n") + monkeypatch.setenv("WEBMENTIONS_SSG_PROXY_FIX_TRUSTED_HOPS", "1") + + class EnvProxyConfig(DevelopmentConfig): + CONFIG_FILE = str(config_path) + LOG_FILE = str(tmp_path / "development.log") + + app = create_app(EnvProxyConfig) + assert app.config["PROXY_FIX_TRUSTED_HOPS"] == 1 + assert app.wsgi_app.__class__.__name__ == "ProxyFix" diff --git a/tests/test_views.py b/tests/test_views.py index 2108b38..129bdbf 100644 --- a/tests/test_views.py +++ b/tests/test_views.py @@ -835,6 +835,32 @@ def test_endpoint_rate_limits_requests_per_ip( assert count == 2 +def test_endpoint_rate_limit_distinguishes_clients_behind_trusted_proxy( + app: Flask, + client: FlaskClient, + views_module: ModuleType, + monkeypatch: pytest.MonkeyPatch, +) -> None: + from werkzeug.middleware.proxy_fix import ProxyFix + + app.config["ENDPOINT_RATE_LIMIT"] = "1/minute" + app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1) + form = mock_endpoint_form(views_module, monkeypatch, valid=True) + monkeypatch.setattr(views_module, "verify_webmention", Mock()) + + def attempt(client_ip: str, index: int) -> int: + form.source.data = f"https://source.example/proxy-post-{index}" + return client.post( + "/endpoint", + environ_overrides={"REMOTE_ADDR": "192.0.2.200"}, + headers={"X-Forwarded-For": client_ip}, + ).status_code + + assert attempt("198.51.100.11", 0) == 201 + assert attempt("198.51.100.11", 1) == 429 + assert attempt("198.51.100.12", 2) == 201 + + def test_endpoint_global_rate_limit( app: Flask, client: FlaskClient, @@ -1040,6 +1066,99 @@ def test_login_rate_limit_is_independent_per_ip( 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, |
