-
Notifications
You must be signed in to change notification settings - Fork 20
fix(auth): add rate limiting to login and register #53
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
4c0c173
fix(auth): add rate limiting to login and register
Flashl3opard ed12f9b
fix(auth): trust CF-Connecting-IP and strengthen rate-limit assertions
Flashl3opard 8dc7179
fix(auth): harden limiter state and retry-after assertions
Flashl3opard 92f27fc
Merge branch 'main' into fix/auth-rate-limit
A1L13N File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -4,6 +4,7 @@ | |
|
|
||
| import base64 | ||
| import json | ||
| import pytest | ||
| from tests.helpers import load_worker, MockRequest, MockRow, MockDB, make_env, make_stmt, json_request | ||
|
|
||
| worker = load_worker() | ||
|
|
@@ -12,6 +13,13 @@ | |
| JWT = "test-jwt-secret" | ||
|
|
||
|
|
||
| @pytest.fixture(autouse=True) | ||
| def clear_auth_rate_limit_state(): | ||
| worker._AUTH_RATE_LIMIT_STATE.clear() | ||
| yield | ||
| worker._AUTH_RATE_LIMIT_STATE.clear() | ||
|
|
||
|
|
||
| def _parse(resp): | ||
| return json.loads(resp.body) | ||
|
|
||
|
|
@@ -35,7 +43,13 @@ def _enc(val: str) -> str: | |
|
|
||
| class TestApiRegister: | ||
| def _req(self, payload): | ||
| return json_request("/api/register", payload) | ||
| return json_request("/api/register", payload, headers={"CF-Connecting-IP": "127.0.0.1"}) | ||
|
|
||
| def _rate_limited_env(self): | ||
| env = make_env(db=MockDB([make_stmt()])) | ||
| env.AUTH_RATE_LIMIT_WINDOW_SECONDS = 60 | ||
| env.AUTH_RATE_LIMIT_MAX_ATTEMPTS = 2 | ||
| return env | ||
|
|
||
| async def test_missing_username_returns_400(self): | ||
| env = make_env() | ||
|
|
@@ -125,18 +139,49 @@ async def test_registration_sends_verification_message(self): | |
|
|
||
| async def test_invalid_json_returns_400(self): | ||
| req = MockRequest(method="POST", url="http://localhost/api/register", | ||
| headers={"CF-Connecting-IP": "127.0.0.1"}, | ||
| body="not-json") | ||
| r = await worker.api_register(req, make_env()) | ||
| assert r.status == 400 | ||
|
|
||
| async def test_register_is_rate_limited_per_ip(self): | ||
| env = self._rate_limited_env() | ||
| ip = "203.0.113.10" | ||
|
|
||
| first_req = self._req({"username": "alice1", "email": "[email protected]", "password": "password123"}) | ||
| first_req.headers["CF-Connecting-IP"] = ip | ||
| second_req = self._req({"username": "alice2", "email": "[email protected]", "password": "password123"}) | ||
| second_req.headers["CF-Connecting-IP"] = ip | ||
| third_req = self._req({"username": "alice3", "email": "[email protected]", "password": "password123"}) | ||
| third_req.headers["CF-Connecting-IP"] = ip | ||
|
|
||
| first = await worker.api_register(first_req, env) | ||
| second = await worker.api_register(second_req, env) | ||
| third = await worker.api_register(third_req, env) | ||
|
|
||
| assert first.status == 200 | ||
| assert second.status == 200 | ||
| assert third.status == 429 | ||
|
Flashl3opard marked this conversation as resolved.
|
||
| assert "Retry-After" in third.headers | ||
| retry_after = third.headers["Retry-After"] | ||
| assert retry_after.isdigit() | ||
| assert int(retry_after) > 0 | ||
| assert _parse(third).get("error") == "Too many requests" | ||
|
|
||
|
|
||
| # --------------------------------------------------------------------------- | ||
| # api_login() | ||
| # --------------------------------------------------------------------------- | ||
|
|
||
| class TestApiLogin: | ||
| def _req(self, payload): | ||
| return json_request("/api/login", payload) | ||
| return json_request("/api/login", payload, headers={"CF-Connecting-IP": "127.0.0.1"}) | ||
|
|
||
| def _rate_limited_env(self): | ||
| env = make_env(db=MockDB([make_stmt(first=None)])) | ||
| env.AUTH_RATE_LIMIT_WINDOW_SECONDS = 60 | ||
| env.AUTH_RATE_LIMIT_MAX_ATTEMPTS = 2 | ||
| return env | ||
|
|
||
| def _make_user_row(self, username="alice", password="password123", role="member", name="Alice"): | ||
| pw_hash = worker.hash_password(password, username) | ||
|
|
@@ -194,6 +239,75 @@ async def test_login_token_is_verifiable(self): | |
| assert payload is not None | ||
|
|
||
| async def test_invalid_json_returns_400(self): | ||
| req = MockRequest(method="POST", url="http://localhost/api/login", body="bad-json") | ||
| req = MockRequest(method="POST", url="http://localhost/api/login", headers={"CF-Connecting-IP": "127.0.0.1"}, body="bad-json") | ||
| r = await worker.api_login(req, make_env()) | ||
| assert r.status == 400 | ||
|
|
||
| async def test_login_is_rate_limited_per_ip(self): | ||
| row = self._make_user_row() | ||
| env = self._rate_limited_env() | ||
| env.DB = MockDB([ | ||
| make_stmt(first=row), | ||
| make_stmt(first=row), | ||
| make_stmt(first=row), | ||
| ]) | ||
|
|
||
| req1 = self._req({"username": "alice", "password": "password123"}) | ||
| req1.headers["CF-Connecting-IP"] = "203.0.113.10" | ||
| req2 = self._req({"username": "alice", "password": "password123"}) | ||
| req2.headers["CF-Connecting-IP"] = "203.0.113.10" | ||
| req3 = self._req({"username": "alice", "password": "password123"}) | ||
| req3.headers["CF-Connecting-IP"] = "203.0.113.10" | ||
|
|
||
| first = await worker.api_login(req1, env) | ||
| second = await worker.api_login(req2, env) | ||
| third = await worker.api_login(req3, env) | ||
|
|
||
|
Flashl3opard marked this conversation as resolved.
|
||
| assert first.status == 200 | ||
| assert second.status == 200 | ||
| assert third.status == 429 | ||
| assert "Retry-After" in third.headers | ||
| retry_after = third.headers["Retry-After"] | ||
| assert retry_after.isdigit() | ||
| assert int(retry_after) > 0 | ||
| assert _parse(third).get("error") == "Too many requests" | ||
|
|
||
| async def test_login_rate_limit_resets_after_window(self, monkeypatch): | ||
| row = self._make_user_row() | ||
| env = self._rate_limited_env() | ||
| env.DB = MockDB([ | ||
| make_stmt(first=row), | ||
| make_stmt(first=row), | ||
| make_stmt(first=row), | ||
| make_stmt(first=row), | ||
| ]) | ||
|
|
||
| worker._AUTH_RATE_LIMIT_STATE.clear() | ||
| monkeypatch.setattr(worker.time, "time", lambda: 1000) | ||
|
|
||
| req1 = self._req({"username": "alice", "password": "password123"}) | ||
| req1.headers["CF-Connecting-IP"] = "198.51.100.10" | ||
| req2 = self._req({"username": "alice", "password": "password123"}) | ||
| req2.headers["CF-Connecting-IP"] = "198.51.100.10" | ||
|
|
||
| assert (await worker.api_login(req1, env)).status == 200 | ||
| assert (await worker.api_login(req2, env)).status == 200 | ||
|
|
||
| monkeypatch.setattr(worker.time, "time", lambda: 1000 + 61) | ||
| req3 = self._req({"username": "alice", "password": "password123"}) | ||
| req3.headers["CF-Connecting-IP"] = "198.51.100.10" | ||
| assert (await worker.api_login(req3, env)).status == 200 | ||
|
|
||
| req4 = self._req({"username": "alice", "password": "password123"}) | ||
| req4.headers["CF-Connecting-IP"] = "198.51.100.10" | ||
| assert (await worker.api_login(req4, env)).status == 200 | ||
|
|
||
| req5 = self._req({"username": "alice", "password": "password123"}) | ||
| req5.headers["CF-Connecting-IP"] = "198.51.100.10" | ||
| limited = await worker.api_login(req5, env) | ||
| assert limited.status == 429 | ||
| assert "Retry-After" in limited.headers | ||
| limited_retry_after = limited.headers["Retry-After"] | ||
| assert limited_retry_after.isdigit() | ||
| assert int(limited_retry_after) > 0 | ||
| assert _parse(limited).get("error") == "Too many requests" | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.