mirror of
https://github.com/yogeshojha/rengine.git
synced 2026-10-19 14:51:31 +02:00
A 2KB body nested a thousand deep returned 500. The request was correctly rejected — the traceback ends in RequestValidationError — but FastAPI then blew the stack building the 422 itself: its default error puts the offending value in `input`, and jsonable_encoder walks that value recursively. Every depth from about 990 up failed this way, until the JSON parser's own limit took over around twenty thousand and returned a clean 400. Errors are now reported as type, loc and msg, which is the shape FastAPI documents in HTTPValidationError and the only part the frontend reads. Dropping `input` removes the recursion and stops the API reflecting submitted values back in error bodies. Verified: depths 100 through 5000 all answer 422, messages and the loc path including its array index are unchanged, and a sweep of every write endpoint shows the same status distribution as before. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01K6LcH8uUddjJbKrahf34ys
29 lines
962 B
Python
29 lines
962 B
Python
"""Report a rejected request body without echoing the body back."""
|
|
|
|
from fastapi import Request
|
|
from fastapi.exceptions import RequestValidationError
|
|
from fastapi.responses import JSONResponse
|
|
from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY
|
|
|
|
|
|
def _part(value: object) -> str | int:
|
|
return value if isinstance(value, str | int) else str(value)
|
|
|
|
|
|
async def validation_error_handler(
|
|
_request: Request, exc: RequestValidationError
|
|
) -> JSONResponse:
|
|
# FastAPI's default puts the offending value in `input`, and encoding a deeply
|
|
# nested one exhausts the stack while building the 422 itself.
|
|
detail = [
|
|
{
|
|
"type": str(error.get("type", "")),
|
|
"loc": [_part(part) for part in error.get("loc", ())],
|
|
"msg": str(error.get("msg", "")),
|
|
}
|
|
for error in exc.errors()
|
|
]
|
|
return JSONResponse(
|
|
status_code=HTTP_422_UNPROCESSABLE_ENTITY, content={"detail": detail}
|
|
)
|