Validate page bounds on preview endpoint

Reject requests where page exceeds the document page count with a clear
400 error, instead of letting pdf2image fail with an opaque exception.
This commit is contained in:
Pier-Jean Malandrino 2026-04-03 13:50:32 +02:00
parent 661568f2cb
commit 7bd7d0f793
2 changed files with 19 additions and 0 deletions

View file

@ -84,6 +84,12 @@ async def preview(
if not doc:
raise HTTPException(status_code=404, detail="Document not found")
if doc.page_count and page > doc.page_count:
raise HTTPException(
status_code=400,
detail=f"Page {page} out of range (document has {doc.page_count} pages)",
)
try:
with open(doc.storage_path, "rb") as f:
file_content = f.read()

View file

@ -104,6 +104,19 @@ class TestDocumentEndpoints:
)
assert resp.status_code == 413
@patch("services.document_service.find_by_id", new_callable=AsyncMock)
def test_preview_page_out_of_range(self, mock_find, client):
mock_find.return_value = Document(
id="d1",
filename="test.pdf",
page_count=3,
storage_path="/tmp/test.pdf",
)
resp = client.get("/api/documents/d1/preview?page=10")
assert resp.status_code == 400
assert "out of range" in resp.json()["detail"]
@patch("services.document_service.delete", new_callable=AsyncMock)
def test_delete_document(self, mock_delete, client):
mock_delete.return_value = True