Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
feat(knowledge): enhance knowledge tag batch update with authorization checks
wizardchenb1fe7abbe10d
diff --git a/internal/application/service/knowledge.go b/internal/application/service/knowledge.goindex 1308746ef..98b17fdbe 100644--- a/internal/application/service/knowledge.go+++ b/internal/application/service/knowledge.go@@ -5269,7 +5269,9 @@ func (s *knowledgeService) UpdateKnowledgeTag(ctx context.Context, knowledgeID s}// UpdateKnowledgeTagBatch updates tags for document knowledge items in batch.-func (s *knowledgeService) UpdateKnowledgeTagBatch(ctx context.Context, updates map[string]*string) error {+// authorizedKBID restricts all updates to knowledge items belonging to this KB;+// pass empty string to skip the check (caller must ensure authorization by other means).+func (s *knowledgeService) UpdateKnowledgeTagBatch(ctx context.Context, authorizedKBID string, updates map[string]*string) error {if len(updates) == 0 {return nil}@@ -5292,6 +5294,19 @@ func (s *knowledgeService) UpdateKnowledgeTagBatch(ctx context.Context, updatesreturn err}+ // Validate all requested IDs were found and belong to the authorized KB+ if authorizedKBID != "" {+ if len(knowledgeList) != len(updates) {+ return werrors.NewForbiddenError("some knowledge IDs are not accessible in the authorized scope")+ }+ for _, k := range knowledgeList {+ if k.KnowledgeBaseID != authorizedKBID {+ return werrors.NewForbiddenError(+ fmt.Sprintf("knowledge %s does not belong to authorized knowledge base", k.ID))+ }+ }+ }+// Build tag ID map for validationtagIDSet := make(map[string]bool)for _, tagID := range updates {diff --git a/internal/handler/knowledge.go b/internal/handler/knowledge.goindex 61649a040..517abfbfa 100644--- a/internal/handler/knowledge.go+++ b/internal/handler/knowledge.go@@ -913,6 +913,10 @@ func (h *KnowledgeHandler) GetKnowledgeBatch(c *gin.Context) {return}+ // agentAllowedKBIDs restricts results to the agent's configured KB scope.+ // nil = no agent restriction; empty slice = agent has no KB access (none mode).+ var agentAllowedKBIDs []string+// Optional agent_id: when using shared agent, resolve agent and use its tenant for batch retrieval (so shared KB files can be loaded after refresh)if agentID := secutils.SanitizeForLog(req.AgentID); agentID != "" && h.agentShareService != nil {userIDVal, ok := c.Get(types.UserIDContextKey.String())@@ -933,13 +937,22 @@ func (h *KnowledgeHandler) GetKnowledgeBatch(c *gin.Context) {return}effectiveTenantID = agent.TenantID- logger.Infof(ctx, "Batch retrieving knowledge with agent_id, effective tenant ID: %d, IDs count: %d",- effectiveTenantID, len(req.IDs))+ agentAllowedKBIDs = resolveAgentAllowedKBIDs(agent)++ if agentAllowedKBIDs != nil && len(agentAllowedKBIDs) == 0 {+ c.JSON(http.StatusOK, gin.H{"success": true, "data": []*types.Knowledge{}})+ return+ }+ logger.Infof(ctx, "Batch retrieving knowledge with agent_id, effective tenant ID: %d, IDs count: %d, allowed KBs: %v",+ effectiveTenantID, len(req.IDs), agentAllowedKBIDs)}var knowledges []*types.Knowledgevar err error+ // scopeKBID tracks the single KB the results must belong to (set by explicit kb_id).+ var scopeKBID string+// Optional kb_id: validate KB access and use effective tenant for shared KBif kbID := secutils.SanitizeForLog(req.KBID); kbID != "" {_, _, effID, _, err := h.validateKnowledgeBaseAccessWithKBID(c, kbID)@@ -947,6 +960,11 @@ func (h *KnowledgeHandler) GetKnowledgeBatch(c *gin.Context) {c.Error(err)return}+ if agentAllowedKBIDs != nil && !sliceContains(agentAllowedKBIDs, kbID) {+ c.Error(errors.NewForbiddenError("Knowledge base not accessible through this agent"))+ return+ }+ scopeKBID = kbIDeffectiveTenantID = effIDctx = context.WithValue(ctx, types.TenantIDContextKey, effectiveTenantID)@@ -962,6 +980,28 @@ func (h *KnowledgeHandler) GetKnowledgeBatch(c *gin.Context) {knowledges, err = h.kgService.GetKnowledgeBatchWithSharedAccess(ctx, effectiveTenantID, req.IDs)}+ // Build the effective allowed-KB set from both scopeKBID and agentAllowedKBIDs.+ // scopeKBID (from explicit kb_id) restricts to a single KB;+ // agentAllowedKBIDs (from shared agent) restricts to the agent's configured KBs.+ var allowedKBSet map[string]bool+ if scopeKBID != "" {+ allowedKBSet = map[string]bool{scopeKBID: true}+ } else if agentAllowedKBIDs != nil {+ allowedKBSet = make(map[string]bool, len(agentAllowedKBIDs))+ for _, id := range agentAllowedKBIDs {+ allowedKBSet[id] = true+ }+ }+ if allowedKBSet != nil && len(knowledges) > 0 {+ filtered := make([]*types.Knowledge, 0, len(knowledges))+ for _, k := range knowledges {+ if allowedKBSet[k.KnowledgeBaseID] {+ filtered = append(filtered, k)+ }+ }+ knowledges = filtered+ }+if err != nil {logger.ErrorWithFields(ctx, err, nil)c.Error(errors.NewInternalServerError("Failed to retrieve knowledge list").WithDetails(err.Error()))@@ -1171,7 +1211,8 @@ func (h *KnowledgeHandler) UpdateKnowledgeTagBatch(c *gin.Context) {c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))return}- // Resolve effective tenant: explicit kb_id, or infer from first knowledge ID (for shared KB when frontend doesn't send kb_id)+ // Resolve effective tenant and the authorized KB scope.+ var authorizedKBID stringif kbID := secutils.SanitizeForLog(req.KBID); kbID != "" {_, _, effID, permission, err := h.validateKnowledgeBaseAccessWithKBID(c, kbID)if err != nil {@@ -1182,6 +1223,7 @@ func (h *KnowledgeHandler) UpdateKnowledgeTagBatch(c *gin.Context) {c.Error(errors.NewForbiddenError("No permission to update knowledge tags"))return}+ authorizedKBID = kbIDctx = context.WithValue(ctx, types.TenantIDContextKey, effID)} else if len(req.Updates) > 0 {// No kb_id: infer from first knowledge ID so shared-KB updates work without client sending kb_id@@ -1191,15 +1233,16 @@ func (h *KnowledgeHandler) UpdateKnowledgeTagBatch(c *gin.Context) {break}if firstKnowledgeID != "" {- _, effCtx, err := h.resolveKnowledgeAndValidateKBAccess(c, firstKnowledgeID, types.OrgRoleEditor)+ knowledge, effCtx, err := h.resolveKnowledgeAndValidateKBAccess(c, firstKnowledgeID, types.OrgRoleEditor)if err != nil {c.Error(err)return}+ authorizedKBID = knowledge.KnowledgeBaseIDctx = effCtx}}- if err := h.kgService.UpdateKnowledgeTagBatch(ctx, req.Updates); err != nil {+ if err := h.kgService.UpdateKnowledgeTagBatch(ctx, authorizedKBID, req.Updates); err != nil {logger.ErrorWithFields(ctx, err, nil)c.Error(err)return@@ -1571,3 +1614,32 @@ func (h *KnowledgeHandler) GetKnowledgeMoveProgress(c *gin.Context) {"data": progress,})}++// resolveAgentAllowedKBIDs returns the set of knowledge base IDs that the+// shared agent is allowed to access based on its KBSelectionMode config.+// Returns nil when no restriction applies ("all" mode), or a concrete slice+// (possibly empty for "none" mode) when the results must be filtered.+func resolveAgentAllowedKBIDs(agent *types.CustomAgent) []string {+ switch agent.Config.KBSelectionMode {+ case "all":+ return nil+ case "none":+ return []string{}+ case "selected":+ return agent.Config.KnowledgeBases+ default:+ if len(agent.Config.KnowledgeBases) > 0 {+ return agent.Config.KnowledgeBases+ }+ return nil+ }+}++func sliceContains(ss []string, target string) bool {+ for _, s := range ss {+ if s == target {+ return true+ }+ }+ return false+}diff --git a/internal/types/interfaces/knowledge.go b/internal/types/interfaces/knowledge.goindex ab4459b1f..713f1b7c1 100644--- a/internal/types/interfaces/knowledge.go+++ b/internal/types/interfaces/knowledge.go@@ -128,7 +128,9 @@ type KnowledgeService interface {// ExportFAQEntries exports all FAQ entries for a knowledge base as CSV data.ExportFAQEntries(ctx context.Context, kbID string) ([]byte, error)// UpdateKnowledgeTagBatch updates tag for document knowledge items in batch.- UpdateKnowledgeTagBatch(ctx context.Context, updates map[string]*string) error+ // authorizedKBID restricts all updates to knowledge items belonging to this KB;+ // pass empty string to skip (caller must ensure authorization by other means).+ UpdateKnowledgeTagBatch(ctx context.Context, authorizedKBID string, updates map[string]*string) error// UpdateFAQEntryTagBatch updates tag for FAQ entries in batch.// Key: entry seq_id, Value: tag seq_id (nil to remove tag)UpdateFAQEntryTagBatch(ctx context.Context, kbID string, updates map[int64]*int64) error