refactor(rbac): KB-access guard at the route layer (no helper in handlers)
Five handler files used to carry near-identical 30-line helpers
(effectiveCtxForKB / validateAndGetKnowledgeBase) that did the same
own-or-shared resolution before every KB-scoped operation:
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)
A bug found in any one of them had to be fixed in five places, and
several already drifted apart (different log levels, slightly
different error messages, one path missing the share-cap check).
Move the resolution to a route-level gin.HandlerFunc:
middleware.RequireKBAccess, exposed on rbacGuards as
g.KBAccessRead("id") / g.KBAccessWrite("id"). The guard runs after
the role/ownership checks, then on success:
- stashes the resolved (KB + effective tenant id + permission)
on c.Keys under middleware.KBAccessContextKey, and
- rewrites c.Request.Context() to carry the effective tenant id
so handlers downstream just read tenant the way they always did
(types.MustTenantIDFromContext) without a per-handler helper.
Refactor FAQ and Tag handlers to drop their helper methods; their
service constructors lose the kbShareService / agentShareService
dependencies (now lifted to the route layer). Routes:
faq.GET("/entries", g.Viewer(), g.KBAccessRead("id"), ...)
faq.POST("/entries", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), ...)
kbTags.GET("", g.Viewer(), g.KBAccessRead("id"), ...)
kbTags.POST("", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), ...)
The middleware also exports KBIDFromKnowledgeIDParam so chunk routes
(URL :knowledge_id) can adopt the same pattern in a follow-up PR
without reshaping the helper.
Five new tests cover own-KB, not-found, shared-with-sufficient-perm,
shared-but-below-min, and missing-tenant-context paths. Handler
tests still pass (no behaviour change).
This commit is contained in:
@@ -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,
|
||||
)
|
||||
}
|
||||
|
||||
+29
-16
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user