refactor(rbac): extend KB-access guard to chunk / knowledge / knowledgebase routes
Follow-up to the FAQ + Tag refactor in this same PR. Three additional
handler areas now run through the route-level g.KBAccess* guard:
- chunk.go : full refactor — helper effectiveCtxForKnowledge and
validateAndGetChunk's access check are gone; the
handler's chunk-fetch + ownership-mismatch check stay
as defence-in-depth (a same-tenant attacker can't
pass mismatched knowledge_id + chunk_id).
- knowledge.go and knowledgebase.go : routes now run the guard
BEFORE the handler. The in-handler
validateKnowledgeBaseAccess /
resolveKnowledgeAndValidateKBAccess helpers stay for
now because they branch on the agent_id query param
(specific-agent check vs. any-agent fallback) — that
handler-specific branch can collapse into the guard
in a follow-up. The duplicated DB roundtrip is
negligible compared to the handler's main work.
New middleware exports:
- KBIDFromChunkIDParam : walks chunk_id → KnowledgeBaseID via the
chunk's denormalised column.
- g.KBAccessReadFromChunkIDParam / g.KBAccessWriteFromChunkIDParam
: convenience methods on rbacGuards.
Route changes are purely additive (existing role / ownership guards
stay in place; the new KB-access guard runs after them and rewrites
the request's tenant context to the source tenant for shared KBs).
No new dependencies on the kbShareService / agentShareService at the
handler level for chunk.go — those move to the route layer.
Tests pass; behaviour unchanged.
This commit is contained in:
+45
-116
@@ -1,7 +1,6 @@
|
|||||||
package handler
|
package handler
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"github.com/Tencent/WeKnora/internal/application/service"
|
"github.com/Tencent/WeKnora/internal/application/service"
|
||||||
@@ -13,57 +12,28 @@ import (
|
|||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ChunkHandler defines HTTP handlers for chunk operations
|
// ChunkHandler defines HTTP handlers for chunk operations.
|
||||||
|
//
|
||||||
|
// All KB-access checks (own / org-shared / via shared agent) are now
|
||||||
|
// performed by the route-level g.KBAccessRead*FromKnowledgeIDParam /
|
||||||
|
// g.KBAccessWrite*FromKnowledgeIDParam / g.KBAccess*FromChunkIDParam
|
||||||
|
// guards in router.go — the guard rewrites c.Request.Context() to
|
||||||
|
// carry the effective tenant ID, so the handler reads tenant from
|
||||||
|
// context the way it always did.
|
||||||
|
//
|
||||||
|
// kgService is retained because the route-level *creator-ownership*
|
||||||
|
// lookup KBCreatorLookupFromKnowledgeIDParam still walks
|
||||||
|
// knowledge_id -> kb_id to resolve creator_id (separate axis from
|
||||||
|
// access — that lookup answers "is the caller the creator of THIS
|
||||||
|
// resource", not "does the caller's tenant have access").
|
||||||
type ChunkHandler struct {
|
type ChunkHandler struct {
|
||||||
service interfaces.ChunkService
|
service interfaces.ChunkService
|
||||||
kgService interfaces.KnowledgeService
|
kgService interfaces.KnowledgeService
|
||||||
kbShareService interfaces.KBShareService
|
|
||||||
agentShareService interfaces.AgentShareService
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewChunkHandler creates a new chunk handler
|
// NewChunkHandler creates a new chunk handler.
|
||||||
func NewChunkHandler(service interfaces.ChunkService, kgService interfaces.KnowledgeService, kbShareService interfaces.KBShareService, agentShareService interfaces.AgentShareService) *ChunkHandler {
|
func NewChunkHandler(service interfaces.ChunkService, kgService interfaces.KnowledgeService) *ChunkHandler {
|
||||||
return &ChunkHandler{service: service, kgService: kgService, kbShareService: kbShareService, agentShareService: agentShareService}
|
return &ChunkHandler{service: service, kgService: kgService}
|
||||||
}
|
|
||||||
|
|
||||||
// effectiveCtxForKnowledge resolves knowledge by ID, validates KB access (owner or shared with required role), and returns context with effectiveTenantID for downstream service calls.
|
|
||||||
func (h *ChunkHandler) effectiveCtxForKnowledge(c *gin.Context, knowledgeID 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)
|
|
||||||
|
|
||||||
knowledge, err := h.kgService.GetKnowledgeByIDOnly(ctx, knowledgeID)
|
|
||||||
if err != nil {
|
|
||||||
return nil, errors.NewNotFoundError("Knowledge not found")
|
|
||||||
}
|
|
||||||
if knowledge.TenantID == tenantID {
|
|
||||||
return context.WithValue(ctx, types.TenantIDContextKey, tenantID), nil
|
|
||||||
}
|
|
||||||
if !userExists {
|
|
||||||
return nil, errors.NewForbiddenError("Permission denied to access this knowledge")
|
|
||||||
}
|
|
||||||
if h.kbShareService != nil {
|
|
||||||
permission, isShared, permErr := h.kbShareService.CheckTenantKBPermission(ctx, knowledge.KnowledgeBaseID, tenantID, callerTenantRole)
|
|
||||||
if permErr == nil && isShared {
|
|
||||||
if !permission.HasPermission(requiredPermission) {
|
|
||||||
return nil, errors.NewForbiddenError("Insufficient permission for this operation")
|
|
||||||
}
|
|
||||||
return context.WithValue(ctx, types.TenantIDContextKey, knowledge.TenantID), nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if requiredPermission == types.OrgRoleViewer && h.agentShareService != nil {
|
|
||||||
kbRef := &types.KnowledgeBase{ID: knowledge.KnowledgeBaseID, TenantID: knowledge.TenantID}
|
|
||||||
can, err := h.agentShareService.TenantCanAccessKBViaSomeSharedAgent(ctx, tenantID, callerTenantRole, kbRef)
|
|
||||||
if err == nil && can {
|
|
||||||
return context.WithValue(ctx, types.TenantIDContextKey, knowledge.TenantID), nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
_ = userID
|
|
||||||
return nil, errors.NewForbiddenError("Permission denied to access this knowledge")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetChunkByIDOnly godoc
|
// GetChunkByIDOnly godoc
|
||||||
@@ -90,7 +60,9 @@ func (h *ChunkHandler) GetChunkByIDOnly(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get chunk by ID without tenant filter (chunk may belong to shared KB)
|
// Get chunk by ID without tenant filter (chunk may belong to shared
|
||||||
|
// KB; the route-level KB-access guard already verified read
|
||||||
|
// permission against the parent KB before we got here).
|
||||||
chunk, err := h.service.GetChunkByIDOnly(ctx, chunkID)
|
chunk, err := h.service.GetChunkByIDOnly(ctx, chunkID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if err == service.ErrChunkNotFound {
|
if err == service.ErrChunkNotFound {
|
||||||
@@ -103,12 +75,6 @@ func (h *ChunkHandler) GetChunkByIDOnly(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
_, err = h.effectiveCtxForKnowledge(c, chunk.KnowledgeID, types.OrgRoleViewer)
|
|
||||||
if err != nil {
|
|
||||||
c.Error(err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// 对 chunk 内容进行安全清理
|
// 对 chunk 内容进行安全清理
|
||||||
if chunk.Content != "" {
|
if chunk.Content != "" {
|
||||||
chunk.Content = secutils.SanitizeForDisplay(chunk.Content)
|
chunk.Content = secutils.SanitizeForDisplay(chunk.Content)
|
||||||
@@ -145,12 +111,6 @@ func (h *ChunkHandler) ListKnowledgeChunks(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
effCtx, err := h.effectiveCtxForKnowledge(c, knowledgeID, types.OrgRoleViewer)
|
|
||||||
if err != nil {
|
|
||||||
c.Error(err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Parse pagination parameters
|
// Parse pagination parameters
|
||||||
var pagination types.Pagination
|
var pagination types.Pagination
|
||||||
if err := c.ShouldBindQuery(&pagination); err != nil {
|
if err := c.ShouldBindQuery(&pagination); err != nil {
|
||||||
@@ -170,8 +130,9 @@ func (h *ChunkHandler) ListKnowledgeChunks(c *gin.Context) {
|
|||||||
|
|
||||||
chunkType := []types.ChunkType{types.ChunkTypeText}
|
chunkType := []types.ChunkType{types.ChunkTypeText}
|
||||||
|
|
||||||
// Use pagination for query (effCtx has effectiveTenantID for shared KB)
|
// The route-level guard has rewritten the request's tenant context
|
||||||
result, err := h.service.ListPagedChunksByKnowledgeID(effCtx, knowledgeID, &pagination, chunkType)
|
// to the effective tenant for shared KBs.
|
||||||
|
result, err := h.service.ListPagedChunksByKnowledgeID(ctx, knowledgeID, &pagination, chunkType)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logger.ErrorWithFields(ctx, err, nil)
|
logger.ErrorWithFields(ctx, err, nil)
|
||||||
c.Error(errors.NewInternalServerError(err.Error()))
|
c.Error(errors.NewInternalServerError(err.Error()))
|
||||||
@@ -205,46 +166,39 @@ type UpdateChunkRequest struct {
|
|||||||
ImageInfo string `json:"image_info"`
|
ImageInfo string `json:"image_info"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// validateAndGetChunk validates request parameters and retrieves the chunk (supports shared KB via effectiveTenantID).
|
// fetchChunkAndVerifyOwnership fetches a chunk by ID and verifies it
|
||||||
// Returns chunk, knowledge ID, context with effectiveTenantID for downstream calls, and error.
|
// belongs to the URL :knowledge_id (defence in depth: the route-level
|
||||||
func (h *ChunkHandler) validateAndGetChunk(c *gin.Context) (*types.Chunk, string, context.Context, error) {
|
// KB-access guard already ensured the caller has write access to the
|
||||||
|
// KB; this check stops a same-tenant attacker from passing one
|
||||||
|
// knowledge_id while addressing a chunk owned by a different
|
||||||
|
// knowledge in the same KB).
|
||||||
|
func (h *ChunkHandler) fetchChunkAndVerifyOwnership(c *gin.Context) (*types.Chunk, string, error) {
|
||||||
ctx := c.Request.Context()
|
ctx := c.Request.Context()
|
||||||
|
|
||||||
knowledgeID := secutils.SanitizeForLog(c.Param("knowledge_id"))
|
knowledgeID := secutils.SanitizeForLog(c.Param("knowledge_id"))
|
||||||
if knowledgeID == "" {
|
if knowledgeID == "" {
|
||||||
logger.Error(ctx, "Knowledge ID is empty")
|
logger.Error(ctx, "Knowledge ID is empty")
|
||||||
return nil, "", nil, errors.NewBadRequestError("Knowledge ID cannot be empty")
|
return nil, "", errors.NewBadRequestError("Knowledge ID cannot be empty")
|
||||||
}
|
}
|
||||||
|
|
||||||
id := secutils.SanitizeForLog(c.Param("id"))
|
id := secutils.SanitizeForLog(c.Param("id"))
|
||||||
if id == "" {
|
if id == "" {
|
||||||
logger.Error(ctx, "Chunk ID is empty")
|
logger.Error(ctx, "Chunk ID is empty")
|
||||||
return nil, knowledgeID, nil, errors.NewBadRequestError("Chunk ID cannot be empty")
|
return nil, knowledgeID, errors.NewBadRequestError("Chunk ID cannot be empty")
|
||||||
}
|
}
|
||||||
|
chunk, err := h.service.GetChunkByID(ctx, id)
|
||||||
effCtx, err := h.effectiveCtxForKnowledge(c, knowledgeID, types.OrgRoleEditor)
|
|
||||||
if err != nil {
|
|
||||||
return nil, knowledgeID, nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
logger.Infof(ctx, "Retrieving knowledge chunk information, knowledge ID: %s, chunk ID: %s", knowledgeID, id)
|
|
||||||
|
|
||||||
chunk, err := h.service.GetChunkByID(effCtx, id)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if err == service.ErrChunkNotFound {
|
if err == service.ErrChunkNotFound {
|
||||||
logger.Warnf(ctx, "Chunk not found, knowledge ID: %s, chunk ID: %s", knowledgeID, id)
|
logger.Warnf(ctx, "Chunk not found, knowledge ID: %s, chunk ID: %s", knowledgeID, id)
|
||||||
return nil, knowledgeID, nil, errors.NewNotFoundError("Chunk not found")
|
return nil, knowledgeID, errors.NewNotFoundError("Chunk not found")
|
||||||
}
|
}
|
||||||
logger.ErrorWithFields(ctx, err, nil)
|
logger.ErrorWithFields(ctx, err, nil)
|
||||||
return nil, knowledgeID, nil, errors.NewInternalServerError(err.Error())
|
return nil, knowledgeID, errors.NewInternalServerError(err.Error())
|
||||||
}
|
}
|
||||||
|
|
||||||
if chunk.KnowledgeID != knowledgeID {
|
if chunk.KnowledgeID != knowledgeID {
|
||||||
logger.Warnf(ctx, "Chunk does not belong to knowledge, knowledge ID: %s, chunk ID: %s", knowledgeID, id)
|
logger.Warnf(ctx, "Chunk does not belong to knowledge, knowledge ID: %s, chunk ID: %s", knowledgeID, id)
|
||||||
return nil, knowledgeID, nil, errors.NewForbiddenError("No permission to access this chunk")
|
return nil, knowledgeID, errors.NewForbiddenError("No permission to access this chunk")
|
||||||
}
|
}
|
||||||
|
return chunk, knowledgeID, nil
|
||||||
return chunk, knowledgeID, effCtx, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// UpdateChunk godoc
|
// UpdateChunk godoc
|
||||||
@@ -266,7 +220,7 @@ func (h *ChunkHandler) UpdateChunk(c *gin.Context) {
|
|||||||
ctx := c.Request.Context()
|
ctx := c.Request.Context()
|
||||||
logger.Info(ctx, "Start updating knowledge chunk")
|
logger.Info(ctx, "Start updating knowledge chunk")
|
||||||
|
|
||||||
chunk, knowledgeID, effCtx, err := h.validateAndGetChunk(c)
|
chunk, knowledgeID, err := h.fetchChunkAndVerifyOwnership(c)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.Error(err)
|
c.Error(err)
|
||||||
return
|
return
|
||||||
@@ -284,7 +238,7 @@ func (h *ChunkHandler) UpdateChunk(c *gin.Context) {
|
|||||||
|
|
||||||
chunk.IsEnabled = req.IsEnabled
|
chunk.IsEnabled = req.IsEnabled
|
||||||
|
|
||||||
if err := h.service.UpdateChunk(effCtx, chunk); err != nil {
|
if err := h.service.UpdateChunk(ctx, chunk); err != nil {
|
||||||
logger.ErrorWithFields(ctx, err, nil)
|
logger.ErrorWithFields(ctx, err, nil)
|
||||||
c.Error(errors.NewInternalServerError(err.Error()))
|
c.Error(errors.NewInternalServerError(err.Error()))
|
||||||
return
|
return
|
||||||
@@ -316,13 +270,13 @@ func (h *ChunkHandler) DeleteChunk(c *gin.Context) {
|
|||||||
ctx := c.Request.Context()
|
ctx := c.Request.Context()
|
||||||
logger.Info(ctx, "Start deleting knowledge chunk")
|
logger.Info(ctx, "Start deleting knowledge chunk")
|
||||||
|
|
||||||
chunk, _, effCtx, err := h.validateAndGetChunk(c)
|
chunk, _, err := h.fetchChunkAndVerifyOwnership(c)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.Error(err)
|
c.Error(err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := h.service.DeleteChunk(effCtx, chunk.ID); err != nil {
|
if err := h.service.DeleteChunk(ctx, chunk.ID); err != nil {
|
||||||
logger.ErrorWithFields(ctx, err, nil)
|
logger.ErrorWithFields(ctx, err, nil)
|
||||||
c.Error(errors.NewInternalServerError(err.Error()))
|
c.Error(errors.NewInternalServerError(err.Error()))
|
||||||
return
|
return
|
||||||
@@ -357,14 +311,7 @@ func (h *ChunkHandler) DeleteChunksByKnowledgeID(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
effCtx, err := h.effectiveCtxForKnowledge(c, knowledgeID, types.OrgRoleEditor)
|
if err := h.service.DeleteChunksByKnowledgeID(ctx, knowledgeID); err != nil {
|
||||||
if err != nil {
|
|
||||||
c.Error(err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
err = h.service.DeleteChunksByKnowledgeID(effCtx, knowledgeID)
|
|
||||||
if err != nil {
|
|
||||||
logger.ErrorWithFields(ctx, err, nil)
|
logger.ErrorWithFields(ctx, err, nil)
|
||||||
c.Error(errors.NewInternalServerError(err.Error()))
|
c.Error(errors.NewInternalServerError(err.Error()))
|
||||||
return
|
return
|
||||||
@@ -410,25 +357,7 @@ func (h *ChunkHandler) DeleteGeneratedQuestion(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
chunk, err := h.service.GetChunkByIDOnly(ctx, chunkID)
|
if err := h.service.DeleteGeneratedQuestion(ctx, chunkID, req.QuestionID); err != nil {
|
||||||
if err != nil {
|
|
||||||
if err == service.ErrChunkNotFound {
|
|
||||||
logger.Warnf(ctx, "Chunk not found, chunk ID: %s", chunkID)
|
|
||||||
c.Error(errors.NewNotFoundError("Chunk not found"))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
logger.ErrorWithFields(ctx, err, nil)
|
|
||||||
c.Error(errors.NewInternalServerError(err.Error()))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
effCtx, err := h.effectiveCtxForKnowledge(c, chunk.KnowledgeID, types.OrgRoleEditor)
|
|
||||||
if err != nil {
|
|
||||||
c.Error(err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := h.service.DeleteGeneratedQuestion(effCtx, chunkID, req.QuestionID); err != nil {
|
|
||||||
logger.ErrorWithFields(ctx, err, nil)
|
logger.ErrorWithFields(ctx, err, nil)
|
||||||
c.Error(errors.NewBadRequestError(err.Error()))
|
c.Error(errors.NewBadRequestError(err.Error()))
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -77,6 +77,13 @@ type KnowledgeLookup interface {
|
|||||||
GetKnowledgeByIDOnly(ctx context.Context, id string) (*types.Knowledge, error)
|
GetKnowledgeByIDOnly(ctx context.Context, id string) (*types.Knowledge, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ChunkLookup mirrors KBLookup for resolving a chunk id back to its
|
||||||
|
// owning knowledge document, which then resolves to the parent KB.
|
||||||
|
// Used by the /chunks/by-id/:id routes that address chunks directly.
|
||||||
|
type ChunkLookup interface {
|
||||||
|
GetChunkByIDOnly(ctx context.Context, id string) (*types.Chunk, error)
|
||||||
|
}
|
||||||
|
|
||||||
// KBIDResolver tells the guard how to find the kb_id for a given
|
// KBIDResolver tells the guard how to find the kb_id for a given
|
||||||
// request. Built-in resolvers below cover the param shapes we use:
|
// request. Built-in resolvers below cover the param shapes we use:
|
||||||
// :id, :kb_id, :kbId, :knowledge_id (-> parent KB).
|
// :id, :kb_id, :kbId, :knowledge_id (-> parent KB).
|
||||||
@@ -110,6 +117,29 @@ func KBIDFromKnowledgeIDParam(param string, kgService KnowledgeLookup) KBIDResol
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// KBIDFromChunkIDParam walks chunk_id -> knowledge_id -> kb_id.
|
||||||
|
// Used by /chunks/by-id/:id routes that address a chunk directly. The
|
||||||
|
// chunk's KnowledgeBaseID is denormalised on the row, so a single
|
||||||
|
// lookup is enough — no need to chain through GetKnowledgeByIDOnly.
|
||||||
|
func KBIDFromChunkIDParam(param string, chunkService ChunkLookup) KBIDResolver {
|
||||||
|
return func(c *gin.Context) (string, error) {
|
||||||
|
v := c.Param(param)
|
||||||
|
if v == "" {
|
||||||
|
return "", apperrors.NewBadRequestError("missing " + param + " in path")
|
||||||
|
}
|
||||||
|
ch, err := chunkService.GetChunkByIDOnly(c.Request.Context(), v)
|
||||||
|
if err != nil || ch == nil {
|
||||||
|
return "", apperrors.NewNotFoundError("Chunk not found")
|
||||||
|
}
|
||||||
|
if ch.KnowledgeBaseID == "" {
|
||||||
|
// Some old chunks may not carry the denormalised KB id;
|
||||||
|
// this is a should-never-happen branch on a fresh schema.
|
||||||
|
return "", apperrors.NewInternalServerError("chunk missing knowledge_base_id")
|
||||||
|
}
|
||||||
|
return ch.KnowledgeBaseID, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// RequireKBAccess returns a gin.HandlerFunc that resolves KB access
|
// RequireKBAccess returns a gin.HandlerFunc that resolves KB access
|
||||||
// (own / org-shared / via shared agent), enforces the minimum required
|
// (own / org-shared / via shared agent), enforces the minimum required
|
||||||
// org-level permission, and on success stores the result under
|
// org-level permission, and on success stores the result under
|
||||||
|
|||||||
@@ -133,6 +133,7 @@ type rbacGuards struct {
|
|||||||
// function.
|
// function.
|
||||||
kbService middleware.KBLookup
|
kbService middleware.KBLookup
|
||||||
knowledgeService middleware.KnowledgeLookup
|
knowledgeService middleware.KnowledgeLookup
|
||||||
|
chunkService middleware.ChunkLookup
|
||||||
kbShareService interfaces.KBShareService
|
kbShareService interfaces.KBShareService
|
||||||
agentShareService interfaces.AgentShareService
|
agentShareService interfaces.AgentShareService
|
||||||
}
|
}
|
||||||
@@ -148,6 +149,7 @@ func newRBACGuards(
|
|||||||
wikiHandler *handler.WikiPageHandler,
|
wikiHandler *handler.WikiPageHandler,
|
||||||
kbService interfaces.KnowledgeBaseService,
|
kbService interfaces.KnowledgeBaseService,
|
||||||
knowledgeService interfaces.KnowledgeService,
|
knowledgeService interfaces.KnowledgeService,
|
||||||
|
chunkService interfaces.ChunkService,
|
||||||
kbShareService interfaces.KBShareService,
|
kbShareService interfaces.KBShareService,
|
||||||
agentShareService interfaces.AgentShareService,
|
agentShareService interfaces.AgentShareService,
|
||||||
) *rbacGuards {
|
) *rbacGuards {
|
||||||
@@ -171,6 +173,7 @@ func newRBACGuards(
|
|||||||
}
|
}
|
||||||
g.kbService = kbService
|
g.kbService = kbService
|
||||||
g.knowledgeService = knowledgeService
|
g.knowledgeService = knowledgeService
|
||||||
|
g.chunkService = chunkService
|
||||||
g.kbShareService = kbShareService
|
g.kbShareService = kbShareService
|
||||||
g.agentShareService = agentShareService
|
g.agentShareService = agentShareService
|
||||||
return g
|
return g
|
||||||
@@ -358,3 +361,29 @@ func (g *rbacGuards) KBAccessWriteFromKnowledgeIDParam(param string) gin.Handler
|
|||||||
g.agentShareService,
|
g.agentShareService,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// KBAccessReadFromChunkIDParam walks chunk_id -> kb_id (using the
|
||||||
|
// chunk's denormalised KnowledgeBaseID column). Used by
|
||||||
|
// /chunks/by-id/:id read routes.
|
||||||
|
func (g *rbacGuards) KBAccessReadFromChunkIDParam(param string) gin.HandlerFunc {
|
||||||
|
return middleware.RequireKBAccess(
|
||||||
|
middleware.KBIDFromChunkIDParam(param, g.chunkService),
|
||||||
|
types.OrgRoleViewer,
|
||||||
|
g.kbService,
|
||||||
|
g.kbShareService,
|
||||||
|
g.agentShareService,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// KBAccessWriteFromChunkIDParam — same as KBAccessReadFromChunkIDParam
|
||||||
|
// but requires Editor minimum. Used by chunk write routes that
|
||||||
|
// address the chunk via /chunks/by-id/:id.
|
||||||
|
func (g *rbacGuards) KBAccessWriteFromChunkIDParam(param string) gin.HandlerFunc {
|
||||||
|
return middleware.RequireKBAccess(
|
||||||
|
middleware.KBIDFromChunkIDParam(param, g.chunkService),
|
||||||
|
types.OrgRoleEditor,
|
||||||
|
g.kbService,
|
||||||
|
g.kbShareService,
|
||||||
|
g.agentShareService,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|||||||
+45
-40
@@ -167,6 +167,7 @@ func NewRouter(params RouterParams) *gin.Engine {
|
|||||||
params.WikiPageHandler,
|
params.WikiPageHandler,
|
||||||
params.KBService,
|
params.KBService,
|
||||||
params.KnowledgeService,
|
params.KnowledgeService,
|
||||||
|
params.ChunkService,
|
||||||
params.KBShareService,
|
params.KBShareService,
|
||||||
params.AgentShareService,
|
params.AgentShareService,
|
||||||
)
|
)
|
||||||
@@ -218,22 +219,22 @@ func RegisterChunkRoutes(r *gin.RouterGroup, handler *handler.ChunkHandler, g *r
|
|||||||
// 分块路由组
|
// 分块路由组
|
||||||
chunks := r.Group("/chunks")
|
chunks := r.Group("/chunks")
|
||||||
{
|
{
|
||||||
// 获取分块列表 — Viewer+
|
// 获取分块列表 — Viewer+ 且对父 KB 有 read 权限(own / shared / via shared agent)
|
||||||
chunks.GET("/:knowledge_id", g.Viewer(), handler.ListKnowledgeChunks)
|
chunks.GET("/:knowledge_id", g.Viewer(), g.KBAccessReadFromKnowledgeIDParam("knowledge_id"), handler.ListKnowledgeChunks)
|
||||||
// 通过chunk_id获取单个chunk(不需要knowledge_id) — Viewer+
|
// 通过chunk_id获取单个chunk(不需要knowledge_id) — Viewer+ 且对父 KB 有 read 权限
|
||||||
chunks.GET("/by-id/:id", g.Viewer(), handler.GetChunkByIDOnly)
|
chunks.GET("/by-id/:id", g.Viewer(), g.KBAccessReadFromChunkIDParam("id"), handler.GetChunkByIDOnly)
|
||||||
// 删除分块 — KB owner OR Admin+
|
// 删除分块 — KB owner OR Admin+,且对父 KB 有 write 权限
|
||||||
chunks.DELETE("/:knowledge_id/:id", g.OwnedChunkKBOrAdmin(), handler.DeleteChunk)
|
chunks.DELETE("/:knowledge_id/:id", g.OwnedChunkKBOrAdmin(), g.KBAccessWriteFromKnowledgeIDParam("knowledge_id"), handler.DeleteChunk)
|
||||||
// 删除知识下的所有分块 — KB owner OR Admin+
|
// 删除知识下的所有分块 — KB owner OR Admin+,且对父 KB 有 write 权限
|
||||||
chunks.DELETE("/:knowledge_id", g.OwnedChunkKBOrAdmin(), handler.DeleteChunksByKnowledgeID)
|
chunks.DELETE("/:knowledge_id", g.OwnedChunkKBOrAdmin(), g.KBAccessWriteFromKnowledgeIDParam("knowledge_id"), handler.DeleteChunksByKnowledgeID)
|
||||||
// 更新分块信息 — KB owner OR Admin+
|
// 更新分块信息 — KB owner OR Admin+,且对父 KB 有 write 权限
|
||||||
chunks.PUT("/:knowledge_id/:id", g.OwnedChunkKBOrAdmin(), handler.UpdateChunk)
|
chunks.PUT("/:knowledge_id/:id", g.OwnedChunkKBOrAdmin(), g.KBAccessWriteFromKnowledgeIDParam("knowledge_id"), handler.UpdateChunk)
|
||||||
// 删除单个生成的问题(通过分块 id) — 与其它 chunk mutation 一致:
|
// 删除单个生成的问题(通过分块 id) — 与其它 chunk mutation 一致:
|
||||||
// KB owner OR Admin+。早期这里因为链路 (chunk_id -> knowledge_id ->
|
// KB owner OR Admin+。早期这里因为链路 (chunk_id -> knowledge_id ->
|
||||||
// kb -> creator_id) 还没接通,被临时降级成 Contributor,导致一个
|
// kb -> creator_id) 还没接通,被临时降级成 Contributor,导致一个
|
||||||
// 「能编辑所有 chunk 的同样规则在这条路由上反而更宽松」的不一致。
|
// 「能编辑所有 chunk 的同样规则在这条路由上反而更宽松」的不一致。
|
||||||
// 现在通过 KBCreatorLookupFromChunkIDParam 把那一跳补上,统一矩阵。
|
// 现在通过 KBCreatorLookupFromChunkIDParam 把那一跳补上,统一矩阵。
|
||||||
chunks.DELETE("/by-id/:id/questions", g.OwnedChunkKBOrAdminFromChunkID(), handler.DeleteGeneratedQuestion)
|
chunks.DELETE("/by-id/:id/questions", g.OwnedChunkKBOrAdminFromChunkID(), g.KBAccessWriteFromChunkIDParam("id"), handler.DeleteGeneratedQuestion)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -248,30 +249,34 @@ func RegisterChunkRoutes(r *gin.RouterGroup, handler *handler.ChunkHandler, g *r
|
|||||||
// Cross-:id batch operations stay Contributor-gated — they don't have
|
// Cross-:id batch operations stay Contributor-gated — they don't have
|
||||||
// a single owning KB to check against.
|
// a single owning KB to check against.
|
||||||
func RegisterKnowledgeRoutes(r *gin.RouterGroup, handler *handler.KnowledgeHandler, g *rbacGuards) {
|
func RegisterKnowledgeRoutes(r *gin.RouterGroup, handler *handler.KnowledgeHandler, g *rbacGuards) {
|
||||||
// 知识库下的知识路由组
|
// 知识库下的知识路由组(URL :id is the KB id)
|
||||||
kb := r.Group("/knowledge-bases/:id/knowledge")
|
kb := r.Group("/knowledge-bases/:id/knowledge")
|
||||||
{
|
{
|
||||||
kb.POST("/file", g.OwnedKBOrAdmin(), handler.CreateKnowledgeFromFile)
|
kb.POST("/file", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), handler.CreateKnowledgeFromFile)
|
||||||
kb.POST("/url", g.OwnedKBOrAdmin(), handler.CreateKnowledgeFromURL)
|
kb.POST("/url", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), handler.CreateKnowledgeFromURL)
|
||||||
kb.POST("/manual", g.OwnedKBOrAdmin(), handler.CreateManualKnowledge)
|
kb.POST("/manual", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), handler.CreateManualKnowledge)
|
||||||
kb.GET("", g.Viewer(), handler.ListKnowledge)
|
kb.GET("", g.Viewer(), g.KBAccessRead("id"), handler.ListKnowledge)
|
||||||
// Clearing all contents under a KB is a destructive op; gate
|
// Clearing all contents under a KB is a destructive op; gate
|
||||||
// behind Admin instead of Contributor.
|
// behind Admin instead of Contributor.
|
||||||
kb.DELETE("", g.Admin(), handler.ClearKnowledgeBaseContents)
|
kb.DELETE("", g.Admin(), g.KBAccessWrite("id"), handler.ClearKnowledgeBaseContents)
|
||||||
}
|
}
|
||||||
|
|
||||||
// 知识路由组
|
// 知识路由组(URL :id is a knowledge id; the guard walks it to the parent KB)
|
||||||
k := r.Group("/knowledge")
|
k := r.Group("/knowledge")
|
||||||
{
|
{
|
||||||
|
// Cross-knowledge endpoints (no :id) can't be gated on a single
|
||||||
|
// KB — they accept arbitrary knowledge IDs and the handler must
|
||||||
|
// fan out the access check itself. So /batch and /search keep
|
||||||
|
// the role-only floor; /move and /batch-delete stay Contributor.
|
||||||
k.GET("/batch", g.Viewer(), handler.GetKnowledgeBatch)
|
k.GET("/batch", g.Viewer(), handler.GetKnowledgeBatch)
|
||||||
k.GET("/:id", g.Viewer(), handler.GetKnowledge)
|
k.GET("/:id", g.Viewer(), g.KBAccessReadFromKnowledgeIDParam("id"), handler.GetKnowledge)
|
||||||
k.DELETE("/:id", g.OwnedKnowledgeKBOrAdmin(), handler.DeleteKnowledge)
|
k.DELETE("/:id", g.OwnedKnowledgeKBOrAdmin(), g.KBAccessWriteFromKnowledgeIDParam("id"), handler.DeleteKnowledge)
|
||||||
k.PUT("/:id", g.OwnedKnowledgeKBOrAdmin(), handler.UpdateKnowledge)
|
k.PUT("/:id", g.OwnedKnowledgeKBOrAdmin(), g.KBAccessWriteFromKnowledgeIDParam("id"), handler.UpdateKnowledge)
|
||||||
k.PUT("/manual/:id", g.OwnedKnowledgeKBOrAdmin(), handler.UpdateManualKnowledge)
|
k.PUT("/manual/:id", g.OwnedKnowledgeKBOrAdmin(), g.KBAccessWriteFromKnowledgeIDParam("id"), handler.UpdateManualKnowledge)
|
||||||
k.POST("/:id/reparse", g.OwnedKnowledgeKBOrAdmin(), handler.ReparseKnowledge)
|
k.POST("/:id/reparse", g.OwnedKnowledgeKBOrAdmin(), g.KBAccessWriteFromKnowledgeIDParam("id"), handler.ReparseKnowledge)
|
||||||
k.GET("/:id/download", g.Viewer(), handler.DownloadKnowledgeFile)
|
k.GET("/:id/download", g.Viewer(), g.KBAccessReadFromKnowledgeIDParam("id"), handler.DownloadKnowledgeFile)
|
||||||
k.GET("/:id/preview", g.Viewer(), handler.PreviewKnowledgeFile)
|
k.GET("/:id/preview", g.Viewer(), g.KBAccessReadFromKnowledgeIDParam("id"), handler.PreviewKnowledgeFile)
|
||||||
k.PUT("/image/:id/:chunk_id", g.OwnedKnowledgeKBOrAdmin(), handler.UpdateImageInfo)
|
k.PUT("/image/:id/:chunk_id", g.OwnedKnowledgeKBOrAdmin(), g.KBAccessWriteFromKnowledgeIDParam("id"), handler.UpdateImageInfo)
|
||||||
// Batch / cross-KB ops stay Contributor-gated: there is no
|
// Batch / cross-KB ops stay Contributor-gated: there is no
|
||||||
// single owning KB to walk back to. A future PR could add a
|
// single owning KB to walk back to. A future PR could add a
|
||||||
// "must own every targeted KB" guard if the requirement
|
// "must own every targeted KB" guard if the requirement
|
||||||
@@ -329,26 +334,26 @@ func RegisterKnowledgeBaseRoutes(r *gin.RouterGroup, handler *handler.KnowledgeB
|
|||||||
// 知识库路由组
|
// 知识库路由组
|
||||||
kb := r.Group("/knowledge-bases")
|
kb := r.Group("/knowledge-bases")
|
||||||
{
|
{
|
||||||
// 创建知识库 — Contributor+
|
// 创建知识库 — Contributor+ (no :id, role-only floor)
|
||||||
kb.POST("", g.Contributor(), handler.CreateKnowledgeBase)
|
kb.POST("", g.Contributor(), handler.CreateKnowledgeBase)
|
||||||
// 获取知识库列表 — Viewer+
|
// 获取知识库列表 — Viewer+ (no :id, role-only floor)
|
||||||
kb.GET("", g.Viewer(), handler.ListKnowledgeBases)
|
kb.GET("", g.Viewer(), handler.ListKnowledgeBases)
|
||||||
// 获取知识库详情 — Viewer+
|
// 获取知识库详情 — Viewer+ 且对 KB 有 read 权限
|
||||||
kb.GET("/:id", g.Viewer(), handler.GetKnowledgeBase)
|
kb.GET("/:id", g.Viewer(), g.KBAccessRead("id"), handler.GetKnowledgeBase)
|
||||||
// 更新知识库 — 创建者本人 OR Admin+
|
// 更新知识库 — 创建者本人 OR Admin+ 且对 KB 有 write 权限
|
||||||
kb.PUT("/:id", g.OwnedKBOrAdmin(), handler.UpdateKnowledgeBase)
|
kb.PUT("/:id", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), handler.UpdateKnowledgeBase)
|
||||||
// 删除知识库 — 创建者本人 OR Admin+
|
// 删除知识库 — 创建者本人 OR Admin+ 且对 KB 有 write 权限
|
||||||
kb.DELETE("/:id", g.OwnedKBOrAdmin(), handler.DeleteKnowledgeBase)
|
kb.DELETE("/:id", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), handler.DeleteKnowledgeBase)
|
||||||
// 置顶/取消置顶知识库 — 创建者本人 OR Admin+
|
// 置顶/取消置顶知识库 — 创建者本人 OR Admin+ 且对 KB 有 write 权限
|
||||||
kb.PUT("/:id/pin", g.OwnedKBOrAdmin(), handler.TogglePinKnowledgeBase)
|
kb.PUT("/:id/pin", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), handler.TogglePinKnowledgeBase)
|
||||||
// 混合搜索 — Viewer+ (read-only)
|
// 混合搜索 — Viewer+ 且对 KB 有 read 权限 (read-only)
|
||||||
kb.GET("/:id/hybrid-search", g.Viewer(), handler.HybridSearch)
|
kb.GET("/:id/hybrid-search", g.Viewer(), g.KBAccessRead("id"), handler.HybridSearch)
|
||||||
// 拷贝知识库 — Contributor+ (副本归调用者所有;不需要原 KB 的所有权)
|
// 拷贝知识库 — Contributor+ (副本归调用者所有;不需要原 KB 的所有权)
|
||||||
kb.POST("/copy", g.Contributor(), handler.CopyKnowledgeBase)
|
kb.POST("/copy", g.Contributor(), handler.CopyKnowledgeBase)
|
||||||
// 获取知识库复制进度 — Viewer+
|
// 获取知识库复制进度 — Viewer+
|
||||||
kb.GET("/copy/progress/:task_id", g.Viewer(), handler.GetKBCloneProgress)
|
kb.GET("/copy/progress/:task_id", g.Viewer(), handler.GetKBCloneProgress)
|
||||||
// 获取可移动目标知识库列表 — Viewer+
|
// 获取可移动目标知识库列表 — Viewer+ 且对 KB 有 read 权限
|
||||||
kb.GET("/:id/move-targets", g.Viewer(), handler.ListMoveTargets)
|
kb.GET("/:id/move-targets", g.Viewer(), g.KBAccessRead("id"), handler.ListMoveTargets)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user