body_limit.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. """Bound public auth bodies before FastAPI assembles JSON for validation."""
  2. from __future__ import annotations
  3. from starlette.exceptions import HTTPException
  4. from starlette.responses import JSONResponse
  5. from starlette.types import ASGIApp, Message, Receive, Scope, Send
  6. from hermes_cli.dashboard_auth.middleware import _path_is_public
  7. # Auth exchanges contain credentials and tokens, not files. Leave ample room for
  8. # those small JSON payloads without allowing anonymous, unbounded buffering.
  9. AUTH_BODY_LIMIT: int = 64 * 1024
  10. class _AuthBodyTooLarge(HTTPException):
  11. def __init__(self) -> None:
  12. super().__init__(status_code=413, detail="Request body too large")
  13. class AuthBodyLimitMiddleware:
  14. def __init__(self, app: ASGIApp) -> None:
  15. self.app = app
  16. async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
  17. if (scope["type"] != "http" or scope["method"] != "POST"
  18. or not scope["path"].startswith("/auth/")
  19. or not _path_is_public(scope["path"])):
  20. await self.app(scope, receive, send)
  21. return
  22. response = JSONResponse({"detail": "Request body too large"}, status_code=413)
  23. for name, value in scope.get("headers", []):
  24. if name == b"content-length":
  25. try:
  26. length = int(value)
  27. except ValueError:
  28. continue
  29. if length > AUTH_BODY_LIMIT:
  30. await response(scope, receive, send)
  31. return
  32. received = 0
  33. started = False
  34. async def limited_receive() -> Message:
  35. nonlocal received
  36. message = await receive()
  37. if message["type"] == "http.request":
  38. received += len(message.get("body", b""))
  39. if received > AUTH_BODY_LIMIT:
  40. # HTTPException survives FastAPI's JSON parsing error handler.
  41. raise _AuthBodyTooLarge()
  42. return message
  43. async def tracked_send(message: Message) -> None:
  44. nonlocal started
  45. if message["type"] == "http.response.start":
  46. started = True
  47. await send(message)
  48. try:
  49. await self.app(scope, limited_receive, tracked_send)
  50. except _AuthBodyTooLarge:
  51. if started:
  52. raise
  53. await response(scope, receive, send)