Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

fix(upload): let upload_pdf read its own multipart form (#6326)

Sebastian Cao6c5a528a7e45
diff --git a/changelog.d/5989.bugfix.md b/changelog.d/5989.bugfix.md
new file mode 100644
index 0000000000..59a03e0f85
--- /dev/null
+++ b/changelog.d/5989.bugfix.md
@@ -0,0 +1,7 @@
+`POST /api/upload/pdf` now reads each uploaded file itself instead of
+receiving a stream FastAPI had already consumed (which rejected every PDF
+with "File signature mismatch"), and no longer answers 500 when a
+multipart field named `files` carries no `filename` parameter. Such parts
+are ignored like any other form field, a request with no real file parts
+gets the usual `400 "No files provided"`, and malformed multipart bodies
+still answer 400 instead of 500.
diff --git a/src/local_deep_research/web/routers/research.py b/src/local_deep_research/web/routers/research.py
index d05591c34e..37cf4c8aa7 100644
--- a/src/local_deep_research/web/routers/research.py
+++ b/src/local_deep_research/web/routers/research.py
@@ -1,8 +1,10 @@
-from fastapi import APIRouter, Depends, Request
+from fastapi import APIRouter, Depends, HTTPException, Request
from fastapi.responses import (
JSONResponse,
RedirectResponse,
)
+from python_multipart.exceptions import FormParserError
+from starlette.exceptions import HTTPException as StarletteHTTPException
from ..dependencies.auth import require_auth
from ..dependencies.rate_limit import (
_api_exempt,
@@ -2758,7 +2760,6 @@ def get_upload_limits(
async def upload_pdf(
request: Request,
username: Annotated[str, Depends(require_auth)],
- files: list = None,
):
"""
Upload and extract text from PDF files with comprehensive security validation.
@@ -2803,126 +2804,161 @@ async def upload_pdf(
# Parse multipart form data — FastAPI's UploadFile parameter binding
# doesn't work cleanly with the `files: list` shape we want, so we
# parse the form manually and pull out everything named "files".
- form = await request.form()
- files: list[UploadFile] = [
- f for f in form.getlist("files") if isinstance(f, UploadFile)
- ]
-
- if not files:
- return JSONResponse({"error": "No files provided"}, status_code=400)
- if all(not f.filename for f in files):
- return JSONResponse({"error": "No files selected"}, status_code=400)
-
- # Validate file count
- is_valid, error_msg = FileUploadValidator.validate_file_count(
- len(files)
- )
- if not is_valid:
- return JSONResponse({"error": error_msg}, status_code=400)
+ #
+ # Nothing in the signature asks FastAPI for the body, so this is
+ # the first parse of the request, and leaving the block closes
+ # every spooled upload whether the loop below reached it or not
+ # (early returns, rejected names, parts under other field names).
+ # FastAPI's form extraction used to register that cleanup.
+ async with request.form() as form:
+ files: list[UploadFile] = [
+ f for f in form.getlist("files") if isinstance(f, UploadFile)
+ ]
+
+ if not files:
+ return JSONResponse(
+ {"error": "No files provided"}, status_code=400
+ )
+ if all(not f.filename for f in files):
+ return JSONResponse(
+ {"error": "No files selected"}, status_code=400
+ )
- # Get PDF extraction service
- pdf_service = get_pdf_extraction_service()
+ # Validate file count
+ is_valid, error_msg = FileUploadValidator.validate_file_count(
+ len(files)
+ )
+ if not is_valid:
+ return JSONResponse({"error": error_msg}, status_code=400)
- extracted_texts = []
- total_files = len(files)
- processed_files = 0
- errors = []
+ # Get PDF extraction service
+ pdf_service = get_pdf_extraction_service()
- for file in files:
- if not file or not file.filename:
- errors.append("Unnamed file: Skipped")
- continue
+ extracted_texts = []
+ total_files = len(files)
+ processed_files = 0
+ errors = []
- try:
- filename = sanitize_filename(
- file.filename, allowed_extensions={".pdf"}
- )
- except UnsafeFilenameError:
- errors.append("Rejected file: invalid or disallowed filename")
- continue
+ for file in files:
+ if not file or not file.filename:
+ errors.append("Unnamed file: Skipped")
+ continue
- try:
- # Read file content (UploadFile spools large bodies to disk)
- pdf_content = await file.read()
-
- # Validation + PDF text extraction are CPU-bound (up to
- # FileUploadValidator.MAX_FILE_SIZE per file ×
- # MAX_FILES_PER_REQUEST files) — run them in the
- # threadpool so they don't freeze the event loop (and
- # with it every other request and WebSocket) for the
- # duration of the parse. No DB session is opened here,
- # so a plain to_thread (not run_db_sync) is correct.
- def _validate_and_extract(content=pdf_content, name=filename):
- ok, err = FileUploadValidator.validate_upload(
- filename=name,
- file_content=content,
- content_length=file.size,
+ try:
+ filename = sanitize_filename(
+ file.filename, allowed_extensions={".pdf"}
)
- if not ok:
- return None, err
- return (
- pdf_service.extract_text_and_metadata(content, name),
- None,
+ except UnsafeFilenameError:
+ errors.append(
+ "Rejected file: invalid or disallowed filename"
)
-
- result, error_msg = await asyncio.to_thread(
- _validate_and_extract
- )
-
- if result is None:
- errors.append(f"{filename}: {error_msg}")
continue
- if result["success"]:
- extracted_texts.append(
- {
- "filename": result["filename"],
- "text": result["text"],
- "size": result["size"],
- "pages": result["pages"],
- }
+ try:
+ # Read file content (UploadFile spools large bodies to disk)
+ pdf_content = await file.read()
+
+ # Validation + PDF text extraction are CPU-bound (up to
+ # FileUploadValidator.MAX_FILE_SIZE per file ×
+ # MAX_FILES_PER_REQUEST files) — run them in the
+ # threadpool so they don't freeze the event loop (and
+ # with it every other request and WebSocket) for the
+ # duration of the parse. No DB session is opened here,
+ # so a plain to_thread (not run_db_sync) is correct.
+ def _validate_and_extract(
+ content=pdf_content, name=filename
+ ):
+ ok, err = FileUploadValidator.validate_upload(
+ filename=name,
+ file_content=content,
+ content_length=file.size,
+ )
+ if not ok:
+ return None, err
+ return (
+ pdf_service.extract_text_and_metadata(
+ content, name
+ ),
+ None,
+ )
+
+ result, error_msg = await asyncio.to_thread(
+ _validate_and_extract
)
- processed_files += 1
- else:
- errors.append(f"{filename}: {result['error']}")
- except Exception:
- logger.exception(f"Error processing {filename}")
- errors.append(f"{filename}: Error processing file")
- finally:
- # Close the file stream to release resources
- try:
- await file.close()
+ if result is None:
+ errors.append(f"{filename}: {error_msg}")
+ continue
+
+ if result["success"]:
+ extracted_texts.append(
+ {
+ "filename": result["filename"],
+ "text": result["text"],
+ "size": result["size"],
+ "pages": result["pages"],
+ }
+ )
+ processed_files += 1
+ else:
+ errors.append(f"{filename}: {result['error']}")
+
except Exception:
- logger.debug("best-effort file stream close", exc_info=True)
+ logger.exception(f"Error processing {filename}")
+ errors.append(f"{filename}: Error processing file")
+ finally:
+ # Close the file stream to release resources
+ try:
+ await file.close()
+ except Exception:
+ logger.debug(
+ "best-effort file stream close", exc_info=True
+ )
- # Prepare response
- response_data = {
- "status": "success",
- "processed_files": processed_files,
- "total_files": total_files,
- "extracted_texts": extracted_texts,
- "combined_text": "\n\n".join(
- [
- f"--- From {item['filename']} ---\n{item['text']}"
- for item in extracted_texts
- ]
- ),
- "errors": errors,
- }
+ # Prepare response
+ response_data = {
+ "status": "success",
+ "processed_files": processed_files,
+ "total_files": total_files,
+ "extracted_texts": extracted_texts,
+ "combined_text": "\n\n".join(
+ [
+ f"--- From {item['filename']} ---\n{item['text']}"
+ for item in extracted_texts
+ ]
+ ),
+ "errors": errors,
+ }
- if processed_files == 0:
- return JSONResponse(
- {
- "status": "error",
- "message": "No files were processed successfully",
- "errors": errors,
- },
- status_code=400,
- )
+ if processed_files == 0:
+ return JSONResponse(
+ {
+ "status": "error",
+ "message": "No files were processed successfully",
+ "errors": errors,
+ },
+ status_code=400,
+ )
- return response_data
+ return response_data
+ except FormParserError as e:
+ # python-multipart could not parse the body (garbage where the
+ # boundary should be, a malformed part header, an over-long
+ # boundary): the client's fault, and the 400 FastAPI's form
+ # handling answered before this handler parsed the form itself.
+ # Only the parser's own errors are relabelled; anything else that
+ # fails while reading the form (an OSError spooling an upload,
+ # say) is the server's and goes to the generic handler below,
+ # which logs it.
+ raise HTTPException(
+ status_code=400, detail="There was an error parsing the body"
+ ) from e
+ except StarletteHTTPException:
+ # Starlette's own multipart limits (missing boundary parameter,
+ # oversized field) already arrive as a 400: let it through instead
+ # of turning it into the generic 500 below.
+ raise
except Exception:
logger.exception("Error processing PDF upload")
return JSONResponse(
diff --git a/tests/web/routers/test_fastapi_port_footguns.py b/tests/web/routers/test_fastapi_port_footguns.py
index cd008de80b..dcf74efd45 100644
--- a/tests/web/routers/test_fastapi_port_footguns.py
+++ b/tests/web/routers/test_fastapi_port_footguns.py
@@ -35,6 +35,11 @@ preventive, in the same spirit as test_error_response_leakage.py:
are scanned (the codebase-wide convention for the Starlette
Request), so ``response.json()`` on a ``requests``/``httpx``
response -- which is sync and correct -- cannot false-positive.
+ ``async with request.form() as form:`` is accepted: Starlette's
+ ``form()`` returns a wrapper whose ``__aenter__`` awaits the parse
+ and whose ``__aexit__`` closes the form, so the block consumes it.
+ That exemption is ``form()``-only -- the other three have no such
+ wrapper, and a sync ``with`` never awaits.
Both scanners are AST-based; comments/docstrings cannot trip them.
Scope: ``web/routers/*.py`` and the top-level ``web/*.py`` (endpoints
@@ -206,10 +211,26 @@ class TestTupleReturnScannerSelfTest:
_COROUTINE_REQUEST_METHODS = frozenset({"json", "form", "body", "stream"})
+def _is_async_with_form(node: ast.Call, parent: ast.AST | None) -> bool:
+ """``async with request.form() as form:`` -- the one context-manager
+ form Starlette supports. ``Request.form()`` returns a wrapper whose
+ ``__aenter__`` awaits the parse and whose ``__aexit__`` closes the
+ form (every spooled upload), so the block consumes the coroutine.
+ ``json()``/``body()``/``stream()`` have no such wrapper, and a sync
+ ``with`` never awaits, so neither is accepted here."""
+ return (
+ node.func.attr == "form"
+ and isinstance(parent, ast.withitem)
+ and parent.context_expr is node
+ and isinstance(getattr(parent, "parent", None), ast.AsyncWith)
+ )
+
+
def find_unawaited_request_coroutines(tree: ast.AST):
"""-> [(lineno, func_name, method)] for every
- ``request.json()/form()/body()/stream()`` call whose direct parent
- is not an ``await``. These return coroutines; without ``await`` the
+ ``request.json()/form()/body()/stream()`` call that is not consumed
+ by ``await``, by ``async for`` (``stream()``) or by ``async with``
+ (``form()`` only). These return coroutines; without ``await`` the
call is never scheduled and the value is unusable."""
violations = []
for fn in ast.walk(tree):
@@ -224,11 +245,17 @@ def find_unawaited_request_coroutines(tree: ast.AST):
and node.func.value.id == "request"
):
parent = getattr(node, "parent", None)
- # Safe forms: `await request.json()` and the async-iterator
+ # Safe forms: `await request.json()`, the async-iterator
# idiom `async for chunk in request.stream():` (stream()
- # yields an async generator, not a coroutine).
- consumed = isinstance(parent, ast.Await) or (
- isinstance(parent, ast.AsyncFor) and parent.iter is node
+ # yields an async generator, not a coroutine) and the
+ # form() context manager `async with request.form() as f:`
+ # (see _is_async_with_form).
+ consumed = (
+ isinstance(parent, ast.Await)
+ or (
+ isinstance(parent, ast.AsyncFor) and parent.iter is node
+ )
+ or _is_async_with_form(node, parent)
)
if not consumed:
violations.append((node.lineno, fn.name, node.func.attr))
@@ -330,6 +357,51 @@ class TestUnawaitedRequestScannerSelfTest:
)
assert self._scan(source) == []
+ def test_ignores_async_with_form_context_manager(self):
+ """`async with request.form() as form:` is the context-manager
+ form Starlette supports: `__aenter__` awaits the parse and
+ `__aexit__` closes the form (research.py's upload_pdf)."""
+ source = (
+ "@router.post('/x')\n"
+ "async def h(request):\n"
+ " async with request.form() as form:\n"
+ " return dict(form)\n"
+ )
+ assert self._scan(source) == []
+
+ def test_flags_bare_form_statement(self):
+ """A `request.form()` that nothing awaits, iterates or enters is
+ still a dropped coroutine, `async def` handler or not."""
+ source = (
+ "@router.post('/x')\n"
+ "async def h(request):\n"
+ " request.form()\n"
+ " return {'ok': True}\n"
+ )
+ assert self._scan(source) == [(3, "h", "form")]
+
+ def test_flags_async_with_on_other_request_methods(self):
+ """Only form() has the context-manager wrapper: `async with
+ request.json()` / `request.body()` is a coroutine misused as a
+ context manager, and being a `with` item does not excuse it."""
+ source = (
+ "@router.post('/x')\n"
+ "async def h(request):\n"
+ " async with request.json() as data, request.body() as raw:\n"
+ " return raw\n"
+ )
+ assert self._scan(source) == [(3, "h", "json"), (3, "h", "body")]
+
+ def test_flags_sync_with_form(self):
+ """A plain `with` never awaits the wrapper's `__aenter__`."""
+ source = (
+ "@router.post('/x')\n"
+ "async def h(request):\n"
+ " with request.form() as form:\n"
+ " return dict(form)\n"
+ )
+ assert self._scan(source) == [(3, "h", "form")]
+
def test_scan_covers_the_endpoint_surface():
"""Same floor discipline as the sibling guards: a layout move must
diff --git a/tests/web/test_multipart_upload_boundary.py b/tests/web/test_multipart_upload_boundary.py
index ae827d8bfa..0717f15280 100644
--- a/tests/web/test_multipart_upload_boundary.py
+++ b/tests/web/test_multipart_upload_boundary.py
@@ -351,6 +351,34 @@ class TestDeclaredContentTypeIsNotTrusted:
assert FILENAME_REJECTED in _errors(resp), resp.text
+# ---------------------------------------------------------------------------
+# The handler must be the first reader of each upload
+# ---------------------------------------------------------------------------
+
+
+class TestUploadBytesReachTheHandler:
+ """``upload_pdf`` reads every part itself. If anything upstream has
+ already read a part's stream to its end, the handler gets empty bytes
+ and rejects every real PDF as a signature mismatch. FastAPI's own
+ form extraction did exactly that while the handler still carried a
+ vestigial ``files`` body parameter (#5989)."""
+
+ def test_pdf_magic_bytes_survive_to_the_handler(self, upload_client):
+ resp = _post_multipart(
+ upload_client, _body(_part("files", "real.pdf", PDF_MAGIC_ONLY))
+ )
+
+ assert resp.status_code == 400, resp.text
+ errors = _errors(resp)
+ assert len(errors) == 1, errors
+ # PDF_MAGIC_ONLY clears the signature check and dies at structure
+ # validation; a signature mismatch means the bytes never arrived.
+ assert "File signature mismatch" not in errors[0], (
+ f"the handler read an already-consumed upload stream: {errors}"
+ )
+
+
# ---------------------------------------------------------------------------
# A part with no filename at all
# ---------------------------------------------------------------------------
@@ -361,51 +389,20 @@ class TestPartWithoutAFilename:
"""A part named ``files`` but carrying no ``filename`` parameter.
python-multipart yields ``str`` for such a part, not ``UploadFile``.
- ``rag.py``'s collection upload copes; ``research.py``'s
- ``upload_pdf`` does not — see the xfail reasons.
+ Both upload routes must filter it out rather than crash. ``upload_pdf``
+ once 500'd here (#5989): a vestigial ``files: list = None`` signature
+ parameter made FastAPI extract the field itself and call ``.read()``
+ on the ``str`` before the handler was entered.
"""
NO_FILENAME_BODY = _body(_part("files", None, PDF_MAGIC_ONLY))
- @pytest.mark.xfail(
- strict=True,
- reason=(
- "DEFECT: POST /api/upload/pdf returns 500 'Server error' (with "
- "a full traceback logged) for a part named 'files' that has no "
- "filename parameter. Mechanism: the handler signature is "
- "`async def upload_pdf(request: Request, files: list = None, "
- "...)`. That `files: list = None` parameter is vestigial — the "
- "body immediately rebinds `files` from `await request.form()` "
- "— but FastAPI still registers it as a form body field, so "
- "solve_dependencies -> request_body_to_args -> "
- "_extract_form_body runs FIRST and does `await "
- "sub_value.read()` over every value of the repeated field. For "
- "a filename-less part that value is a `str`, giving "
- "`AttributeError: 'str' object has no attribute 'read'`. It "
- "escapes the handler's own `except Exception` because it is "
- "raised before the handler is entered. Expected: 400 'No files "
- "provided', which is exactly what the sibling route answers "
- "(see test_sibling_collection_route_handles_it_cleanly). Fix: "
- "delete the unused `files: list = None` parameter — but see "
- "TestMalformedBodies.test_garbage_body_is_a_400_not_a_500, "
- "which pins the 400 that deletion would otherwise regress."
- ),
- )
def test_filenameless_part_should_be_a_400_not_a_crash(self, upload_client):
resp = _post_multipart(upload_client, self.NO_FILENAME_BODY)
assert resp.status_code == 400, resp.text
assert resp.json().get("error") == "No files provided", resp.text
- @pytest.mark.xfail(
- strict=True,
- reason=(
- "DEFECT, same mechanism as the test above, and this is the "
- "shape a real client hits: a genuine file part plus one stray "
- "filename-less part sharing the field name. The valid file is "
- "never processed — the request 500s before the handler runs."
- ),
- )
def test_valid_file_beside_a_filenameless_part_still_succeeds(
self, upload_client
):
@@ -417,14 +414,19 @@ class TestPartWithoutAFilename:
),
)
- assert resp.status_code < 500, (
+ # PDF_MAGIC_ONLY dies at structure validation, so the proof that
+ # real.pdf was processed is its per-file entry, not a 200. A
+ # handler that dropped every file would answer 400 "No files
+ # provided" with no errors list at all.
+ assert resp.status_code == 400, resp.text
+ assert [_reported_name(e) for e in _errors(resp)] == ["real.pdf"], (
f"a valid file was lost to a stray form field: {resp.text[:200]}"
)
def test_sibling_collection_route_handles_it_cleanly(self, upload_client):
- """Negative control for the two xfails: the same body, the other
- upload route, no crash — so this is route-local, not a parser or
- framework limitation."""
+ """Negative control for the two tests above: the same body, the
+ other upload route, no crash. A regression there would be
+ route-local, not a parser or framework limitation."""
create = upload_client.post(
"/library/api/collections",
json={"name": f"multipart-{uuid.uuid4().hex[:6]}"},
@@ -485,6 +487,31 @@ class TestMalformedBodies:
assert resp.status_code == 400, resp.text
+ def test_overlong_boundary_is_a_400(self, upload_client):
+ """python-multipart refuses a boundary longer than its
+ ``MAX_BOUNDARY_LENGTH`` (256 in 0.0.32) before reading a byte of
+ the body, and does so with its base ``FormParserError`` rather
+ than the ``MultipartParseError`` a garbage body raises. Both are
+ the client's doing and must answer the same 400."""
+ boundary = "B" * 300
+ raw = (
+ (
+ f"--{boundary}\r\n"
+ 'Content-Disposition: form-data; name="files"; '
+ 'filename="a.pdf"\r\n'
+ "Content-Type: application/pdf\r\n\r\n"
+ ).encode()
+ + PDF_MAGIC_ONLY
+ + f"\r\n--{boundary}--\r\n".encode()
+ )
+
+ resp = _post_multipart(
+ upload_client, raw, ct=f"multipart/form-data; boundary={boundary}"
+ )
+
+ assert resp.status_code == 400, resp.text
+ assert resp.json() == {"detail": "There was an error parsing the body"}
+
def test_oversized_non_file_field_is_a_400(self, upload_client):
"""Starlette caps *non-file* parts at ``max_part_size`` (1 MB).
@@ -537,6 +564,64 @@ class TestMalformedBodies:
)
+# ---------------------------------------------------------------------------
+# Failures inside the form read keep their blame
+# ---------------------------------------------------------------------------
+
+
+class TestFormReadFailuresKeepTheirBlame:
+ """``upload_pdf`` reads the form itself, so it also decides whose
+ fault a failed read is. python-multipart's own errors are the
+ client's and keep the 400 FastAPI used to answer; anything else
+ raised while reading the form (an ``OSError`` spooling an upload to
+ disk, say) is the server's and must reach the handler's generic
+ path, which logs it and answers 500, rather than be relabelled as a
+ malformed request nobody hears about.
+ """
+
+ @staticmethod
+ def _post_with_form_read_raising(client, monkeypatch, exc):
+ """POST a well-formed body through a ``Request.form()`` that
+ raises ``exc``: the handler's own read is the only place this
+ route touches the form."""
+ from starlette.requests import Request
+
+ def _failing_form(self, *args, **kwargs):
+ raise exc
+
+ monkeypatch.setattr(Request, "form", _failing_form)
+ return _post_multipart(
+ client, _body(_part("files", "real.pdf", PDF_MAGIC_ONLY))
+ )
+
+ def test_parser_error_keeps_the_historical_400(
+ self, upload_client, monkeypatch
+ ):
+ from python_multipart.exceptions import MultipartParseError
+
+ resp = self._post_with_form_read_raising(
+ upload_client, monkeypatch, MultipartParseError("no boundary")
+ )
+
+ assert resp.status_code == 400, resp.text
+ assert resp.json() == {"detail": "There was an error parsing the body"}
+
+ def test_any_other_failure_is_a_logged_500(
+ self, upload_client, monkeypatch, loguru_caplog_full
+ ):
+ resp = self._post_with_form_read_raising(
+ upload_client, monkeypatch, OSError("no space left to spool")
+ )
+
+ assert resp.status_code == 500, resp.text
+ assert resp.json() == {"error": "Failed to process PDF files"}
+ assert "Error processing PDF upload" in loguru_caplog_full.text
+ assert "no space left to spool" in loguru_caplog_full.text, (
+ "the generic handler must log the failure it hides from the client"
+ )
+
+
# ---------------------------------------------------------------------------
# ASGI-level cases: the size cap and a mid-upload disconnect
# ---------------------------------------------------------------------------