fix(security): enhance path traversal protection in file uploads

- Import and use sanitize_filename utility in ui_upload endpoint
- Enhance sanitize_filename to handle Windows-style paths (backslashes)
- Add protection against path traversal patterns (..)
- Replace all path separators with underscores
- Add comprehensive security tests for Windows-style paths and mixed separators
- All existing tests pass with improved security

This addresses the "Uncontrolled data used in path expression" code scanning alert
by ensuring all user-provided filenames are properly sanitized before being used
in any file operations or stored in the database.

Co-authored-by: christianlouis <361235+christianlouis@users.noreply.github.com>
This commit is contained in:
copilot-swe-agent[bot]
2026-02-09 21:00:51 +00:00
parent ef484f85a4
commit 2bcd774d6d
3 changed files with 69 additions and 7 deletions
+5 -1
View File
@@ -19,6 +19,7 @@ from app.models import FileRecord, ProcessingLog
from app.tasks.convert_to_pdf import convert_to_pdf
from app.tasks.process_document import process_document
from app.utils.file_status import get_files_processing_status
from app.utils.filename_utils import sanitize_filename
# Set up logging
logger = logging.getLogger(__name__)
@@ -657,7 +658,10 @@ async def ui_upload(request: Request, file: UploadFile = File(...)):
workdir = settings.workdir
# Extract just the filename without any path components to prevent path traversal
safe_filename = os.path.basename(file.filename)
# First, use basename to remove any directory components
base_filename = os.path.basename(file.filename)
# Then sanitize the filename to remove special characters and ensure filesystem compatibility
safe_filename = sanitize_filename(base_filename)
# Generate a unique filename with UUID to prevent overwriting and filename conflicts
unique_id = str(uuid.uuid4())