RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.
Go agent-harnessagent-native-databaseagentic-aiagentic-retrievalagentic-searchaiai-agentscontext-enginecontext-engineeringcontext-managementharness-engineeringknowledge-compilationragretrieval-augmented-generationretrieval-harnesssearch-harness
fix(file): reject folder names containing "/" in create/rename (#18586)
euvre71188aadcd05
diff --git a/api/apps/services/file_api_service.py b/api/apps/services/file_api_service.pyindex 8bff299055..29cb6a2a7a 100644--- a/api/apps/services/file_api_service.py+++ b/api/apps/services/file_api_service.py@@ -28,6 +28,8 @@ from common import settingsfrom common.constants import FileSourcefrom common.misc_utils import get_uuid, thread_pool_exec+logger = logging.getLogger(__name__)+async def upload_file(tenant_id: str, pf_id: str, file_objs: list):"""@@ -48,7 +50,7 @@ async def upload_file(tenant_id: str, pf_id: str, file_objs: list):file_res = []for file_obj in file_objs:- MAX_FILE_NUM_PER_USER = int(os.environ.get("MAX_FILE_NUM_PER_USER", 0))+ MAX_FILE_NUM_PER_USER = int(os.environ.get("MAX_FILE_NUM_PER_USER", "0"))if 0 < MAX_FILE_NUM_PER_USER <= await thread_pool_exec(DocumentService.get_doc_count, tenant_id):return False, "Exceed the maximum file number of a free user!"@@ -96,7 +98,7 @@ async def upload_file(tenant_id: str, pf_id: str, file_objs: list):return True, file_res-async def create_folder(tenant_id: str, name: str, pf_id: str = None, file_type: str = None):+async def create_folder(tenant_id: str, name: str, pf_id: str | None = None, file_type: str | None = None):"""Create a new folder or virtual file.@@ -106,6 +108,12 @@ async def create_folder(tenant_id: str, name: str, pf_id: str = None, file_type::param file_type: file type (folder or virtual):return: (success, result) or (success, error_message)"""+ # "/" is the root folder name and the path separator used by recursive+ # folder creation, so names containing it collide with the root folder+ # and break path-based lookups.+ if "/" in name:+ return False, 'Folder name cannot contain "/"'+if not pf_id:root_folder = FileService.get_root_folder(tenant_id)pf_id = root_folder["id"]@@ -156,7 +164,7 @@ def list_files(tenant_id: str, args: dict):FileService.init_knowledgebase_docs(pf_id, tenant_id)FileService.init_skills_folder(pf_id, tenant_id)- e, file = FileService.get_by_id(pf_id)+ e, _ = FileService.get_by_id(pf_id)if not e:return False, "Folder not found!"@@ -169,7 +177,7 @@ def list_files(tenant_id: str, args: dict):return True, {"total": total, "files": files, "parent_folder": parent_folder.to_json()}-def get_parent_folder(file_id: str, user_id: str = None):+def get_parent_folder(file_id: str, user_id: str | None = None):"""Get parent folder of a file with permission check.@@ -191,7 +199,7 @@ def get_parent_folder(file_id: str, user_id: str = None):return True, {"parent_folder": parent_folder.to_json()}-def get_all_parent_folders(file_id: str, user_id: str = None):+def get_all_parent_folders(file_id: str, user_id: str | None = None):"""Get all ancestor folders of a file with permission check.@@ -250,8 +258,8 @@ async def delete_files(uid: str, file_ids: list, auth_header: str = ""):for space in spaces:if space.get("name") == space_name:return space.get("id")- except Exception as e:- logging.warning(f"Error getting space UUID: {e}")+ except Exception as e: # noqa: BLE001 - best-effort lookup; any failure falls back to the raw space name+ logger.warning(f"Error getting space UUID: {e}")return Nonedef _delete_skill_index(tenant_id, space_name, skill_name, authorization):@@ -261,9 +269,10 @@ async def delete_files(uid: str, file_ids: list, auth_header: str = ""):bool: True if deletion succeeded (HTTP 200), False otherwise."""try:- import requestsfrom urllib.parse import quote+ import requests+# Construct service URL from settingshost = getattr(settings, "HOST_IP", "127.0.0.1")# Go service runs on port+4 (9384 by default)@@ -284,24 +293,24 @@ async def delete_files(uid: str, file_ids: list, auth_header: str = ""):try:data = response.json()if data.get("code") == 0:- logging.info(f"Successfully deleted skill index: space={space_name}, skill={skill_name}, status={response.status_code}, code=0")+ logger.info(f"Successfully deleted skill index: space={space_name}, skill={skill_name}, status={response.status_code}, code=0")return Trueelse:app_code = data.get("code", "unknown")app_msg = data.get("message", "no message")- logging.error(+ logger.error(f"Failed to delete skill index: space={space_name}, skill={skill_name}, status={response.status_code}, app_code={app_code}, app_msg={app_msg}, response={response.text}")return Falseexcept ValueError as json_err:# JSON decode error - treat as failure- logging.error(f"Failed to parse delete response JSON: space={space_name}, skill={skill_name}, error={json_err}, raw_response={response.text}")+ logger.error(f"Failed to parse delete response JSON: space={space_name}, skill={skill_name}, error={json_err}, raw_response={response.text}")return Falseelse:- logging.error(f"Failed to delete skill index: space={space_name}, skill={skill_name}, status={response.status_code}, response={response.text}")+ logger.error(f"Failed to delete skill index: space={space_name}, skill={skill_name}, status={response.status_code}, response={response.text}")return False- except Exception as e:- logging.error(f"Exception deleting skill index: space={space_name}, skill={skill_name}, error={e}")+ except Exception as e: # noqa: BLE001 - deletion is best-effort; any failure is reported as False+ logger.error(f"Exception deleting skill index: space={space_name}, skill={skill_name}, error={e}")return Falsedef _delete_single_file(file) -> int:@@ -309,7 +318,7 @@ async def delete_files(uid: str, file_ids: list, auth_header: str = ""):if file.location:settings.STORAGE_IMPL.rm(file.parent_id, file.location)except Exception as e:- logging.exception(f"Fail to remove object: {file.parent_id}/{file.location}, error: {e}")+ logger.exception(f"Fail to remove object: {file.parent_id}/{file.location}")errors.append(f"Failed to remove object {file.parent_id}/{file.location}: {e}")informs = File2DocumentService.get_by_file_id(file.id)@@ -331,13 +340,13 @@ async def delete_files(uid: str, file_ids: list, auth_header: str = ""):try:File2DocumentService.delete_by_file_id(file.id)except Exception as e:- logging.exception(f"Fail to remove file-document relations for file {file.id}, error: {e}")+ logger.exception(f"Fail to remove file-document relations for file {file.id}")errors.append(f"Failed to remove file-document relations for file {file.id}: {e}")try:FileService.delete(file)except Exception as e:- logging.exception(f"Fail to delete file record {file.id}, error: {e}")+ logger.exception(f"Fail to delete file record {file.id}")errors.append(f"Failed to delete file record {file.id}: {e}")else:return 1@@ -374,27 +383,27 @@ async def delete_files(uid: str, file_ids: list, auth_header: str = ""):if parent_success and parent_folder and parent_folder.source_type == "skill_space":is_skill_folder = Truecurrent_space_name = parent_folder.name- logging.info(f"Identified skill folder '{folder.name}' (parent space: {current_space_name})")+ logger.info(f"Identified skill folder '{folder.name}' (parent space: {current_space_name})")else:ancestor_success, ancestor_folder = _find_ancestor_skill_space(folder.parent_id, tenant_id)if ancestor_success and ancestor_folder:is_skill_folder = Truecurrent_space_name = ancestor_folder.name- logging.info(f"Identified skill folder '{folder.name}' (ancestor space: {current_space_name})")+ logger.info(f"Identified skill folder '{folder.name}' (ancestor space: {current_space_name})")if is_space_folder:current_space_name = folder.name- logging.info(f"Processing space folder '{folder.name}' - will delete all skill indexes within")+ logger.info(f"Processing space folder '{folder.name}' - will delete all skill indexes within")if is_skill_folder and current_space_name and not is_space_folder:- logging.info(f"Deleting skill index for skill '{folder.name}' in space '{current_space_name}'")+ logger.info(f"Deleting skill index for skill '{folder.name}' in space '{current_space_name}'")index_deleted = _delete_skill_index(tenant_id, current_space_name, folder.name, auth_header)if not index_deleted:- logging.error(f"Aborting folder deletion due to index deletion failure: folder={folder.name}, space={current_space_name}")+ logger.error(f"Aborting folder deletion due to index deletion failure: folder={folder.name}, space={current_space_name}")errors.append(f"Failed to delete skill index for folder '{folder.name}' in space '{current_space_name}'. Folder deletion aborted to prevent orphaned indexes.")return deletedsub_files = FileService.list_all_files_by_parent_id(folder.id)- logging.info(f"Folder '{folder.name}': found {len(sub_files)} children to delete")+ logger.info(f"Folder '{folder.name}': found {len(sub_files)} children to delete")for sub_file in sub_files:if sub_file.type == FileType.FOLDER.value:@@ -404,19 +413,19 @@ async def delete_files(uid: str, file_ids: list, auth_header: str = ""):try:FileService.delete(folder)except Exception as e:- logging.exception(f"Fail to delete folder record {folder.id}, error: {e}")+ logger.exception(f"Fail to delete folder record {folder.id}")errors.append(f"Failed to delete folder record {folder.id}: {e}")else:deleted += 1try:if hasattr(settings.STORAGE_IMPL, "remove_bucket"):- logging.info(f"Removing storage bucket for folder '{folder.name}' (id={folder.id})")+ logger.info(f"Removing storage bucket for folder '{folder.name}' (id={folder.id})")settings.STORAGE_IMPL.remove_bucket(folder.id)else:- logging.debug(f"Storage implementation does not support remove_bucket, skipping for folder '{folder.name}'")- except Exception as e:- logging.warning(f"Failed to remove storage bucket for folder '{folder.name}' (id={folder.id}): {e}")+ logger.debug(f"Storage implementation does not support remove_bucket, skipping for folder '{folder.name}'")+ except Exception as e: # noqa: BLE001 - bucket removal is best-effort; storage backends raise SDK-specific errors+ logger.warning(f"Failed to remove storage bucket for folder '{folder.name}' (id={folder.id}): {e}")return deleted@@ -453,7 +462,7 @@ async def delete_files(uid: str, file_ids: list, auth_header: str = ""):return await thread_pool_exec(_rm_sync)-async def move_files(uid: str, src_file_ids: list, dest_file_id: str = None, new_name: str = None):+async def move_files(uid: str, src_file_ids: list, dest_file_id: str | None = None, new_name: str | None = None):"""Move and/or rename files. Follows Linux mv semantics:- new_name only: rename in place (no storage operation)@@ -489,6 +498,8 @@ async def move_files(uid: str, src_file_ids: list, dest_file_id: str = None, newif new_name:file = files_dict[src_file_ids[0]]+ if "/" in new_name:+ return False, 'Name cannot contain "/"'if file.type != FileType.FOLDER.value and pathlib.Path(new_name.lower()).suffix != pathlib.Path(file.name.lower()).suffix:return False, "The extension of file can't be changed"target_parent_id = dest_folder.id if dest_folder else file.parent_id@@ -555,8 +566,8 @@ async def move_files(uid: str, src_file_ids: list, dest_file_id: str = None, newdest_folder_entry.id,new_location,)- except Exception as storage_err:- raise RuntimeError(f"Move file failed at storage layer: {str(storage_err)}")+ except Exception as storage_err: # noqa: BLE001 - re-raised as RuntimeError with context; storage backends raise SDK-specific errors+ raise RuntimeError(f"Move file failed at storage layer: {storage_err!s}")if moved is False:raise RuntimeError("Move file failed at storage layer")updates["parent_id"] = dest_folder_entry.iddiff --git a/internal/service/file/file_folder.go b/internal/service/file/file_folder.goindex a8c3f8aba2..703761c0a1 100644--- a/internal/service/file/file_folder.go+++ b/internal/service/file/file_folder.go@@ -2,6 +2,7 @@ package fileimport ("context"+ "errors""fmt""path/filepath""ragflow/internal/common"@@ -308,6 +309,13 @@ func (s *FileService) getUniqueFilename(ctx context.Context, name, parentID, ten// CreateFolder creates a new folder or virtual filefunc (s *FileService) CreateFolder(ctx context.Context, tenantID, name, parentID, fileType string) (map[string]interface{}, error) {+ // "/" is the root folder name and the path separator used by recursive+ // folder creation, so names containing it collide with the root folder+ // and break path-based lookups.+ if strings.Contains(name, "/") {+ return nil, errors.New(`Folder name cannot contain "/"`)+ }+if parentID == "" {rootFolder, err := s.fileDAO.GetRootFolder(ctx, dao.DB, tenantID)if err != nil {@@ -425,6 +433,9 @@ func (s *FileService) MoveFiles(ctx context.Context, uid string, srcFileIDs []stif len(srcFileIDs) > 1 {return false, "new name can only be used with a single file"}+ if strings.Contains(newName, "/") {+ return false, `Name cannot contain "/"`+ }file := filesMap[srcFileIDs[0]]// Check extension for non-folder filesdiff --git a/internal/service/file/file_folder_test.go b/internal/service/file/file_folder_test.gonew file mode 100644index 0000000000..0ffe39529c--- /dev/null+++ b/internal/service/file/file_folder_test.go@@ -0,0 +1,53 @@+package file++import (+ "context"+ "strings"+ "testing"++ "ragflow/internal/dao"+ "ragflow/internal/entity"++ "github.com/glebarez/sqlite"+ "gorm.io/gorm"+)++func TestFileService_CreateFolder_RejectsSlashInName(t *testing.T) {+ svc := testFileService()+ for _, name := range []string{"/", "a/b", "dir/sub/"} {+ _, err := svc.CreateFolder(context.Background(), "tenant1", name, "pf1", FileTypeFolder)+ if err == nil || !strings.Contains(err.Error(), `cannot contain "/"`) {+ t.Fatalf("CreateFolder(%q) error = %v, want slash validation error", name, err)+ }+ }+}++func TestFileService_MoveFiles_RejectsSlashInNewName(t *testing.T) {+ db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{TranslateError: true})+ if err != nil {+ t.Fatalf("open sqlite: %v", err)+ }+ // Keep a single connection so the :memory: database is shared across+ // goroutines (sqlite :memory: is otherwise per-connection).+ if sqlDB, serr := db.DB(); serr == nil {+ sqlDB.SetMaxOpenConns(1)+ sqlDB.SetMaxIdleConns(1)+ }+ if err := db.AutoMigrate(&entity.File{}); err != nil {+ t.Fatalf("auto migrate: %v", err)+ }+ old := dao.DB+ dao.DB = db+ t.Cleanup(func() { dao.DB = old })++ folder := &entity.File{ID: "f1", ParentID: "pf1", TenantID: "tenant1", Name: "old", Type: FileTypeFolder}+ if err := db.Create(folder).Error; err != nil {+ t.Fatalf("seed folder: %v", err)+ }++ svc := testFileService()+ ok, msg := svc.MoveFiles(context.Background(), "tenant1", []string{"f1"}, "", "a/b")+ if ok || !strings.Contains(msg, `cannot contain "/"`) {+ t.Fatalf("MoveFiles rename = %v, %q, want slash validation error", ok, msg)+ }+}diff --git a/test/testcases/restful_api/test_file_routes_unit.py b/test/testcases/restful_api/test_file_routes_unit.pyindex 5813de2fd8..c3a4b82f31 100644--- a/test/testcases/restful_api/test_file_routes_unit.py+++ b/test/testcases/restful_api/test_file_routes_unit.py@@ -24,7 +24,6 @@ from types import ModuleType, SimpleNamespaceimport pytest-LOGGER = logging.getLogger(__name__)@@ -473,7 +472,7 @@ def _load_file2document_module(monkeypatch):@staticmethoddef insert(_payload):- return SimpleNamespace(to_json=lambda: {})+ return SimpleNamespace(to_json=dict)file2document_mod.File2DocumentService = _StubFile2DocumentServicemonkeypatch.setitem(sys.modules, "api.db.services.file2document_service", file2document_mod)@@ -669,7 +668,7 @@ def test_convert_files_mode_add_and_replace_unit(monkeypatch):monkeypatch.setattr(module.File2DocumentService, "get_by_file_id", lambda file_id: [SimpleNamespace(document_id=f"doc-{file_id}")])monkeypatch.setattr(module.File2DocumentService, "delete_by_document_id", lambda doc_id: deleted_doc_links.append(doc_id))monkeypatch.setattr(module.File2DocumentService, "delete_by_file_id", lambda file_id: deleted_file_links.append(file_id))- monkeypatch.setattr(module.File2DocumentService, "insert", lambda payload: inserted.append(payload) or SimpleNamespace(to_json=lambda: {}))+ monkeypatch.setattr(module.File2DocumentService, "insert", lambda payload: inserted.append(payload) or SimpleNamespace(to_json=dict))monkeypatch.setattr(module.DocumentService, "get_by_id", lambda doc_id: (True, SimpleNamespace(id=doc_id, kb_id="kb-old")))monkeypatch.setattr(module.DocumentService, "get_tenant_id", lambda _doc_id: "tenant-1")monkeypatch.setattr(module.DocumentService, "remove_document", lambda doc, tenant_id: removed.append((doc.id, tenant_id)) or True)@@ -892,6 +891,15 @@ def test_create_folder_rejects_duplicate_name(monkeypatch):assert message == "Duplicated folder name in the same folder."+def test_create_folder_rejects_slash_in_name(monkeypatch):+ module = _load_file_api_service(monkeypatch)++ ok, message = _run(module.create_folder("tenant1", "/", "pf1", module.FileType.FOLDER.value))+ assert ok is False+ assert message == 'Folder name cannot contain "/"'++@pytest.mark.p2def test_delete_files_checks_team_permission(monkeypatch):module = _load_file_api_service(monkeypatch)@@ -921,6 +929,20 @@ def test_move_files_rejects_extension_change_in_new_name(monkeypatch):assert message == "The extension of file can't be changed"+def test_move_files_rejects_slash_in_new_name(monkeypatch):+ module = _load_file_api_service(monkeypatch)+ monkeypatch.setattr(+ module.FileService,+ "get_by_ids",+ lambda _ids: [_DummyFile("file1", module.FileType.FOLDER.value, name="old")],+ )++ ok, message = _run(module.move_files("tenant1", ["file1"], new_name="a/b"))+ assert ok is False+ assert message == 'Name cannot contain "/"'++@pytest.mark.p2def test_move_files_handles_dest_and_storage_move(monkeypatch):module = _load_file_api_service(monkeypatch)diff --git a/test/testcases/test_http_api/test_file_app/test_file_routes.py b/test/testcases/test_http_api/test_file_app/test_file_routes.pyindex 9998665b30..af8aa96f95 100644--- a/test/testcases/test_http_api/test_file_app/test_file_routes.py+++ b/test/testcases/test_http_api/test_file_app/test_file_routes.py@@ -250,6 +250,15 @@ def test_create_folder_rejects_duplicate_name(monkeypatch):assert message == "Duplicated folder name in the same folder."+def test_create_folder_rejects_slash_in_name(monkeypatch):+ module = _load_file_api_service(monkeypatch)++ ok, message = _run(module.create_folder("tenant1", "/", "pf1", module.FileType.FOLDER.value))+ assert ok is False+ assert message == 'Folder name cannot contain "/"'++@pytest.mark.p2def test_delete_files_checks_team_permission(monkeypatch):module = _load_file_api_service(monkeypatch)@@ -279,6 +288,20 @@ def test_move_files_rejects_extension_change_in_new_name(monkeypatch):assert message == "The extension of file can't be changed"+def test_move_files_rejects_slash_in_new_name(monkeypatch):+ module = _load_file_api_service(monkeypatch)+ monkeypatch.setattr(+ module.FileService,+ "get_by_ids",+ lambda _ids: [_DummyFile("file1", module.FileType.FOLDER.value, name="old")],+ )++ ok, message = _run(module.move_files("tenant1", ["file1"], new_name="a/b"))+ assert ok is False+ assert message == 'Name cannot contain "/"'++@pytest.mark.p2def test_move_files_handles_dest_and_storage_move(monkeypatch):module = _load_file_api_service(monkeypatch)diff --git a/web/src/components/rename-dialog/index.tsx b/web/src/components/rename-dialog/index.tsxindex 4fc14b0292..edb97cd3b8 100644--- a/web/src/components/rename-dialog/index.tsx+++ b/web/src/components/rename-dialog/index.tsx@@ -34,7 +34,12 @@ export function RenameDialog({onOk,loading,title,-}: IModalProps<any> & { initialName?: string; title?: ReactNode }) {+ forbidSlash,+}: IModalProps<any> & {+ initialName?: string;+ title?: ReactNode;+ forbidSlash?: boolean;+}) {const { t } = useTranslation();return (@@ -47,6 +52,7 @@ export function RenameDialog({initialName={initialName}hideModal={hideModal}onOk={onOk}+ forbidSlash={forbidSlash}></RenameForm><DialogFooter><ButtonLoadingdiff --git a/web/src/components/rename-dialog/rename-form.tsx b/web/src/components/rename-dialog/rename-form.tsxindex 41bf3783c5..6733e34c15 100644--- a/web/src/components/rename-dialog/rename-form.tsx+++ b/web/src/components/rename-dialog/rename-form.tsx@@ -38,15 +38,21 @@ export function RenameForm({initialName,hideModal,onOk,-}: IModalProps<any> & { initialName?: string }) {+ forbidSlash = false,+}: IModalProps<any> & { initialName?: string; forbidSlash?: boolean }) {const { t } = useTranslation();+ const baseNameSchema = z+ .string()+ .min(1, {+ message: t('common.namePlaceholder'),+ })+ .trim();const FormSchema = z.object({- name: z- .string()- .min(1, {- message: t('common.namePlaceholder'),- })- .trim(),+ name: forbidSlash+ ? baseNameSchema.refine((value) => !value.includes('/'), {+ message: t('common.nameSlashError'),+ })+ : baseNameSchema,});const form = useForm<z.infer<typeof FormSchema>>({diff --git a/web/src/locales/en.ts b/web/src/locales/en.tsindex 95563f3759..c480255357 100644--- a/web/src/locales/en.ts+++ b/web/src/locales/en.ts@@ -22,6 +22,7 @@ export default {stop: 'Stop',resume: 'Resume',namePlaceholder: 'Please input name',+ nameSlashError: 'Name cannot contain "/"',descriptionPlaceholder: 'Enter description',next: 'Next',create: 'Create',diff --git a/web/src/locales/zh-traditional.ts b/web/src/locales/zh-traditional.tsindex b757ed89ef..a77d2a5ce7 100644--- a/web/src/locales/zh-traditional.ts+++ b/web/src/locales/zh-traditional.ts@@ -10,6 +10,7 @@ export default {name: '名稱',save: '保持',namePlaceholder: '請輸入名稱',+ nameSlashError: '名稱不能包含 "/"',next: '下一步',create: '創建',edit: '編輯',diff --git a/web/src/locales/zh.ts b/web/src/locales/zh.tsindex 308630b031..77fe846cec 100644--- a/web/src/locales/zh.ts+++ b/web/src/locales/zh.ts@@ -22,6 +22,7 @@ export default {stop: '停止',resume: '恢复',namePlaceholder: '请输入名称',+ nameSlashError: '名称不能包含 "/"',descriptionPlaceholder: '请输入描述',next: '下一步',create: '创建',diff --git a/web/src/pages/files/create-folder-dialog/create-folder-form.tsx b/web/src/pages/files/create-folder-dialog/create-folder-form.tsxindex a575d42c5a..2bc045cf7c 100644--- a/web/src/pages/files/create-folder-dialog/create-folder-form.tsx+++ b/web/src/pages/files/create-folder-dialog/create-folder-form.tsx@@ -25,7 +25,10 @@ export function CreateFolderForm({ hideModal, onOk }: IModalProps<any>) {.min(1, {message: t('common.namePlaceholder'),})- .trim(),+ .trim()+ .refine((value) => !value.includes('/'), {+ message: t('common.nameSlashError'),+ }),});const form = useForm<z.infer<typeof FormSchema>>({diff --git a/web/src/pages/files/files-table.tsx b/web/src/pages/files/files-table.tsxindex 4c1268ccf5..96d3155258 100644--- a/web/src/pages/files/files-table.tsx+++ b/web/src/pages/files/files-table.tsx@@ -414,6 +414,7 @@ export function FilesTable({onOk={onFileRenameOk}initialName={initialFileName}loading={fileRenameLoading}+ forbidSlash></RenameDialog>)}</>