Files
rengine/api/app/core/validation_errors.py
T
Yogesh OjhaandClaude Opus 5 7460e4a1f4 fix(api): a deeply nested request body answered 500 instead of 422
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
2026-09-07 07:44:26 +05:30

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}
)