diff --git a/internal/handler/faq.go b/internal/handler/faq.go index 7070349b..2aa4ccdb 100644 --- a/internal/handler/faq.go +++ b/internal/handler/faq.go @@ -1,14 +1,11 @@ package handler import ( - "context" - stderrors "errors" "net/http" "strconv" "github.com/gin-gonic/gin" - "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" @@ -17,79 +14,47 @@ import ( ) // FAQHandler handles FAQ knowledge base operations. +// +// All KB-access checks (own / org-shared / via shared agent) are now +// performed by the route-level g.KBAccessRead / g.KBAccessWrite +// guards in router.go — the guard rewrites c.Request.Context() to +// carry the effective tenant ID for the duration of the handler, so +// the handler reads tenant from context the way it always did. type FAQHandler struct { - knowledgeService interfaces.KnowledgeService - kbService interfaces.KnowledgeBaseService - kbShareService interfaces.KBShareService - agentShareService interfaces.AgentShareService + knowledgeService interfaces.KnowledgeService + kbService interfaces.KnowledgeBaseService } -// NewFAQHandler creates a new FAQ handler +// NewFAQHandler creates a new FAQ handler. func NewFAQHandler( knowledgeService interfaces.KnowledgeService, kbService interfaces.KnowledgeBaseService, - kbShareService interfaces.KBShareService, - agentShareService interfaces.AgentShareService, ) *FAQHandler { return &FAQHandler{ - knowledgeService: knowledgeService, - kbService: kbService, - kbShareService: kbShareService, - agentShareService: agentShareService, + knowledgeService: knowledgeService, + kbService: kbService, } } -// effectiveCtxForKB validates KB access (owner, shared, or via shared agent when requiredPermission is Viewer) and returns context with effectiveTenantID. -func (h *FAQHandler) effectiveCtxForKB(c *gin.Context, kbID string, requiredPermission types.OrgMemberRole) (context.Context, error) { - ctx := c.Request.Context() - tenantID := c.GetUint64(types.TenantIDContextKey.String()) - if tenantID == 0 { - return nil, errors.NewUnauthorizedError("Unauthorized") - } - userID, userExists := c.Get(types.UserIDContextKey.String()) - callerTenantRole := types.TenantRoleFromContext(ctx) - kbID = secutils.SanitizeForLog(kbID) - if kbID == "" { - return nil, errors.NewBadRequestError("Knowledge base ID cannot be empty") - } - kb, err := h.kbService.GetKnowledgeBaseByID(ctx, kbID) - if err != nil { - // ErrKnowledgeBaseNotFound is the expected response for a stale - // or probed kb id; the FAQ endpoints went out of their way to - // surface internal-server-error for those, which both confused - // clients (real 5xx vs. wrong URL) and burned ops attention on - // monitoring alerts. Mirror knowledgebase.go's mapping. - if stderrors.Is(err, repository.ErrKnowledgeBaseNotFound) { - return nil, errors.NewNotFoundError("knowledge base not found") - } - logger.ErrorWithFields(ctx, err, nil) - return nil, errors.NewInternalServerError(err.Error()) - } - if kb.TenantID == tenantID { - return context.WithValue(ctx, types.TenantIDContextKey, tenantID), nil - } - if h.kbShareService != nil { - permission, isShared, permErr := h.kbShareService.CheckTenantKBPermission(ctx, kbID, tenantID, callerTenantRole) - if permErr == nil && isShared && permission.HasPermission(requiredPermission) { - sourceTenantID, srcErr := h.kbShareService.GetKBSourceTenant(ctx, kbID) - if srcErr == nil { - logger.Infof(ctx, "Tenant %d accessing shared KB %s with permission %s, source tenant: %d", - tenantID, kbID, permission, sourceTenantID) - return context.WithValue(ctx, types.TenantIDContextKey, sourceTenantID), nil - } - } - } - if requiredPermission == types.OrgRoleViewer && h.agentShareService != nil { - can, err := h.agentShareService.TenantCanAccessKBViaSomeSharedAgent(ctx, tenantID, callerTenantRole, kb) - if err == nil && can { - logger.Infof(ctx, "Tenant %d accessing KB %s via some shared agent", tenantID, kbID) - return context.WithValue(ctx, types.TenantIDContextKey, kb.TenantID), nil - } - } - _ = userID - _ = userExists - logger.Warnf(ctx, "Permission denied to access KB %s", kbID) - return nil, errors.NewForbiddenError("Permission denied to access this knowledge base") +// faqDeleteRequest is a request for deleting FAQ entries in batch +type faqDeleteRequest struct { + IDs []int64 `json:"ids" binding:"required,min=1"` +} + +// faqEntryTagBatchRequest is a request for updating tags for FAQ entries in batch +// key: entry seq_id, value: tag seq_id (nil to remove tag) +type faqEntryTagBatchRequest struct { + Updates map[int64]*int64 `json:"updates" binding:"required,min=1"` +} + +// addSimilarQuestionsRequest is a request for adding similar questions to a FAQ entry +type addSimilarQuestionsRequest struct { + SimilarQuestions []string `json:"similar_questions" binding:"required,min=1"` +} + +// updateLastFAQImportResultDisplayStatusRequest is the request payload for UpdateLastImportResultDisplayStatus +type updateLastFAQImportResultDisplayStatusRequest struct { + DisplayStatus string `json:"display_status" binding:"required,oneof=open close"` } // ListEntries godoc @@ -113,11 +78,7 @@ func (h *FAQHandler) effectiveCtxForKB(c *gin.Context, kbID string, requiredPerm func (h *FAQHandler) ListEntries(c *gin.Context) { ctx := c.Request.Context() kbID := secutils.SanitizeForLog(c.Param("id")) - effCtx, err := h.effectiveCtxForKB(c, kbID, types.OrgRoleViewer) - if err != nil { - c.Error(err) - return - } + var page types.Pagination if err := c.ShouldBindQuery(&page); err != nil { logger.Error(ctx, "Failed to bind pagination query", err) @@ -139,7 +100,7 @@ func (h *FAQHandler) ListEntries(c *gin.Context) { searchField := secutils.SanitizeForLog(c.Query("search_field")) sortOrder := secutils.SanitizeForLog(c.Query("sort_order")) - result, err := h.knowledgeService.ListFAQEntries(effCtx, kbID, &page, tagSeqID, keyword, searchField, sortOrder) + result, err := h.knowledgeService.ListFAQEntries(ctx, kbID, &page, tagSeqID, keyword, searchField, sortOrder) if err != nil { logger.ErrorWithFields(ctx, err, nil) c.Error(err) @@ -170,11 +131,7 @@ func (h *FAQHandler) ListEntries(c *gin.Context) { func (h *FAQHandler) UpsertEntries(c *gin.Context) { ctx := c.Request.Context() kbID := secutils.SanitizeForLog(c.Param("id")) - effCtx, err := h.effectiveCtxForKB(c, kbID, types.OrgRoleEditor) - if err != nil { - c.Error(err) - return - } + var req types.FAQBatchUpsertPayload if err := c.ShouldBindJSON(&req); err != nil { logger.Error(ctx, "Failed to bind FAQ upsert payload", err) @@ -182,8 +139,7 @@ func (h *FAQHandler) UpsertEntries(c *gin.Context) { return } - // 统一使用 UpsertFAQEntries,通过 DryRun 字段区分模式 - taskID, err := h.knowledgeService.UpsertFAQEntries(effCtx, kbID, &req) + taskID, err := h.knowledgeService.UpsertFAQEntries(ctx, kbID, &req) if err != nil { logger.ErrorWithFields(ctx, err, nil) c.Error(err) @@ -214,11 +170,7 @@ func (h *FAQHandler) UpsertEntries(c *gin.Context) { func (h *FAQHandler) CreateEntry(c *gin.Context) { ctx := c.Request.Context() kbID := secutils.SanitizeForLog(c.Param("id")) - effCtx, err := h.effectiveCtxForKB(c, kbID, types.OrgRoleEditor) - if err != nil { - c.Error(err) - return - } + var req types.FAQEntryPayload if err := c.ShouldBindJSON(&req); err != nil { logger.Error(ctx, "Failed to bind FAQ entry payload", err) @@ -226,7 +178,7 @@ func (h *FAQHandler) CreateEntry(c *gin.Context) { return } - entry, err := h.knowledgeService.CreateFAQEntry(effCtx, kbID, &req) + entry, err := h.knowledgeService.CreateFAQEntry(ctx, kbID, &req) if err != nil { logger.ErrorWithFields(ctx, err, nil) c.Error(err) @@ -256,11 +208,7 @@ func (h *FAQHandler) CreateEntry(c *gin.Context) { func (h *FAQHandler) UpdateEntry(c *gin.Context) { ctx := c.Request.Context() kbID := secutils.SanitizeForLog(c.Param("id")) - effCtx, err := h.effectiveCtxForKB(c, kbID, types.OrgRoleEditor) - if err != nil { - c.Error(err) - return - } + var req types.FAQEntryPayload if err := c.ShouldBindJSON(&req); err != nil { logger.Error(ctx, "Failed to bind FAQ entry payload", err) @@ -274,8 +222,7 @@ func (h *FAQHandler) UpdateEntry(c *gin.Context) { return } - entry, err := h.knowledgeService.UpdateFAQEntry(effCtx, - kbID, entrySeqID, &req) + entry, err := h.knowledgeService.UpdateFAQEntry(ctx, kbID, entrySeqID, &req) if err != nil { logger.ErrorWithFields(ctx, err, nil) c.Error(err) @@ -304,19 +251,14 @@ func (h *FAQHandler) UpdateEntry(c *gin.Context) { func (h *FAQHandler) UpdateEntryTagBatch(c *gin.Context) { ctx := c.Request.Context() kbID := secutils.SanitizeForLog(c.Param("id")) - effCtx, err := h.effectiveCtxForKB(c, kbID, types.OrgRoleEditor) - if err != nil { - c.Error(err) - return - } + var req faqEntryTagBatchRequest if err := c.ShouldBindJSON(&req); err != nil { logger.Error(ctx, "Failed to bind FAQ entry tag batch payload", err) c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error())) return } - if err := h.knowledgeService.UpdateFAQEntryTagBatch(effCtx, - kbID, req.Updates); err != nil { + if err := h.knowledgeService.UpdateFAQEntryTagBatch(ctx, kbID, req.Updates); err != nil { logger.ErrorWithFields(ctx, err, nil) c.Error(err) return @@ -342,19 +284,14 @@ func (h *FAQHandler) UpdateEntryTagBatch(c *gin.Context) { func (h *FAQHandler) UpdateEntryFieldsBatch(c *gin.Context) { ctx := c.Request.Context() kbID := secutils.SanitizeForLog(c.Param("id")) - effCtx, err := h.effectiveCtxForKB(c, kbID, types.OrgRoleEditor) - if err != nil { - c.Error(err) - return - } + var req types.FAQEntryFieldsBatchUpdate if err := c.ShouldBindJSON(&req); err != nil { logger.Error(ctx, "Failed to bind FAQ entry fields batch payload", err) c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error())) return } - if err := h.knowledgeService.UpdateFAQEntryFieldsBatch(effCtx, - kbID, &req); err != nil { + if err := h.knowledgeService.UpdateFAQEntryFieldsBatch(ctx, kbID, &req); err != nil { logger.ErrorWithFields(ctx, err, nil) c.Error(err) return @@ -364,22 +301,6 @@ func (h *FAQHandler) UpdateEntryFieldsBatch(c *gin.Context) { }) } -// faqDeleteRequest is a request for deleting FAQ entries in batch -type faqDeleteRequest struct { - IDs []int64 `json:"ids" binding:"required,min=1"` -} - -// faqEntryTagBatchRequest is a request for updating tags for FAQ entries in batch -// key: entry seq_id, value: tag seq_id (nil to remove tag) -type faqEntryTagBatchRequest struct { - Updates map[int64]*int64 `json:"updates" binding:"required,min=1"` -} - -// addSimilarQuestionsRequest is a request for adding similar questions to a FAQ entry -type addSimilarQuestionsRequest struct { - SimilarQuestions []string `json:"similar_questions" binding:"required,min=1"` -} - // DeleteEntries godoc // @Summary 批量删除FAQ条目 // @Description 批量删除指定的FAQ条目 @@ -396,11 +317,7 @@ type addSimilarQuestionsRequest struct { func (h *FAQHandler) DeleteEntries(c *gin.Context) { ctx := c.Request.Context() kbID := secutils.SanitizeForLog(c.Param("id")) - effCtx, err := h.effectiveCtxForKB(c, kbID, types.OrgRoleEditor) - if err != nil { - c.Error(err) - return - } + var req faqDeleteRequest if err := c.ShouldBindJSON(&req); err != nil { logger.Errorf(ctx, "Failed to bind FAQ delete payload: %s", secutils.SanitizeForLog(err.Error())) @@ -408,9 +325,7 @@ func (h *FAQHandler) DeleteEntries(c *gin.Context) { return } - if err := h.knowledgeService.DeleteFAQEntries(effCtx, - kbID, - req.IDs); err != nil { + if err := h.knowledgeService.DeleteFAQEntries(ctx, kbID, req.IDs); err != nil { logger.ErrorWithFields(ctx, err, nil) c.Error(err) return @@ -437,11 +352,7 @@ func (h *FAQHandler) DeleteEntries(c *gin.Context) { func (h *FAQHandler) SearchFAQ(c *gin.Context) { ctx := c.Request.Context() kbID := secutils.SanitizeForLog(c.Param("id")) - effCtx, err := h.effectiveCtxForKB(c, kbID, types.OrgRoleViewer) - if err != nil { - c.Error(err) - return - } + var req types.FAQSearchRequest if err := c.ShouldBindJSON(&req); err != nil { logger.Error(ctx, "Failed to bind FAQ search payload", err) @@ -455,7 +366,7 @@ func (h *FAQHandler) SearchFAQ(c *gin.Context) { if req.MatchCount > 200 { req.MatchCount = 200 } - entries, err := h.knowledgeService.SearchFAQEntries(effCtx, kbID, &req) + entries, err := h.knowledgeService.SearchFAQEntries(ctx, kbID, &req) if err != nil { logger.ErrorWithFields(ctx, err, nil) c.Error(err) @@ -483,13 +394,8 @@ func (h *FAQHandler) SearchFAQ(c *gin.Context) { func (h *FAQHandler) ExportEntries(c *gin.Context) { ctx := c.Request.Context() kbID := secutils.SanitizeForLog(c.Param("id")) - effCtx, err := h.effectiveCtxForKB(c, kbID, types.OrgRoleViewer) - if err != nil { - c.Error(err) - return - } - csvData, err := h.knowledgeService.ExportFAQEntries(effCtx, kbID) + csvData, err := h.knowledgeService.ExportFAQEntries(ctx, kbID) if err != nil { logger.ErrorWithFields(ctx, err, nil) c.Error(err) @@ -521,18 +427,14 @@ func (h *FAQHandler) ExportEntries(c *gin.Context) { func (h *FAQHandler) GetEntry(c *gin.Context) { ctx := c.Request.Context() kbID := secutils.SanitizeForLog(c.Param("id")) - effCtx, err := h.effectiveCtxForKB(c, kbID, types.OrgRoleViewer) - if err != nil { - c.Error(err) - return - } + entrySeqID, err := strconv.ParseInt(c.Param("entry_id"), 10, 64) if err != nil { c.Error(errors.NewBadRequestError("entry_id 必须是整数")) return } - entry, err := h.knowledgeService.GetFAQEntry(effCtx, kbID, entrySeqID) + entry, err := h.knowledgeService.GetFAQEntry(ctx, kbID, entrySeqID) if err != nil { logger.ErrorWithFields(ctx, err, nil) c.Error(err) @@ -574,11 +476,6 @@ func (h *FAQHandler) GetImportProgress(c *gin.Context) { }) } -// updateLastFAQImportResultDisplayStatusRequest is the request payload for UpdateLastImportResultDisplayStatus -type updateLastFAQImportResultDisplayStatusRequest struct { - DisplayStatus string `json:"display_status" binding:"required,oneof=open close"` -} - // UpdateLastImportResultDisplayStatus godoc // @Summary 更新FAQ最后一次导入结果显示状态 // @Description 更新FAQ知识库导入结果统计卡片的显示或隐藏状态 @@ -596,11 +493,6 @@ type updateLastFAQImportResultDisplayStatusRequest struct { func (h *FAQHandler) UpdateLastImportResultDisplayStatus(c *gin.Context) { ctx := c.Request.Context() kbID := secutils.SanitizeForLog(c.Param("id")) - effCtx, err := h.effectiveCtxForKB(c, kbID, types.OrgRoleEditor) - if err != nil { - c.Error(err) - return - } var req updateLastFAQImportResultDisplayStatusRequest if err := c.ShouldBindJSON(&req); err != nil { @@ -609,7 +501,7 @@ func (h *FAQHandler) UpdateLastImportResultDisplayStatus(c *gin.Context) { return } - if err := h.knowledgeService.UpdateLastFAQImportResultDisplayStatus(effCtx, kbID, req.DisplayStatus); err != nil { + if err := h.knowledgeService.UpdateLastFAQImportResultDisplayStatus(ctx, kbID, req.DisplayStatus); err != nil { logger.ErrorWithFields(ctx, err, nil) c.Error(err) return @@ -638,11 +530,6 @@ func (h *FAQHandler) UpdateLastImportResultDisplayStatus(c *gin.Context) { func (h *FAQHandler) AddSimilarQuestions(c *gin.Context) { ctx := c.Request.Context() kbID := secutils.SanitizeForLog(c.Param("id")) - effCtx, err := h.effectiveCtxForKB(c, kbID, types.OrgRoleEditor) - if err != nil { - c.Error(err) - return - } entrySeqID, err := strconv.ParseInt(c.Param("entry_id"), 10, 64) if err != nil { @@ -657,7 +544,7 @@ func (h *FAQHandler) AddSimilarQuestions(c *gin.Context) { return } - entry, err := h.knowledgeService.AddSimilarQuestions(effCtx, kbID, entrySeqID, req.SimilarQuestions) + entry, err := h.knowledgeService.AddSimilarQuestions(ctx, kbID, entrySeqID, req.SimilarQuestions) if err != nil { logger.ErrorWithFields(ctx, err, nil) c.Error(err) diff --git a/internal/handler/tag.go b/internal/handler/tag.go index 623eecb2..3145d179 100644 --- a/internal/handler/tag.go +++ b/internal/handler/tag.go @@ -2,13 +2,11 @@ package handler import ( "context" - stderrors "errors" "net/http" "strconv" "github.com/gin-gonic/gin" - "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" @@ -17,13 +15,16 @@ import ( ) // TagHandler handles knowledge base tag operations. +// +// All KB-access checks (own / org-shared / via shared agent) are now +// performed by the route-level g.KBAccessRead / g.KBAccessWrite +// guards in router.go — the guard rewrites c.Request.Context() to +// carry the effective tenant ID, so handlers below just use +// c.Request.Context() the way they always did. type TagHandler struct { - tagService interfaces.KnowledgeTagService - tagRepo interfaces.KnowledgeTagRepository - chunkRepo interfaces.ChunkRepository - kbService interfaces.KnowledgeBaseService - kbShareService interfaces.KBShareService - agentShareService interfaces.AgentShareService + tagService interfaces.KnowledgeTagService + tagRepo interfaces.KnowledgeTagRepository + chunkRepo interfaces.ChunkRepository } // DeleteTagRequest represents the request body for deleting a tag @@ -36,71 +37,18 @@ func NewTagHandler( tagService interfaces.KnowledgeTagService, tagRepo interfaces.KnowledgeTagRepository, chunkRepo interfaces.ChunkRepository, - kbService interfaces.KnowledgeBaseService, - kbShareService interfaces.KBShareService, - agentShareService interfaces.AgentShareService, ) *TagHandler { - return &TagHandler{tagService: tagService, tagRepo: tagRepo, chunkRepo: chunkRepo, kbService: kbService, kbShareService: kbShareService, agentShareService: agentShareService} -} - -// effectiveCtxForKB validates KB access (owner or shared) and returns context with effectiveTenantID for downstream service calls. -func (h *TagHandler) effectiveCtxForKB(c *gin.Context, kbID string) (context.Context, error) { - ctx := c.Request.Context() - tenantID := c.GetUint64(types.TenantIDContextKey.String()) - if tenantID == 0 { - return nil, errors.NewUnauthorizedError("Unauthorized") - } - userID, userExists := c.Get(types.UserIDContextKey.String()) - callerTenantRole := types.TenantRoleFromContext(ctx) - kbID = secutils.SanitizeForLog(kbID) - if kbID == "" { - return nil, errors.NewBadRequestError("Knowledge base ID cannot be empty") - } - kb, err := h.kbService.GetKnowledgeBaseByID(ctx, kbID) - if err != nil { - // Same not-found-vs-real-error split as the other helper sites: - // a missing or cross-tenant kb id should render as 404 so clients - // can tell "wrong URL" from a real 5xx. - if stderrors.Is(err, repository.ErrKnowledgeBaseNotFound) { - return nil, errors.NewNotFoundError("knowledge base not found") - } - logger.ErrorWithFields(ctx, err, nil) - return nil, errors.NewInternalServerError(err.Error()) - } - if kb.TenantID == tenantID { - return context.WithValue(ctx, types.TenantIDContextKey, tenantID), nil - } - if h.kbShareService != nil { - permission, isShared, permErr := h.kbShareService.CheckTenantKBPermission(ctx, kbID, tenantID, callerTenantRole) - if permErr == nil && isShared { - sourceTenantID, srcErr := h.kbShareService.GetKBSourceTenant(ctx, kbID) - if srcErr == nil { - logger.Infof(ctx, "Tenant %d accessing shared KB %s with permission %s, source tenant: %d", - tenantID, kbID, permission, sourceTenantID) - return context.WithValue(ctx, types.TenantIDContextKey, sourceTenantID), nil - } - } - } - if h.agentShareService != nil { - can, err := h.agentShareService.TenantCanAccessKBViaSomeSharedAgent(ctx, tenantID, callerTenantRole, kb) - if err == nil && can { - logger.Infof(ctx, "Tenant %d accessing KB %s via some shared agent", tenantID, kbID) - return context.WithValue(ctx, types.TenantIDContextKey, kb.TenantID), nil - } - } - _ = userID - _ = userExists - logger.Warnf(ctx, "Permission denied to access KB %s", kbID) - return nil, errors.NewForbiddenError("Permission denied to access this knowledge base") + return &TagHandler{tagService: tagService, tagRepo: tagRepo, chunkRepo: chunkRepo} } // resolveTagID resolves tag_id parameter which can be either UUID or seq_id (integer). -// Uses tenant from c's context. Use resolveTagIDWithCtx when effectiveTenantID is set (e.g. shared KB). +// Uses tenant from c's context — which the route-level KB-access guard +// has already rewritten to the effective tenant for shared KBs. func (h *TagHandler) resolveTagID(c *gin.Context) (string, error) { return h.resolveTagIDWithCtx(c, c.Request.Context()) } -// resolveTagIDWithCtx resolves tag_id using the given context for tenant (e.g. effCtx for shared KB). +// resolveTagIDWithCtx resolves tag_id using the given context for tenant. func (h *TagHandler) resolveTagIDWithCtx(c *gin.Context, ctx context.Context) (string, error) { tagIDParam := secutils.SanitizeForLog(c.Param("tag_id")) @@ -139,12 +87,6 @@ func (h *TagHandler) ListTags(c *gin.Context) { ctx := c.Request.Context() kbID := secutils.SanitizeForLog(c.Param("id")) - effCtx, err := h.effectiveCtxForKB(c, kbID) - if err != nil { - c.Error(err) - return - } - var page types.Pagination if err := c.ShouldBindQuery(&page); err != nil { logger.Error(ctx, "Failed to bind pagination query", err) @@ -154,7 +96,7 @@ func (h *TagHandler) ListTags(c *gin.Context) { keyword := secutils.SanitizeForLog(c.Query("keyword")) - tags, err := h.tagService.ListTags(effCtx, kbID, &page, keyword) + tags, err := h.tagService.ListTags(ctx, kbID, &page, keyword) if err != nil { logger.ErrorWithFields(ctx, err, nil) c.Error(err) @@ -190,12 +132,6 @@ func (h *TagHandler) CreateTag(c *gin.Context) { ctx := c.Request.Context() kbID := secutils.SanitizeForLog(c.Param("id")) - effCtx, err := h.effectiveCtxForKB(c, kbID) - if err != nil { - c.Error(err) - return - } - var req createTagRequest if err := c.ShouldBindJSON(&req); err != nil { logger.Error(ctx, "Failed to bind create tag payload", err) @@ -203,7 +139,7 @@ func (h *TagHandler) CreateTag(c *gin.Context) { return } - tag, err := h.tagService.CreateTag(effCtx, kbID, + tag, err := h.tagService.CreateTag(ctx, kbID, secutils.SanitizeForLog(req.Name), secutils.SanitizeForLog(req.Color), req.SortOrder) if err != nil { logger.ErrorWithFields(ctx, err, map[string]interface{}{ @@ -241,15 +177,8 @@ type updateTagRequest struct { // @Router /knowledge-bases/{id}/tags/{tag_id} [put] func (h *TagHandler) UpdateTag(c *gin.Context) { ctx := c.Request.Context() - kbID := secutils.SanitizeForLog(c.Param("id")) - effCtx, err := h.effectiveCtxForKB(c, kbID) - if err != nil { - c.Error(err) - return - } - - tagID, err := h.resolveTagIDWithCtx(c, effCtx) + tagID, err := h.resolveTagID(c) if err != nil { c.Error(err) return @@ -262,7 +191,7 @@ func (h *TagHandler) UpdateTag(c *gin.Context) { return } - tag, err := h.tagService.UpdateTag(effCtx, tagID, req.Name, req.Color, req.SortOrder) + tag, err := h.tagService.UpdateTag(ctx, tagID, req.Name, req.Color, req.SortOrder) if err != nil { logger.ErrorWithFields(ctx, err, map[string]interface{}{ "tag_id": tagID, @@ -295,15 +224,8 @@ func (h *TagHandler) UpdateTag(c *gin.Context) { // @Router /knowledge-bases/{id}/tags/{tag_id} [delete] func (h *TagHandler) DeleteTag(c *gin.Context) { ctx := c.Request.Context() - kbID := secutils.SanitizeForLog(c.Param("id")) - effCtx, err := h.effectiveCtxForKB(c, kbID) - if err != nil { - c.Error(err) - return - } - - tagID, err := h.resolveTagIDWithCtx(c, effCtx) + tagID, err := h.resolveTagID(c) if err != nil { c.Error(err) return @@ -317,8 +239,8 @@ func (h *TagHandler) DeleteTag(c *gin.Context) { var excludeUUIDs []string if len(req.ExcludeIDs) > 0 { - tenantID := effCtx.Value(types.TenantIDContextKey).(uint64) - chunks, err := h.getChunksBySeqIDs(effCtx, tenantID, req.ExcludeIDs) + tenantID := types.MustTenantIDFromContext(ctx) + chunks, err := h.getChunksBySeqIDs(ctx, tenantID, req.ExcludeIDs) if err != nil { logger.Warnf(ctx, "Failed to resolve exclude_ids: %v", err) } else { @@ -329,7 +251,7 @@ func (h *TagHandler) DeleteTag(c *gin.Context) { } } - if err := h.tagService.DeleteTag(effCtx, tagID, force, contentOnly, excludeUUIDs); err != nil { + if err := h.tagService.DeleteTag(ctx, tagID, force, contentOnly, excludeUUIDs); err != nil { logger.ErrorWithFields(ctx, err, map[string]interface{}{ "tag_id": tagID, }) diff --git a/internal/middleware/kb_access.go b/internal/middleware/kb_access.go new file mode 100644 index 00000000..ee4e23b1 --- /dev/null +++ b/internal/middleware/kb_access.go @@ -0,0 +1,257 @@ +package middleware + +import ( + "context" + stderrors "errors" + + apprepo "github.com/Tencent/WeKnora/internal/application/repository" + apperrors "github.com/Tencent/WeKnora/internal/errors" + "github.com/Tencent/WeKnora/internal/logger" + "github.com/Tencent/WeKnora/internal/types" + "github.com/Tencent/WeKnora/internal/types/interfaces" + "github.com/gin-gonic/gin" +) + +// kb_access.go centralises the share-fallback that previously lived as +// near-identical 30-line helpers in five handler files (chunk.go, +// faq.go, tag.go, knowledge.go, knowledgebase.go). Each was a copy of +// the same three checks: +// +// 1. KB belongs to caller's tenant -> grant own access +// 2. Org-shared KB -> grant min(share, role) cap +// 3. Shared agent carries the KB -> grant Viewer (read-only) +// +// Putting the resolution in a route-level gin.HandlerFunc makes the +// route declaration the single source of truth for "what permission +// is required" and "where does the kb_id come from". Handlers no +// longer carry an effectiveCtxForKB / validateAndGetKnowledgeBase +// helper — the guard runs first, stashes the resolution under +// KBAccessContextKey and rewrites c.Request to carry the +// effective-tenant-ID context, then handlers just read TenantIDFromContext +// the way they always did. +// +// Plan 3's 3-D cap (tenant Viewer pinned to OrgRoleViewer) is enforced +// inside CheckTenantKBPermission itself, so the guard here just +// propagates the result. + +// KBAccess captures the result of a successful KB access resolution. +// Stashed on gin.Context under KBAccessContextKey so handlers that +// need the resolved KB / permission (e.g. to render +// my_permission in the response) can pull it without re-running the +// resolution. +type KBAccess struct { + KnowledgeBase *types.KnowledgeBase + EffectiveTenantID uint64 + Permission types.OrgMemberRole +} + +// KBAccessContextKey is the gin.Context key under which a successful +// KB access resolution is stored. +const KBAccessContextKey = "rbac.kb_access" + +// KBAccessFromContext returns the KBAccess stashed by the guard, if +// any. Handlers that don't care can just rely on the rewritten +// c.Request.Context() for tenant scoping. +func KBAccessFromContext(c *gin.Context) (*KBAccess, bool) { + v, ok := c.Get(KBAccessContextKey) + if !ok { + return nil, false + } + a, ok := v.(*KBAccess) + return a, ok +} + +// KBLookup is the minimum surface ResolveKBAccess needs from the +// knowledge-base service: a single method that turns an ID into a +// KnowledgeBase pointer (or repo.ErrKnowledgeBaseNotFound). Defining +// it as a tiny dedicated interface keeps the guard testable without +// forcing test stubs to satisfy the full KnowledgeBaseService surface. +type KBLookup interface { + GetKnowledgeBaseByID(ctx context.Context, id string) (*types.KnowledgeBase, error) +} + +// KnowledgeLookup mirrors KBLookup but for resolving a knowledge id +// (document id) back to its parent KB. Used by the chunk routes whose +// URL param is a knowledge_id, not a kb_id. +type KnowledgeLookup interface { + GetKnowledgeByIDOnly(ctx context.Context, id string) (*types.Knowledge, error) +} + +// KBIDResolver tells the guard how to find the kb_id for a given +// request. Built-in resolvers below cover the param shapes we use: +// :id, :kb_id, :kbId, :knowledge_id (-> parent KB). +type KBIDResolver func(c *gin.Context) (string, error) + +// KBIDFromParam returns a resolver that reads a fixed gin param. +func KBIDFromParam(param string) KBIDResolver { + return func(c *gin.Context) (string, error) { + v := c.Param(param) + if v == "" { + return "", apperrors.NewBadRequestError("missing " + param + " in path") + } + return v, nil + } +} + +// KBIDFromKnowledgeIDParam reads `:knowledge_id` from the URL, looks +// up the knowledge document, and returns its KB id. Used by the chunk +// routes that address a chunk via /chunks/:knowledge_id. +func KBIDFromKnowledgeIDParam(param string, kgService KnowledgeLookup) KBIDResolver { + return func(c *gin.Context) (string, error) { + v := c.Param(param) + if v == "" { + return "", apperrors.NewBadRequestError("missing " + param + " in path") + } + k, err := kgService.GetKnowledgeByIDOnly(c.Request.Context(), v) + if err != nil || k == nil { + return "", apperrors.NewNotFoundError("Knowledge not found") + } + return k.KnowledgeBaseID, nil + } +} + +// RequireKBAccess returns a gin.HandlerFunc that resolves KB access +// (own / org-shared / via shared agent), enforces the minimum required +// org-level permission, and on success stores the result under +// KBAccessContextKey AND rewrites c.Request.Context() to carry the +// effective tenant ID. Handlers downstream just read tenant from +// context as before. +// +// On failure the guard aborts with the appropriate HTTP status (400 / +// 401 / 404 / 403 / 500). Behaviour matches what each handler's +// effectiveCtxForKB helper used to do; the guard is what consolidates +// the repetition so a fix in the resolution order propagates to every +// gated route at once. +// +// Required permission semantics: +// - OrgRoleViewer -> read-only routes (the agent-share fallback path +// activates only at this level) +// - OrgRoleEditor -> mutating routes (org-shared editor or own KB) +// - OrgRoleAdmin -> share-management routes (only the original +// sharer / KB owner / Org admin should pass) +func RequireKBAccess( + resolveKBID KBIDResolver, + requiredPermission types.OrgMemberRole, + kbService KBLookup, + kbShareService interfaces.KBShareService, + agentShareService interfaces.AgentShareService, +) gin.HandlerFunc { + return func(c *gin.Context) { + kbID, err := resolveKBID(c) + if err != nil { + _ = c.Error(err) + c.Abort() + return + } + + ctx := c.Request.Context() + access, err := resolveKBAccessOnce(ctx, kbID, requiredPermission, kbService, kbShareService, agentShareService) + switch { + case stderrors.Is(err, errKBAccessUnauthorized): + _ = c.Error(apperrors.NewUnauthorizedError("Unauthorized")) + c.Abort() + return + case stderrors.Is(err, errKBAccessNotFound): + _ = c.Error(apperrors.NewNotFoundError("knowledge base not found")) + c.Abort() + return + case stderrors.Is(err, errKBAccessForbidden): + _ = c.Error(apperrors.NewForbiddenError("Permission denied to access this knowledge base")) + c.Abort() + return + case err != nil: + logger.ErrorWithFields(ctx, err, nil) + _ = c.Error(apperrors.NewInternalServerError(err.Error())) + c.Abort() + return + } + + // Stash the resolution and rewrite the request to carry the + // effective tenant id. Handlers reading tenant from context now + // see the source-tenant for shared KBs (so retrieval queries + // hit the right embedding store) without having to know. + c.Set(KBAccessContextKey, access) + newCtx := context.WithValue(ctx, types.TenantIDContextKey, access.EffectiveTenantID) + c.Request = c.Request.WithContext(newCtx) + c.Next() + } +} + +// resolveKBAccessOnce performs the actual three-step resolution. Kept +// unexported and using package-private sentinel errors so the guard's +// error mapping is the only public surface. +func resolveKBAccessOnce( + ctx context.Context, + kbID string, + requiredPermission types.OrgMemberRole, + kbService KBLookup, + kbShareService interfaces.KBShareService, + agentShareService interfaces.AgentShareService, +) (*KBAccess, error) { + tenantID, ok := types.TenantIDFromContext(ctx) + if !ok || tenantID == 0 { + return nil, errKBAccessUnauthorized + } + callerTenantRole := types.TenantRoleFromContext(ctx) + + kb, err := kbService.GetKnowledgeBaseByID(ctx, kbID) + if err != nil { + if stderrors.Is(err, apprepo.ErrKnowledgeBaseNotFound) { + return nil, errKBAccessNotFound + } + return nil, err + } + if kb == nil { + return nil, errKBAccessNotFound + } + + // 1. Own KB. + if kb.TenantID == tenantID { + return &KBAccess{ + KnowledgeBase: kb, + EffectiveTenantID: tenantID, + Permission: types.OrgRoleAdmin, + }, nil + } + + // 2. Org-shared KB. Plan 3's 3-D cap is applied inside + // CheckTenantKBPermission; we just check the result satisfies + // the minimum requirement. + if kbShareService != nil { + permission, isShared, permErr := kbShareService.CheckTenantKBPermission(ctx, kbID, tenantID, callerTenantRole) + if permErr == nil && isShared && permission.HasPermission(requiredPermission) { + source, srcErr := kbShareService.GetKBSourceTenant(ctx, kbID) + if srcErr == nil { + logger.Infof(ctx, "[kb_access] tenant %d -> shared KB %s perm=%s source=%d", + tenantID, kbID, permission, source) + return &KBAccess{ + KnowledgeBase: kb, + EffectiveTenantID: source, + Permission: permission, + }, nil + } + } + } + + // 3. Shared agent that carries this KB — only ever grants read. + if requiredPermission == types.OrgRoleViewer && agentShareService != nil { + can, err := agentShareService.TenantCanAccessKBViaSomeSharedAgent(ctx, tenantID, callerTenantRole, kb) + if err == nil && can { + logger.Infof(ctx, "[kb_access] tenant %d -> KB %s via shared agent", tenantID, kbID) + return &KBAccess{ + KnowledgeBase: kb, + EffectiveTenantID: kb.TenantID, + Permission: types.OrgRoleViewer, + }, nil + } + } + + logger.Warnf(ctx, "[kb_access] tenant %d -> KB %s denied (required=%s)", tenantID, kbID, requiredPermission) + return nil, errKBAccessForbidden +} + +var ( + errKBAccessUnauthorized = stderrors.New("kb_access: unauthorized") + errKBAccessNotFound = stderrors.New("kb_access: not found") + errKBAccessForbidden = stderrors.New("kb_access: forbidden") +) diff --git a/internal/middleware/kb_access_test.go b/internal/middleware/kb_access_test.go new file mode 100644 index 00000000..0dd6604e --- /dev/null +++ b/internal/middleware/kb_access_test.go @@ -0,0 +1,188 @@ +package middleware + +import ( + "context" + "errors" + "net/http/httptest" + "testing" + + apprepo "github.com/Tencent/WeKnora/internal/application/repository" + "github.com/Tencent/WeKnora/internal/types" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +// stubKBLookup is a tiny KBLookup stand-in for tests; satisfies the +// KBLookup interface (a single method) without dragging in the full +// KnowledgeBaseService surface. +type stubKBLookup struct { + kbs map[string]*types.KnowledgeBase + getErr error +} + +func (s *stubKBLookup) GetKnowledgeBaseByID(_ context.Context, id string) (*types.KnowledgeBase, error) { + if s.getErr != nil { + return nil, s.getErr + } + if kb, ok := s.kbs[id]; ok { + return kb, nil + } + return nil, apprepo.ErrKnowledgeBaseNotFound +} + +// stubKBShareForGuard implements just the methods the guard touches — +// CheckTenantKBPermission and GetKBSourceTenant. The other methods on +// the interface panic so any unintended new dependency surfaces +// immediately. +type stubKBShareForGuard struct { + permission map[string]types.OrgMemberRole + shared map[string]bool + source map[string]uint64 +} + +func (s *stubKBShareForGuard) CheckTenantKBPermission(_ context.Context, kbID string, _ uint64, _ types.TenantRole) (types.OrgMemberRole, bool, error) { + if s.shared[kbID] { + return s.permission[kbID], true, nil + } + return "", false, nil +} + +func (s *stubKBShareForGuard) GetKBSourceTenant(_ context.Context, kbID string) (uint64, error) { + if v, ok := s.source[kbID]; ok { + return v, nil + } + return 0, errors.New("not found") +} + +func (s *stubKBShareForGuard) ShareKnowledgeBase(context.Context, string, string, string, uint64, types.OrgMemberRole) (*types.KnowledgeBaseShare, error) { + panic("not implemented") +} +func (s *stubKBShareForGuard) UpdateSharePermission(context.Context, string, types.OrgMemberRole, string, uint64) error { + panic("not implemented") +} +func (s *stubKBShareForGuard) RemoveShare(context.Context, string, string, uint64) error { + panic("not implemented") +} +func (s *stubKBShareForGuard) ListSharesByKnowledgeBase(context.Context, string, uint64) ([]*types.KnowledgeBaseShare, error) { + panic("not implemented") +} +func (s *stubKBShareForGuard) ListSharesByOrganization(context.Context, string) ([]*types.KnowledgeBaseShare, error) { + panic("not implemented") +} +func (s *stubKBShareForGuard) ListSharedKnowledgeBases(context.Context, uint64, types.TenantRole) ([]*types.SharedKnowledgeBaseInfo, error) { + panic("not implemented") +} +func (s *stubKBShareForGuard) ListSharedKnowledgeBasesInOrganization(context.Context, string, uint64, types.TenantRole) ([]*types.OrganizationSharedKnowledgeBaseItem, error) { + panic("not implemented") +} +func (s *stubKBShareForGuard) ListSharedKnowledgeBaseIDsByOrganizations(context.Context, []string, uint64) (map[string][]string, error) { + panic("not implemented") +} +func (s *stubKBShareForGuard) GetShare(context.Context, string) (*types.KnowledgeBaseShare, error) { + panic("not implemented") +} +func (s *stubKBShareForGuard) GetShareByKBAndOrg(context.Context, string, string) (*types.KnowledgeBaseShare, error) { + panic("not implemented") +} +func (s *stubKBShareForGuard) HasTenantKBPermission(context.Context, string, uint64, types.TenantRole, types.OrgMemberRole) (bool, error) { + panic("not implemented") +} +func (s *stubKBShareForGuard) CountSharesByKnowledgeBaseIDs(context.Context, []string) (map[string]int64, error) { + panic("not implemented") +} +func (s *stubKBShareForGuard) CountByOrganizations(context.Context, []string) (map[string]int64, error) { + panic("not implemented") +} + +// runGuard fires a single request through the guard and returns the +// gin recorder + the kb access (if any) the guard stashed. +func runGuard(t *testing.T, tenantID uint64, kbID string, requiredPerm types.OrgMemberRole, kb *types.KnowledgeBase, share *stubKBShareForGuard) (*httptest.ResponseRecorder, *gin.Context) { + t.Helper() + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Params = gin.Params{{Key: "id", Value: kbID}} + req := httptest.NewRequest("GET", "/", nil) + ctx := context.WithValue(req.Context(), types.TenantIDContextKey, tenantID) + c.Request = req.WithContext(ctx) + + kbsvc := &stubKBLookup{kbs: map[string]*types.KnowledgeBase{}} + if kb != nil { + kbsvc.kbs[kbID] = kb + } + guard := RequireKBAccess(KBIDFromParam("id"), requiredPerm, kbsvc, share, nil) + guard(c) + return rec, c +} + +func TestRequireKBAccess_OwnKB(t *testing.T) { + rec, c := runGuard(t, 100, "kb-1", + types.OrgRoleViewer, + &types.KnowledgeBase{ID: "kb-1", TenantID: 100}, + nil, + ) + require.False(t, c.IsAborted(), "should pass through") + require.Equal(t, 200, rec.Code) // gin's default; nothing wrote a status + access, ok := KBAccessFromContext(c) + require.True(t, ok) + require.Equal(t, uint64(100), access.EffectiveTenantID) + require.Equal(t, types.OrgRoleAdmin, access.Permission, "own KB grants admin") + // The request context's tenant should still be the caller's own. + got, ok := types.TenantIDFromContext(c.Request.Context()) + require.True(t, ok) + require.Equal(t, uint64(100), got) +} + +func TestRequireKBAccess_NotFound_Aborts(t *testing.T) { + rec, c := runGuard(t, 100, "kb-missing", types.OrgRoleViewer, nil, nil) + require.True(t, c.IsAborted(), "missing KB must abort") + require.NotEmpty(t, c.Errors) + _, ok := KBAccessFromContext(c) + require.False(t, ok, "no access should be stashed on failure") + _ = rec +} + +func TestRequireKBAccess_SharedKB_RewritesTenantContext(t *testing.T) { + share := &stubKBShareForGuard{ + permission: map[string]types.OrgMemberRole{"kb-shared": types.OrgRoleEditor}, + shared: map[string]bool{"kb-shared": true}, + source: map[string]uint64{"kb-shared": 200}, + } + _, c := runGuard(t, 100, "kb-shared", + types.OrgRoleEditor, + &types.KnowledgeBase{ID: "kb-shared", TenantID: 200}, + share, + ) + require.False(t, c.IsAborted()) + access, ok := KBAccessFromContext(c) + require.True(t, ok) + require.Equal(t, uint64(200), access.EffectiveTenantID) + // The downstream handler should see tenant=200 from context. + got, _ := types.TenantIDFromContext(c.Request.Context()) + require.Equal(t, uint64(200), got, "guard must rewrite context to source tenant") +} + +func TestRequireKBAccess_SharedKB_PermissionBelowMin_Aborts(t *testing.T) { + share := &stubKBShareForGuard{ + permission: map[string]types.OrgMemberRole{"kb-shared": types.OrgRoleViewer}, + shared: map[string]bool{"kb-shared": true}, + source: map[string]uint64{"kb-shared": 200}, + } + _, c := runGuard(t, 100, "kb-shared", + types.OrgRoleEditor, // require Editor + &types.KnowledgeBase{ID: "kb-shared", TenantID: 200}, + share, + ) + require.True(t, c.IsAborted(), "Viewer share must reject when Editor required") +} + +func TestRequireKBAccess_NoTenant_Aborts(t *testing.T) { + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Params = gin.Params{{Key: "id", Value: "kb-x"}} + c.Request = httptest.NewRequest("GET", "/", nil) // no tenant in context + guard := RequireKBAccess(KBIDFromParam("id"), types.OrgRoleViewer, &stubKBLookup{}, nil, nil) + guard(c) + require.True(t, c.IsAborted()) +} diff --git a/internal/router/rbac.go b/internal/router/rbac.go index 1c219f06..2cf34087 100644 --- a/internal/router/rbac.go +++ b/internal/router/rbac.go @@ -5,6 +5,7 @@ import ( "github.com/Tencent/WeKnora/internal/handler" "github.com/Tencent/WeKnora/internal/middleware" "github.com/Tencent/WeKnora/internal/types" + "github.com/Tencent/WeKnora/internal/types/interfaces" "github.com/gin-gonic/gin" ) @@ -125,6 +126,15 @@ type rbacGuards struct { chunkKBCreator middleware.CreatorLookup chunkKBCreatorFromID middleware.CreatorLookup // chunk routes that address chunks by :id (no knowledge id in URL) wikiKBCreator middleware.CreatorLookup + + // Services for the KB-access guard (own / org-shared / via shared + // agent). Captured here so route lines can reference g.KBAccess() + // without having to plumb the services through every Register* + // function. + kbService middleware.KBLookup + knowledgeService middleware.KnowledgeLookup + kbShareService interfaces.KBShareService + agentShareService interfaces.AgentShareService } // newRBACGuards wires the guards from the live configuration and the @@ -136,6 +146,10 @@ func newRBACGuards( knowledgeHandler *handler.KnowledgeHandler, chunkHandler *handler.ChunkHandler, wikiHandler *handler.WikiPageHandler, + kbService interfaces.KnowledgeBaseService, + knowledgeService interfaces.KnowledgeService, + kbShareService interfaces.KBShareService, + agentShareService interfaces.AgentShareService, ) *rbacGuards { g := &rbacGuards{cfg: cfg} if kbHandler != nil { @@ -155,6 +169,10 @@ func newRBACGuards( if wikiHandler != nil { g.wikiKBCreator = wikiHandler.KBCreatorLookupFromKBPath } + g.kbService = kbService + g.knowledgeService = knowledgeService + g.kbShareService = kbShareService + g.agentShareService = agentShareService return g } @@ -265,3 +283,78 @@ func (g *rbacGuards) CrossTenant() gin.HandlerFunc { func (g *rbacGuards) PathTenantMatch() gin.HandlerFunc { return middleware.RequirePathTenantMatch(g.cfg) } + +// KB-access guards — orthogonal to the role-and-ownership matrix +// above. They answer "can the caller's tenant operate on THIS KB?" +// taking into account three paths: +// +// 1. Own KB — full access (Admin) +// 2. Org-shared KB (Plan 3) — capped permission +// 3. Visible via shared agent — read-only +// +// On success the resolved (KB + effective tenant id + permission) +// tuple is stashed on c.Keys under middleware.KBAccessContextKey AND +// the request context's tenant ID is rewritten to the effective tenant +// — so handlers downstream just read tenant the way they always did +// (types.MustTenantIDFromContext) without knowing whether the KB is +// owned or shared. +// +// These guards replace the per-handler effectiveCtxForKB / +// validateAndGetKnowledgeBase helpers that used to be re-implemented +// in chunk.go, faq.go, tag.go, knowledge.go and knowledgebase.go; +// the share-fallback logic now lives in exactly one place +// (middleware/kb_access.go). + +// KBAccessRead gates a KB-scoped read route on the caller having at +// least Viewer-level access. The agent-share fallback only activates +// at this level — Editor/Admin reads never go through "I just see it +// because someone shared an agent". The kbID is read from the gin +// param named in `param` (typically "id" for /knowledge-bases/:id/...). +func (g *rbacGuards) KBAccessRead(param string) gin.HandlerFunc { + return middleware.RequireKBAccess( + middleware.KBIDFromParam(param), + types.OrgRoleViewer, + g.kbService, + g.kbShareService, + g.agentShareService, + ) +} + +// KBAccessWrite gates a KB-scoped mutating route on the caller having +// at least Editor-level access (own KB or org-shared with editor). +// Used by FAQ upsert, tag CRUD, chunk update/delete, etc. +func (g *rbacGuards) KBAccessWrite(param string) gin.HandlerFunc { + return middleware.RequireKBAccess( + middleware.KBIDFromParam(param), + types.OrgRoleEditor, + g.kbService, + g.kbShareService, + g.agentShareService, + ) +} + +// KBAccessReadFromKnowledgeIDParam is like KBAccessRead but resolves +// the kb_id by walking a knowledge document (URL `:knowledge_id`) +// back to its parent KB. Used by the chunk routes whose URL addresses +// the chunk via /chunks/:knowledge_id rather than /knowledge-bases/:id. +func (g *rbacGuards) KBAccessReadFromKnowledgeIDParam(param string) gin.HandlerFunc { + return middleware.RequireKBAccess( + middleware.KBIDFromKnowledgeIDParam(param, g.knowledgeService), + types.OrgRoleViewer, + g.kbService, + g.kbShareService, + g.agentShareService, + ) +} + +// KBAccessWriteFromKnowledgeIDParam mirrors KBAccessReadFromKnowledgeIDParam +// for mutating routes (Editor minimum). +func (g *rbacGuards) KBAccessWriteFromKnowledgeIDParam(param string) gin.HandlerFunc { + return middleware.RequireKBAccess( + middleware.KBIDFromKnowledgeIDParam(param, g.knowledgeService), + types.OrgRoleEditor, + g.kbService, + g.kbShareService, + g.agentShareService, + ) +} diff --git a/internal/router/router.go b/internal/router/router.go index 4b86a488..d683581f 100644 --- a/internal/router/router.go +++ b/internal/router/router.go @@ -44,6 +44,8 @@ type RouterParams struct { MessageService interfaces.MessageService ModelService interfaces.ModelService EvaluationService interfaces.EvaluationService + KBShareService interfaces.KBShareService + AgentShareService interfaces.AgentShareService KBHandler *handler.KnowledgeBaseHandler KnowledgeHandler *handler.KnowledgeHandler TenantHandler *handler.TenantHandler @@ -163,6 +165,10 @@ func NewRouter(params RouterParams) *gin.Engine { params.KnowledgeHandler, params.ChunkHandler, params.WikiPageHandler, + params.KBService, + params.KnowledgeService, + params.KBShareService, + params.AgentShareService, ) RegisterAuthRoutes(v1, params.AuthHandler) @@ -293,20 +299,23 @@ func RegisterFAQRoutes(r *gin.RouterGroup, handler *handler.FAQHandler, g *rbacG // 改不属于自己的 KB 的 FAQ。 faq := r.Group("/knowledge-bases/:id/faq") { - faq.GET("/entries", g.Viewer(), handler.ListEntries) - faq.GET("/entries/export", g.Viewer(), handler.ExportEntries) - faq.GET("/entries/:entry_id", g.Viewer(), handler.GetEntry) - faq.POST("/entries", g.OwnedKBOrAdmin(), handler.UpsertEntries) - faq.POST("/entry", g.OwnedKBOrAdmin(), handler.CreateEntry) - faq.PUT("/entries/:entry_id", g.OwnedKBOrAdmin(), handler.UpdateEntry) - faq.POST("/entries/:entry_id/similar-questions", g.OwnedKBOrAdmin(), handler.AddSimilarQuestions) + // KBAccessRead/Write resolve own/shared/agent-visible access and + // rewrite the request's tenant context — handler no longer + // carries an effectiveCtxForKB helper. + faq.GET("/entries", g.Viewer(), g.KBAccessRead("id"), handler.ListEntries) + faq.GET("/entries/export", g.Viewer(), g.KBAccessRead("id"), handler.ExportEntries) + faq.GET("/entries/:entry_id", g.Viewer(), g.KBAccessRead("id"), handler.GetEntry) + faq.POST("/entries", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), handler.UpsertEntries) + faq.POST("/entry", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), handler.CreateEntry) + faq.PUT("/entries/:entry_id", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), handler.UpdateEntry) + faq.POST("/entries/:entry_id/similar-questions", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), handler.AddSimilarQuestions) // Unified batch update API - supports is_enabled, is_recommended, tag_id - faq.PUT("/entries/fields", g.OwnedKBOrAdmin(), handler.UpdateEntryFieldsBatch) - faq.PUT("/entries/tags", g.OwnedKBOrAdmin(), handler.UpdateEntryTagBatch) - faq.DELETE("/entries", g.OwnedKBOrAdmin(), handler.DeleteEntries) - faq.POST("/search", g.Viewer(), handler.SearchFAQ) + faq.PUT("/entries/fields", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), handler.UpdateEntryFieldsBatch) + faq.PUT("/entries/tags", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), handler.UpdateEntryTagBatch) + faq.DELETE("/entries", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), handler.DeleteEntries) + faq.POST("/search", g.Viewer(), g.KBAccessRead("id"), handler.SearchFAQ) // FAQ import result display status - faq.PUT("/import/last-result/display", g.OwnedKBOrAdmin(), handler.UpdateLastImportResultDisplayStatus) + faq.PUT("/import/last-result/display", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), handler.UpdateLastImportResultDisplayStatus) } // FAQ import progress route (outside of knowledge-base scope) — Viewer+ faqImport := r.Group("/faq/import") @@ -357,10 +366,14 @@ func RegisterKnowledgeTagRoutes(r *gin.RouterGroup, tagHandler *handler.TagHandl // 关 Contributor 在他人 KB 里乱建/删标签影响 KB owner 的内容组织。 kbTags := r.Group("/knowledge-bases/:id/tags") { - kbTags.GET("", g.Viewer(), tagHandler.ListTags) - kbTags.POST("", g.OwnedKBOrAdmin(), tagHandler.CreateTag) - kbTags.PUT("/:tag_id", g.OwnedKBOrAdmin(), tagHandler.UpdateTag) - kbTags.DELETE("/:tag_id", g.OwnedKBOrAdmin(), tagHandler.DeleteTag) + // KBAccessRead/Write resolve own/shared/agent-visible access and + // rewrite the request's tenant context to the effective tenant + // for the duration of the handler — so the handler no longer + // needs its own effectiveCtxForKB helper. + kbTags.GET("", g.Viewer(), g.KBAccessRead("id"), tagHandler.ListTags) + kbTags.POST("", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), tagHandler.CreateTag) + kbTags.PUT("/:tag_id", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), tagHandler.UpdateTag) + kbTags.DELETE("/:tag_id", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), tagHandler.DeleteTag) } }