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: Address AI code review feedback for PDF upload

LearningCircuit6a0e9e6d5f82
diff --git a/.gitleaks.toml b/.gitleaks.toml
index 2bfe78dd64..0287412533 100644
--- a/.gitleaks.toml
+++ b/.gitleaks.toml
@@ -82,10 +82,7 @@ paths = [
'''.*example.*\.py$''',
'''mock.*\.py$''',
'''fixture.*\.py$''',
- # Exclude CI/CD workflow files that contain test credentials
- '''\.github/workflows/.*\.yml$''',
- '''\.github/workflows/.*\.yaml$''',
- '''\.gitleaks\.toml$''',
+ # Note: Workflow files are scanned - use specific commit allowlists for test credentials
'''src/local_deep_research/security/file_integrity/.*\.py$''',
'''src/local_deep_research/library/download_management/.*\.py$''',
'''src/local_deep_research/research_library/services/download_service\.py$''',
@@ -138,20 +135,19 @@ regexes = [
'''user_password = session_password_store''',
'''get_session_password''',
'''user_password = getattr''',
- # Allow variable names containing password/secret (not actual values)
- '''user_password\s*=''',
- '''password\s*:\s*Optional''',
- '''password\s*:\s*str''',
- '''session_password_store''',
- '''password\)\s*:''',
- # Allow parameter names and type hints
- '''\bpassword:\s*Optional\[str\]''',
- '''\bpassword:\s*str\b''',
- # Allow getattr patterns for password retrieval
- '''getattr\(g,\s*["']user_password["']''',
- # Allow user_password parameter names (not actual passwords)
+ # Allow specific password variable patterns with safe context (not arbitrary assignments)
+ '''user_password\s*=\s*getattr\(g''',
+ '''user_password\s*=\s*session_password_store\.get_session_password''',
'''user_password\s*=\s*user_password''',
'''user_password=user_password''',
+ '''session_password_store\.get_session_password''',
+ '''password\)\s*:''',
+ # Allow type hints only (not assignments)
+ '''\bpassword:\s*Optional\[str\]\s*[=)]''',
+ '''\bpassword:\s*str\s*[=)]''',
+ '''password\s*:\s*Optional\[str\]\s*=\s*None''',
+ # Allow getattr patterns for password retrieval from Flask g context
+ '''getattr\(g,\s*["']user_password["']''',
# Allow SHA256 hashes in pdm.lock (package integrity hashes)
'''hash\s*=\s*"sha256:[a-fA-F0-9]{64}"''',
'''content_hash\s*=\s*"sha256:[a-fA-F0-9]{64}"''',
@@ -165,10 +161,13 @@ paths = [
'''src/''',
'''scripts/''',
'''docs/''',
+ '''\.github/''',
'''\.py$''',
'''\.js$''',
'''\.ts$''',
'''\.json$''',
+ '''\.yml$''',
+ '''\.yaml$''',
'''\.env$''',
'''\.sh$''',
'''Dockerfile.*''',
diff --git a/.pre-commit-hooks/check-env-vars.py b/.pre-commit-hooks/check-env-vars.py
index ae1eb75bfc..5843d0be2d 100755
--- a/.pre-commit-hooks/check-env-vars.py
+++ b/.pre-commit-hooks/check-env-vars.py
@@ -26,6 +26,7 @@ ALLOWED_PATTERNS = {
"log_utils.py", # Logging configuration
"server_config.py", # Server configuration
"app_factory.py", # App initialization (needs env check before imports)
+ "rate_limiter.py", # Rate limiter config (decorator needs env at module load)
# Database initialization (needs env vars before DB exists)
"alembic/",
"migrations/",
diff --git a/src/local_deep_research/security/rate_limiter.py b/src/local_deep_research/security/rate_limiter.py
index 8bca80ee6d..f8427beedc 100644
--- a/src/local_deep_research/security/rate_limiter.py
+++ b/src/local_deep_research/security/rate_limiter.py
@@ -3,8 +3,18 @@ Rate limiting for API endpoints using Flask-Limiter.
Provides decorators and configuration for rate limiting HTTP requests
to prevent abuse and resource exhaustion.
+
+Configuration:
+ RATE_LIMIT_FAIL_CLOSED: Set to "true" in production to fail closed
+ when rate limiter is not initialized. Default is fail-open for
+ easier development setup.
+
+ For production, also configure:
+ storage_uri="redis://localhost:6379" for multi-worker support
"""
+import os
+
from flask import g
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
@@ -14,6 +24,11 @@ from loguru import logger
# Global limiter instance (initialized by app factory)
_limiter = None
+# Configuration: fail-closed in production, fail-open in development
+RATE_LIMIT_FAIL_CLOSED = (
+ os.environ.get("RATE_LIMIT_FAIL_CLOSED", "false").lower() == "true"
+)
+
def get_rate_limiter() -> Limiter:
"""
@@ -90,9 +105,12 @@ def upload_rate_limit(f):
Note:
If the rate limiter is not initialized (e.g., flask_limiter not installed),
- this decorator will pass through without rate limiting. This is intentional
- to allow the application to run without optional dependencies, but rate
- limiting should be enabled in production environments.
+ behavior depends on RATE_LIMIT_FAIL_CLOSED environment variable:
+ - "false" (default): Pass through without rate limiting (fail-open)
+ - "true": Raise RuntimeError, crashing the application (fail-closed)
+
+ Set RATE_LIMIT_FAIL_CLOSED=true in production to ensure rate limiting
+ is always active.
"""
try:
limiter = get_rate_limiter()
@@ -101,16 +119,30 @@ def upload_rate_limit(f):
except RuntimeError:
# Rate limiter not initialized - this is expected if flask_limiter
# is not installed or init_rate_limiter was not called
+ if RATE_LIMIT_FAIL_CLOSED:
+ logger.exception(
+ f"Rate limiter not initialized for {f.__name__} and "
+ "RATE_LIMIT_FAIL_CLOSED is enabled. Application will fail."
+ )
+ raise
logger.warning(
f"Rate limiting disabled for {f.__name__}: "
- "limiter not initialized. Install flask_limiter for rate limiting."
+ "limiter not initialized. Install flask_limiter for rate limiting. "
+ "Set RATE_LIMIT_FAIL_CLOSED=true to enforce rate limiting in production."
)
return f
except Exception:
# Unexpected error - log it but don't break the application
+ if RATE_LIMIT_FAIL_CLOSED:
+ logger.exception(
+ f"Unexpected error applying rate limit to {f.__name__} and "
+ "RATE_LIMIT_FAIL_CLOSED is enabled. Application will fail."
+ )
+ raise
logger.exception(
f"Unexpected error applying rate limit to {f.__name__}. "
- "Rate limiting disabled for this endpoint."
+ "Rate limiting disabled for this endpoint. "
+ "Set RATE_LIMIT_FAIL_CLOSED=true to enforce rate limiting in production."
)
return f
diff --git a/src/local_deep_research/web/static/js/pdf_upload_handler.js b/src/local_deep_research/web/static/js/pdf_upload_handler.js
index 386a486cba..e33e901aa3 100644
--- a/src/local_deep_research/web/static/js/pdf_upload_handler.js
+++ b/src/local_deep_research/web/static/js/pdf_upload_handler.js
@@ -11,6 +11,7 @@ class PDFUploadHandler {
this.uploadedPDFs = [];
this.maxFileSize = 10 * 1024 * 1024; // 10MB limit
this.maxFiles = 100; // Maximum 100 PDFs at once
+ this.statusTimers = []; // Track setTimeout IDs to prevent timer leaks
this.init();
}
@@ -376,10 +377,21 @@ class PDFUploadHandler {
statusDiv.style.display = 'none';
}
+ /**
+ * Clear all pending status timers to prevent timer leaks
+ */
+ clearStatusTimers() {
+ this.statusTimers.forEach(timerId => clearTimeout(timerId));
+ this.statusTimers = [];
+ }
+
/**
* Show success message
*/
showSuccess(processedFiles, errors) {
+ // Clear any existing status timers to prevent timer leaks
+ this.clearStatusTimers();
+
const statusDiv = this.getOrCreateStatusDiv();
// Clear existing content safely
@@ -412,16 +424,20 @@ class PDFUploadHandler {
statusDiv.appendChild(container);
statusDiv.style.display = 'block';
- // Auto-hide after 5 seconds
- setTimeout(() => {
+ // Auto-hide after 5 seconds (store timer ID to prevent leaks)
+ const timerId = setTimeout(() => {
statusDiv.style.display = 'none';
}, 5000);
+ this.statusTimers.push(timerId);
}
/**
* Show error message
*/
showError(message) {
+ // Clear any existing status timers to prevent timer leaks
+ this.clearStatusTimers();
+
const statusDiv = this.getOrCreateStatusDiv();
// Clear existing content safely
@@ -441,10 +457,11 @@ class PDFUploadHandler {
statusDiv.appendChild(container);
statusDiv.style.display = 'block';
- // Auto-hide after 5 seconds
- setTimeout(() => {
+ // Auto-hide after 5 seconds (store timer ID to prevent leaks)
+ const timerId = setTimeout(() => {
statusDiv.style.display = 'none';
}, 5000);
+ this.statusTimers.push(timerId);
}
/**
diff --git a/tests/pdf_tests/__init__.py b/tests/pdf_tests/__init__.py
new file mode 100644
index 0000000000..6bec8a06cd
--- /dev/null
+++ b/tests/pdf_tests/__init__.py
@@ -0,0 +1 @@
+# PDF upload tests
diff --git a/tests/pdf_tests/test_file_validator.py b/tests/pdf_tests/test_file_validator.py
new file mode 100644
index 0000000000..c8ca23d53e
--- /dev/null
+++ b/tests/pdf_tests/test_file_validator.py
@@ -0,0 +1,285 @@
+"""
+Unit tests for FileUploadValidator.
+
+Tests cover all validation methods:
+- File size validation
+- File count validation
+- MIME type validation
+- PDF structure validation
+- Comprehensive upload validation
+"""
+
+from src.local_deep_research.security.file_upload_validator import (
+ FileUploadValidator,
+)
+
+
+class TestValidateFileSize:
+ """Tests for validate_file_size method."""
+
+ def test_valid_size_via_content_length(self):
+ """Test that valid size passes via Content-Length header."""
+ is_valid, error = FileUploadValidator.validate_file_size(
+ content_length=1024 * 1024 # 1MB
+ )
+ assert is_valid is True
+ assert error is None
+
+ def test_valid_size_via_file_content(self):
+ """Test that valid size passes via actual file content."""
+ content = b"x" * (1024 * 1024) # 1MB
+ is_valid, error = FileUploadValidator.validate_file_size(
+ content_length=None, file_content=content
+ )
+ assert is_valid is True
+ assert error is None
+
+ def test_oversized_via_content_length(self):
+ """Test that oversized file is rejected via Content-Length."""
+ is_valid, error = FileUploadValidator.validate_file_size(
+ content_length=11 * 1024 * 1024 # 11MB
+ )
+ assert is_valid is False
+ assert error is not None
+ assert "too large" in error.lower()
+
+ def test_oversized_via_file_content(self):
+ """Test that oversized file is rejected via actual content."""
+ content = b"x" * (11 * 1024 * 1024) # 11MB
+ is_valid, error = FileUploadValidator.validate_file_size(
+ content_length=None, file_content=content
+ )
+ assert is_valid is False
+ assert error is not None
+ assert "too large" in error.lower()
+
+ def test_exactly_at_limit(self):
+ """Test that file exactly at limit passes."""
+ is_valid, error = FileUploadValidator.validate_file_size(
+ content_length=FileUploadValidator.MAX_FILE_SIZE
+ )
+ assert is_valid is True
+ assert error is None
+
+ def test_one_byte_over_limit(self):
+ """Test that file one byte over limit is rejected."""
+ is_valid, error = FileUploadValidator.validate_file_size(
+ content_length=FileUploadValidator.MAX_FILE_SIZE + 1
+ )
+ assert is_valid is False
+ assert error is not None
+
+ def test_both_none_returns_valid(self):
+ """Test that both None values return valid (no info to validate)."""
+ is_valid, error = FileUploadValidator.validate_file_size(
+ content_length=None, file_content=None
+ )
+ assert is_valid is True
+ assert error is None
+
+
+class TestValidateFileCount:
+ """Tests for validate_file_count method."""
+
+ def test_valid_file_count(self):
+ """Test that valid file count passes."""
+ is_valid, error = FileUploadValidator.validate_file_count(10)
+ assert is_valid is True
+ assert error is None
+
+ def test_single_file_valid(self):
+ """Test that single file passes."""
+ is_valid, error = FileUploadValidator.validate_file_count(1)
+ assert is_valid is True
+ assert error is None
+
+ def test_max_files_valid(self):
+ """Test that exactly max files passes."""
+ is_valid, error = FileUploadValidator.validate_file_count(
+ FileUploadValidator.MAX_FILES_PER_REQUEST
+ )
+ assert is_valid is True
+ assert error is None
+
+ def test_too_many_files(self):
+ """Test that exceeding max files is rejected."""
+ is_valid, error = FileUploadValidator.validate_file_count(
+ FileUploadValidator.MAX_FILES_PER_REQUEST + 1
+ )
+ assert is_valid is False
+ assert error is not None
+ assert "too many" in error.lower()
+
+ def test_zero_files(self):
+ """Test that zero files is rejected."""
+ is_valid, error = FileUploadValidator.validate_file_count(0)
+ assert is_valid is False
+ assert error is not None
+ assert "no files" in error.lower()
+
+ def test_negative_count(self):
+ """Test that negative count is rejected."""
+ is_valid, error = FileUploadValidator.validate_file_count(-1)
+ assert is_valid is False
+ assert error is not None
+
+
+class TestValidateMimeType:
+ """Tests for validate_mime_type method."""
+
+ def test_valid_pdf_extension_and_magic(self):
+ """Test that valid PDF passes."""
+ content = b"%PDF-1.4\ntest content"
+ is_valid, error = FileUploadValidator.validate_mime_type(
+ "test.pdf", content
+ )
+ assert is_valid is True
+ assert error is None
+
+ def test_uppercase_extension_valid(self):
+ """Test that uppercase .PDF extension passes."""
+ content = b"%PDF-1.4\ntest content"
+ is_valid, error = FileUploadValidator.validate_mime_type(
+ "test.PDF", content
+ )
+ assert is_valid is True
+ assert error is None
+
+ def test_mixed_case_extension_valid(self):
+ """Test that mixed case .Pdf extension passes."""
+ content = b"%PDF-1.4\ntest content"
+ is_valid, error = FileUploadValidator.validate_mime_type(
+ "test.PdF", content
+ )
+ assert is_valid is True
+ assert error is None
+
+ def test_wrong_extension_rejected(self):
+ """Test that wrong extension is rejected."""
+ content = b"%PDF-1.4\ntest content"
+ is_valid, error = FileUploadValidator.validate_mime_type(
+ "test.txt", content
+ )
+ assert is_valid is False
+ assert error is not None
+ assert "only pdf" in error.lower()
+
+ def test_no_extension_rejected(self):
+ """Test that file without extension is rejected."""
+ content = b"%PDF-1.4\ntest content"
+ is_valid, error = FileUploadValidator.validate_mime_type(
+ "testfile", content
+ )
+ assert is_valid is False
+ assert error is not None
+
+ def test_wrong_magic_bytes_rejected(self):
+ """Test that wrong magic bytes are rejected."""
+ content = b"This is not a PDF"
+ is_valid, error = FileUploadValidator.validate_mime_type(
+ "test.pdf", content
+ )
+ assert is_valid is False
+ assert error is not None
+ assert "signature mismatch" in error.lower()
+
+ def test_empty_content_rejected(self):
+ """Test that empty content is rejected."""
+ content = b""
+ is_valid, error = FileUploadValidator.validate_mime_type(
+ "test.pdf", content
+ )
+ assert is_valid is False
+ assert error is not None
+
+ def test_exe_disguised_as_pdf_rejected(self):
+ """Test that executable disguised as PDF is rejected."""
+ # MZ header for executable
+ content = b"MZ" + b"\x00" * 100
+ is_valid, error = FileUploadValidator.validate_mime_type(
+ "malware.pdf", content
+ )
+ assert is_valid is False
+ assert error is not None
+
+
+class TestValidatePdfStructure:
+ """Tests for validate_pdf_structure method."""
+
+ def test_malformed_pdf_structure(self):
+ """Test that malformed PDF structure is rejected."""
+ # Has magic bytes but invalid structure
+ content = b"%PDF-1.4\nthis is not valid pdf structure"
+ is_valid, error = FileUploadValidator.validate_pdf_structure(
+ "test.pdf", content
+ )
+ assert is_valid is False
+ assert error is not None
+ assert "invalid" in error.lower() or "corrupted" in error.lower()
+
+ def test_truncated_pdf_rejected(self):
+ """Test that truncated PDF is rejected."""
+ content = b"%PDF-1.4" # Just the header
+ is_valid, error = FileUploadValidator.validate_pdf_structure(
+ "test.pdf", content
+ )
+ assert is_valid is False
+ assert error is not None
+
+
+class TestValidateUpload:
+ """Tests for validate_upload comprehensive method."""
+
+ def test_all_validations_run(self):
+ """Test that all validations are executed."""
+ # Invalid size should fail first
+ large_content = b"%PDF-1.4\n" + (b"x" * (11 * 1024 * 1024))
+ is_valid, error = FileUploadValidator.validate_upload(
+ filename="test.pdf",
+ file_content=large_content,
+ )
+ assert is_valid is False
+ assert "too large" in error.lower()
+
+ def test_invalid_mime_fails_after_size(self):
+ """Test that MIME validation runs after size validation."""
+ content = b"not a pdf"
+ is_valid, error = FileUploadValidator.validate_upload(
+ filename="test.txt", # Wrong extension
+ file_content=content,
+ )
+ assert is_valid is False
+ assert "pdf" in error.lower()
+
+ def test_returns_first_error(self):
+ """Test that first validation error stops processing."""
+ # Large file with wrong extension - should fail on size first
+ large_content = b"x" * (11 * 1024 * 1024)
+ is_valid, error = FileUploadValidator.validate_upload(
+ filename="test.txt",
+ file_content=large_content,
+ )
+ assert is_valid is False
+ # Should fail on size before checking extension
+ assert "too large" in error.lower()
+
+
+class TestConstants:
+ """Tests for class constants."""
+
+ def test_max_file_size_is_10mb(self):
+ """Verify MAX_FILE_SIZE is 10MB."""
+ expected = 10 * 1024 * 1024
+ assert FileUploadValidator.MAX_FILE_SIZE == expected
+
+ def test_max_files_is_100(self):
+ """Verify MAX_FILES_PER_REQUEST is 100."""
+ assert FileUploadValidator.MAX_FILES_PER_REQUEST == 100
+
+ def test_pdf_magic_bytes(self):
+ """Verify PDF magic bytes."""
+ assert FileUploadValidator.PDF_MAGIC_BYTES == b"%PDF"
+
+ def test_allowed_mime_types(self):
+ """Verify allowed MIME types."""
+ assert "application/pdf" in FileUploadValidator.ALLOWED_MIME_TYPES
diff --git a/tests/pdf_tests/test_pdf_upload.py b/tests/pdf_tests/test_pdf_upload.py
new file mode 100644
index 0000000000..fb3dfba687
--- /dev/null
+++ b/tests/pdf_tests/test_pdf_upload.py
@@ -0,0 +1,243 @@
+"""
+Tests for PDF upload endpoint.
+
+Tests cover:
+- Authentication requirements
+- File validation (size, count, type)
+- Successful upload and text extraction
+- Error handling for invalid files
+"""
+
+import io
+
+
+class TestPDFUpload:
+ """Integration tests for /api/upload/pdf endpoint."""
+
+ def test_upload_requires_authentication(self, client):
+ """Test that unauthenticated requests are rejected."""
+ # Create a minimal PDF
+ pdf_content = b"%PDF-1.4\ntest content"
+ data = {"files": (io.BytesIO(pdf_content), "test.pdf")}
+
+ response = client.post(
+ "/api/upload/pdf",
+ data=data,
+ content_type="multipart/form-data",
+ )
+
+ # Should redirect to login or return 401/302
+ assert response.status_code in [302, 401]
+
+ def test_upload_no_files_returns_error(self, authenticated_client):
+ """Test that requests without files return appropriate error."""
+ response = authenticated_client.post(
+ "/api/upload/pdf",
+ data={},
+ content_type="multipart/form-data",
+ )
+
+ assert response.status_code == 400
+ data = response.get_json()
+ assert "error" in data or "No files" in str(data)
+
+ def test_upload_empty_file_list_returns_error(self, authenticated_client):
+ """Test that empty file list returns appropriate error."""
+ data = {"files": (io.BytesIO(b""), "")}
+
+ response = authenticated_client.post(
+ "/api/upload/pdf",
+ data=data,
+ content_type="multipart/form-data",
+ )
+
+ assert response.status_code == 400
+
+ def test_upload_invalid_file_type_rejected(self, authenticated_client):
+ """Test that non-PDF files are rejected."""
+ # Create a text file masquerading as PDF
+ txt_content = b"This is not a PDF file"
+ data = {"files": (io.BytesIO(txt_content), "test.pdf")}
+
+ response = authenticated_client.post(
+ "/api/upload/pdf",
+ data=data,
+ content_type="multipart/form-data",
+ )
+
+ # Should fail validation
+ data = response.get_json()
+ # Either 400 with error or success with errors list
+ if response.status_code == 200:
+ assert len(data.get("errors", [])) > 0
+ else:
+ assert response.status_code == 400
+
+ def test_upload_file_with_wrong_extension_rejected(
+ self, authenticated_client
+ ):
+ """Test that files with wrong extension are rejected."""
+ # Valid PDF content but wrong extension
+ pdf_content = b"%PDF-1.4\n1 0 obj\n<<\n>>\nendobj\nxref\ntrailer\n"
+ data = {"files": (io.BytesIO(pdf_content), "test.txt")}
+
+ response = authenticated_client.post(
+ "/api/upload/pdf",
+ data=data,
+ content_type="multipart/form-data",
+ )
+
+ data = response.get_json()
+ # Should have errors due to extension
+ if response.status_code == 200:
+ assert len(data.get("errors", [])) > 0
+ else:
+ assert response.status_code == 400
+
+ def test_upload_oversized_file_rejected(self, authenticated_client):
+ """Test that files over size limit are rejected."""
+ # Create file over 10MB limit
+ large_content = b"%PDF-1.4\n" + (b"x" * (11 * 1024 * 1024)) # 11MB
+ data = {"files": (io.BytesIO(large_content), "large.pdf")}
+
+ response = authenticated_client.post(
+ "/api/upload/pdf",
+ data=data,
+ content_type="multipart/form-data",
+ )
+
+ # Should be rejected
+ data = response.get_json()
+ if response.status_code == 200:
+ # If 200, should have errors
+ assert len(data.get("errors", [])) > 0
+ else:
+ assert response.status_code in [400, 413]
+
+ def test_upload_too_many_files_rejected(self, authenticated_client):
+ """Test that more than 100 files are rejected."""
+ files = []
+ # Create 101 minimal PDFs
+ for i in range(101):
+ pdf_content = b"%PDF-1.4\ntest"
+ files.append(("files", (io.BytesIO(pdf_content), f"test_{i}.pdf")))
+
+ response = authenticated_client.post(
+ "/api/upload/pdf",
+ data=files,
+ content_type="multipart/form-data",
+ )
+
+ assert response.status_code == 400
+ data = response.get_json()
+ assert "error" in data
+
+ def test_upload_malformed_pdf_handled(self, authenticated_client):
+ """Test that malformed PDFs are handled gracefully."""
+ # PDF magic bytes but invalid structure
+ malformed_pdf = b"%PDF-1.4\nthis is not valid pdf structure"
+ data = {"files": (io.BytesIO(malformed_pdf), "malformed.pdf")}
+
+ response = authenticated_client.post(
+ "/api/upload/pdf",
+ data=data,
+ content_type="multipart/form-data",
+ )
+
+ # Should not crash - either 200 with errors or 400
+ data = response.get_json()
+ assert response.status_code in [200, 400]
+ if response.status_code == 200:
+ # Should report errors for the malformed file
+ assert (
+ data.get("processed_files", 0) == 0
+ or len(data.get("errors", [])) > 0
+ )
+
+ def test_upload_returns_correct_structure(self, authenticated_client):
+ """Test that successful upload returns expected response structure."""
+ # Note: This test may fail if pdfplumber can't parse minimal PDF
+ # In that case, it should at least not crash
+ pdf_content = b"%PDF-1.4\nminimal pdf"
+ data = {"files": (io.BytesIO(pdf_content), "test.pdf")}
+
+ response = authenticated_client.post(
+ "/api/upload/pdf",
+ data=data,
+ content_type="multipart/form-data",
+ )
+
+ # Response should have expected keys
+ data = response.get_json()
+ assert "status" in data or "error" in data
+
+ def test_upload_multiple_files(self, authenticated_client):
+ """Test uploading multiple files at once."""
+ files = []
+ for i in range(3):
+ pdf_content = b"%PDF-1.4\ntest " + str(i).encode()
+ files.append(("files", (io.BytesIO(pdf_content), f"test_{i}.pdf")))
+
+ response = authenticated_client.post(
+ "/api/upload/pdf",
+ data=files,
+ content_type="multipart/form-data",
+ )
+
+ # Should process all files (may have errors for invalid PDFs)
+ data = response.get_json()
+ assert "status" in data or "error" in data
+
+
+class TestPDFUploadSecurity:
+ """Security-focused tests for PDF upload."""
+
+ def test_path_traversal_in_filename_sanitized(self, authenticated_client):
+ """Test that path traversal attempts in filenames are handled."""
+ pdf_content = b"%PDF-1.4\ntest"
+ malicious_filename = "../../../etc/passwd.pdf"
+ data = {"files": (io.BytesIO(pdf_content), malicious_filename)}
+
+ response = authenticated_client.post(
+ "/api/upload/pdf",
+ data=data,
+ content_type="multipart/form-data",
+ )
+
+ # Should not crash and should sanitize filename
+ assert response.status_code in [200, 400]
+ if response.status_code == 200:
+ data = response.get_json()
+ # Check filename is sanitized in response
+ for text in data.get("extracted_texts", []):
+ assert "../" not in text.get("filename", "")
+
+ def test_null_byte_in_filename_handled(self, authenticated_client):
+ """Test that null bytes in filenames are handled."""
+ pdf_content = b"%PDF-1.4\ntest"
+ null_filename = "test\x00.exe.pdf"
+ data = {"files": (io.BytesIO(pdf_content), null_filename)}
+
+ response = authenticated_client.post(
+ "/api/upload/pdf",
+ data=data,
+ content_type="multipart/form-data",
+ )
+
+ # Should handle gracefully
+ assert response.status_code in [200, 400]
+
+ def test_very_long_filename_handled(self, authenticated_client):
+ """Test that very long filenames are handled."""
+ pdf_content = b"%PDF-1.4\ntest"
+ long_filename = "a" * 1000 + ".pdf"
+ data = {"files": (io.BytesIO(pdf_content), long_filename)}
+
+ response = authenticated_client.post(
+ "/api/upload/pdf",
+ data=data,
+ content_type="multipart/form-data",
+ )
+
+ # Should handle gracefully
+ assert response.status_code in [200, 400]