From d65da600e5c741c3bc0cb9857d48ac2adc45eee8 Mon Sep 17 00:00:00 2001 From: GuanMu Date: Thu, 27 Mar 2025 16:46:10 +0800 Subject: [PATCH] fix: enhance filename validation and extraction in FileService #16867 (#16869) --- api/services/file_service.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/api/services/file_service.py b/api/services/file_service.py index d417e81734..284e96c97a 100644 --- a/api/services/file_service.py +++ b/api/services/file_service.py @@ -1,5 +1,6 @@ import datetime import hashlib +import os import uuid from typing import Any, Literal, Union @@ -38,7 +39,12 @@ class FileService: source_url: str = "", ) -> UploadFile: # get file extension - extension = filename.split(".")[-1].lower() + extension = os.path.splitext(filename)[1].lstrip(".").lower() + + # check if filename contains invalid characters + if any(c in filename for c in ["/", "\\", ":", "*", "?", '"', "<", ">", "|"]): + raise ValueError("Filename contains invalid characters") + if len(filename) > 200: filename = filename.split(".")[0][:200] + "." + extension