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: implement tenant isolation for knowledge base retrieval
wizardchen602086d884b7
diff --git a/internal/application/repository/knowledgebase.go b/internal/application/repository/knowledgebase.goindex fff4be132..a3dffc3fe 100644--- a/internal/application/repository/knowledgebase.go+++ b/internal/application/repository/knowledgebase.go@@ -26,7 +26,7 @@ func (r *knowledgeBaseRepository) CreateKnowledgeBase(ctx context.Context, kb *treturn r.db.WithContext(ctx).Create(kb).Error}-// GetKnowledgeBaseByID gets a knowledge base by id+// GetKnowledgeBaseByID gets a knowledge base by id (no tenant scope; caller must enforce isolation where needed)func (r *knowledgeBaseRepository) GetKnowledgeBaseByID(ctx context.Context, id string) (*types.KnowledgeBase, error) {var kb types.KnowledgeBaseif err := r.db.WithContext(ctx).Where("id = ?", id).First(&kb).Error; err != nil {@@ -38,6 +38,18 @@ func (r *knowledgeBaseRepository) GetKnowledgeBaseByID(ctx context.Context, id sreturn &kb, nil}+// GetKnowledgeBaseByIDAndTenant gets a knowledge base by id only if it belongs to the given tenant (enforces tenant isolation)+func (r *knowledgeBaseRepository) GetKnowledgeBaseByIDAndTenant(ctx context.Context, id string, tenantID uint64) (*types.KnowledgeBase, error) {+ var kb types.KnowledgeBase+ if err := r.db.WithContext(ctx).Where("id = ? AND tenant_id = ?", id, tenantID).First(&kb).Error; err != nil {+ if errors.Is(err, gorm.ErrRecordNotFound) {+ return nil, ErrKnowledgeBaseNotFound+ }+ return nil, err+ }+ return &kb, nil+}+// GetKnowledgeBaseByIDs gets knowledge bases by multiple idsfunc (r *knowledgeBaseRepository) GetKnowledgeBaseByIDs(ctx context.Context, ids []string) ([]*types.KnowledgeBase, error) {if len(ids) == 0 {diff --git a/internal/application/service/knowledgebase.go b/internal/application/service/knowledgebase.goindex 92d2d5999..f2b9f4895 100644--- a/internal/application/service/knowledgebase.go+++ b/internal/application/service/knowledgebase.go@@ -437,21 +437,23 @@ func (s *knowledgeBaseService) SetEmbeddingModel(ctx context.Context, id string,return nil}-// CopyKnowledgeBase copies a knowledge base to a new knowledge base-// 浅拷贝+// CopyKnowledgeBase copies a knowledge base to a new knowledge base (shallow copy).+// Source and target must belong to the tenant in context; cross-tenant access is rejected.func (s *knowledgeBaseService) CopyKnowledgeBase(ctx context.Context,srcKB string, dstKB string,) (*types.KnowledgeBase, *types.KnowledgeBase, error) {- sourceKB, err := s.repo.GetKnowledgeBaseByID(ctx, srcKB)+ tenantID := ctx.Value(types.TenantIDContextKey).(uint64)+ // Load source KB with tenant scope to prevent cross-tenant cloning+ sourceKB, err := s.repo.GetKnowledgeBaseByIDAndTenant(ctx, srcKB, tenantID)if err != nil {logger.Errorf(ctx, "Get source knowledge base failed: %v", err)return nil, nil, err}sourceKB.EnsureDefaults()- tenantID := ctx.Value(types.TenantIDContextKey).(uint64)var targetKB *types.KnowledgeBaseif dstKB != "" {- targetKB, err = s.repo.GetKnowledgeBaseByID(ctx, dstKB)+ // Load target KB with tenant scope so we only clone into the caller's tenant+ targetKB, err = s.repo.GetKnowledgeBaseByIDAndTenant(ctx, dstKB, tenantID)if err != nil {return nil, nil, err}diff --git a/internal/handler/knowledgebase.go b/internal/handler/knowledgebase.goindex abbb6aaab..7f6dc7e9b 100644--- a/internal/handler/knowledgebase.go+++ b/internal/handler/knowledgebase.go@@ -2,10 +2,12 @@ package handlerimport ("encoding/json"+ stderrors "errors""net/http""strconv""time"+ "github.com/Tencent/WeKnora/internal/application/repository""github.com/Tencent/WeKnora/internal/errors""github.com/Tencent/WeKnora/internal/logger""github.com/Tencent/WeKnora/internal/types"@@ -372,6 +374,45 @@ func (h *KnowledgeBaseHandler) CopyKnowledgeBase(c *gin.Context) {return}+ // Validate source knowledge base exists and belongs to caller's tenant (prevent cross-tenant clone)+ sourceKB, err := h.service.GetKnowledgeBaseByID(ctx, req.SourceID)+ if err != nil {+ if stderrors.Is(err, repository.ErrKnowledgeBaseNotFound) {+ c.Error(errors.NewNotFoundError("Source knowledge base not found"))+ return+ }+ logger.ErrorWithFields(ctx, err, nil)+ c.Error(errors.NewInternalServerError(err.Error()))+ return+ }+ if sourceKB.TenantID != tenantID.(uint64) {+ logger.Warnf(ctx,+ "Copy rejected: source knowledge base belongs to another tenant, source_id: %s, caller_tenant: %d, kb_tenant: %d",+ secutils.SanitizeForLog(req.SourceID), tenantID.(uint64), sourceKB.TenantID)+ c.Error(errors.NewForbiddenError("No permission to copy this knowledge base"))+ return+ }++ // If target_id provided, validate target belongs to caller's tenant+ if req.TargetID != "" {+ targetKB, err := h.service.GetKnowledgeBaseByID(ctx, req.TargetID)+ if err != nil {+ if stderrors.Is(err, repository.ErrKnowledgeBaseNotFound) {+ c.Error(errors.NewNotFoundError("Target knowledge base not found"))+ return+ }+ logger.ErrorWithFields(ctx, err, nil)+ c.Error(errors.NewInternalServerError(err.Error()))+ return+ }+ if targetKB.TenantID != tenantID.(uint64) {+ logger.Warnf(ctx, "Copy rejected: target knowledge base belongs to another tenant, target_id: %s",+ secutils.SanitizeForLog(req.TargetID))+ c.Error(errors.NewForbiddenError("No permission to copy to this knowledge base"))+ return+ }+ }+// Generate task ID if not providedtaskID := req.TaskIDif taskID == "" {diff --git a/internal/types/interfaces/knowledgebase.go b/internal/types/interfaces/knowledgebase.goindex dca22b0bf..ae1f2d658 100644--- a/internal/types/interfaces/knowledgebase.go+++ b/internal/types/interfaces/knowledgebase.go@@ -120,6 +120,17 @@ type KnowledgeBaseRepository interface {// - Possible errors such as record not existing, database errors, etc.GetKnowledgeBaseByID(ctx context.Context, id string) (*types.KnowledgeBase, error)+ // GetKnowledgeBaseByIDAndTenant queries a knowledge base by ID scoped to a tenant.+ // Returns ErrKnowledgeBaseNotFound if the KB does not exist or does not belong to the tenant.+ // Parameters:+ // - ctx: Context information+ // - id: Knowledge base ID+ // - tenantID: Tenant ID (enforces tenant isolation)+ // Returns:+ // - Knowledge base object, if found and owned by tenant+ // - Possible errors such as record not existing or wrong tenant, database errors, etc.+ GetKnowledgeBaseByIDAndTenant(ctx context.Context, id string, tenantID uint64) (*types.KnowledgeBase, error)+// GetKnowledgeBaseByIDs queries knowledge bases by multiple IDs// Parameters:// - ctx: Context information