feat: implement tenant isolation for knowledge base retrieval

- Added GetKnowledgeBaseByIDAndTenant method to enforce tenant isolation when retrieving knowledge bases by ID.
- Updated CopyKnowledgeBase method to use tenant-scoped retrieval, preventing cross-tenant cloning.
- Enhanced error handling in the KnowledgeBaseHandler to validate tenant ownership for source and target knowledge bases during copy operations.
This commit is contained in:
wizardchen
2026-02-06 14:45:37 +08:00
committed by lyingbug
parent 67fba0679a
commit 602086d884
4 changed files with 72 additions and 6 deletions
@@ -26,7 +26,7 @@ func (r *knowledgeBaseRepository) CreateKnowledgeBase(ctx context.Context, kb *t
return 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.KnowledgeBase
if 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 s
return &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 ids
func (r *knowledgeBaseRepository) GetKnowledgeBaseByIDs(ctx context.Context, ids []string) ([]*types.KnowledgeBase, error) {
if len(ids) == 0 {
@@ -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.KnowledgeBase
if 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
}
+41
View File
@@ -2,10 +2,12 @@ package handler
import (
"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 provided
taskID := req.TaskID
if taskID == "" {
@@ -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