feat(knowledge): enhance knowledge tag batch update with authorization checks
- Updated UpdateKnowledgeTagBatch method to include an authorizedKBID parameter for restricting updates to specific knowledge items. - Implemented validation to ensure that all requested knowledge IDs belong to the authorized knowledge base. - Enhanced GetKnowledgeBatch and UpdateKnowledgeTagBatch methods to incorporate agent-specific knowledge base access restrictions. - Added utility functions to resolve allowed knowledge base IDs for agents based on their configuration.
This commit is contained in:
@@ -5269,7 +5269,9 @@ func (s *knowledgeService) UpdateKnowledgeTag(ctx context.Context, knowledgeID s
|
|||||||
}
|
}
|
||||||
|
|
||||||
// UpdateKnowledgeTagBatch updates tags for document knowledge items in batch.
|
// 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 {
|
if len(updates) == 0 {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -5292,6 +5294,19 @@ func (s *knowledgeService) UpdateKnowledgeTagBatch(ctx context.Context, updates
|
|||||||
return err
|
return 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 validation
|
// Build tag ID map for validation
|
||||||
tagIDSet := make(map[string]bool)
|
tagIDSet := make(map[string]bool)
|
||||||
for _, tagID := range updates {
|
for _, tagID := range updates {
|
||||||
|
|||||||
@@ -913,6 +913,10 @@ func (h *KnowledgeHandler) GetKnowledgeBatch(c *gin.Context) {
|
|||||||
return
|
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)
|
// 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 {
|
if agentID := secutils.SanitizeForLog(req.AgentID); agentID != "" && h.agentShareService != nil {
|
||||||
userIDVal, ok := c.Get(types.UserIDContextKey.String())
|
userIDVal, ok := c.Get(types.UserIDContextKey.String())
|
||||||
@@ -933,13 +937,22 @@ func (h *KnowledgeHandler) GetKnowledgeBatch(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
effectiveTenantID = agent.TenantID
|
effectiveTenantID = agent.TenantID
|
||||||
logger.Infof(ctx, "Batch retrieving knowledge with agent_id, effective tenant ID: %d, IDs count: %d",
|
agentAllowedKBIDs = resolveAgentAllowedKBIDs(agent)
|
||||||
effectiveTenantID, len(req.IDs))
|
|
||||||
|
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.Knowledge
|
var knowledges []*types.Knowledge
|
||||||
var err error
|
var 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 KB
|
// Optional kb_id: validate KB access and use effective tenant for shared KB
|
||||||
if kbID := secutils.SanitizeForLog(req.KBID); kbID != "" {
|
if kbID := secutils.SanitizeForLog(req.KBID); kbID != "" {
|
||||||
_, _, effID, _, err := h.validateKnowledgeBaseAccessWithKBID(c, kbID)
|
_, _, effID, _, err := h.validateKnowledgeBaseAccessWithKBID(c, kbID)
|
||||||
@@ -947,6 +960,11 @@ func (h *KnowledgeHandler) GetKnowledgeBatch(c *gin.Context) {
|
|||||||
c.Error(err)
|
c.Error(err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if agentAllowedKBIDs != nil && !sliceContains(agentAllowedKBIDs, kbID) {
|
||||||
|
c.Error(errors.NewForbiddenError("Knowledge base not accessible through this agent"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
scopeKBID = kbID
|
||||||
effectiveTenantID = effID
|
effectiveTenantID = effID
|
||||||
ctx = context.WithValue(ctx, types.TenantIDContextKey, effectiveTenantID)
|
ctx = 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)
|
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 {
|
if err != nil {
|
||||||
logger.ErrorWithFields(ctx, err, nil)
|
logger.ErrorWithFields(ctx, err, nil)
|
||||||
c.Error(errors.NewInternalServerError("Failed to retrieve knowledge list").WithDetails(err.Error()))
|
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()))
|
c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
|
||||||
return
|
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 string
|
||||||
if kbID := secutils.SanitizeForLog(req.KBID); kbID != "" {
|
if kbID := secutils.SanitizeForLog(req.KBID); kbID != "" {
|
||||||
_, _, effID, permission, err := h.validateKnowledgeBaseAccessWithKBID(c, kbID)
|
_, _, effID, permission, err := h.validateKnowledgeBaseAccessWithKBID(c, kbID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -1182,6 +1223,7 @@ func (h *KnowledgeHandler) UpdateKnowledgeTagBatch(c *gin.Context) {
|
|||||||
c.Error(errors.NewForbiddenError("No permission to update knowledge tags"))
|
c.Error(errors.NewForbiddenError("No permission to update knowledge tags"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
authorizedKBID = kbID
|
||||||
ctx = context.WithValue(ctx, types.TenantIDContextKey, effID)
|
ctx = context.WithValue(ctx, types.TenantIDContextKey, effID)
|
||||||
} else if len(req.Updates) > 0 {
|
} else if len(req.Updates) > 0 {
|
||||||
// No kb_id: infer from first knowledge ID so shared-KB updates work without client sending kb_id
|
// 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
|
break
|
||||||
}
|
}
|
||||||
if firstKnowledgeID != "" {
|
if firstKnowledgeID != "" {
|
||||||
_, effCtx, err := h.resolveKnowledgeAndValidateKBAccess(c, firstKnowledgeID, types.OrgRoleEditor)
|
knowledge, effCtx, err := h.resolveKnowledgeAndValidateKBAccess(c, firstKnowledgeID, types.OrgRoleEditor)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.Error(err)
|
c.Error(err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
authorizedKBID = knowledge.KnowledgeBaseID
|
||||||
ctx = effCtx
|
ctx = 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)
|
logger.ErrorWithFields(ctx, err, nil)
|
||||||
c.Error(err)
|
c.Error(err)
|
||||||
return
|
return
|
||||||
@@ -1571,3 +1614,32 @@ func (h *KnowledgeHandler) GetKnowledgeMoveProgress(c *gin.Context) {
|
|||||||
"data": progress,
|
"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
|
||||||
|
}
|
||||||
|
|||||||
@@ -128,7 +128,9 @@ type KnowledgeService interface {
|
|||||||
// ExportFAQEntries exports all FAQ entries for a knowledge base as CSV data.
|
// ExportFAQEntries exports all FAQ entries for a knowledge base as CSV data.
|
||||||
ExportFAQEntries(ctx context.Context, kbID string) ([]byte, error)
|
ExportFAQEntries(ctx context.Context, kbID string) ([]byte, error)
|
||||||
// UpdateKnowledgeTagBatch updates tag for document knowledge items in batch.
|
// 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.
|
// UpdateFAQEntryTagBatch updates tag for FAQ entries in batch.
|
||||||
// Key: entry seq_id, Value: tag seq_id (nil to remove tag)
|
// Key: entry seq_id, Value: tag seq_id (nil to remove tag)
|
||||||
UpdateFAQEntryTagBatch(ctx context.Context, kbID string, updates map[int64]*int64) error
|
UpdateFAQEntryTagBatch(ctx context.Context, kbID string, updates map[int64]*int64) error
|
||||||
|
|||||||
Reference in New Issue
Block a user