The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(dashboard-auth): cap request bodies on the public auth routes
unsupportedpastelsed4c35076b79
diff --git a/hermes_cli/dashboard_auth/body_limit.py b/hermes_cli/dashboard_auth/body_limit.pynew file mode 100644index 00000000000..92a66eb2375--- /dev/null+++ b/hermes_cli/dashboard_auth/body_limit.py@@ -0,0 +1,66 @@+"""Bound public auth bodies before FastAPI assembles JSON for validation."""+from __future__ import annotations++from starlette.exceptions import HTTPException+from starlette.responses import JSONResponse+from starlette.types import ASGIApp, Message, Receive, Scope, Send++from hermes_cli.dashboard_auth.middleware import _path_is_public++# Auth exchanges contain credentials and tokens, not files. Leave ample room for+# those small JSON payloads without allowing anonymous, unbounded buffering.+AUTH_BODY_LIMIT: int = 64 * 1024+++class _AuthBodyTooLarge(HTTPException):+ def __init__(self) -> None:+ super().__init__(status_code=413, detail="Request body too large")+++class AuthBodyLimitMiddleware:+ def __init__(self, app: ASGIApp) -> None:+ self.app = app++ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:+ if (scope["type"] != "http" or scope["method"] != "POST"+ or not scope["path"].startswith("/auth/")+ or not _path_is_public(scope["path"])):+ await self.app(scope, receive, send)+ return++ response = JSONResponse({"detail": "Request body too large"}, status_code=413)+ for name, value in scope.get("headers", []):+ if name == b"content-length":+ try:+ length = int(value)+ except ValueError:+ continue+ if length > AUTH_BODY_LIMIT:+ await response(scope, receive, send)+ return++ received = 0+ started = False++ async def limited_receive() -> Message:+ nonlocal received+ message = await receive()+ if message["type"] == "http.request":+ received += len(message.get("body", b""))+ if received > AUTH_BODY_LIMIT:+ # HTTPException survives FastAPI's JSON parsing error handler.+ raise _AuthBodyTooLarge()+ return message++ async def tracked_send(message: Message) -> None:+ nonlocal started+ if message["type"] == "http.response.start":+ started = True+ await send(message)++ try:+ await self.app(scope, limited_receive, tracked_send)+ except _AuthBodyTooLarge:+ if started:+ raise+ await response(scope, receive, send)diff --git a/hermes_cli/web_server.py b/hermes_cli/web_server.pyindex fdbc439b1d1..a2892d550ed 100644--- a/hermes_cli/web_server.py+++ b/hermes_cli/web_server.py@@ -355,6 +355,11 @@ def _get_pty_active_session_files(app: "FastAPI") -> dict[str, Path]:app = FastAPI(title="Hermes Agent", version=get_version_info().base_version, lifespan=_lifespan)+from hermes_cli.dashboard_auth.body_limit import AuthBodyLimitMiddleware # noqa: E402++# Register first (innermost): auth gates run before this, JSON parsing after it.+app.add_middleware(AuthBodyLimitMiddleware)+# Memory-provider OAuth connect routes live in the memory layer, not here.from hermes_cli.memory_oauth import router as _memory_oauth_router # noqa: E402diff --git a/tests/hermes_cli/test_dashboard_auth_body_limit.py b/tests/hermes_cli/test_dashboard_auth_body_limit.pynew file mode 100644index 00000000000..17ca64f9680--- /dev/null+++ b/tests/hermes_cli/test_dashboard_auth_body_limit.py@@ -0,0 +1,104 @@+"""Body budgets apply before parsing public auth requests, not to uploads."""+from __future__ import annotations++from collections.abc import Iterator++import pytest+from fastapi import FastAPI+from starlette.types import Message, Scope++from hermes_cli import web_server+++def app(monkeypatch: pytest.MonkeyPatch) -> Iterator[FastAPI]:+ monkeypatch.setattr(web_server.app.state, "bound_host", None, raising=False)+ application = FastAPI(middleware=web_server.app.user_middleware)+ application.state.auth_required = True+ application.state.calls = 0++ async def endpoint(payload: dict[str, str]) -> dict[str, str]:+ application.state.calls += 1+ return payload++ for path in ("/auth/password-login", "/auth/native/token", "/auth/native/refresh",+ "/api/upload"):+ application.post(path)(endpoint)+ yield application+++async def _request(+ app: FastAPI, path: str, chunks: list[bytes], headers: list[tuple[bytes, bytes]],+) -> tuple[list[Message], int]:+ scope: Scope = {+ "type": "http", "asgi": {"version": "3.0"}, "http_version": "1.1",+ "method": "POST", "scheme": "http", "path": path, "raw_path": path.encode(),+ "query_string": b"", "headers": [(b"host", b"testserver"),+ (b"content-type", b"application/json"), *headers],+ "client": ("127.0.0.1", 1234), "server": ("testserver", 80),+ }+ reads = 0+ messages: list[Message] = []++ async def receive() -> Message:+ nonlocal reads+ if reads == len(chunks):+ return {"type": "http.disconnect"}+ body = chunks[reads]+ reads += 1+ return {"type": "http.request", "body": body, "more_body": reads < len(chunks)}++ async def send(message: Message) -> None:+ messages.append(message)++ await app(scope, receive, send)+ return messages, reads+++async def test_oversized_content_length_rejected_before_handler(app: FastAPI) -> None:+ messages, reads = await _request(+ app, "/auth/password-login", [b'{}'], [(b"content-length", b"65537")])+ assert messages[0]["status"] == 413+ assert app.state.calls == 0+ assert reads == 0++[email protected]("path", ["/auth/password-login", "/auth/native/token", "/auth/native/refresh"])[email protected]("headers", [[], [(b"content-length", b"2")]], ids=["chunked", "understated"])+async def test_stream_cut_off_before_remaining_body(+ app: FastAPI, path: str, headers: list[tuple[bytes, bytes]],+) -> None:+ messages, reads = await _request(+ app, path, [b' ', b' ' * 65536, b'{}'], headers)+ assert messages[0]["status"] == 413+ assert app.state.calls == 0+ assert reads == 2++[email protected]("size", [2, 65536], ids=["small", "at-limit"])+async def test_normal_login_reaches_handler(app: FastAPI, size: int) -> None:+ messages, _ = await _request(app, "/auth/password-login", [b' ' * (size - 2) + b'{}'], [])+ assert messages[0]["status"] == 200+ assert app.state.calls == 1+++async def test_non_auth_upload_is_not_limited(app: FastAPI) -> None:+ app.state.auth_required = False+ messages, _ = await _request(+ app, "/api/upload", [b' ' * 65536 + b'{}'],+ [(web_server._SESSION_HEADER_NAME.lower().encode(), web_server._SESSION_TOKEN.encode()),+ (b"content-length", b"65538")])+ assert messages[0]["status"] == 200+ assert app.state.calls == 1+++async def test_non_public_path_rejected_without_reading_body(app: FastAPI) -> None:+ messages, reads = await _request(app, "/api/upload", [b' ' * 65537], [])+ assert messages[0]["status"] == 401+ assert reads == 0+ assert app.state.calls == 0