Skip to content

Commit

Permalink
fix: Duplicate RateLimit-* headers with caching (#3855)
Browse files Browse the repository at this point in the history
* create test to check headers values

* update headers values instead of adding duplicates
  • Loading branch information
mohammedbabelly20 authored Nov 12, 2024
1 parent f00f87d commit 4b88735
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
2 changes: 1 addition & 1 deletion litestar/middleware/rate_limit.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ async def send_wrapper(message: Message) -> None:
message.setdefault("headers", [])
headers = MutableScopeHeaders(message)
for key, value in self.create_response_headers(cache_object=cache_object).items():
headers.add(key, value)
headers[key] = value
await send(message)

return send_wrapper
Expand Down
19 changes: 19 additions & 0 deletions tests/unit/test_middleware/test_rate_limit_middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -238,3 +238,22 @@ def handler() -> None:
response = client.get("/src/static/test.css")
assert response.status_code == HTTP_200_OK
assert response.text == "styles content"


async def test_rate_limiting_works_with_cache() -> None:
@get("/", cache=True)
def handler() -> None:
return None

config = RateLimitConfig(rate_limit=("minute", 2))
app = Litestar(route_handlers=[handler], middleware=[config.middleware])

with TestClient(app=app) as client:
response = client.get("/")
assert response.headers.get(config.rate_limit_remaining_header_key) == "1"

response = client.get("/")
assert response.headers.get(config.rate_limit_remaining_header_key) == "0"

response = client.get("/")
assert response.status_code == HTTP_429_TOO_MANY_REQUESTS

0 comments on commit 4b88735

Please sign in to comment.