mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-11-25 10:25:09 +00:00
fix(api): take 256 cache files and an 8 MiB body on the login routes
This commit is contained in:
@@ -663,7 +663,7 @@ suffix, which is the `Cacher` cache key the service reads it with:
|
||||
Both sides reject a cache key with a drive letter, a root, a `..` segment, an empty
|
||||
segment, or more than 8 segments before it becomes a path, so a peer cannot write
|
||||
outside the cache directory. Both sides also refuse a `cache` map with more than
|
||||
64 entries. The server skips a cache key it cannot write, such as one that names an
|
||||
256 entries, and the server refuses the request body of a remote session creation or of a search when it is larger than 8 MiB. The server skips a cache key it cannot write, such as one that names an
|
||||
existing file as a directory, and logs a warning.
|
||||
|
||||
### Remote session info response
|
||||
|
||||
@@ -22,6 +22,8 @@ from unshackle.core.remote_protocol import APIErrorCode
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
ABOVE_APP_LIMIT = 2 * 1024 * 1024
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def make_app():
|
||||
@@ -389,3 +391,30 @@ def test_setup_routes_with_docs_registers_each_route_once() -> None:
|
||||
routes_with_docs = Counter((r.method, r.resource.canonical) for r in documented.router.routes())
|
||||
assert max(routes_with_docs.values()) == 1
|
||||
assert {route for route in routes_with_docs if not route[1].startswith("/api/docs")} == set(collect_paths(plain))
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"path, handler", [("/api/session/create", "session_create_handler"), ("/api/search", "search_handler")]
|
||||
)
|
||||
async def test_a_login_route_reads_a_body_above_the_application_limit(
|
||||
path: str, handler: str, make_app, aiohttp_client, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
async def echo(data: dict, request: web.Request) -> web.Response:
|
||||
return web.json_response({"size": len(data["cache"]["a"])})
|
||||
|
||||
monkeypatch.setattr(routes, handler, echo)
|
||||
client = await aiohttp_client(make_app())
|
||||
|
||||
taken = await client.post(path, json={"cache": {"a": "x" * ABOVE_APP_LIMIT}})
|
||||
refused = await client.post(path, json={"cache": {"a": "x" * routes.MAX_LOGIN_BODY_BYTES}})
|
||||
|
||||
assert await taken.json() == {"size": ABOVE_APP_LIMIT}
|
||||
assert (await refused.json())["error_code"] == APIErrorCode.INVALID_INPUT.value
|
||||
|
||||
|
||||
async def test_another_route_keeps_the_application_body_limit(make_app, aiohttp_client) -> None:
|
||||
client = await aiohttp_client(make_app())
|
||||
|
||||
refused = await client.post("/api/list-titles", json={"cache": {"a": "x" * ABOVE_APP_LIMIT}})
|
||||
|
||||
assert "Too Large" in (await refused.json())["details"]["error"]
|
||||
|
||||
@@ -179,14 +179,21 @@ def categorized(handler: Handler) -> Handler:
|
||||
return wrapper
|
||||
|
||||
|
||||
async def json_body(request: web.Request) -> Any:
|
||||
"""The request's JSON object; raises INVALID_INPUT when it does not parse or is not an object."""
|
||||
MAX_LOGIN_BODY_BYTES = 8 * 1024 * 1024
|
||||
|
||||
|
||||
async def json_body(request: web.Request, max_size: Optional[int] = None) -> Any:
|
||||
"""The request's JSON object; raises INVALID_INPUT when it does not parse or is not an object.
|
||||
|
||||
``max_size`` replaces the body limit of the application for this read.
|
||||
"""
|
||||
try:
|
||||
data = await request.json()
|
||||
data = await (request.clone(client_max_size=max_size) if max_size else request).json()
|
||||
except Exception as e:
|
||||
raise APIError(APIErrorCode.INVALID_INPUT, "Invalid JSON request body", details={"error": str(e)}) from e
|
||||
if not isinstance(data, dict):
|
||||
raise APIError(APIErrorCode.INVALID_INPUT, "The request body must be a JSON object")
|
||||
request["json_body"] = data
|
||||
return data
|
||||
|
||||
|
||||
@@ -688,7 +695,7 @@ async def search(request: web.Request) -> web.Response:
|
||||
'400':
|
||||
description: Invalid request
|
||||
"""
|
||||
data = await json_body(request)
|
||||
data = await json_body(request, MAX_LOGIN_BODY_BYTES)
|
||||
return await search_handler(data, request)
|
||||
|
||||
|
||||
@@ -2112,7 +2119,7 @@ async def session_create(request: web.Request) -> web.Response:
|
||||
'401':
|
||||
description: Authentication failed
|
||||
"""
|
||||
data = await json_body(request)
|
||||
data = await json_body(request, MAX_LOGIN_BODY_BYTES)
|
||||
return await session_create_handler(data, request)
|
||||
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ from pathlib import PureWindowsPath
|
||||
from typing import Optional
|
||||
|
||||
MAX_CACHE_KEY_DEPTH = 8
|
||||
MAX_SESSION_CACHE_KEYS = 64
|
||||
MAX_SESSION_CACHE_KEYS = 256
|
||||
|
||||
|
||||
CONTROL_CHARS = re.compile(r"[\x00-\x1f\x7f-\x9f]")
|
||||
|
||||
@@ -388,12 +388,16 @@ def _reply_json(response: Any) -> Dict[str, Any]:
|
||||
|
||||
|
||||
async def _consumed_json(request: web.Request) -> Dict[str, Any]:
|
||||
"""The JSON object of the request body when the handler consumed it (aiohttp caches that read), else ``{}``.
|
||||
"""The JSON object of the request body when the handler consumed it, else ``{}``.
|
||||
|
||||
``json_body`` keeps the object on the request, and aiohttp caches a direct read.
|
||||
|
||||
A body nobody read belongs to a call refused before the handler, a 401 or a 429. It stays
|
||||
unread: reading it would spend time and memory on an unauthenticated caller, and wait on a
|
||||
body that never finishes arriving.
|
||||
"""
|
||||
if "json_body" in request:
|
||||
return request["json_body"]
|
||||
if not request.content.at_eof():
|
||||
return {}
|
||||
try:
|
||||
|
||||
Reference in New Issue
Block a user