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(api): enforce readonly access to team-shared chat and agent sessions (#19340)
euvre9538c2825c7d
diff --git a/internal/service/agent_sessions.go b/internal/service/agent_sessions.goindex 09d9998b30..1cc214ac9c 100644--- a/internal/service/agent_sessions.go+++ b/internal/service/agent_sessions.go@@ -417,6 +417,25 @@ func (s *AgentService) DeleteAgentSessionItem(ctx context.Context, userID, agentreturn false, common.CodeOperatingError, errors.New("agent not found or no permission")}+ // Shared-session readonly rule (same design as the owner-only batch+ // delete below): deleting a session is a write, so it is limited to the+ // canvas owner or the session's creator. Team members who can read the+ // shared agent see the session readonly.+ conv, cerr := s.api4ConversationDAO.GetBySessionID(ctx, dao.DB, sessionID, agentID)+ if cerr != nil {+ return false, common.CodeServerError, cerr+ }+ if conv == nil {+ return false, common.CodeSuccess, nil+ }+ canvasOwned, oerr := s.canvasOwnedByUser(ctx, userID, agentID)+ if oerr != nil {+ return false, common.CodeServerError, oerr+ }+ if !canvasOwned && conv.UserID != userID {+ return false, common.CodeAuthenticationError, errors.New("shared session is readonly")+ }+row, err := s.api4ConversationDAO.DeleteBySessionIDAndAgentID(ctx, dao.DB, sessionID, agentID)if err != nil {return false, common.CodeServerError, err@@ -427,6 +446,20 @@ func (s *AgentService) DeleteAgentSessionItem(ctx context.Context, userID, agentreturn true, common.CodeSuccess, nil}+// canvasOwnedByUser reports whether the canvas is directly owned by userID+// (canvas.user_id), ignoring team sharing. Companion of CheckCanvasAccess,+// which authorizes the wider team-read scope.+func (s *AgentService) canvasOwnedByUser(ctx context.Context, userID, canvasID string) (bool, error) {+ canvas, err := s.canvasDAO.GetByID(ctx, dao.DB, canvasID)+ if err != nil {+ if errors.Is(err, dao.ErrUserCanvasNotFound) {+ return false, nil+ }+ return false, err+ }+ return canvas.UserID == userID, nil+}+// DeleteAgentSessions removes multiple conversations owned by agentID.// When ids is empty and deleteAll is true, every session under agentID is// removed.diff --git a/internal/service/agent_test.go b/internal/service/agent_test.goindex c3e3de4b83..fd63f2a4ef 100644--- a/internal/service/agent_test.go+++ b/internal/service/agent_test.go@@ -2380,3 +2380,85 @@ func TestOpenAICompatPriorHistoryPreservesConversation(t *testing.T) {t.Fatalf("prior history = %#v, want %#v", history, want)}}++// Shared-agent readonly rule: deleting a session is a write, so only the+// canvas owner or the session's creator may do it. Team members who can+// read the shared agent see its sessions readonly.+func createTeamSharedAgentTestFixtures(t *testing.T, canvasOwner, teammate, sessionID, sessionOwner string) {+ t.Helper()+ if err := dao.DB.Create(&entity.UserCanvas{+ ID: "canvas-1",+ UserID: canvasOwner,+ Title: sptr("Shared Agent"),+ CanvasCategory: "agent_canvas",+ Permission: string(entity.TenantPermissionTeam),+ }).Error; err != nil {+ t.Fatalf("failed to create canvas: %v", err)+ }+ if err := dao.DB.Create(&entity.UserTenant{+ ID: "ut-" + teammate + "-" + canvasOwner,+ UserID: teammate,+ TenantID: canvasOwner,+ Role: "normal",+ Status: sptr("1"),+ }).Error; err != nil {+ t.Fatalf("failed to create user tenant: %v", err)+ }+ createAgentSessionTestConversation(t, sessionID, "canvas-1", sessionOwner, 1000)+}++func TestDeleteAgentSessionItem_SharedSessionReadonlyForTeammate(t *testing.T) {+ setupAgentSessionServiceTest(t)+ createTeamSharedAgentTestFixtures(t, "owner-1", "user-1", "session-1", "owner-1")++ deleted, code, err := NewAgentService().DeleteAgentSessionItem(t.Context(), "user-1", "canvas-1", "session-1")+ if err == nil || err.Error() != "shared session is readonly" {+ t.Fatalf("err=%v", err)+ }+ if code != common.CodeAuthenticationError {+ t.Fatalf("code=%v", code)+ }+ if deleted {+ t.Fatal("shared session must not be deleted by a team member")+ }++ var count int64+ if err = dao.DB.Model(&entity.API4Conversation{}).Where("id = ?", "session-1").Count(&count).Error; err != nil {+ t.Fatalf("failed to count session: %v", err)+ }+ if count != 1 {+ t.Fatalf("session should remain, count=%d", count)+ }+}++func TestDeleteAgentSessionItem_SessionCreatorCanDeleteOwnSession(t *testing.T) {+ setupAgentSessionServiceTest(t)+ createTeamSharedAgentTestFixtures(t, "owner-1", "user-1", "session-1", "user-1")++ deleted, code, err := NewAgentService().DeleteAgentSessionItem(t.Context(), "user-1", "canvas-1", "session-1")+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if code != common.CodeSuccess {+ t.Fatalf("code=%v", code)+ }+ if !deleted {+ t.Fatal("session creator should be able to delete their own session")+ }+}++func TestDeleteAgentSessionItem_CanvasOwnerCanDeleteAnySession(t *testing.T) {+ setupAgentSessionServiceTest(t)+ createTeamSharedAgentTestFixtures(t, "owner-1", "user-1", "session-1", "user-1")++ deleted, code, err := NewAgentService().DeleteAgentSessionItem(t.Context(), "owner-1", "canvas-1", "session-1")+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if code != common.CodeSuccess {+ t.Fatalf("code=%v", code)+ }+ if !deleted {+ t.Fatal("canvas owner should be able to delete any session of the shared agent")+ }+}diff --git a/internal/service/chat_session.go b/internal/service/chat_session.goindex 7c6694f236..2e84f85304 100644--- a/internal/service/chat_session.go+++ b/internal/service/chat_session.go@@ -432,6 +432,15 @@ func (s *ChatSessionService) DeleteSessions(ctx context.Context, userID, chatIDcontinue}+ writable, werr := s.ensureSessionWritable(ctx, userID, chatID, session)+ if werr != nil {+ return nil, "", common.CodeServerError, werr+ }+ if !writable {+ errorsList = append(errorsList, fmt.Sprintf("No permission to delete the readonly session %s", sid))+ continue+ }+s.removeSessionUploadFiles(ctx, userID, session)if err = s.chatSessionDAO.DeleteByID(ctx, dao.DB, sid); err != nil {@@ -555,13 +564,22 @@ func (s *ChatSessionService) UpdateSession(ctx context.Context, userID, chatID,return nil, common.CodeAuthenticationError, errors.New("no authorization")}- if _, err = s.chatSessionDAO.GetBySessionIDAndChatID(ctx, dao.DB, sessionID, chatID); err != nil {+ session, err := s.chatSessionDAO.GetBySessionIDAndChatID(ctx, dao.DB, sessionID, chatID)+ if err != nil {if isChatSessionNotFound(err) {return nil, common.CodeDataError, errors.New("session not found")}return nil, common.CodeServerError, err}+ writable, err := s.ensureSessionWritable(ctx, userID, chatID, session)+ if err != nil {+ return nil, common.CodeServerError, err+ }+ if !writable {+ return nil, common.CodeAuthenticationError, errSharedSessionReadonly+ }+if _, ok = req["message"]; ok {return nil, common.CodeDataError, errors.New("`messages` cannot be changed")}@@ -604,7 +622,7 @@ func (s *ChatSessionService) UpdateSession(ctx context.Context, userID, chatID,}}- session, err := s.chatSessionDAO.GetByID(ctx, dao.DB, sessionID)+ session, err = s.chatSessionDAO.GetByID(ctx, dao.DB, sessionID)if err != nil {if isChatSessionNotFound(err) {return nil, common.CodeDataError, errors.New("fail to update a session")@@ -632,6 +650,14 @@ func (s *ChatSessionService) DeleteSessionMessage(ctx context.Context, userID, creturn nil, common.CodeDataError, errors.New("session not found")}+ writable, werr := s.ensureSessionWritable(ctx, userID, chatID, session)+ if werr != nil {+ return nil, common.CodeServerError, werr+ }+ if !writable {+ return nil, common.CodeAuthenticationError, errSharedSessionReadonly+ }+// parseMessages / parseReferenceList return nil for// malformed input, so the existing `nil` guards below are// the single source of truth for "this blob is corrupt".@@ -720,6 +746,12 @@ func (s *ChatSessionService) UpdateMessageFeedback(ctx context.Context, userID,return nil, common.CodeDataError, errors.New("session not found")}+ // Shared-session readonly rule: the chat owner (ownerTenantID) or the+ // session's creator may leave feedback; other team members cannot.+ if ownerTenantID != userID && (session.UserID == nil || *session.UserID != userID) {+ return nil, common.CodeAuthenticationError, errSharedSessionReadonly+ }+thumbRaw, ok := req["thumbup"]if !ok {return nil, common.CodeDataError, errors.New("thumb-up must be a boolean")@@ -1133,6 +1165,25 @@ func (s *ChatSessionService) ensureOwnedChat(ctx context.Context, userID, chatIDreturn exists, nil}+// errSharedSessionReadonly is returned when a caller who can read a chat+// shared with their team tries to mutate a session created by someone else.+var errSharedSessionReadonly = errors.New("shared session is readonly")++// ensureSessionWritable enforces the shared-session readonly rule: team+// members can read the sessions of a chat shared with their tenant, but a+// session may only be mutated by the chat owner (the dialog tenant) or by+// the session's creator. Everyone else sees the session readonly.+func (s *ChatSessionService) ensureSessionWritable(ctx context.Context, userID, chatID string, session *entity.ChatSession) (bool, error) {+ owns, err := s.chatSessionDAO.CheckDialogExists(ctx, dao.DB, userID, chatID)+ if err != nil {+ return false, err+ }+ if owns {+ return true, nil+ }+ return session.UserID != nil && *session.UserID == userID, nil+}+func (s *ChatSessionService) buildSessionPayload(session *entity.ChatSession, dialog *entity.Chat, includeAvatar bool) *ChatSessionPayload {var avatar *stringif includeAvatar {@@ -1497,6 +1548,12 @@ func (s *ChatSessionService) ChatCompletions(if session.DialogID != chatID {return fail(common.NewCodedError(common.CodeDataError, "Session does not belong to this chat!"))}+ // Shared-session readonly rule: only the chat owner (the dialog+ // tenant) or the session's creator may append to a session.+ // Team members who can read the shared chat see it readonly.+ if dialog.TenantID != userID && (session.UserID == nil || *session.UserID != userID) {+ return fail(common.NewCodedError(common.CodeAuthenticationError, errSharedSessionReadonly.Error()))+ }} else {session, err = s.createSessionForCompletion(ctx, chatID, dialog, userID, storeHistory)if err != nil {diff --git a/internal/service/chat_session_test.go b/internal/service/chat_session_test.goindex 5e2ce26b73..200ab6140b 100644--- a/internal/service/chat_session_test.go+++ b/internal/service/chat_session_test.go@@ -543,6 +543,7 @@ func TestDeleteSessionMessage_RemovesMessagePairAndReference(t *testing.T) {store.sessions["session-1"] = &entity.ChatSession{ID: "session-1",DialogID: "chat-1",+ UserID: strPtr("user-1"),Message: json.RawMessage(`[{"role":"assistant","content":"Welcome!"},{"role":"user","content":"first","id":"msg-1"},@@ -598,6 +599,7 @@ func TestUpdateMessageFeedback_AppliesChunkFeedbackWithResolvedTenantAndContext(store.sessions["session-1"] = &entity.ChatSession{ID: "session-1",DialogID: "chat-1",+ UserID: strPtr("user-1"),Message: json.RawMessage(`[{"role":"assistant","content":"Welcome!"},{"role":"user","content":"question","id":"msg-1"},@@ -656,6 +658,7 @@ func TestUpdateMessageFeedback_ToggleUsesResolvedTenantForUndoAndApply(t *testinstore.sessions["session-1"] = &entity.ChatSession{ID: "session-1",DialogID: "chat-1",+ UserID: strPtr("user-1"),Message: json.RawMessage(`[{"role":"assistant","content":"Welcome!"},{"role":"user","content":"question","id":"msg-1"},@@ -892,6 +895,7 @@ func TestChatCompletionsPassesRequestUserIDToPipeline(t *testing.T) {store.sessions["session-1"] = &entity.ChatSession{ID: "session-1",DialogID: "dialog-1",+ UserID: strPtr("user-1"),Message: json.RawMessage(`[{"role":"assistant","content":"Welcome!"}]`),Reference: json.RawMessage(`[]`),}@@ -951,6 +955,7 @@ func TestChatCompletionsStreamFinalCarriesDecoratedReference(t *testing.T) {store.sessions["session-1"] = &entity.ChatSession{ID: "session-1",DialogID: "dialog-1",+ UserID: strPtr("user-1"),Message: json.RawMessage(`[{"role":"assistant","content":"Welcome!"}]`),Reference: json.RawMessage(`[]`),}@@ -1069,6 +1074,7 @@ func TestChatCompletionsModelIDOverrideUsesModelResolver(t *testing.T) {store.sessions["session-1"] = &entity.ChatSession{ID: "session-1",DialogID: "dialog-1",+ UserID: strPtr("user-1"),Message: json.RawMessage(`[]`),Reference: json.RawMessage(`[]`),}@@ -1713,3 +1719,155 @@ func TestAccumulateNonStreamAnswer_AccumulatesDeltasUntilFinal(t *testing.T) {t.Fatalf("reference=%v, want nil", ref)}}++// ===================================================================+// Shared-session readonly rule (team-shared chats): only the chat owner+// (the dialog tenant) or the session's creator may mutate a session.+// ===================================================================++func newSharedChatReadonlyService() (*ChatSessionService, *fakeSessionStore) {+ store := newFakeSessionStore()+ // The chat is owned by tenant-owner and team-shared: "user-1" joined+ // that tenant, so reads pass ensureOwnedChat.+ store.dialogExists["tenant-owner|chat-1"] = true+ // The session was created by the chat owner, not by user-1.+ owner := "tenant-owner"+ store.sessions["session-1"] = &entity.ChatSession{+ ID: "session-1",+ DialogID: "chat-1",+ Name: &owner,+ UserID: &owner,+ Message: json.RawMessage(`[{"role":"assistant","content":"Welcome!"}]`),+ }+ svc := &ChatSessionService{+ chatSessionDAO: store,+ userTenantDAO: &fakeTenantStore{tenantIDs: []string{"tenant-owner"}},+ pipeline: &fakePipeline{},+ }+ return svc, store+}++func TestUpdateSession_SharedSessionReadonlyForTeammate(t *testing.T) {+ svc, store := newSharedChatReadonlyService()++ _, code, err := svc.UpdateSession(t.Context(), "user-1", "chat-1", "session-1", map[string]interface{}{"name": "renamed"})+ if err == nil || err.Error() != "shared session is readonly" {+ t.Fatalf("err=%v", err)+ }+ if code != common.CodeAuthenticationError {+ t.Fatalf("code=%v", code)+ }+ if len(store.updateCalled) != 0 {+ t.Fatalf("update calls=%d, want 0", len(store.updateCalled))+ }+}++func TestUpdateSession_SessionCreatorCanRenameInSharedChat(t *testing.T) {+ svc, store := newSharedChatReadonlyService()+ // Re-attribute the session to the requester: a team member may still+ // rename sessions they created themselves on the shared chat.+ store.sessions["session-1"].UserID = strPtr("user-1")++ resp, code, err := svc.UpdateSession(t.Context(), "user-1", "chat-1", "session-1", map[string]interface{}{"name": "renamed"})+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if code != common.CodeSuccess {+ t.Fatalf("code=%v", code)+ }+ if resp.Name == nil || *resp.Name != "renamed" {+ t.Fatalf("name=%v", resp.Name)+ }+}++func TestUpdateSession_ChatOwnerCanRenameAnySession(t *testing.T) {+ svc, store := newSharedChatReadonlyService()+ // The dialog tenant itself may manage every session of its chat.+ store.dialogExists["tenant-owner|chat-1"] = true++ _, code, err := svc.UpdateSession(t.Context(), "tenant-owner", "chat-1", "session-1", map[string]interface{}{"name": "renamed"})+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if code != common.CodeSuccess {+ t.Fatalf("code=%v", code)+ }+}++func TestDeleteSessions_SharedSessionReadonlyForTeammate(t *testing.T) {+ svc, store := newSharedChatReadonlyService()++ resp, msg, code, err := svc.DeleteSessions(t.Context(), "user-1", "chat-1", map[string]interface{}{"ids": []interface{}{"session-1"}})+ if err == nil || !strings.Contains(err.Error(), "readonly") {+ t.Fatalf("err=%v", err)+ }+ if code != common.CodeDataError {+ t.Fatalf("code=%v", code)+ }+ // The all-failed branch carries the detail in the error, not the message.+ _ = msg+ if _, stillThere := store.sessions["session-1"]; !stillThere {+ t.Fatalf("shared session should not be deleted by a team member")+ }+ if resp != nil {+ t.Fatalf("resp=%v, want nil", resp)+ }+}++func TestDeleteSessionMessage_SharedSessionReadonlyForTeammate(t *testing.T) {+ svc, _ := newSharedChatReadonlyService()++ _, code, err := svc.DeleteSessionMessage(t.Context(), "user-1", "chat-1", "session-1", "msg-1")+ if err == nil || err.Error() != "shared session is readonly" {+ t.Fatalf("err=%v", err)+ }+ if code != common.CodeAuthenticationError {+ t.Fatalf("code=%v", code)+ }+}++func TestUpdateMessageFeedback_SharedSessionReadonlyForTeammate(t *testing.T) {+ svc, _ := newSharedChatReadonlyService()++ _, code, err := svc.UpdateMessageFeedback(t.Context(), "user-1", "chat-1", "session-1", "msg-1", map[string]interface{}{"thumbup": true})+ if err == nil || err.Error() != "shared session is readonly" {+ t.Fatalf("err=%v", err)+ }+ if code != common.CodeAuthenticationError {+ t.Fatalf("code=%v", code)+ }+}++func TestChatCompletions_SharedSessionReadonlyForTeammate(t *testing.T) {+ svc, store := newSharedChatReadonlyService()+ store.dialogs["chat-1"] = &entity.Chat{+ ID: "chat-1",+ TenantID: "tenant-owner",+ LLMID: "chat@factory",+ LLMSetting: entity.JSONMap{},+ PromptConfig: entity.JSONMap{"parameters": []interface{}{}},+ }++ pipeline := &fakePipeline{resultChan: makeResultChan(AsyncChatResult{Answer: "ok", Final: true})}+ svc.pipeline = pipeline++ _, err := svc.ChatCompletions(+ t.Context(),+ "user-1",+ "chat-1",+ "session-1",+ []map[string]interface{}{{"role": "user", "content": "hi"}},+ "", nil, "", nil, nil,+ false, true, false, false, nil,+ )+ if err == nil {+ t.Fatalf("expected readonly rejection")+ }+ coded := common.NewCodedError(0, "")+ if !errors.As(err, &coded) || coded.Code != common.CodeAuthenticationError {+ t.Fatalf("err=%v", err)+ }+ if len(store.updateCalled) != 0 {+ t.Fatalf("update calls=%d, want 0", len(store.updateCalled))+ }+}