Files
Enterprise-Knowledge-Base/internal/router/rbac.go
T
wizardchen d42a41b784 feat(rbac): per-KB ownership for knowledge / chunks / wiki pages (#1303)
PR 1–4 of the multi-tenant RBAC series gated KB-level and Agent-level
mutations behind a "creator OR Admin+" check via OwnedKBOrAdmin /
OwnedAgentOrAdmin. The layer underneath — knowledge entries, chunks,
wiki pages — was still gated only by Contributor, which is wider than
intended: any tenant Contributor could edit/delete documents in a
private KB they didn't own. PR 2 / wiki author left explicit follow-up
breadcrumbs at the three call sites in router.go acknowledging this gap.

This PR closes those breadcrumbs by reusing the existing scaffolding:

- KnowledgeService.GetOwningKBCreatorID walks knowledge_id -> kb_id ->
  KB.CreatorID, tenant-scoped through GetKnowledgeByID. The chain lives
  in the service layer so the handler-side lookups stay pure adapters.
- Three new CreatorLookup closures (KBCreatorLookupFromKnowledgeID,
  KBCreatorLookupFromKnowledgeIDParam, KBCreatorLookupFromKBPath) are
  added in handler/rbac_lookups.go alongside the existing
  KBCreatorLookup / AgentCreatorLookup. Each translates the repository
  sentinels into middleware.ErrResourceNotFound and re-checks tenant
  scope as defence-in-depth, mirroring KBCreatorLookup exactly.
- router/rbac.go gains three guard factories — OwnedKnowledgeKBOrAdmin,
  OwnedChunkKBOrAdmin, OwnedWikiKBOrAdmin — wired through the same
  rbacGuards bundle.
- Mutating routes in RegisterKnowledgeRoutes / RegisterChunkRoutes /
  RegisterWikiPageRoutes switch from g.Contributor() to the new
  ownership guards. Cross-KB batch operations (POST /knowledge/move,
  POST /knowledge/batch-delete, PUT /knowledge/tags) stay
  Contributor-gated since there's no single owning KB to check
  against. KB-scoped uploads (POST /knowledge-bases/:id/knowledge/...)
  reuse the existing OwnedKBOrAdmin because the URL :id is the KB id
  directly. The chunks.DELETE("/by-id/:id/questions") route addresses
  chunks by their own id with no knowledge id in the URL, so it stays
  Contributor-gated as a documented carve-out.

No schema changes: documents inside a shared KB are KB-owned content,
not personal uploads — that's how the product is positioned and matches
the original "per-KB-ownership granularity" wording from the PR 2
breadcrumbs. Legacy/built-in KBs with empty CreatorID surface as
tenant-owned (Admin+ only), same rule as built-in agents.

Tests:
- 9 new test cases in handler/rbac_lookups_test.go covering the three
  new lookups: NotFoundMapsToSentinel (each repository sentinel),
  CrossTenantIsHiddenAsNotFound, OwnerMatchReturnsCreatorID,
  MissingTenantContext (fail-closed), and ChunkRouteShape (param-name
  regression guard).
- 5 new test cases in service/knowledge_owner_chain_test.go covering
  the chain helper: knowledge-not-found, kb-not-found, nil-kb-without-
  err, happy path, and legacy KB with empty CreatorID.

Build, vet, and the targeted ./internal/middleware/...
./internal/handler/... ./internal/router/...
./internal/application/service test runs are clean. Pre-existing
TestCreateStore_* / TestOssEnsureBucket_CreateFails failures on main
are unrelated and reproduce on a clean checkout.
2026-05-18 17:28:58 +08:00

160 lines
6.6 KiB
Go

package router
import (
"github.com/Tencent/WeKnora/internal/config"
"github.com/Tencent/WeKnora/internal/handler"
"github.com/Tencent/WeKnora/internal/middleware"
"github.com/Tencent/WeKnora/internal/types"
"github.com/gin-gonic/gin"
)
// rbacGuards is the centralised role-matrix bundle for tenant-level RBAC
// (issue #1303 PR 2). NewRouter constructs it once and threads it into
// each Register* function that registers gated routes.
//
// Each method returns a fresh gin.HandlerFunc; routes call the method
// and inline the guard, so a glance at a route line tells you what
// authority it requires:
//
// kb.PUT("/:id", g.OwnedKBOrAdmin(), handler.UpdateKnowledgeBase)
//
// All guards honour cfg.Tenant.EnableRBAC: when the flag is off they log
// the would-be rejection and let the request through, preserving today's
// "anyone in the tenant can edit anything" behaviour during the rollout
// window. When the flag flips to true, the same code paths start
// rejecting unauthorised callers.
type rbacGuards struct {
cfg *config.Config
// Lookup closures resolve a request's :id into the resource's creator
// user ID. Captured up front so the handler-level methods don't have
// to be exported into every Register* function as well.
kbCreator middleware.CreatorLookup
agentCreator middleware.CreatorLookup
// Per-KB-ownership lookups for knowledge / chunk / wiki page routes
// (PR 5, #1303). They walk the URL param back to KB.CreatorID so a
// Contributor who owns the KB can edit/delete its sub-resources
// (documents, chunks, wiki pages); a Contributor who merely belongs
// to the tenant gets 403 unless they're also Admin+.
knowledgeKBCreator middleware.CreatorLookup
chunkKBCreator middleware.CreatorLookup
wikiKBCreator middleware.CreatorLookup
}
// newRBACGuards wires the guards from the live configuration and the
// already-built handlers. Called once from NewRouter.
func newRBACGuards(
cfg *config.Config,
kbHandler *handler.KnowledgeBaseHandler,
agentHandler *handler.CustomAgentHandler,
knowledgeHandler *handler.KnowledgeHandler,
chunkHandler *handler.ChunkHandler,
wikiHandler *handler.WikiPageHandler,
) *rbacGuards {
g := &rbacGuards{cfg: cfg}
if kbHandler != nil {
g.kbCreator = kbHandler.KBCreatorLookup
}
if agentHandler != nil {
g.agentCreator = agentHandler.AgentCreatorLookup
}
if knowledgeHandler != nil {
g.knowledgeKBCreator = knowledgeHandler.KBCreatorLookupFromKnowledgeID
}
if chunkHandler != nil {
g.chunkKBCreator = chunkHandler.KBCreatorLookupFromKnowledgeIDParam
}
if wikiHandler != nil {
g.wikiKBCreator = wikiHandler.KBCreatorLookupFromKBPath
}
return g
}
// Role-only guards — pure RequireRole convenience wrappers, named after
// the matrix entries so route lines stay readable.
func (g *rbacGuards) Viewer() gin.HandlerFunc {
return middleware.RequireRole(types.TenantRoleViewer, g.cfg)
}
func (g *rbacGuards) Contributor() gin.HandlerFunc {
return middleware.RequireRole(types.TenantRoleContributor, g.cfg)
}
func (g *rbacGuards) Admin() gin.HandlerFunc {
return middleware.RequireRole(types.TenantRoleAdmin, g.cfg)
}
func (g *rbacGuards) Owner() gin.HandlerFunc {
return middleware.RequireRole(types.TenantRoleOwner, g.cfg)
}
// Ownership-or-role guards. Required role here is the privilege level
// that bypasses the ownership check; Contributors ALWAYS pass when they
// own the resource.
// OwnedKBOrAdmin: KB mutations (update/delete/pin/copy). The original
// creator may proceed; otherwise Admin+ is required. Contributors who
// did not create the KB get 403 (when enforcement is on).
func (g *rbacGuards) OwnedKBOrAdmin() gin.HandlerFunc {
return middleware.RequireOwnershipOrRole(types.TenantRoleAdmin, g.kbCreator, g.cfg)
}
// OwnedAgentOrAdmin: same shape as OwnedKBOrAdmin but for CustomAgent.
// Built-in agents (IsBuiltin=true) are tenant-owned; their creator
// lookup returns "" and only Admin+ may mutate them.
func (g *rbacGuards) OwnedAgentOrAdmin() gin.HandlerFunc {
return middleware.RequireOwnershipOrRole(types.TenantRoleAdmin, g.agentCreator, g.cfg)
}
// OwnedKnowledgeKBOrAdmin: per-knowledge mutations (update / delete /
// reparse / image edit) — the URL :id is a knowledge id, the lookup
// walks it back to the owning KB's CreatorID. Same "creator OR Admin+"
// rule as OwnedKBOrAdmin, just one chain hop deeper. PR 5 (#1303).
func (g *rbacGuards) OwnedKnowledgeKBOrAdmin() gin.HandlerFunc {
return middleware.RequireOwnershipOrRole(types.TenantRoleAdmin, g.knowledgeKBCreator, g.cfg)
}
// OwnedChunkKBOrAdmin: chunk mutations addressed via :knowledge_id.
// Reuses the same chain helper as OwnedKnowledgeKBOrAdmin so a
// Contributor with KB ownership can manage all chunks under any of
// their documents. The chunks.DELETE("/by-id/:id/questions") route
// addresses chunks by :id (no knowledge id), so it is intentionally
// not wired through this guard — see router.go for the carve-out.
func (g *rbacGuards) OwnedChunkKBOrAdmin() gin.HandlerFunc {
return middleware.RequireOwnershipOrRole(types.TenantRoleAdmin, g.chunkKBCreator, g.cfg)
}
// OwnedWikiKBOrAdmin: wiki page CRUD and maintenance ops. Wiki routes
// use :kb_id directly so the lookup is a single hop into the KB
// service — no knowledge chain. Same matrix as OwnedKBOrAdmin.
func (g *rbacGuards) OwnedWikiKBOrAdmin() gin.HandlerFunc {
return middleware.RequireOwnershipOrRole(types.TenantRoleAdmin, g.wikiKBCreator, g.cfg)
}
// Tenant-access guards. Distinct from the role guards above: these
// answer the orthogonal question "may this caller touch this tenant
// at all", before role membership inside the tenant is even
// considered. Both delegate to middleware/access.go which centralises
// the cross-tenant rules so the router stays declarative.
// CrossTenant gates a route on the caller being an org-level
// superuser (CanAccessAllTenants AND EnableCrossTenantAccess). Used by
// /tenants/all, /tenants/search, POST /tenants, GET /tenants — the
// endpoints that operate across tenants. Replaces the if-blocks that
// used to live inside ListAllTenants/SearchTenants/CreateTenant.
func (g *rbacGuards) CrossTenant() gin.HandlerFunc {
return middleware.RequireCrossTenantAccess(g.cfg)
}
// PathTenantMatch enforces that the URL :id matches the caller's
// active tenant context (cross-tenant superusers bypass). Routes apply
// it at the /tenants/:id group level so every per-tenant endpoint —
// GetTenant / UpdateTenant / DeleteTenant / ResetAPIKey / member
// management / leave — shares the same check. Replaces the
// authorizeTenantAccess helper that used to live inside the tenant
// handler.
func (g *rbacGuards) PathTenantMatch() gin.HandlerFunc {
return middleware.RequirePathTenantMatch(g.cfg)
}