Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: cap every /api write body before auth; keep chat text out of INFO logs (#13192)
Daniel Han583f937ed817
diff --git a/studio/backend/core/inference/inference.py b/studio/backend/core/inference/inference.pyindex dd22856ca8d..52b7e9a1d13 100644--- a/studio/backend/core/inference/inference.py+++ b/studio/backend/core/inference/inference.py@@ -2962,7 +2962,7 @@ class InferenceBackend:logger.info(f"Sending {len(chat_messages)} messages to tokenizer:")for i, msg in enumerate(chat_messages):- logger.info(f" {i}: {msg['role']} - {msg['content'][:50]}...")+ logger.debug(f" {i}: {msg['role']} - {msg['content'][:50]}...")try:formatted_prompt = render_prompt_with_boundary(@@ -2995,7 +2995,7 @@ class InferenceBackend:template_type,chat_template_info.get("special_tokens", {}),)- logger.info(f"Manual template result: {manual_prompt[:200]}...")+ logger.debug(f"Manual template result: {manual_prompt[:200]}...")else:logger.info("Using generic chat formatting for base model")manual_prompt = self._format_generic_template(manual_messages, {})diff --git a/studio/backend/main.py b/studio/backend/main.pyindex 84546d4f3ad..a78e2a4b0af 100644--- a/studio/backend/main.py+++ b/studio/backend/main.py@@ -1397,6 +1397,9 @@ _BODY_PROTECTED_PREFIXES = (# Unauthenticated (login, refresh): every route takes a few hundred bytes of JSON."/api/auth","/mcp",+ # Everything else under /api. FastAPI reads a body before the route's auth dependency runs, so an unlisted+ # prefix let an unauthenticated client stream an unbounded body into memory.+ "/api/",)_DATASET_UPLOAD_PASSTHROUGH_PREFIXES = ("/api/datasets/upload",@@ -1419,6 +1422,11 @@ _VIDEO_MULTIPART_UPLOAD_PATHS = ("/api/inference/videos",)_LIBRARY_UPLOAD_PATH = "/api/library/uploads"+# RAG document uploads (knowledge base, thread, project): multipart, capped by RAG_MAX_UPLOAD_BYTES in the route and+# spooled by FastAPI, so they pass through on Content-Length instead of being held in memory here.+_RAG_DOCUMENT_UPLOAD_RE = _re.compile(+ r"^/api/rag/(?:knowledge-bases|threads|projects)/[^/]+/documents/?$"+)# Streamed to disk and capped by the route itself; buffering here would hold 200 MiB in memory._AUDIO_INPUT_UPLOAD_PATHS = ("/api/inference/audio/inputs", "/v1/audio/inputs")_BODY_UPLOAD_PASSTHROUGH_PREFIXES = (@@ -1454,6 +1462,13 @@ def _get_upload_passthrough_request_max_bytes(path: str) -> int:return upload_request_limit_bytes(LIBRARY_UPLOAD_MAX_BYTES)if path.rstrip("/") in _AUDIO_INPUT_UPLOAD_PATHS:return AUDIO_INPUT_MAX_BYTES+ if _RAG_DOCUMENT_UPLOAD_RE.match(path):+ from core.rag import config as _rag_config++ # RAG_MAX_UPLOAD_BYTES=0 means no cap, as the route treats it.+ if _rag_config.MAX_UPLOAD_BYTES <= 0:+ return sys.maxsize+ return upload_request_limit_bytes(_rag_config.MAX_UPLOAD_BYTES)# The trailing-slash variant reaches this middleware BEFORE the router's redirect_slashes# 307, so it must resolve to the same cap. JSON sub-routes keep extra path components.if (@@ -1527,6 +1542,7 @@ class MaxBodyMiddleware:upload_passthrough_max_bytes_getter = None,upload_passthrough_exact_paths: tuple = (),chunked_upload_exact_paths: tuple = (),+ upload_passthrough_pattern = None,):self.app = appself.max_bytes_getter = max_bytes_getter@@ -1538,11 +1554,18 @@ class MaxBodyMiddleware:self.upload_passthrough_exact_paths = upload_passthrough_exact_paths# The subset of those allowed to omit Content-Length; the rest still get a 411.self.chunked_upload_exact_paths = chunked_upload_exact_paths+ # Uploads whose path carries an id (RAG documents), matched by a compiled pattern.+ self.upload_passthrough_pattern = upload_passthrough_patterndef _is_upload_passthrough(self, path: str) -> bool:# Exact paths also match their trailing-slash variant (this runs before redirect_slashes).- return path.rstrip("/") in self.upload_passthrough_exact_paths or any(- path.startswith(p) for p in self.upload_passthrough_prefixes+ return (+ path.rstrip("/") in self.upload_passthrough_exact_paths+ or any(path.startswith(p) for p in self.upload_passthrough_prefixes)+ or (+ self.upload_passthrough_pattern is not None+ and self.upload_passthrough_pattern.match(path) is not None+ ))def _upload_passthrough_max_bytes(self, path: str) -> int:@@ -1572,7 +1595,12 @@ class MaxBodyMiddleware:returnmethod = scope.get("method", "").upper()path = scope.get("path", "")- if method not in ("POST", "PUT", "PATCH") or not any(+ # Under `--root-path /x`, uvicorn keeps the prefix in `path`; match on the route path the router sees.+ root_path = scope.get("root_path") or ""+ if root_path and path.startswith(root_path):+ path = path[len(root_path) :] or "/"+ # DELETE too: several routes take a JSON body on DELETE (delete-cached, bulk thread delete).+ if method not in ("POST", "PUT", "PATCH", "DELETE") or not any(path.startswith(p) for p in self.protected_prefixes):await self.app(scope, receive, send)@@ -1588,7 +1616,7 @@ class MaxBodyMiddleware:declared = Nonebreak- if self._is_upload_passthrough(path):+ if method != "DELETE" and self._is_upload_passthrough(path):upload_max_bytes = self._upload_passthrough_max_bytes(path)if declared is not None:if declared > upload_max_bytes:@@ -1650,6 +1678,7 @@ app.add_middleware(upload_passthrough_max_bytes_getter = _get_upload_passthrough_request_max_bytes,upload_passthrough_exact_paths = _BODY_UPLOAD_PASSTHROUGH_EXACT_PATHS,chunked_upload_exact_paths = _CHUNKED_UPLOAD_EXACT_PATHS,+ upload_passthrough_pattern = _RAG_DOCUMENT_UPLOAD_RE,)# Tracks in-flight inference requests for idle auto-unload; off -> passthrough.diff --git a/studio/backend/tests/test_middleware.py b/studio/backend/tests/test_middleware.pyindex fc746704e8b..c50b3232a30 100644--- a/studio/backend/tests/test_middleware.py+++ b/studio/backend/tests/test_middleware.py@@ -1614,3 +1614,115 @@ def test_health_reports_the_default_for_a_settings_saved_endpoint(main_module, m"hf_endpoint": "https://huggingface.co","hf_datasets_server": "https://datasets-server.huggingface.co",}+++def test_every_api_write_route_is_body_capped(main_module):+ # FastAPI reads a body before the route's auth dependency, so an uncapped /api write route let an+ # unauthenticated client stream an unbounded body into memory.+ writes = [+ route.path+ for route in main_module.app.routes+ if getattr(route, "methods", None)+ and route.methods & {"POST", "PUT", "PATCH", "DELETE"}+ and route.path.startswith("/api/")+ ]+ assert writes+ for path in writes:+ assert any(path.startswith(p) for p in main_module._BODY_PROTECTED_PREFIXES), path+++def test_rag_document_uploads_pass_through_on_their_own_cap(main_module, monkeypatch):+ from core.rag import config as rag_config+ from utils.upload_limits import upload_request_limit_bytes++ # A positive cap, whatever RAG_MAX_UPLOAD_BYTES the suite runs with (0 is covered separately).+ monkeypatch.setattr(rag_config, "MAX_UPLOAD_BYTES", 200 * 1024 * 1024)++ pattern = main_module._RAG_DOCUMENT_UPLOAD_RE+ for path in (+ "/api/rag/knowledge-bases/kb1/documents",+ "/api/rag/threads/t1/documents",+ "/api/rag/projects/p1/documents/",+ ):+ assert pattern.match(path), path+ assert main_module._get_upload_passthrough_request_max_bytes(+ path+ ) == upload_request_limit_bytes(rag_config.MAX_UPLOAD_BYTES)+ # JSON routes keep the default buffered cap.+ for path in (+ "/api/rag/search",+ "/api/rag/knowledge-bases",+ "/api/rag/knowledge-bases/kb1/linked-folders",+ ):+ assert not pattern.match(path), path+++def test_pattern_passthrough_streams_and_refuses_oversized_declared_bodies(main_module):+ app = FastAPI()+ app.add_middleware(+ main_module.MaxBodyMiddleware,+ max_bytes_getter = lambda: 128,+ protected_prefixes = ("/api/",),+ upload_passthrough_max_bytes_getter = lambda path: 4096,+ upload_passthrough_pattern = re.compile(r"^/api/rag/threads/[^/]+/documents$"),+ )++ @app.post("/api/rag/threads/{tid}/documents")+ async def upload(request: Request):+ return {"total": len(await request.body())}++ @app.post("/api/skills")+ async def skills(payload: dict):+ return {"ok": True}++ c = TestClient(app)+ # Over the buffered default but under the upload cap: passes through.+ assert c.post("/api/rag/threads/t/documents", content = b"x" * 1024).json() == {"total": 1024}+ assert c.post("/api/rag/threads/t/documents", content = b"x" * 8192).status_code == 413++ def gen():+ for _ in range(4):+ yield b"y" * 64++ # A newly covered prefix: a chunked body past the cap is refused before the route runs.+ assert (+ c.post(+ "/api/skills", content = gen(), headers = {"content-type": "application/json"}+ ).status_code+ == 413+ )+++def test_rag_zero_upload_cap_means_unlimited(main_module, monkeypatch):+ from core.rag import config as rag_config+ monkeypatch.setattr(rag_config, "MAX_UPLOAD_BYTES", 0)+ assert (+ main_module._get_upload_passthrough_request_max_bytes("/api/rag/threads/t1/documents")+ == sys.maxsize+ )+++def test_delete_bodies_and_root_path_are_capped(main_module):+ app = FastAPI(root_path = "/studio")+ app.add_middleware(+ main_module.MaxBodyMiddleware,+ max_bytes_getter = lambda: 128,+ protected_prefixes = ("/api/",),+ )++ @app.api_route("/api/models/delete-cached", methods = ["DELETE", "POST"])+ async def delete_cached(request: Request):+ return {"total": len(await request.body())}++ c = TestClient(app, root_path = "/studio")++ def gen():+ for _ in range(4):+ yield b"y" * 64++ # DELETE with a body past the cap, and a plain DELETE without one.+ assert c.request("DELETE", "/studio/api/models/delete-cached", content = gen()).status_code == 413+ assert c.request("DELETE", "/studio/api/models/delete-cached").json() == {"total": 0}+ # The root_path prefix in scope["path"] does not hide the protected prefix.+ assert c.post("/studio/api/models/delete-cached", content = b"x" * 512).status_code == 413+ assert c.post("/studio/api/models/delete-cached", content = b"x" * 64).json() == {"total": 64}