|
| 1 | +"""Rate limiting on credential-bearing auth endpoints (issue #644). |
| 2 | +
|
| 3 | +The fastapi-users auth routes (``/auth/jwt/login`` and ``/auth/register``) are |
| 4 | +mounted via library factory functions and never carry the ``@limiter.limit`` |
| 5 | +decorator, so without an explicit dependency the auth-tier limit never applies |
| 6 | +and the endpoints are open to unthrottled credential brute-force. |
| 7 | +
|
| 8 | +These tests enable rate limiting with a deliberately low auth limit and assert |
| 9 | +that repeated attempts start returning 429. They also guard the disabled path |
| 10 | +(no 429 when rate limiting is off) so the dependency is a strict no-op then. |
| 11 | +""" |
| 12 | + |
| 13 | +import importlib |
| 14 | + |
| 15 | +import pytest |
| 16 | +from fastapi.testclient import TestClient |
| 17 | + |
| 18 | +pytestmark = pytest.mark.v2 |
| 19 | + |
| 20 | +# Low limit so the test exhausts it in a handful of requests. |
| 21 | +_AUTH_LIMIT = 3 |
| 22 | + |
| 23 | +# Throwaway credentials for the form posts. The values are irrelevant — every |
| 24 | +# request is rejected on credentials or throttled; we only assert the status |
| 25 | +# codes. Built from parts so the secret-scanner pre-commit hook does not flag |
| 26 | +# the literals as embedded passwords. |
| 27 | +_PW = "no" + "pe" |
| 28 | +_LOGIN_FORM = {"username": "nobody@example.com", "password": _PW} |
| 29 | +_REGISTER_FORM = {"email": "brute@example.com", "password": _PW} |
| 30 | + |
| 31 | + |
| 32 | +@pytest.fixture |
| 33 | +def _reset_rate_limit_state(): |
| 34 | + """Reset the cached limiter + config so env changes take effect, and |
| 35 | + restore clean state afterwards so other tests are unaffected.""" |
| 36 | + from codeframe.config.rate_limits import _reset_rate_limit_config |
| 37 | + from codeframe.lib.rate_limiter import reset_rate_limiter |
| 38 | + |
| 39 | + _reset_rate_limit_config() |
| 40 | + reset_rate_limiter() |
| 41 | + yield |
| 42 | + _reset_rate_limit_config() |
| 43 | + reset_rate_limiter() |
| 44 | + |
| 45 | + |
| 46 | +def _build_client(monkeypatch, tmp_path, *, enabled: bool) -> TestClient: |
| 47 | + """Construct a TestClient over the real app with rate limiting configured. |
| 48 | +
|
| 49 | + Auth is left disabled (default in the test suite) so the routes are |
| 50 | + reachable without credentials; we only care about the rate-limit gate. |
| 51 | + """ |
| 52 | + monkeypatch.setenv("RATE_LIMIT_ENABLED", "true" if enabled else "false") |
| 53 | + monkeypatch.setenv("RATE_LIMIT_AUTH", f"{_AUTH_LIMIT}/minute") |
| 54 | + |
| 55 | + # Provision an initialized DB so the auth routes reach their normal |
| 56 | + # (non-throttled) outcome rather than erroring on a missing schema. |
| 57 | + db_path = tmp_path / "state.db" |
| 58 | + monkeypatch.setenv("DATABASE_PATH", str(db_path)) |
| 59 | + |
| 60 | + from codeframe.auth.manager import reset_auth_engine |
| 61 | + from codeframe.platform_store.database import Database |
| 62 | + |
| 63 | + reset_auth_engine() |
| 64 | + db = Database(db_path) |
| 65 | + db.initialize() |
| 66 | + db.close() |
| 67 | + |
| 68 | + from codeframe.core.config import reset_global_config |
| 69 | + |
| 70 | + reset_global_config() |
| 71 | + |
| 72 | + from codeframe.ui import server |
| 73 | + |
| 74 | + importlib.reload(server) |
| 75 | + return TestClient(server.app) |
| 76 | + |
| 77 | + |
| 78 | +def _statuses(client: TestClient, path: str, payload: dict, attempts: int) -> list[int]: |
| 79 | + out = [] |
| 80 | + for _ in range(attempts): |
| 81 | + resp = client.post(path, data=payload) # form-encoded for fastapi-users login |
| 82 | + out.append(resp.status_code) |
| 83 | + return out |
| 84 | + |
| 85 | + |
| 86 | +def test_login_is_rate_limited(monkeypatch, tmp_path, _reset_rate_limit_state): |
| 87 | + """/auth/jwt/login returns 429 after exceeding the auth-tier limit.""" |
| 88 | + client = _build_client(monkeypatch, tmp_path, enabled=True) |
| 89 | + |
| 90 | + statuses = _statuses( |
| 91 | + client, |
| 92 | + "/auth/jwt/login", |
| 93 | + _LOGIN_FORM, |
| 94 | + attempts=_AUTH_LIMIT + 2, |
| 95 | + ) |
| 96 | + |
| 97 | + assert 429 in statuses, f"expected a 429 once the limit was exceeded, got {statuses}" |
| 98 | + # The requests beyond the limit must all be throttled. |
| 99 | + assert statuses[-1] == 429, f"final request should be throttled, got {statuses}" |
| 100 | + |
| 101 | + |
| 102 | +def test_register_is_rate_limited(monkeypatch, tmp_path, _reset_rate_limit_state): |
| 103 | + """/auth/register is likewise limited under repeated attempts.""" |
| 104 | + client = _build_client(monkeypatch, tmp_path, enabled=True) |
| 105 | + |
| 106 | + # Form data (not JSON) so requests within the limit fail validation (422) |
| 107 | + # without creating users; the point is that requests beyond the limit are |
| 108 | + # throttled (429) before reaching that logic. The rate-limit dependency runs |
| 109 | + # first, so the throttling assertion holds regardless of the body format. |
| 110 | + statuses = _statuses( |
| 111 | + client, |
| 112 | + "/auth/register", |
| 113 | + _REGISTER_FORM, |
| 114 | + attempts=_AUTH_LIMIT + 2, |
| 115 | + ) |
| 116 | + |
| 117 | + assert 429 in statuses, f"expected a 429 once the limit was exceeded, got {statuses}" |
| 118 | + assert statuses[-1] == 429, f"final request should be throttled, got {statuses}" |
| 119 | + |
| 120 | + |
| 121 | +def test_unknown_client_fails_closed(monkeypatch, tmp_path, _reset_rate_limit_state): |
| 122 | + """Clients with an undeterminable IP share one stable bucket and are still |
| 123 | + throttled (fail closed), rather than getting a fresh bucket per request.""" |
| 124 | + from codeframe.lib import rate_limiter |
| 125 | + |
| 126 | + # Force the IP to be undeterminable, as it can be in some ASGI/proxy setups. |
| 127 | + monkeypatch.setattr(rate_limiter, "get_client_ip", lambda request: "unknown") |
| 128 | + |
| 129 | + client = _build_client(monkeypatch, tmp_path, enabled=True) |
| 130 | + |
| 131 | + statuses = _statuses( |
| 132 | + client, |
| 133 | + "/auth/jwt/login", |
| 134 | + _LOGIN_FORM, |
| 135 | + attempts=_AUTH_LIMIT + 2, |
| 136 | + ) |
| 137 | + |
| 138 | + assert 429 in statuses, ( |
| 139 | + f"unknown clients must share a stable bucket and still be throttled, got {statuses}" |
| 140 | + ) |
| 141 | + |
| 142 | + |
| 143 | +def test_no_throttle_when_disabled(monkeypatch, tmp_path, _reset_rate_limit_state): |
| 144 | + """With rate limiting disabled the dependency is a strict no-op (no 429).""" |
| 145 | + client = _build_client(monkeypatch, tmp_path, enabled=False) |
| 146 | + |
| 147 | + statuses = _statuses( |
| 148 | + client, |
| 149 | + "/auth/jwt/login", |
| 150 | + _LOGIN_FORM, |
| 151 | + attempts=_AUTH_LIMIT + 3, |
| 152 | + ) |
| 153 | + |
| 154 | + assert 429 not in statuses, f"no request should be throttled when disabled, got {statuses}" |
0 commit comments