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
refa: derive service identity from context (#21942)
buua43618562f2cdc2c
diff --git a/internal/handler/agent.go b/internal/handler/agent.goindex 04fc5ccba0..fd9223c674 100644--- a/internal/handler/agent.go+++ b/internal/handler/agent.go@@ -56,10 +56,10 @@ type agentFileService interface {DownloadAgentFile(ctx context.Context, tenantID, location string) ([]byte, error)// UploadInfos stores raw bytes in the per-user downloads bucket and// returns lightweight descriptors.- UploadInfos(ctx context.Context, userID string, files []*multipart.FileHeader) ([]map[string]interface{}, error)+ UploadInfos(ctx context.Context, files []*multipart.FileHeader) ([]map[string]interface{}, error)// UploadFromURL downloads a remote file (with SSRF protection) and// stores it as an info blob.- UploadFromURL(ctx context.Context, tenantID, rawURL string) (map[string]interface{}, error)+ UploadFromURL(ctx context.Context, rawURL string) (map[string]interface{}, error)}// chatAgentService is the subset of AgentService used by the chat-completiondiff --git a/internal/handler/agent_download_test.go b/internal/handler/agent_download_test.goindex 1b48fb3609..30774d5ae1 100644--- a/internal/handler/agent_download_test.go+++ b/internal/handler/agent_download_test.go@@ -44,13 +44,13 @@ type fakeAgentFileService struct {urlUploadErr error}-func (f *fakeAgentFileService) UploadInfos(ctx context.Context, _ string, _ []*multipart.FileHeader) ([]map[string]interface{}, error) {+func (f *fakeAgentFileService) UploadInfos(ctx context.Context, _ []*multipart.FileHeader) ([]map[string]interface{}, error) {if f.uploadErr != nil {return nil, f.uploadErr}return f.uploadList, nil}-func (f *fakeAgentFileService) UploadFromURL(ctx context.Context, _ string, _ string) (map[string]interface{}, error) {+func (f *fakeAgentFileService) UploadFromURL(ctx context.Context, _ string) (map[string]interface{}, error) {if f.urlUploadErr != nil {return nil, f.urlUploadErr}diff --git a/internal/handler/agent_upload.go b/internal/handler/agent_upload.goindex 0125a3e0dc..41175c241d 100644--- a/internal/handler/agent_upload.go+++ b/internal/handler/agent_upload.go@@ -56,11 +56,6 @@ const canvasNoAccessMessage = "Make sure you have permission to access the agent// UploadAgentFile POST /api/v1/agents/:canvas_id/uploadfunc (h *AgentHandler) UploadAgentFile(c *gin.Context) {- user, code, msg := GetUser(c)- if code != common.CodeSuccess {- common.RespondError(c, code, msg)- return- }canvasID := c.Param("canvas_id")if canvasID == "" {common.RespondError(c, common.CodeArgumentError, "`canvas_id` is required.")@@ -115,7 +110,7 @@ func (h *AgentHandler) UploadAgentFile(c *gin.Context) {// conditions are met.ctx := c.Request.Context()if url := c.Query("url"); url != "" && len(files) == 1 {- uploaded, err := h.fileService.UploadFromURL(ctx, user.ID, url)+ uploaded, err := h.fileService.UploadFromURL(ctx, url)if err != nil {common.RespondError(c, common.CodeServerError, err.Error())return@@ -129,7 +124,7 @@ func (h *AgentHandler) UploadAgentFile(c *gin.Context) {return}- results, err := h.fileService.UploadInfos(ctx, user.ID, files)+ results, err := h.fileService.UploadInfos(ctx, files)if err != nil {common.RespondError(c, common.CodeServerError, err.Error())returndiff --git a/internal/handler/bot_test.go b/internal/handler/bot_test.goindex c5839beb73..44386a3cdd 100644--- a/internal/handler/bot_test.go+++ b/internal/handler/bot_test.go@@ -773,11 +773,11 @@ func (f *fakeFileService) DownloadAgentFile(ctx context.Context, tenantID, locatreturn f.blob, f.err}-func (f *fakeFileService) UploadInfos(ctx context.Context, userID string, files []*multipart.FileHeader) ([]map[string]interface{}, error) {+func (f *fakeFileService) UploadInfos(ctx context.Context, files []*multipart.FileHeader) ([]map[string]interface{}, error) {return nil, nil}-func (f *fakeFileService) UploadFromURL(ctx context.Context, tenantID, rawURL string) (map[string]interface{}, error) {+func (f *fakeFileService) UploadFromURL(ctx context.Context, rawURL string) (map[string]interface{}, error) {return nil, nil}diff --git a/internal/handler/compilation_template_group.go b/internal/handler/compilation_template_group.goindex e21e0f53ea..dfb7f8f529 100644--- a/internal/handler/compilation_template_group.go+++ b/internal/handler/compilation_template_group.go@@ -55,11 +55,6 @@ func NewCompilationTemplateGroupHandler(svc *service.CompilationTemplateGroupSer// @Success 200 {object} map[string]interface{}// @Router /v1/compilation-template-groups [get]func (h *CompilationTemplateGroupHandler) List(c *gin.Context) {- user, code, msg := GetUser(c)- if code != common.CodeSuccess {- common.RespondError(c, code, msg)- return- }page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "30"))if page < 1 {@@ -71,10 +66,14 @@ func (h *CompilationTemplateGroupHandler) List(c *gin.Context) {keywords := c.Query("keywords")scope := c.Query("scope")tenantID := c.Query("tenant_id")+ ctx := c.Request.Context()if tenantID == "" {- tenantID = user.ID+ tenantID = permission.TenantIDFromContext(ctx)+ if tenantID == "" {+ tenantID = permission.UserIDFromContext(ctx)+ }} else if err := permission.NewDatabaseChecker(dao.DB).CheckTenant(- c.Request.Context(), tenantID, permission.TenantMember,+ ctx, tenantID, permission.TenantMember,); err != nil {respondPermissionError(c, err, false)return@@ -83,7 +82,7 @@ func (h *CompilationTemplateGroupHandler) List(c *gin.Context) {desc := c.DefaultQuery("desc", "true") != "false"terms := orderTermsFromQuery(c, orderby, desc)- groups, err := h.compilationTemplateGroupService.ListSaved(c.Request.Context(), tenantID, keywords, scope, terms)+ groups, err := h.compilationTemplateGroupService.ListSaved(ctx, tenantID, keywords, scope, terms)if err != nil {common.RespondError(c, common.CodeExceptionError, err.Error())return@@ -113,13 +112,8 @@ func (h *CompilationTemplateGroupHandler) List(c *gin.Context) {// @Success 200 {object} map[string]interface{}// @Router /v1/compilation-template-groups/{group_id} [get]func (h *CompilationTemplateGroupHandler) Get(c *gin.Context) {- user, code, msg := GetUser(c)- if code != common.CodeSuccess {- common.RespondError(c, code, msg)- return- }id := c.Param("group_id")- group, err := h.compilationTemplateGroupService.GetSaved(c.Request.Context(), user.ID, id)+ group, err := h.compilationTemplateGroupService.GetSaved(c.Request.Context(), id)if err != nil {common.RespondError(c, common.CodeExceptionError, err.Error())return@@ -140,11 +134,6 @@ func (h *CompilationTemplateGroupHandler) Get(c *gin.Context) {// @Success 200 {object} map[string]interface{}// @Router /v1/compilation-template-groups [post]func (h *CompilationTemplateGroupHandler) Save(c *gin.Context) {- user, code, msg := GetUser(c)- if code != common.CodeSuccess {- common.RespondError(c, code, msg)- return- }var req service.GroupRequestif err := c.ShouldBindJSON(&req); err != nil {common.RespondError(c, common.CodeArgumentError, "Invalid request: "+err.Error())@@ -154,7 +143,7 @@ func (h *CompilationTemplateGroupHandler) Save(c *gin.Context) {common.RespondError(c, common.CodeDataError, err.Error())return}- group, err := h.compilationTemplateGroupService.CreateGroup(c.Request.Context(), user.ID, &req)+ group, err := h.compilationTemplateGroupService.CreateGroup(c.Request.Context(), &req)if err != nil {common.RespondError(c, common.CodeDataError, err.Error())return@@ -172,11 +161,6 @@ func (h *CompilationTemplateGroupHandler) Save(c *gin.Context) {// @Success 200 {object} map[string]interface{}// @Router /v1/compilation-template-groups/{group_id} [put]func (h *CompilationTemplateGroupHandler) Update(c *gin.Context) {- user, code, msg := GetUser(c)- if code != common.CodeSuccess {- common.RespondError(c, code, msg)- return- }id := c.Param("group_id")var req service.GroupRequestif err := c.ShouldBindJSON(&req); err != nil {@@ -188,7 +172,7 @@ func (h *CompilationTemplateGroupHandler) Update(c *gin.Context) {return}if req.Name != "" {- nameExists, nerr := h.compilationTemplateGroupService.NameExists(c.Request.Context(), user.ID, req.Name, id)+ nameExists, nerr := h.compilationTemplateGroupService.NameExists(c.Request.Context(), req.Name, id)if nerr != nil {common.RespondError(c, common.CodeExceptionError, nerr.Error())return@@ -198,7 +182,7 @@ func (h *CompilationTemplateGroupHandler) Update(c *gin.Context) {return}}- group, err := h.compilationTemplateGroupService.UpdateGroup(c.Request.Context(), user.ID, id, &req)+ group, err := h.compilationTemplateGroupService.UpdateGroup(c.Request.Context(), id, &req)if err != nil {common.RespondError(c, common.CodeDataError, err.Error())return@@ -219,13 +203,8 @@ func (h *CompilationTemplateGroupHandler) Update(c *gin.Context) {// @Success 200 {object} map[string]interface{}// @Router /v1/compilation-template-groups/{group_id} [delete]func (h *CompilationTemplateGroupHandler) Delete(c *gin.Context) {- user, code, msg := GetUser(c)- if code != common.CodeSuccess {- common.RespondError(c, code, msg)- return- }id := c.Param("group_id")- ok, err := h.compilationTemplateGroupService.DeleteGroup(c.Request.Context(), user.ID, id)+ ok, err := h.compilationTemplateGroupService.DeleteGroup(c.Request.Context(), id)if err != nil {common.RespondError(c, common.CodeExceptionError, err.Error())returndiff --git a/internal/handler/compilation_template_group_test.go b/internal/handler/compilation_template_group_test.goindex b817b9d196..3fc2f311b2 100644--- a/internal/handler/compilation_template_group_test.go+++ b/internal/handler/compilation_template_group_test.go@@ -30,6 +30,7 @@ import ("ragflow/internal/common""ragflow/internal/dao""ragflow/internal/entity"+ "ragflow/internal/permission""ragflow/internal/service")@@ -63,11 +64,11 @@ func newCompilationTemplateGroupHandlerRouter() *gin.Engine {h := NewCompilationTemplateGroupHandler(service.NewCompilationTemplateGroupService())r := gin.New()r.POST("/api/v1/compilation-template-groups", func(c *gin.Context) {- c.Set("user", &entity.User{ID: "user-1"})+ c.Request = c.Request.WithContext(permission.WithIdentity(c.Request.Context(), "user-1", "user-1"))h.Save(c)})r.PUT("/api/v1/compilation-template-groups/:group_id", func(c *gin.Context) {- c.Set("user", &entity.User{ID: "user-1"})+ c.Request = c.Request.WithContext(permission.WithIdentity(c.Request.Context(), "user-1", "user-1"))h.Update(c)})return rdiff --git a/internal/handler/document.go b/internal/handler/document.goindex 58ebc76cdc..8cfb43bcc4 100644--- a/internal/handler/document.go+++ b/internal/handler/document.go@@ -93,8 +93,8 @@ type latestIngestionEventLookup interface {// fileUploadIface defines the FileService upload methods used by DocumentHandler.type fileUploadIface interface {- UploadDocumentInfos(ctx context.Context, userID string, files []*multipart.FileHeader) ([]map[string]interface{}, common.ErrorCode, error)- UploadDocumentInfoByURL(ctx context.Context, userID, rawURL string) (map[string]interface{}, common.ErrorCode, error)+ UploadDocumentInfos(ctx context.Context, files []*multipart.FileHeader) ([]map[string]interface{}, common.ErrorCode, error)+ UploadDocumentInfoByURL(ctx context.Context, rawURL string) (map[string]interface{}, common.ErrorCode, error)}// DocumentHandler document handler@@ -1771,7 +1771,7 @@ func (h *DocumentHandler) UploadInfo(c *gin.Context) {}if rawURL != "" {- data, code, err := h.fileService.UploadDocumentInfoByURL(ctx, user.ID, rawURL)+ data, code, err := h.fileService.UploadDocumentInfoByURL(ctx, rawURL)if err != nil {common.RespondError(c, code, err.Error())return@@ -1780,7 +1780,7 @@ func (h *DocumentHandler) UploadInfo(c *gin.Context) {return}- data, code, err := h.fileService.UploadDocumentInfos(ctx, user.ID, fileHeaders)+ data, code, err := h.fileService.UploadDocumentInfos(ctx, fileHeaders)if err != nil {common.RespondError(c, code, err.Error())returndiff --git a/internal/handler/file.go b/internal/handler/file.goindex 82b7cafd4f..d506701828 100644--- a/internal/handler/file.go+++ b/internal/handler/file.go@@ -128,7 +128,7 @@ func (h *FileHandler) ListFiles(c *gin.Context) {terms := orderTermsFromQuery(c, orderBy, desc)ctx := c.Request.Context()- result, err := h.fileService.ListFilesForTenant(ctx, userID, tenantID, parentID, page, pageSize, terms, keywords)+ result, err := h.fileService.ListFilesForTenant(ctx, tenantID, parentID, page, pageSize, terms, keywords)if err != nil {respondFileServiceError(c, err)return@@ -145,13 +145,11 @@ func (h *FileHandler) ListFiles(c *gin.Context) {// @Success 200 {object} map[string]interface{}// @Router /api/v1/files/{id}/parent [get]func (h *FileHandler) GetParentFolder(c *gin.Context) {- user, errorCode, errorMessage := GetUser(c)+ _, errorCode, errorMessage := GetUser(c)if errorCode != common.CodeSuccess {common.RespondError(c, errorCode, errorMessage)return}- userID := user.ID-fileID := c.Param("id")if fileID == "" {common.RespondError(c, common.CodeBadRequest, "file_id is required")@@ -160,7 +158,7 @@ func (h *FileHandler) GetParentFolder(c *gin.Context) {ctx := c.Request.Context()// Get parent folder with permission check- parentFolder, err := h.fileService.GetParentFolder(ctx, userID, fileID)+ parentFolder, err := h.fileService.GetParentFolder(ctx, fileID)if err != nil {respondFileServiceError(c, err)return@@ -178,13 +176,11 @@ func (h *FileHandler) GetParentFolder(c *gin.Context) {// @Success 200 {object} map[string]interface{}// @Router /api/v1/files/{id}/ancestors [get]func (h *FileHandler) GetFileAncestors(c *gin.Context) {- user, errorCode, errorMessage := GetUser(c)+ _, errorCode, errorMessage := GetUser(c)if errorCode != common.CodeSuccess {common.RespondError(c, errorCode, errorMessage)return}- userID := user.ID-fileID := c.Param("id")if fileID == "" {common.RespondError(c, common.CodeBadRequest, "file id is required")@@ -197,9 +193,9 @@ func (h *FileHandler) GetFileAncestors(c *gin.Context) {var parentFolders []map[string]interface{}var err errorif tenantID == "" {- parentFolders, err = h.fileService.GetAllParentFolders(ctx, userID, fileID)+ parentFolders, err = h.fileService.GetAllParentFolders(ctx, fileID)} else {- parentFolders, err = h.fileService.GetAllParentFoldersForTenant(ctx, userID, tenantID, fileID)+ parentFolders, err = h.fileService.GetAllParentFoldersForTenant(ctx, tenantID, fileID)}if err != nil {respondFileServiceError(c, err)@@ -289,11 +285,7 @@ func (h *FileHandler) UploadFile(c *gin.Context) {}parentID := c.PostForm("parent_id")if parentID == "" {- tenantID := strings.TrimSpace(c.GetString("tenant_id"))- if tenantID == "" {- tenantID = userID- }- rootFolder, err := h.fileService.GetRootFolder(ctx, tenantID)+ rootFolder, err := h.fileService.GetRootFolder(ctx)if err != nil {respondFileServiceError(c, err)operationLog.Code = int(common.CodeBadRequest)@@ -346,11 +338,7 @@ func (h *FileHandler) UploadFile(c *gin.Context) {parentID := req.ParentIDif parentID == "" {- tenantID := strings.TrimSpace(c.GetString("tenant_id"))- if tenantID == "" {- tenantID = userID- }- rootFolder, err := h.fileService.GetRootFolder(ctx, tenantID)+ rootFolder, err := h.fileService.GetRootFolder(ctx)if err != nil {respondFileServiceError(c, err)operationLog.Code = int(common.CodeBadRequest)@@ -361,7 +349,7 @@ func (h *FileHandler) UploadFile(c *gin.Context) {}operationLog.Resources["directory_name"] = req.Name- result, err := h.fileService.CreateFolder(ctx, userID, req.Name, parentID, req.Type)+ result, err := h.fileService.CreateFolder(ctx, req.Name, parentID, req.Type)if err != nil {if respondPermissionErrorIf(c, err, true) {return@@ -502,7 +490,7 @@ func (h *FileHandler) MoveFiles(c *gin.Context) {}ctx := c.Request.Context()- if err := h.fileService.MoveFiles(ctx, user.ID, req.SrcFileIDs, req.DestFileID, req.NewName); err != nil {+ if err := h.fileService.MoveFiles(ctx, req.SrcFileIDs, req.DestFileID, req.NewName); err != nil {if respondPermissionErrorIf(c, err, true) {return}@@ -688,7 +676,7 @@ func (h *FileHandler) LinkToDatasets(c *gin.Context) {return}ctx := c.Request.Context()- if err := h.file2DocumentService.LinkToDatasets(ctx, user.ID, &req, mode); err != nil {+ if err := h.file2DocumentService.LinkToDatasets(ctx, &req, mode); err != nil {errorCode = linkToDatasetsErrorCode(err)common.RespondError(c, errorCode, err.Error())operationLog.Code = int(errorCode)diff --git a/internal/service/compilation_template_group_service.go b/internal/service/compilation_template_group_service.goindex 41441a078c..235271da5f 100644--- a/internal/service/compilation_template_group_service.go+++ b/internal/service/compilation_template_group_service.go@@ -104,7 +104,15 @@ func (s *CompilationTemplateGroupService) ListSaved(ctx context.Context, tenantI// GetSaved returns a single group with its nested templates, or nil. Mirrors// Python get_saved().-func (s *CompilationTemplateGroupService) GetSaved(ctx context.Context, tenantID, groupID string) (*GroupListItem, error) {+func (s *CompilationTemplateGroupService) GetSaved(ctx context.Context, groupID string) (*GroupListItem, error) {+ userID := strings.TrimSpace(permission.UserIDFromContext(ctx))+ if userID == "" {+ return nil, permission.ErrUnauthenticated+ }+ tenantID := strings.TrimSpace(permission.TenantIDFromContext(ctx))+ if tenantID == "" {+ tenantID = userID+ }group, err := s.groupDAO.GetSaved(ctx, dao.DB, tenantID, groupID)if err != nil || group == nil {return nil, err@@ -116,7 +124,15 @@ func (s *CompilationTemplateGroupService) GetSaved(ctx context.Context, tenantID// create_group(). It returns a GroupValidationError for payload/scope problems.// The group and all child writes are committed atomically so a mid-way failure// cannot leave a partially-populated group behind.-func (s *CompilationTemplateGroupService) CreateGroup(ctx context.Context, tenantID string, req *GroupRequest) (*GroupListItem, error) {+func (s *CompilationTemplateGroupService) CreateGroup(ctx context.Context, req *GroupRequest) (*GroupListItem, error) {+ creatorID := strings.TrimSpace(permission.UserIDFromContext(ctx))+ if creatorID == "" {+ return nil, permission.ErrUnauthenticated+ }+ tenantID := strings.TrimSpace(permission.TenantIDFromContext(ctx))+ if tenantID == "" {+ tenantID = creatorID+ }if err := validateGroupPayload(req, true); err != nil {return nil, err}@@ -133,7 +149,6 @@ func (s *CompilationTemplateGroupService) CreateGroup(ctx context.Context, tenan}groupID := common.GenerateUUID()- creatorID := identityForTemplateTenant(ctx, tenantID).UserIDif err := dao.DB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {group := &entity.CompilationTemplateGroup{ID: groupID,@@ -151,13 +166,21 @@ func (s *CompilationTemplateGroupService) CreateGroup(ctx context.Context, tenan}); err != nil {return nil, err}- return s.GetSaved(ctx, tenantID, groupID)+ return s.GetSaved(ctx, groupID)}// UpdateGroup applies a partial update to a group and reconciles its child// templates. Mirrors Python update_group(). The field update and child// reconciliation are committed atomically.-func (s *CompilationTemplateGroupService) UpdateGroup(ctx context.Context, tenantID, groupID string, req *GroupRequest) (*GroupListItem, error) {+func (s *CompilationTemplateGroupService) UpdateGroup(ctx context.Context, groupID string, req *GroupRequest) (*GroupListItem, error) {+ userID := strings.TrimSpace(permission.UserIDFromContext(ctx))+ if userID == "" {+ return nil, permission.ErrUnauthenticated+ }+ tenantID := strings.TrimSpace(permission.TenantIDFromContext(ctx))+ if tenantID == "" {+ tenantID = userID+ }existing, err := s.groupDAO.GetSaved(ctx, dao.DB, tenantID, groupID)if err != nil {return nil, err@@ -197,12 +220,20 @@ func (s *CompilationTemplateGroupService) UpdateGroup(ctx context.Context, tenan}); err != nil {return nil, err}- return s.GetSaved(ctx, tenantID, groupID)+ return s.GetSaved(ctx, groupID)}// DeleteGroup soft-deletes a group and its valid child templates. Mirrors// Python delete_group(). Returns (false, nil) when the group is missing.-func (s *CompilationTemplateGroupService) DeleteGroup(ctx context.Context, tenantID, groupID string) (bool, error) {+func (s *CompilationTemplateGroupService) DeleteGroup(ctx context.Context, groupID string) (bool, error) {+ userID := strings.TrimSpace(permission.UserIDFromContext(ctx))+ if userID == "" {+ return false, permission.ErrUnauthenticated+ }+ tenantID := strings.TrimSpace(permission.TenantIDFromContext(ctx))+ if tenantID == "" {+ tenantID = userID+ }existing, err := s.groupDAO.GetSaved(ctx, dao.DB, tenantID, groupID)if err != nil {return false, err@@ -231,7 +262,15 @@ func groupValidationErrorf(format string, a ...interface{}) error {// NameExists reports whether a valid group with the given name exists for the// tenant (optionally excluding excludeID), mirroring Python name_exists().-func (s *CompilationTemplateGroupService) NameExists(ctx context.Context, tenantID, name string, excludeIDs ...string) (bool, error) {+func (s *CompilationTemplateGroupService) NameExists(ctx context.Context, name string, excludeIDs ...string) (bool, error) {+ userID := strings.TrimSpace(permission.UserIDFromContext(ctx))+ if userID == "" {+ return false, permission.ErrUnauthenticated+ }+ tenantID := strings.TrimSpace(permission.TenantIDFromContext(ctx))+ if tenantID == "" {+ tenantID = userID+ }excludeID := ""if len(excludeIDs) > 0 {excludeID = excludeIDs[0]diff --git a/internal/service/compilation_template_group_service_test.go b/internal/service/compilation_template_group_service_test.goindex 0d5b56996c..8dcb794c5e 100644--- a/internal/service/compilation_template_group_service_test.go+++ b/internal/service/compilation_template_group_service_test.go@@ -27,6 +27,7 @@ import ("ragflow/internal/dao""ragflow/internal/entity"+ "ragflow/internal/permission")// setupCompilationGroupTestDB migrates the minimal schema for the group@@ -59,7 +60,8 @@ func seedCompilationGroup(t *testing.T, svc *CompilationTemplateGroupService, tefor _, name := range templateNames {templates = append(templates, &GroupTemplate{Name: name, Kind: "text", Config: entity.JSONMap{}})}- group, err := svc.CreateGroup(t.Context(), tenantID, &GroupRequest{Name: groupName, Templates: templates})+ ctx := permission.WithIdentity(t.Context(), tenantID, tenantID)+ group, err := svc.CreateGroup(ctx, &GroupRequest{Name: groupName, Templates: templates})if err != nil {t.Fatalf("seed group %q: %v", groupName, err)}@@ -130,14 +132,14 @@ func templateByID(t *testing.T, group *GroupListItem, id string) *TemplateListItfunc TestCreateGroupDoesNotMutateRequestName(t *testing.T) {setupCompilationGroupTestDB(t)svc := NewCompilationTemplateGroupService()- ctx := t.Context()+ ctx := permission.WithIdentity(t.Context(), "tenant-1", "tenant-1")req := &GroupRequest{Name: "Group A",Templates: []*GroupTemplate{{Name: "tpl", Kind: "text", Config: entity.JSONMap{}}},}- first, err := svc.CreateGroup(ctx, "tenant-1", req)+ first, err := svc.CreateGroup(ctx, req)if err != nil {t.Fatalf("first CreateGroup: %v", err)}@@ -148,7 +150,7 @@ func TestCreateGroupDoesNotMutateRequestName(t *testing.T) {t.Fatalf("CreateGroup mutated req.Name to %q", req.Name)}- second, err := svc.CreateGroup(ctx, "tenant-1", req)+ second, err := svc.CreateGroup(ctx, req)if err != nil {t.Fatalf("second CreateGroup: %v", err)}@@ -165,12 +167,12 @@ func TestCreateGroupDoesNotMutateRequestName(t *testing.T) {func TestReconcileChildrenAllowsRenameOntoRemovedName(t *testing.T) {setupCompilationGroupTestDB(t)svc := NewCompilationTemplateGroupService()- ctx := t.Context()+ ctx := permission.WithIdentity(t.Context(), "tenant-1", "tenant-1")group := seedCompilationGroup(t, svc, "tenant-1", "Group A", "A", "B")b := templateByName(t, group, "B")- updated, err := svc.UpdateGroup(ctx, "tenant-1", group.ID, &GroupRequest{+ updated, err := svc.UpdateGroup(ctx, group.ID, &GroupRequest{Templates: []*GroupTemplate{{ID: b.ID, Name: "A", Kind: "text", Config: entity.JSONMap{}}},})if err != nil {@@ -189,13 +191,13 @@ func TestReconcileChildrenAllowsRenameOntoRemovedName(t *testing.T) {func TestReconcileChildrenAllowsNameSwap(t *testing.T) {setupCompilationGroupTestDB(t)svc := NewCompilationTemplateGroupService()- ctx := t.Context()+ ctx := permission.WithIdentity(t.Context(), "tenant-1", "tenant-1")group := seedCompilationGroup(t, svc, "tenant-1", "Group A", "A", "B")a := templateByName(t, group, "A")b := templateByName(t, group, "B")- updated, err := svc.UpdateGroup(ctx, "tenant-1", group.ID, &GroupRequest{+ updated, err := svc.UpdateGroup(ctx, group.ID, &GroupRequest{Templates: []*GroupTemplate{{ID: a.ID, Name: "B", Kind: "text", Config: entity.JSONMap{}},{ID: b.ID, Name: "A", Kind: "text", Config: entity.JSONMap{}},@@ -216,13 +218,13 @@ func TestReconcileChildrenAllowsNameSwap(t *testing.T) {func TestReconcileChildrenRejectsDuplicateSurvivingName(t *testing.T) {setupCompilationGroupTestDB(t)svc := NewCompilationTemplateGroupService()- ctx := t.Context()+ ctx := permission.WithIdentity(t.Context(), "tenant-1", "tenant-1")group := seedCompilationGroup(t, svc, "tenant-1", "Group A", "A", "B")a := templateByName(t, group, "A")b := templateByName(t, group, "B")- _, err := svc.UpdateGroup(ctx, "tenant-1", group.ID, &GroupRequest{+ _, err := svc.UpdateGroup(ctx, group.ID, &GroupRequest{Templates: []*GroupTemplate{{ID: a.ID, Name: "b", Kind: "text", Config: entity.JSONMap{}},{ID: b.ID, Name: "B", Kind: "text", Config: entity.JSONMap{}},@@ -239,11 +241,11 @@ func TestReconcileChildrenRejectsDuplicateSurvivingName(t *testing.T) {func TestReconcileChildrenAllowsLegacyCaseVariantDuplicates(t *testing.T) {setupCompilationGroupTestDB(t)svc := NewCompilationTemplateGroupService()- ctx := t.Context()+ ctx := permission.WithIdentity(t.Context(), "tenant-1", "tenant-1")ids := seedLegacyCompilationGroup(t, "tenant-1", "legacy-group", "A", "a")- updated, err := svc.UpdateGroup(ctx, "tenant-1", "legacy-group", &GroupRequest{+ updated, err := svc.UpdateGroup(ctx, "legacy-group", &GroupRequest{Templates: []*GroupTemplate{{ID: ids["A"], Name: "A", Kind: "text", Config: entity.JSONMap{}},{ID: ids["a"], Name: "a", Kind: "text", Config: entity.JSONMap{}},@@ -262,11 +264,11 @@ func TestReconcileChildrenAllowsLegacyCaseVariantDuplicates(t *testing.T) {func TestReconcileChildrenRejectsRenameOntoUnchangedLegacyName(t *testing.T) {setupCompilationGroupTestDB(t)svc := NewCompilationTemplateGroupService()- ctx := t.Context()+ ctx := permission.WithIdentity(t.Context(), "tenant-1", "tenant-1")ids := seedLegacyCompilationGroup(t, "tenant-1", "legacy-group-2", "A", "a", "B")- _, err := svc.UpdateGroup(ctx, "tenant-1", "legacy-group-2", &GroupRequest{+ _, err := svc.UpdateGroup(ctx, "legacy-group-2", &GroupRequest{Templates: []*GroupTemplate{{ID: ids["A"], Name: "b", Kind: "text", Config: entity.JSONMap{}},{ID: ids["a"], Name: "a", Kind: "text", Config: entity.JSONMap{}},@@ -284,7 +286,7 @@ func TestReconcileChildrenRejectsRenameOntoUnchangedLegacyName(t *testing.T) {func TestCreateGroupSingleTemplateSharesFallbackName(t *testing.T) {setupCompilationGroupTestDB(t)svc := NewCompilationTemplateGroupService()- ctx := t.Context()+ ctx := permission.WithIdentity(t.Context(), "tenant-1", "tenant-1")first := seedCompilationGroup(t, svc, "tenant-1", "Group A", "tpl")if first.Templates[0].Name != "Group A" {@@ -299,7 +301,7 @@ func TestCreateGroupSingleTemplateSharesFallbackName(t *testing.T) {t.Fatalf("second template name = %q, want %q", second.Templates[0].Name, "Group A(1)")}- updated, err := svc.UpdateGroup(ctx, "tenant-1", second.ID, &GroupRequest{+ updated, err := svc.UpdateGroup(ctx, second.ID, &GroupRequest{Name: "Group A(1)",Templates: []*GroupTemplate{{ID: second.Templates[0].ID, Name: "Group A(1)", Kind: "text", Config: entity.JSONMap{}},diff --git a/internal/service/document/file2document.go b/internal/service/document/file2document.goindex 81702e54cb..78a9d49f8e 100644--- a/internal/service/document/file2document.go+++ b/internal/service/document/file2document.go@@ -79,7 +79,7 @@ type LinkToDatasetsRequest struct {//// On validation failure it returns a sentinel error (see ErrLink* above) so the// handler can map it to a Python-compatible response without leaking internals.-func (s *File2DocumentService) LinkToDatasets(ctx context.Context, userID string, req *LinkToDatasetsRequest, mode string) error {+func (s *File2DocumentService) LinkToDatasets(ctx context.Context, req *LinkToDatasetsRequest, mode string) error {// ── 1. Validate files exist ───────────────────────────────────────────────files, err := s.fileDAO.GetByIDs(ctx, dao.DB, req.FileIDs)if err != nil {@@ -164,8 +164,8 @@ func (s *File2DocumentService) LinkToDatasets(ctx context.Context, userID string// ── 6. Run conversion in background (fire-and-forget) ────────────────────kbIDs := req.KbIDsgo func() {- newCtx := context.Background()- if err = s.convertFiles(newCtx, allFileIDs, kbIDs, userID, mode); err != nil {+ newCtx := context.WithoutCancel(ctx)+ if err := s.convertFiles(newCtx, allFileIDs, kbIDs, mode); err != nil {common.Warn("file2document.convertFiles failed",zap.Strings("file_ids", allFileIDs),zap.Strings("kb_ids", kbIDs),@@ -178,7 +178,8 @@ func (s *File2DocumentService) LinkToDatasets(ctx context.Context, userID string// convertFiles mirrors Python _convert_files: keep existing links, remove links// outside the requested KBs in replace mode, then add any missing links.-func (s *File2DocumentService) convertFiles(ctx context.Context, fileIDs, kbIDs []string, userID, mode string) error {+func (s *File2DocumentService) convertFiles(ctx context.Context, fileIDs, kbIDs []string, mode string) error {+ userID := permission.UserIDFromContext(ctx)replaceExisting := mode != "add"kbIDs = dedupeStrings(kbIDs)requestedKBIDs := make(map[string]struct{}, len(kbIDs))diff --git a/internal/service/file/access.go b/internal/service/file/access.goindex cc5fec1cd5..ef24733381 100644--- a/internal/service/file/access.go+++ b/internal/service/file/access.go@@ -8,7 +8,7 @@ import ("ragflow/internal/permission")-func checkFileAccess(ctx context.Context, userID string, file *entity.File, operation permission.Operation) error {+func checkFileAccess(ctx context.Context, file *entity.File, operation permission.Operation) error {if file == nil {return permission.ErrResourceNotFound}@@ -37,15 +37,6 @@ func fileRequestIdentity(ctx context.Context, identity string) (string, string,return userID, tenantID, nil}-func tenantFileContext(ctx context.Context, userID, tenantID string) (context.Context, error) {- contextUserID := permission.UserIDFromContext(ctx)- contextTenantID := permission.TenantIDFromContext(ctx)- if contextUserID != "" && contextUserID != userID || contextTenantID != "" && contextTenantID != tenantID {- return nil, permission.ErrIdentityMismatch- }- return permission.WithIdentity(ctx, userID, tenantID), nil-}-func (s *FileService) checkFileTreeAccess(ctx context.Context, file *entity.File, operation permission.Operation) error {if file == nil {return permission.ErrResourceNotFounddiff --git a/internal/service/file/file_browse_permission_test.go b/internal/service/file/file_browse_permission_test.goindex 51abd5bd0b..ccb4d57e6a 100644--- a/internal/service/file/file_browse_permission_test.go+++ b/internal/service/file/file_browse_permission_test.go@@ -41,7 +41,7 @@ func TestTenantMemberSeesOnlyReadableFilesAndPaths(t *testing.T) {seedFileBrowsing(t)svc := testFileService()ctx := permission.WithIdentity(t.Context(), "reader", "owner")- list, err := svc.ListFilesForTenant(ctx, "reader", "owner", "", 1, 1, nil, "")+ list, err := svc.ListFilesForTenant(ctx, "owner", "", 1, 1, nil, "")if err != nil {t.Fatalf("list shared tenant files: %v", err)}@@ -54,20 +54,20 @@ func TestTenantMemberSeesOnlyReadableFilesAndPaths(t *testing.T) {if list.Files[0]["operator_permission"] != permission.ResourcePermissionOwner {t.Fatalf("owner file permission mask = %v, want %d", list.Files[0]["operator_permission"], permission.ResourcePermissionOwner)}- ancestors, err := svc.GetAllParentFoldersForTenant(ctx, "reader", "owner", "tags")+ ancestors, err := svc.GetAllParentFoldersForTenant(ctx, "owner", "tags")if err != nil {t.Fatalf("resolve shared tenant tag file: %v", err)}if len(ancestors) != 2 {t.Fatalf("ancestor count = %d, want 2", len(ancestors))}- if _, err := svc.GetAllParentFoldersForTenant(ctx, "reader", "owner", "private"); !errors.Is(err, permission.ErrPermissionDenied) {+ if _, err := svc.GetAllParentFoldersForTenant(ctx, "owner", "private"); !errors.Is(err, permission.ErrPermissionDenied) {t.Fatalf("resolve private file path error = %v, want permission denied", err)}if _, err := svc.GetFileContent(ctx, "reader", "private"); !errors.Is(err, permission.ErrPermissionDenied) {t.Fatalf("read private file error = %v, want permission denied", err)}- if err := svc.MoveFiles(ctx, "reader", []string{"private"}, "", "new-private.txt"); !errors.Is(err, permission.ErrPermissionDenied) {+ if err := svc.MoveFiles(ctx, []string{"private"}, "", "new-private.txt"); !errors.Is(err, permission.ErrPermissionDenied) {t.Fatalf("rename private file error = %v, want permission denied", err)}}@@ -76,17 +76,17 @@ func TestTenantFileBrowsingRejectsNonmember(t *testing.T) {seedFileBrowsing(t)svc := testFileService()outsiderCtx := permission.WithIdentity(t.Context(), "outsider", "owner")- if _, err := svc.ListFilesForTenant(outsiderCtx, "outsider", "owner", "", 1, 100, nil, ""); err == nil {+ if _, err := svc.ListFilesForTenant(outsiderCtx, "owner", "", 1, 100, nil, ""); err == nil {t.Fatal("nonmember listed another tenant's files")}- if _, err := svc.GetAllParentFoldersForTenant(outsiderCtx, "outsider", "owner", "tags"); err == nil {+ if _, err := svc.GetAllParentFoldersForTenant(outsiderCtx, "owner", "tags"); err == nil {t.Fatal("nonmember resolved another tenant's file path")}if err := dao.DB.Model(&entity.UserTenant{}).Where("id = ?", "reader-membership").Update("status", "0").Error; err != nil {t.Fatal(err)}readerCtx := permission.WithIdentity(t.Context(), "reader", "owner")- if _, err := svc.ListFilesForTenant(readerCtx, "reader", "owner", "", 1, 100, nil, ""); err == nil {+ if _, err := svc.ListFilesForTenant(readerCtx, "owner", "", 1, 100, nil, ""); err == nil {t.Fatal("inactive member listed another tenant's files")}}@@ -95,10 +95,10 @@ func TestTenantFileBrowsingRejectsForeignEntries(t *testing.T) {seedFileBrowsing(t)svc := testFileService()readerCtx := permission.WithIdentity(t.Context(), "reader", "owner")- if _, err := svc.ListFilesForTenant(readerCtx, "reader", "owner", "foreign-root", 1, 100, nil, ""); !errors.Is(err, permission.ErrResourceNotFound) {+ if _, err := svc.ListFilesForTenant(readerCtx, "owner", "foreign-root", 1, 100, nil, ""); !errors.Is(err, permission.ErrResourceNotFound) {t.Fatalf("foreign folder error = %v, want resource not found", err)}- if _, err := svc.GetAllParentFoldersForTenant(readerCtx, "reader", "owner", "foreign-tags"); !errors.Is(err, permission.ErrResourceNotFound) {+ if _, err := svc.GetAllParentFoldersForTenant(readerCtx, "owner", "foreign-tags"); !errors.Is(err, permission.ErrResourceNotFound) {t.Fatalf("foreign file error = %v, want resource not found", err)}}diff --git a/internal/service/file/file_content.go b/internal/service/file/file_content.goindex 3574ec9c3b..3da60e9d2b 100644--- a/internal/service/file/file_content.go+++ b/internal/service/file/file_content.go@@ -23,7 +23,7 @@ func (s *FileService) GetFileContent(ctx context.Context, uid, fileID string) (*if err != nil || file == nil {return nil, fmt.Errorf("document not found")}- if err := checkFileAccess(ctx, uid, file, permission.OperationRead); err != nil {+ if err := checkFileAccess(ctx, file, permission.OperationRead); err != nil {return nil, err}return file, nildiff --git a/internal/service/file/file_folder.go b/internal/service/file/file_folder.goindex db2b36381e..48e14ea947 100644--- a/internal/service/file/file_folder.go+++ b/internal/service/file/file_folder.go@@ -15,13 +15,21 @@ import ("gorm.io/gorm")-// GetRootFolder gets or creates root folder for tenant-func (s *FileService) GetRootFolder(ctx context.Context, tenantID string) (map[string]interface{}, error) {+// GetRootFolder gets or creates root folder for the active tenant.+func (s *FileService) GetRootFolder(ctx context.Context) (map[string]interface{}, error) {+ userID := permission.UserIDFromContext(ctx)+ if userID == "" {+ return nil, permission.ErrUnauthenticated+ }+ tenantID := permission.TenantIDFromContext(ctx)+ if tenantID == "" {+ tenantID = userID+ }file, err := s.fileDAO.GetRootFolder(ctx, dao.DB, tenantID)if err != nil {return nil, err}- if err = checkFileAccess(ctx, tenantID, file, permission.OperationRead); err != nil {+ if err = checkFileAccess(ctx, file, permission.OperationRead); err != nil {return nil, err}return s.toFileResponse(file), nil@@ -37,28 +45,22 @@ func lookupError(err error, message string) error {return err}-// ListFiles lists files by parent folder ID (matching Python /files endpoint)-// This method includes init_dataset_docs initialization when parent_id is empty-func (s *FileService) ListFiles(ctx context.Context, tenantID, pfID string, page, pageSize int, terms []dao.OrderTerm, keywords string) (*ListFilesResponse, error) {- return s.listFiles(ctx, tenantID, tenantID, pfID, page, pageSize, terms, keywords)-}-// ListFilesForTenant allows active tenant members to browse the tenant's files.-func (s *FileService) ListFilesForTenant(ctx context.Context, userID, tenantID, pfID string, page, pageSize int, terms []dao.OrderTerm, keywords string) (*ListFilesResponse, error) {+func (s *FileService) ListFilesForTenant(ctx context.Context, tenantID, pfID string, page, pageSize int, terms []dao.OrderTerm, keywords string) (*ListFilesResponse, error) {+ userID := permission.UserIDFromContext(ctx)+ if userID == "" {+ return nil, permission.ErrUnauthenticated+ }if userID != tenantID {if err := permission.NewDatabaseChecker(dao.DB).CheckTenant(ctx, tenantID, permission.TenantMember); err != nil {return nil, err}}- var err error- ctx, err = tenantFileContext(ctx, userID, tenantID)- if err != nil {- return nil, err- }- return s.listFiles(ctx, userID, tenantID, pfID, page, pageSize, terms, keywords)+ return s.listFiles(ctx, tenantID, pfID, page, pageSize, terms, keywords)}-func (s *FileService) listFiles(ctx context.Context, userID, tenantID, pfID string, page, pageSize int, terms []dao.OrderTerm, keywords string) (*ListFilesResponse, error) {+func (s *FileService) listFiles(ctx context.Context, tenantID, pfID string, page, pageSize int, terms []dao.OrderTerm, keywords string) (*ListFilesResponse, error) {+ userID := permission.UserIDFromContext(ctx)if tenantID == "" {return nil, permission.ErrInvalidPermission}@@ -68,7 +70,7 @@ func (s *FileService) listFiles(ctx context.Context, userID, tenantID, pfID striif err != nil {return nil, fmt.Errorf("failed to get root folder: %w", err)}- if err := checkFileAccess(ctx, userID, rootFolder, permission.OperationRead); err != nil {+ if err := checkFileAccess(ctx, rootFolder, permission.OperationRead); err != nil {return nil, err}pfID = rootFolder.ID@@ -99,7 +101,7 @@ func (s *FileService) listFiles(ctx context.Context, userID, tenantID, pfID striif folder.TenantID != tenantID {return nil, permission.ErrResourceNotFound}- if err := s.checkFilePathAccess(ctx, userID, tenantID, folder.ID); err != nil {+ if err := s.checkFilePathAccess(ctx, tenantID, folder.ID); err != nil {return nil, err}@@ -306,7 +308,7 @@ func (s *FileService) fileInfoToResponse(info *FileInfo) map[string]interface{}}// GetParentFolder gets parent folder of a file with permission check-func (s *FileService) GetParentFolder(ctx context.Context, userID, fileID string) (map[string]interface{}, error) {+func (s *FileService) GetParentFolder(ctx context.Context, fileID string) (map[string]interface{}, error) {// Get filefile, err := s.fileDAO.GetByID(ctx, dao.DB, fileID)if err != nil {@@ -314,7 +316,7 @@ func (s *FileService) GetParentFolder(ctx context.Context, userID, fileID string}// Permission check- if err := checkFileAccess(ctx, userID, file, permission.OperationRead); err != nil {+ if err := checkFileAccess(ctx, file, permission.OperationRead); err != nil {return nil, err}@@ -323,7 +325,7 @@ func (s *FileService) GetParentFolder(ctx context.Context, userID, fileID stringif err != nil {return nil, err}- if err := checkFileAccess(ctx, userID, parentFolder, permission.OperationRead); err != nil {+ if err := checkFileAccess(ctx, parentFolder, permission.OperationRead); err != nil {return nil, err}@@ -331,30 +333,29 @@ func (s *FileService) GetParentFolder(ctx context.Context, userID, fileID string}// GetAllParentFolders gets all parent folders in path with permission check-func (s *FileService) GetAllParentFolders(ctx context.Context, userID, fileID string) ([]map[string]interface{}, error) {- return s.getAllParentFolders(ctx, userID, "", fileID)+func (s *FileService) GetAllParentFolders(ctx context.Context, fileID string) ([]map[string]interface{}, error) {+ return s.getAllParentFolders(ctx, "", fileID)}// GetAllParentFoldersForTenant allows active tenant members to resolve file paths.// The file and every ancestor must belong to tenantID.-func (s *FileService) GetAllParentFoldersForTenant(ctx context.Context, userID, tenantID, fileID string) ([]map[string]interface{}, error) {+func (s *FileService) GetAllParentFoldersForTenant(ctx context.Context, tenantID, fileID string) ([]map[string]interface{}, error) {if tenantID == "" {return nil, permission.ErrInvalidPermission}+ userID := permission.UserIDFromContext(ctx)+ if userID == "" {+ return nil, permission.ErrUnauthenticated+ }if userID != tenantID {if err := permission.NewDatabaseChecker(dao.DB).CheckTenant(ctx, tenantID, permission.TenantMember); err != nil {return nil, err}}- var err error- ctx, err = tenantFileContext(ctx, userID, tenantID)- if err != nil {- return nil, err- }- return s.getAllParentFolders(ctx, userID, tenantID, fileID)+ return s.getAllParentFolders(ctx, tenantID, fileID)}-func (s *FileService) getAllParentFolders(ctx context.Context, userID, tenantID, fileID string) ([]map[string]interface{}, error) {+func (s *FileService) getAllParentFolders(ctx context.Context, tenantID, fileID string) ([]map[string]interface{}, error) {// Get filefile, err := s.fileDAO.GetByID(ctx, dao.DB, fileID)if err != nil {@@ -365,7 +366,7 @@ func (s *FileService) getAllParentFolders(ctx context.Context, userID, tenantID,}// Permission check- if err := checkFileAccess(ctx, userID, file, permission.OperationRead); err != nil {+ if err := checkFileAccess(ctx, file, permission.OperationRead); err != nil {return nil, err}@@ -378,7 +379,7 @@ func (s *FileService) getAllParentFolders(ctx context.Context, userID, tenantID,if tenantID != "" && folder.TenantID != tenantID {return nil, permission.ErrResourceNotFound}- if err := checkFileAccess(ctx, userID, folder, permission.OperationRead); err != nil {+ if err := checkFileAccess(ctx, folder, permission.OperationRead); err != nil {return nil, err}}@@ -392,7 +393,7 @@ func (s *FileService) getAllParentFolders(ctx context.Context, userID, tenantID,return result, nil}-func (s *FileService) checkFilePathAccess(ctx context.Context, userID, tenantID, fileID string) error {+func (s *FileService) checkFilePathAccess(ctx context.Context, tenantID, fileID string) error {folders, err := s.fileDAO.GetAllParentFolders(ctx, dao.DB, fileID)if err != nil {return err@@ -401,7 +402,7 @@ func (s *FileService) checkFilePathAccess(ctx context.Context, userID, tenantID,if folder.TenantID != tenantID {return permission.ErrResourceNotFound}- if err := checkFileAccess(ctx, userID, folder, permission.OperationRead); err != nil {+ if err := checkFileAccess(ctx, folder, permission.OperationRead); err != nil {return err}}@@ -414,7 +415,7 @@ func (s *FileService) GetDocCount(ctx context.Context, tenantID string) (int64,return documentDAO.CountByTenantID(ctx, dao.DB, tenantID)}-func (s *FileService) createFolderRecursive(ctx context.Context, parentFolder *entity.File, names []string, count int, tenantID, userID string) (*entity.File, error) {+func (s *FileService) createFolderRecursive(ctx context.Context, parentFolder *entity.File, names []string, count int, tenantID string) (*entity.File, error) {if count > len(names)-2 {return parentFolder, nil}@@ -422,7 +423,7 @@ func (s *FileService) createFolderRecursive(ctx context.Context, parentFolder *evar newFolder *entity.Fileerr := dao.DB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {var createErr error- newFolder, createErr = s.fileDAO.CreateFolder(ctx, tx, parentFolder.ID, tenantID, userID, names[count], FileTypeFolder)+ newFolder, createErr = s.fileDAO.CreateFolder(ctx, tx, parentFolder.ID, tenantID, permission.UserIDFromContext(ctx), names[count], FileTypeFolder)if createErr != nil {return createErr}@@ -432,7 +433,7 @@ func (s *FileService) createFolderRecursive(ctx context.Context, parentFolder *ereturn nil, err}- return s.createFolderRecursive(ctx, newFolder, names, count+1, tenantID, userID)+ return s.createFolderRecursive(ctx, newFolder, names, count+1, tenantID)}// getUniqueFilename returns a non-colliding file name within the folder,@@ -444,11 +445,16 @@ func (s *FileService) getUniqueFilename(ctx context.Context, name, parentID, ten}// CreateFolder creates a new folder or virtual file-func (s *FileService) CreateFolder(ctx context.Context, userID, name, parentID, fileType string) (map[string]interface{}, error) {- userID, tenantID, err := fileRequestIdentity(ctx, userID)- if err != nil {- return nil, err+func (s *FileService) CreateFolder(ctx context.Context, name, parentID, fileType string) (map[string]interface{}, error) {+ userID := permission.UserIDFromContext(ctx)+ if userID == "" {+ return nil, permission.ErrUnauthenticated+ }+ tenantID := permission.TenantIDFromContext(ctx)+ if tenantID == "" {+ tenantID = userID}+ var err errorif err = permission.NewDatabaseChecker(dao.DB).CheckFeature(ctx, "file", permission.ActionWrite); err != nil {return nil, err}@@ -474,7 +480,7 @@ func (s *FileService) CreateFolder(ctx context.Context, userID, name, parentID,if parentFolder.TenantID != tenantID {return nil, permission.ErrResourceNotFound}- if err = checkFileAccess(ctx, userID, parentFolder, permission.OperationCreate); err != nil {+ if err = checkFileAccess(ctx, parentFolder, permission.OperationCreate); err != nil {return nil, err}@@ -525,7 +531,11 @@ func (s *FileService) CreateFolder(ctx context.Context, userID, name, parentID,// - new_name only: rename in place (no storage operation)// - dest_file_id only: move to new folder (keep names)// - both: move and rename simultaneously-func (s *FileService) MoveFiles(ctx context.Context, userID string, srcFileIDs []string, destFileID string, newName string) error {+func (s *FileService) MoveFiles(ctx context.Context, srcFileIDs []string, destFileID string, newName string) error {+ userID := permission.UserIDFromContext(ctx)+ if userID == "" {+ return permission.ErrUnauthenticated+ }files, err := s.fileDAO.GetByIDs(ctx, dao.DB, srcFileIDs)if err != nil {return err@@ -561,7 +571,7 @@ func (s *FileService) MoveFiles(ctx context.Context, userID string, srcFileIDs [if err != nil || destFolder == nil || destFolder.Type != FileTypeFolder {return errors.New("parent folder not found")}- if err := checkFileAccess(ctx, userID, destFolder, permission.OperationCreate); err != nil {+ if err := checkFileAccess(ctx, destFolder, permission.OperationCreate); err != nil {return err}@@ -637,7 +647,7 @@ func (s *FileService) MoveFiles(ctx context.Context, userID string, srcFileIDs [if destFolder != nil {for _, fileID := range srcFileIDs {- if err := s.moveEntryRecursive(ctx, userID, filesByID[fileID], destFolder, newName); err != nil {+ if err := s.moveEntryRecursive(ctx, filesByID[fileID], destFolder, newName); err != nil {return err}}@@ -716,7 +726,7 @@ func (s *FileService) renameLinkedDocuments(ctx context.Context, fileID, newName}// moveEntryRecursive recursively moves a file or folder entry-func (s *FileService) moveEntryRecursive(ctx context.Context, userID string, sourceFile *entity.File, destFolder *entity.File, overrideName string) error {+func (s *FileService) moveEntryRecursive(ctx context.Context, sourceFile *entity.File, destFolder *entity.File, overrideName string) error {effectiveName := overrideNameif effectiveName == "" {effectiveName = sourceFile.Name@@ -735,13 +745,13 @@ func (s *FileService) moveEntryRecursive(ctx context.Context, userID string, soureturn fmt.Errorf("cannot move folder into itself")}newFolder = existingFolders[0]- if err := checkFileAccess(ctx, userID, newFolder, permission.OperationCreate); err != nil {+ if err := checkFileAccess(ctx, newFolder, permission.OperationCreate); err != nil {return err}} else {// Create new foldervar err error- newFolder, err = s.fileDAO.CreateFolder(ctx, dao.DB, destFolder.ID, sourceFile.TenantID, userID, effectiveName, FileTypeFolder)+ newFolder, err = s.fileDAO.CreateFolder(ctx, dao.DB, destFolder.ID, sourceFile.TenantID, permission.UserIDFromContext(ctx), effectiveName, FileTypeFolder)if err != nil {return fmt.Errorf("failed to create destination folder: %w", err)}@@ -753,7 +763,7 @@ func (s *FileService) moveEntryRecursive(ctx context.Context, userID string, soureturn err}for _, subFile := range subFiles {- if err = s.moveEntryRecursive(ctx, userID, subFile, newFolder, ""); err != nil {+ if err = s.moveEntryRecursive(ctx, subFile, newFolder, ""); err != nil {return err}}diff --git a/internal/service/file/file_folder_test.go b/internal/service/file/file_folder_test.goindex f05392388e..602e343693 100644--- a/internal/service/file/file_folder_test.go+++ b/internal/service/file/file_folder_test.go@@ -20,7 +20,7 @@ func TestFileService_CreateFolder_RejectsSlashInName(t *testing.T) {svc := testFileService()ctx := permission.WithIdentity(context.Background(), "tenant1", "")for _, name := range []string{"/", "a/b", "dir/sub/"} {- _, err := svc.CreateFolder(ctx, "tenant1", name, "pf1", FileTypeFolder)+ _, err := svc.CreateFolder(ctx, name, "pf1", FileTypeFolder)if err == nil || !strings.Contains(err.Error(), `cannot contain "/"`) {t.Fatalf("CreateFolder(%q) error = %v, want slash validation error", name, err)}@@ -38,7 +38,7 @@ func TestFileService_CreateFolderDedupesDuplicateName(t *testing.T) {svc := testFileService()ctx := fileTestContext(t, "tenant-1", "tenant-1")- created, err := svc.CreateFolder(ctx, "tenant-1", "notes", "pf1", FileTypeFolder)+ created, err := svc.CreateFolder(ctx, "notes", "pf1", FileTypeFolder)if err != nil {t.Fatalf("CreateFolder failed: %v", err)}@@ -48,7 +48,7 @@ func TestFileService_CreateFolderDedupesDuplicateName(t *testing.T) {// A second create with the same name in the same folder appends a counter// instead of failing.- created, err = svc.CreateFolder(ctx, "tenant-1", "notes", "pf1", FileTypeFolder)+ created, err = svc.CreateFolder(ctx, "notes", "pf1", FileTypeFolder)if err != nil {t.Fatalf("CreateFolder failed: %v", err)}@@ -57,10 +57,10 @@ func TestFileService_CreateFolderDedupesDuplicateName(t *testing.T) {}// Virtual files keep the extension at the end of the generated name.- if _, err = svc.CreateFolder(ctx, "tenant-1", "report.pdf", "pf1", FileTypeVirtual); err != nil {+ if _, err = svc.CreateFolder(ctx, "report.pdf", "pf1", FileTypeVirtual); err != nil {t.Fatalf("CreateFolder failed: %v", err)}- created, err = svc.CreateFolder(ctx, "tenant-1", "report.pdf", "pf1", FileTypeVirtual)+ created, err = svc.CreateFolder(ctx, "report.pdf", "pf1", FileTypeVirtual)if err != nil {t.Fatalf("CreateFolder failed: %v", err)}@@ -93,7 +93,7 @@ func TestFileService_CreateFolderRecordsRequesterAsOwner(t *testing.T) {}ctx := fileTestContext(t, "member", "owner", "owner")- created, err := testFileService().CreateFolder(ctx, "member", "notes", "root", FileTypeFolder)+ created, err := testFileService().CreateFolder(ctx, "notes", "root", FileTypeFolder)if err != nil {t.Fatalf("create folder: %v", err)}@@ -110,7 +110,7 @@ func TestFileService_CreateFolderRecordsRequesterAsOwner(t *testing.T) {// firstCreatedFolderName creates one entry and returns its resulting name.func firstCreatedFolderName(t *testing.T, svc *FileService, ctx context.Context, name, fileType string) string {t.Helper()- created, err := svc.CreateFolder(ctx, "tenant-1", name, "pf1", fileType)+ created, err := svc.CreateFolder(ctx, name, "pf1", fileType)if err != nil {t.Fatalf("CreateFolder(%q) failed: %v", name, err)}@@ -126,7 +126,7 @@ func TestFileService_MoveFiles_RejectsSlashInNewName(t *testing.T) {}svc := testFileService()- err := svc.MoveFiles(fileTestContext(t, "tenant1", "tenant1"), "tenant1", []string{"f1"}, "", "a/b")+ err := svc.MoveFiles(fileTestContext(t, "tenant1", "tenant1"), []string{"f1"}, "", "a/b")if err == nil || !strings.Contains(err.Error(), `cannot contain "/"`) {t.Fatalf("MoveFiles rename error = %v, want slash validation error", err)}@@ -145,12 +145,12 @@ func TestFileService_MoveFilesRejectsDuplicateName(t *testing.T) {svc := testFileService()ctx := fileTestContext(t, "tenant-1", "tenant-1")- err := svc.MoveFiles(ctx, "tenant-1", []string{"s1"}, "", "TARGET")+ err := svc.MoveFiles(ctx, []string{"s1"}, "", "TARGET")if err == nil || !strings.Contains(err.Error(), "duplicated file name") {t.Fatalf("rename to case-variant duplicate error = %v, want duplicate error", err)}- if err = svc.MoveFiles(ctx, "tenant-1", []string{"s1"}, "", "SOURCE"); err != nil {+ if err = svc.MoveFiles(ctx, []string{"s1"}, "", "SOURCE"); err != nil {t.Fatalf("case-only rename failed: %v", err)}}@@ -172,7 +172,7 @@ func TestFileService_MoveFilesRejectsCaseVariantDuplicateInDestinationFolder(t *}svc := testFileService()- err := svc.MoveFiles(fileTestContext(t, "tenant-1", "tenant-1"), "tenant-1", []string{"s1"}, "d1", "REPORT.TXT")+ err := svc.MoveFiles(fileTestContext(t, "tenant-1", "tenant-1"), []string{"s1"}, "d1", "REPORT.TXT")if err == nil || !strings.Contains(err.Error(), "duplicated file name") {t.Fatalf("move+case-variant rename error = %v, want duplicate error", err)}@@ -195,7 +195,7 @@ func TestFileService_MoveFilesRejectsCaseVariantDuplicateWithoutRename(t *testin}svc := testFileService()- err := svc.MoveFiles(fileTestContext(t, "tenant-1", "tenant-1"), "tenant-1", []string{"s1"}, "d1", "")+ err := svc.MoveFiles(fileTestContext(t, "tenant-1", "tenant-1"), []string{"s1"}, "d1", "")if err == nil || !strings.Contains(err.Error(), "Duplicated file name") {t.Fatalf("plain move into case-variant duplicate error = %v, want duplicate error", err)}@@ -264,7 +264,7 @@ func TestFileService_ListFilesMissingParentReturnsNotFound(t *testing.T) {}svc := testFileService()- _, err := svc.ListFiles(fileTestContext(t, "tenant-1", "tenant-1"), "tenant-1", "missing-folder", 1, 10, nil, "")+ _, err := svc.ListFilesForTenant(fileTestContext(t, "tenant-1", "tenant-1"), "tenant-1", "missing-folder", 1, 10, nil, "")var coded *common.CodedErrorif !errors.As(err, &coded) || coded.Code != common.CodeNotFound {t.Fatalf("ListFiles error = %v, want CodeNotFound CodedError", err)@@ -277,8 +277,8 @@ func TestFileService_AncestryMissingIDReturnsNotFound(t *testing.T) {svc := testFileService()ctx := permission.WithIdentity(t.Context(), "user-1", "tenant-1")for name, call := range map[string]func() error{- "GetParentFolder": func() error { _, err := svc.GetParentFolder(ctx, "user-1", "missing-file"); return err },- "GetAllParentFolders": func() error { _, err := svc.GetAllParentFolders(ctx, "user-1", "missing-file"); return err },+ "GetParentFolder": func() error { _, err := svc.GetParentFolder(ctx, "missing-file"); return err },+ "GetAllParentFolders": func() error { _, err := svc.GetAllParentFolders(ctx, "missing-file"); return err },} {var coded *common.CodedErrorif err := call(); !errors.As(err, &coded) || coded.Code != common.CodeNotFound {@@ -301,9 +301,9 @@ func TestFileService_DatabaseErrorIsNotReportedAsNotFound(t *testing.T) {svc := testFileService()ctx := permission.WithIdentity(t.Context(), "user-1", "tenant-1")for name, call := range map[string]func() error{- "ListFiles": func() error { _, err := svc.ListFiles(ctx, "tenant-1", "any", 1, 10, nil, ""); return err },- "GetParentFolder": func() error { _, err := svc.GetParentFolder(ctx, "user-1", "any"); return err },- "GetAllParentFolders": func() error { _, err := svc.GetAllParentFolders(ctx, "user-1", "any"); return err },+ "ListFilesForTenant": func() error { _, err := svc.ListFilesForTenant(ctx, "tenant-1", "any", 1, 10, nil, ""); return err },+ "GetParentFolder": func() error { _, err := svc.GetParentFolder(ctx, "any"); return err },+ "GetAllParentFolders": func() error { _, err := svc.GetAllParentFolders(ctx, "any"); return err },} {coded := (*common.CodedError)(nil)if err := call(); err == nil {@@ -320,8 +320,8 @@ func TestFileService_AncestryRejectsUnauthorized(t *testing.T) {svc := testFileService()ctx := fileTestContext(t, "user-2", "tenant-1", "tenant-1")for _, call := range []func() error{- func() error { _, err := svc.GetParentFolder(ctx, "user-2", "file-1"); return err },- func() error { _, err := svc.GetAllParentFolders(ctx, "user-2", "file-1"); return err },+ func() error { _, err := svc.GetParentFolder(ctx, "file-1"); return err },+ func() error { _, err := svc.GetAllParentFolders(ctx, "file-1"); return err },} {if err := call(); !errors.Is(err, permission.ErrPermissionDenied) {t.Fatalf("error = %v, want permission denied", err)@@ -346,7 +346,7 @@ func TestFileService_ListFilesRejectsInaccessibleParent(t *testing.T) {t.Fatalf("seed foreign folder: %v", err)}- _, err := testFileService().ListFiles(fileTestContext(t, "user-1", "user-1"), "user-1", foreignFolder.ID, 1, 15, nil, "")+ _, err := testFileService().ListFilesForTenant(fileTestContext(t, "user-1", "user-1"), "user-1", foreignFolder.ID, 1, 15, nil, "")if !errors.Is(err, permission.ErrResourceNotFound) {t.Fatalf("ListFiles error = %v, want resource not found", err)}@@ -359,7 +359,7 @@ func TestFileService_CreateFolderRejectsInaccessibleParent(t *testing.T) {t.Fatalf("seed foreign folder: %v", err)}- _, err := testFileService().CreateFolder(fileTestContext(t, "user-1", "user-1"), "user-1", "child", foreignFolder.ID, FileTypeFolder)+ _, err := testFileService().CreateFolder(fileTestContext(t, "user-1", "user-1"), "child", foreignFolder.ID, FileTypeFolder)if !errors.Is(err, permission.ErrResourceNotFound) {t.Fatalf("CreateFolder error = %v, want resource not found", err)}@@ -379,7 +379,7 @@ func TestFileService_MoveFilesRejectsInaccessibleSource(t *testing.T) {t.Fatalf("seed foreign file: %v", err)}- err := testFileService().MoveFiles(fileTestContext(t, "user-1", "user-1"), "user-1", []string{foreignFile.ID}, "", "renamed.pdf")+ err := testFileService().MoveFiles(fileTestContext(t, "user-1", "user-1"), []string{foreignFile.ID}, "", "renamed.pdf")if !errors.Is(err, permission.ErrPermissionDenied) {t.Fatalf("MoveFiles error = %v, want permission denied", err)}@@ -400,7 +400,7 @@ func TestFileService_MoveFilesRejectsInaccessibleDestination(t *testing.T) {t.Fatalf("seed foreign folder: %v", err)}- err := testFileService().MoveFiles(fileTestContext(t, "user-1", "tenant-1"), "user-1", []string{"file-1"}, foreignFolder.ID, "")+ err := testFileService().MoveFiles(fileTestContext(t, "user-1", "tenant-1"), []string{"file-1"}, foreignFolder.ID, "")if !errors.Is(err, permission.ErrPermissionDenied) {t.Fatalf("MoveFiles error = %v, want permission denied", err)}@@ -468,7 +468,7 @@ func TestMoveFilesRenameUpdatesAllLinkedDocuments(t *testing.T) {svc := testFileService()ctx := fileTestContext(t, "tenant-1", "tenant-1")- if err := svc.MoveFiles(ctx, "tenant-1", []string{"file-1"}, "", "new.pdf"); err != nil {+ if err := svc.MoveFiles(ctx, []string{"file-1"}, "", "new.pdf"); err != nil {t.Fatalf("MoveFiles failed: %v", err)}@@ -514,7 +514,7 @@ func TestRenameLinkedDocumentsLookupErrorPropagates(t *testing.T) {t.Fatal("renameLinkedDocuments returned nil error on update failure")}- err := svc.MoveFiles(ctx, "tenant-1", []string{"file-1"}, "", "new.pdf")+ err := svc.MoveFiles(ctx, []string{"file-1"}, "", "new.pdf")if err == nil {t.Fatal("MoveFiles succeeded despite file2document lookup failure")}@@ -547,7 +547,7 @@ func TestMoveEntryRecursiveRenameUpdatesAllLinkedDocuments(t *testing.T) {t.Fatalf("get file: %v", err)}- if err = svc.moveEntryRecursive(ctx, "tenant-1", srcFile, destFolder, "new.pdf"); err != nil {+ if err = svc.moveEntryRecursive(ctx, srcFile, destFolder, "new.pdf"); err != nil {t.Fatalf("moveEntryRecursive failed: %v", err)}@@ -617,7 +617,7 @@ func TestMoveFilesRejectsFolderAndSubfolder(t *testing.T) {seedMoveHierarchyDB(t)svc := testFileService()- err := svc.MoveFiles(fileTestContext(t, "tenant-1", "tenant-1"), "tenant-1", []string{"A", "B"}, "D", "")+ err := svc.MoveFiles(fileTestContext(t, "tenant-1", "tenant-1"), []string{"A", "B"}, "D", "")if err == nil || !strings.Contains(err.Error(), "descendant") {t.Fatalf("move folder+subfolder error = %v, want descendant rejection", err)}@@ -634,7 +634,7 @@ func TestMoveFilesRejectsFolderAndGrandchild(t *testing.T) {seedMoveHierarchyDB(t)svc := testFileService()- err := svc.MoveFiles(fileTestContext(t, "tenant-1", "tenant-1"), "tenant-1", []string{"A", "C"}, "D", "")+ err := svc.MoveFiles(fileTestContext(t, "tenant-1", "tenant-1"), []string{"A", "C"}, "D", "")if err == nil || !strings.Contains(err.Error(), "descendant") {t.Fatalf("move folder+grandchild error = %v, want descendant rejection", err)}@@ -652,7 +652,7 @@ func TestMoveFilesRejectsFolderAndContainedFile(t *testing.T) {insertFolderTestFile(t, "f1", "A", "inside.pdf")svc := testFileService()- err := svc.MoveFiles(fileTestContext(t, "tenant-1", "tenant-1"), "tenant-1", []string{"A", "f1"}, "D", "")+ err := svc.MoveFiles(fileTestContext(t, "tenant-1", "tenant-1"), []string{"A", "f1"}, "D", "")if err == nil || !strings.Contains(err.Error(), "descendant") {t.Fatalf("move folder+contained file error = %v, want descendant rejection", err)}@@ -670,7 +670,7 @@ func TestMoveFilesRejectsNestedSourcesInEitherOrder(t *testing.T) {svc := testFileService()for _, src := range [][]string{{"A", "B"}, {"B", "A"}} {- err := svc.MoveFiles(fileTestContext(t, "tenant-1", "tenant-1"), "tenant-1", src, "D", "")+ err := svc.MoveFiles(fileTestContext(t, "tenant-1", "tenant-1"), src, "D", "")if err == nil || !strings.Contains(err.Error(), "descendant") {t.Fatalf("move %v error = %v, want descendant rejection", src, err)}@@ -698,7 +698,7 @@ func TestMoveFilesAllowsUnrelatedEntries(t *testing.T) {}svc := testFileService()- if err := svc.MoveFiles(fileTestContext(t, "tenant-1", "tenant-1"), "tenant-1", []string{"A", "X"}, "D", ""); err != nil {+ if err := svc.MoveFiles(fileTestContext(t, "tenant-1", "tenant-1"), []string{"A", "X"}, "D", ""); err != nil {t.Fatalf("move unrelated entries failed: %v", err)}if got := countChildren(t, "D"); got != 2 {@@ -714,7 +714,7 @@ func TestMoveFilesSingleFolderWithSubtreeStillMoves(t *testing.T) {seedMoveHierarchyDB(t)svc := testFileService()- if err := svc.MoveFiles(fileTestContext(t, "tenant-1", "tenant-1"), "tenant-1", []string{"A"}, "D", ""); err != nil {+ if err := svc.MoveFiles(fileTestContext(t, "tenant-1", "tenant-1"), []string{"A"}, "D", ""); err != nil {t.Fatalf("move single folder failed: %v", err)}diff --git a/internal/service/file/file_test.go b/internal/service/file/file_test.goindex 1eda6fcb8c..22fa4af784 100644--- a/internal/service/file/file_test.go+++ b/internal/service/file/file_test.go@@ -16,6 +16,7 @@ import ("unicode/utf8""ragflow/internal/dao"+ "ragflow/internal/permission""ragflow/internal/storage""ragflow/internal/utility")@@ -451,14 +452,14 @@ func TestFileService_UploadFromURL_PDFAddsExtensionAndStoresToDownloads(t *testifactory.SetStorage(mockStorage)t.Cleanup(func() { factory.SetStorage(originalStorage) })- ctx := t.Context()+ ctx := permission.WithIdentity(t.Context(), "user123", "")svc := testFileService()- resp, err := svc.UploadFromURL(ctx, "tenant123", server.URL+"/report")+ resp, err := svc.UploadFromURL(ctx, server.URL+"/report")if err != nil {t.Fatalf("UploadFromURL failed: %v", err)}- if mockStorage.lastBucket != "tenant123-downloads" {+ if mockStorage.lastBucket != "user123-downloads" {t.Fatalf("bucket = %q", mockStorage.lastBucket)}if resp["name"] != "report.pdf" {@@ -498,9 +499,9 @@ func TestFileService_UploadFromURL_HTMLNormalizesReadableContent(t *testing.T) {factory.SetStorage(mockStorage)t.Cleanup(func() { factory.SetStorage(originalStorage) })- ctx := t.Context()+ ctx := permission.WithIdentity(t.Context(), "user123", "")svc := testFileService()- resp, err := svc.UploadFromURL(ctx, "tenant123", server.URL+"/page")+ resp, err := svc.UploadFromURL(ctx, server.URL+"/page")if err != nil {t.Fatalf("UploadFromURL failed: %v", err)}@@ -571,7 +572,8 @@ func TestFileService_UploadFromURL_ShortensLongNamesWithinTheLimit(t *testing.T)factory.SetStorage(&fakeStorage{})t.Cleanup(func() { factory.SetStorage(originalStorage) })- resp, err := testFileService().UploadFromURL(t.Context(), "tenant123", server.URL+"/"+url.PathEscape(c.path))+ ctx := permission.WithIdentity(t.Context(), "user123", "")+ resp, err := testFileService().UploadFromURL(ctx, server.URL+"/"+url.PathEscape(c.path))if err != nil {t.Fatalf("UploadFromURL failed: %v", err)}diff --git a/internal/service/file/file_upload.go b/internal/service/file/file_upload.goindex e18a810b76..2bdf016d5b 100644--- a/internal/service/file/file_upload.go+++ b/internal/service/file/file_upload.go@@ -3,7 +3,6 @@ package fileimport ("context""fmt"- "gorm.io/gorm""io""mime/multipart""net/http"@@ -15,6 +14,8 @@ import ("ragflow/internal/utility""strings""time"++ "gorm.io/gorm")const defaultDeploymentUploadMaxBytes int64 = common.DefaultMaxMultipartRequestBodyBytes@@ -48,7 +49,7 @@ func (s *FileService) UploadFile(ctx context.Context, tenantID, parentID string,if parentFolder.TenantID != tenantID {return nil, permission.ErrResourceNotFound}- if err := checkFileAccess(ctx, userID, parentFolder, permission.OperationCreate); err != nil {+ if err := checkFileAccess(ctx, parentFolder, permission.OperationCreate); err != nil {return nil, err}@@ -102,7 +103,7 @@ func (s *FileService) UploadFile(ctx context.Context, tenantID, parentID string,return nil, fmt.Errorf("folder not found")}var createdFolder *entity.File- createdFolder, err = s.createFolderRecursive(ctx, lastFolder, fileObjNames, len(idList), tenantID, userID)+ createdFolder, err = s.createFolderRecursive(ctx, lastFolder, fileObjNames, len(idList), tenantID)if err != nil {return nil, fmt.Errorf("failed to create folder: %w", err)}@@ -190,7 +191,7 @@ func readDeploymentUploadData(r io.Reader, maxBytes int64) ([]byte, error) {// UploadInfos mirrors Python's upload_info file branch: store raw bytes in the// per-user downloads bucket and return lightweight upload descriptors instead// of creating full File rows in the file-management tree.-func (s *FileService) UploadInfos(ctx context.Context, userID string, files []*multipart.FileHeader) ([]map[string]interface{}, error) {+func (s *FileService) UploadInfos(ctx context.Context, files []*multipart.FileHeader) ([]map[string]interface{}, error) {storageImpl := storage.GetStorageFactory().GetStorage()if storageImpl == nil {return nil, fmt.Errorf("storage not initialized")@@ -199,7 +200,7 @@ func (s *FileService) UploadInfos(ctx context.Context, userID string, files []*mresults := make([]map[string]interface{}, 0, len(files))for _, fileHeader := range files {filename := fileHeader.Filename- if err := s.checkUploadInfoHealth(ctx, userID, filename); err != nil {+ if err := s.checkUploadInfoHealth(ctx, filename); err != nil {return nil, err}src, err := fileHeader.Open()@@ -217,7 +218,7 @@ func (s *FileService) UploadInfos(ctx context.Context, userID string, files []*mcontentType = http.DetectContentType(data)}filename, contentType, data = utility.NormalizeUploadInfoContent(filename, contentType, data)- resp, err := s.storeUploadInfoBlob(ctx, storageImpl, userID, filename, contentType, data)+ resp, err := s.storeUploadInfoBlob(ctx, storageImpl, filename, contentType, data)if err != nil {return nil, err}@@ -269,7 +270,8 @@ func (s *FileService) toUploadInfoResponse(file *entity.File, mimeType string) m}}-func (s *FileService) checkUploadInfoHealth(ctx context.Context, userID, filename string) error {+func (s *FileService) checkUploadInfoHealth(ctx context.Context, filename string) error {+ userID := permission.UserIDFromContext(ctx)if filename == "" {return fmt.Errorf("No file selected!")}@@ -293,7 +295,8 @@ func (s *FileService) checkUploadInfoHealth(ctx context.Context, userID, filenamreturn nil}-func (s *FileService) storeUploadInfoBlob(ctx context.Context, storageImpl storage.Storage, userID, filename, contentType string, data []byte) (map[string]interface{}, error) {+func (s *FileService) storeUploadInfoBlob(ctx context.Context, storageImpl storage.Storage, filename, contentType string, data []byte) (map[string]interface{}, error) {+ userID := permission.UserIDFromContext(ctx)location := common.GenerateUUID()bucket := fmt.Sprintf("%s-downloads", userID)if err := storageImpl.Put(ctx, bucket, location, data); err != nil {@@ -318,8 +321,8 @@ func (s *FileService) storeUploadInfoBlob(ctx context.Context, storageImpl stora// UploadDocumentInfos is the document-level wrapper that stores uploaded blobs// without creating Document rows, then returns the file metadata including// size/mime-type/extension.-func (s *FileService) UploadDocumentInfos(ctx context.Context, userID string, files []*multipart.FileHeader) ([]map[string]interface{}, common.ErrorCode, error) {- data, err := s.UploadInfos(ctx, userID, files)+func (s *FileService) UploadDocumentInfos(ctx context.Context, files []*multipart.FileHeader) ([]map[string]interface{}, common.ErrorCode, error) {+ data, err := s.UploadInfos(ctx, files)if err != nil {return nil, common.CodeDataError, err}@@ -328,8 +331,12 @@ func (s *FileService) UploadDocumentInfos(ctx context.Context, userID string, fi// UploadDocumentInfoByURL fetches a remote URL, stores the content without// creating a Document row, then returns file metadata.-func (s *FileService) UploadDocumentInfoByURL(ctx context.Context, userID, rawURL string) (map[string]interface{}, common.ErrorCode, error) {- data, err := s.UploadFromURL(ctx, userID, rawURL)+func (s *FileService) UploadDocumentInfoByURL(ctx context.Context, rawURL string) (map[string]interface{}, common.ErrorCode, error) {+ userID := permission.UserIDFromContext(ctx)+ if userID == "" {+ return nil, common.CodeUnauthorized, permission.ErrUnauthenticated+ }+ data, err := s.UploadFromURL(ctx, rawURL)if err != nil {return nil, common.CodeDataError, err}diff --git a/internal/service/file/file_url.go b/internal/service/file/file_url.goindex 89461a2062..9e1ac8e776 100644--- a/internal/service/file/file_url.go+++ b/internal/service/file/file_url.go@@ -5,17 +5,18 @@ import ("fmt""net/url""path/filepath"+ "strings"++ "ragflow/internal/permission""ragflow/internal/storage""ragflow/internal/utility"- "strings")// maxUploadFilenameBytes is the longest name checkUploadInfoHealth accepts.const maxUploadFilenameBytes = 255-// UploadFromURL fetches a remote URL, saves the content to the tenant's root-// folder, and returns the file metadata map — mirroring Python-// FileService.upload_info(tenant_id, None, url).+// UploadFromURL fetches a remote URL, saves the content to the current user's+// downloads bucket, and returns the file metadata map.//// The remote fetch is SSRF-guarded (mirrors Python's assert_url_is_safe): the// scheme must be http/https and every address the host resolves to must be@@ -24,7 +25,10 @@ const maxUploadFilenameBytes = 255// carries connect and overall timeouts, and the response body is bounded with// truncation detection so an oversized file is rejected rather than silently// clipped.-func (s *FileService) UploadFromURL(ctx context.Context, tenantID, rawURL string) (map[string]interface{}, error) {+func (s *FileService) UploadFromURL(ctx context.Context, rawURL string) (map[string]interface{}, error) {+ if permission.UserIDFromContext(ctx) == "" {+ return nil, permission.ErrUnauthenticated+ }if rawURL == "" {return nil, fmt.Errorf("url is required")}@@ -45,11 +49,11 @@ func (s *FileService) UploadFromURL(ctx context.Context, tenantID, rawURL stringcontentType := headers.Get("Content-Type")filename := normalizeRemoteUploadFilename(finalURL, contentType, data)- if err = s.checkUploadInfoHealth(ctx, tenantID, filename); err != nil {+ if err = s.checkUploadInfoHealth(ctx, filename); err != nil {return nil, err}filename, contentType, data = utility.NormalizeUploadInfoContent(filename, contentType, data)- return s.storeUploadInfoBlob(ctx, storageImpl, tenantID, filename, contentType, data)+ return s.storeUploadInfoBlob(ctx, storageImpl, filename, contentType, data)}func normalizeRemoteUploadFilename(rawURL, contentType string, data []byte) string {