add level 3
This commit is contained in:
@@ -0,0 +1,67 @@
|
||||
"""Offline tests of login throttling and bounded request bodies."""
|
||||
import asyncio
|
||||
import sys
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from src.login_limit import LoginLimiter
|
||||
from src.main import app
|
||||
|
||||
|
||||
async def request(chunks, limiter=None):
|
||||
app.state.settings = SimpleNamespace(instance_id="test")
|
||||
app.state.login_limiter = limiter or LoginLimiter(attempts=1, window_seconds=60)
|
||||
app.state.store = object()
|
||||
messages = [{"type": "http.request", "body": chunk, "more_body": i < len(chunks) - 1}
|
||||
for i, chunk in enumerate(chunks)]
|
||||
response = []
|
||||
async def receive():
|
||||
if messages:
|
||||
return messages.pop(0)
|
||||
await asyncio.Event().wait()
|
||||
async def send(message):
|
||||
response.append(message)
|
||||
scope = {"type": "http", "asgi": {"version": "3.0"}, "http_version": "1.1",
|
||||
"method": "POST", "scheme": "http", "path": "/api/v1/auth/sessions",
|
||||
"raw_path": b"/api/v1/auth/sessions", "query_string": b"", "headers": [],
|
||||
"client": ("127.0.0.1", 1234), "server": ("localhost", 8080), "root_path": ""}
|
||||
await app(scope, receive, send)
|
||||
return response
|
||||
|
||||
|
||||
class LimitsTests(unittest.TestCase):
|
||||
def test_window_and_retry(self):
|
||||
now = [100.0]
|
||||
limiter = LoginLimiter(2, 60, lambda: now[0])
|
||||
self.assertEqual([limiter.retry_after() for _ in range(3)], [0, 0, 60])
|
||||
now[0] = 159.5
|
||||
self.assertEqual(limiter.retry_after(), 1)
|
||||
now[0] = 160
|
||||
self.assertEqual(limiter.retry_after(), 0)
|
||||
|
||||
def test_chunked_oversized_body(self):
|
||||
result = asyncio.run(request([b"x" * 40000, b"x" * 30000]))
|
||||
start = result[0]
|
||||
self.assertEqual(start["status"], 413)
|
||||
headers = dict(start["headers"])
|
||||
self.assertIn(b"x-request-id", headers)
|
||||
self.assertIn(b"x-instance-id", headers)
|
||||
self.assertIn(b'"payload_too_large"', b"".join(x.get("body", b"") for x in result))
|
||||
|
||||
def test_small_body_reaches_route(self):
|
||||
result = asyncio.run(request([b""]))
|
||||
self.assertEqual(result[0]["status"], 401)
|
||||
|
||||
def test_rate_limit_returns_retry_after(self):
|
||||
limiter = LoginLimiter(attempts=1, window_seconds=60)
|
||||
first = asyncio.run(request([b""], limiter))
|
||||
second = asyncio.run(request([b""], limiter))
|
||||
self.assertEqual(first[0]["status"], 401)
|
||||
self.assertEqual(second[0]["status"], 429)
|
||||
self.assertGreater(int(dict(second[0]["headers"])[b"retry-after"]), 0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user