Bug: Default response cache keys collide across path and query boundaries
Description
The default response-cache key builder concatenates the request method, path, and encoded query without separators or length framing:
return request.method + request.url.path + urlencode(query_params, doseq=True)Consequently, distinct request targets can generate the same cache key:
GET /foo?a=b → "GET" + "/foo" + "a=b" = "GET/fooa=b"
GET /fooa=b → "GET" + "/fooa=b" + "" = "GET/fooa=b"When both matching route handlers have response caching enabled, the first request populates the shared key. The second request then receives that cached response without executing its own handler.
Because complete ASGI response messages are cached, this can return the wrong body, status, headers, or cookies. Response caching is opt-in, and exploitation requires compatible cache-enabled routes, but the collision is deterministic.
The default key also omits the request origin. Applications serving responses that vary by host can therefore share cached responses across hosts.
The key should encode its components unambiguously and include the request method, origin, path, and canonical query parameters.
Suggested fix in PR #5101
URL to code causing the issue
MCVE
from litestar import Litestar, Response, get
from litestar.testing import TestClient
calls = {"with-query": 0, "without-query": 0}
@get("/foo", cache=True)
async def handler_with_query() -> Response[str]:
calls["with-query"] += 1
return Response("with-query", headers={"x-handler": "with-query"})
@get("/fooa=b", cache=True)
async def handler_without_query() -> Response[str]:
calls["without-query"] += 1
return Response("without-query", headers={"x-handler": "without-query"})
app = Litestar([handler_with_query, handler_without_query])
with TestClient(app) as client:
response_with_query = client.get("/foo?a=b")
response_without_query = client.get("/fooa=b")
print(response_with_query.text)
print(response_without_query.text)
print(calls)
assert response_with_query.text == "with-query"
assert response_without_query.text == "without-query"
assert calls == {"with-query": 1, "without-query": 1}Steps to reproduce
- Install Litestar from the affected
mainrevision. - Save and run the MCVE.
- Request
/foo?a=bto populate the response cache. - Request
/fooa=b. - Observe that the second response contains
with-query, and thathandler_without_querywas never called.
Screenshots
N/A
Logs
with-query
with-query
{'with-query': 1, 'without-query': 0}
AssertionErrorLitestar Version
GitHub main at 45416e1a5d381845f4774b3798b7b8a0bcb024c8 Version: 2.24.0
Platform
- Linux
- Mac
- Windows
- Other (Please specify in the description above)
Source: litestar-org/litestar