refactor(api-keys): simplify authorization to a single-role gate

Redesign tenant API key authorization around one dimension (role) plus a
central default-deny gate, replacing the previous role + KB-scoped flag model.

- Add APIKeyGate as the single authority for API-key authorization: routes
  declare one policy (MinRole) via apiKeyGroup/apiKeyRoute helpers; undeclared
  routes are denied by default. JWT principals short-circuit the gate and the
  JWT-centric RBAC guards short-circuit for API-key principals.
- Roles: viewer/contributor/admin are knowledge-base data-plane only (KB scope
  is a pure downstream data filter); owner is a full-access tenant tier that
  unlocks tenant-level infrastructure routes and is required for every method.
- Drop the KBScoped policy flag and the KB-restricted-vs-tenant branching.
- Security hardening: never disclose HMAC secret (return presence only), abort
  writes on API-key encryption failure, deny KB-restricted keys on /files, and
  backfill legacy key hashes at startup instead of O(N) plaintext scans.
- Frontend: two-level create dialog (access type -> permission level), rename
  role labels to reflect actual scope, sync en/zh/ko/ru locales.
- Fix startup self-check false-positive on trailing-slash routes and normalize
  gin paths before comparison; add regression tests.
This commit is contained in:
wizardchen
2026-07-06 17:34:52 +08:00
committed by lyingbug
parent fedb6c3f7e
commit d2ffc1b973
26 changed files with 1045 additions and 500 deletions
+139 -15
View File
@@ -1,6 +1,10 @@
package router
import (
"net/http"
"path"
"strings"
"github.com/Tencent/WeKnora/internal/config"
"github.com/Tencent/WeKnora/internal/handler"
"github.com/Tencent/WeKnora/internal/middleware"
@@ -122,10 +126,10 @@ type rbacGuards struct {
// 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
chunkKBCreatorFromID middleware.CreatorLookup // chunk routes that address chunks by :id (no knowledge id in URL)
wikiKBCreator middleware.CreatorLookup
knowledgeKBCreator middleware.CreatorLookup
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()
@@ -136,6 +140,12 @@ type rbacGuards struct {
chunkService middleware.ChunkLookup
kbShareService interfaces.KBShareService
agentShareService interfaces.AgentShareService
// apiKeyAuthorizer is the single source of truth for which routes an
// X-API-Key principal may call. Routes opt in via the apiKeyGroup
// helpers below; anything not declared is denied by the gate. See
// middleware.APIKeyRouteAuthorizer.
apiKeyAuthorizer *middleware.APIKeyRouteAuthorizer
}
// newRBACGuards wires the guards from the live configuration and the
@@ -153,7 +163,7 @@ func newRBACGuards(
kbShareService interfaces.KBShareService,
agentShareService interfaces.AgentShareService,
) *rbacGuards {
g := &rbacGuards{cfg: cfg}
g := &rbacGuards{cfg: cfg, apiKeyAuthorizer: middleware.NewAPIKeyRouteAuthorizer()}
if kbHandler != nil {
g.kbCreator = kbHandler.KBCreatorLookup
g.kbCreatorFromKbIDParam = kbHandler.KBCreatorLookupFromKbIDParam
@@ -198,23 +208,137 @@ func (g *rbacGuards) Owner() gin.HandlerFunc {
return middleware.RequireRole(types.TenantRoleOwner, g.cfg)
}
// API-key guards — orthogonal to JWT role guards. They only constrain
// X-API-Key principals; bearer sessions pass through unchanged.
// API-key authorization — a SEPARATE authority from the JWT role/ownership
// guards above. Instead of stacking a per-route guard that also had to know
// the caller's ownership, every API-key-accessible route declares one
// APIKeyRoutePolicy via the apiKeyGroup helpers; the gate on /api/v1 enforces
// it and denies any undeclared route by default. JWT sessions ignore all of
// this (they short-circuit the gate).
//
// Policy constructors. A single dimension — the minimum role — decides
// access; the key's knowledge_base_ids allow-list is a pure data filter
// applied downstream (KBAccess guards + handler scope checks), never here.
//
// - apiKeyViewer : data-plane reads/searches (Viewer floor).
// - apiKeyContributor : data-plane content writes (Contributor+).
// - apiKeyAdmin : destructive data-plane ops, e.g. clearing a KB (Admin+).
// - apiKeyOwner : tenant-level infrastructure (models, vector stores,
// MCP, data sources, channels, tenant KV, ...). Requires the Owner role
// for EVERY method, mirroring the original full-access tenant key. A key
// below Owner can only ever touch knowledge-base data.
func (g *rbacGuards) APIKeyDeny() gin.HandlerFunc {
return middleware.RequireAPIKeyDeny()
func apiKeyViewer() middleware.APIKeyRoutePolicy {
return middleware.APIKeyRoutePolicy{MinRole: types.TenantRoleViewer}
}
func (g *rbacGuards) APIKeyViewer() gin.HandlerFunc {
return middleware.RequireAPIKeyMinRole(types.TenantRoleViewer)
func apiKeyContributor() middleware.APIKeyRoutePolicy {
return middleware.APIKeyRoutePolicy{MinRole: types.TenantRoleContributor}
}
func (g *rbacGuards) APIKeyContributor() gin.HandlerFunc {
return middleware.RequireAPIKeyMinRoleForUnsafe(types.TenantRoleContributor)
func apiKeyAdmin() middleware.APIKeyRoutePolicy {
return middleware.APIKeyRoutePolicy{MinRole: types.TenantRoleAdmin}
}
func (g *rbacGuards) APIKeyAdmin() gin.HandlerFunc {
return middleware.RequireAPIKeyMinRoleForUnsafe(types.TenantRoleAdmin)
func apiKeyOwner() middleware.APIKeyRoutePolicy {
return middleware.APIKeyRoutePolicy{MinRole: types.TenantRoleOwner}
}
// apiKeyRouteGroup wraps a *gin.RouterGroup so route registration also records
// the route's API-key policy into the authorizer. Use g.apiKeyGroup(grp,
// policy) then register the API-key-accessible routes through it; register
// API-key-denied routes on the raw *gin.RouterGroup so they stay undeclared
// (default-deny). Per-route overrides use With().
type apiKeyRouteGroup struct {
g *rbacGuards
grp *gin.RouterGroup
policy middleware.APIKeyRoutePolicy
}
// ensureAPIKeyAuthorizer lazily allocates the authorizer so route
// registration is safe even when rbacGuards is built directly in tests
// (bypassing newRBACGuards). In production it is always pre-allocated.
func (g *rbacGuards) ensureAPIKeyAuthorizer() *middleware.APIKeyRouteAuthorizer {
if g.apiKeyAuthorizer == nil {
g.apiKeyAuthorizer = middleware.NewAPIKeyRouteAuthorizer()
}
return g.apiKeyAuthorizer
}
// apiKeyGroup returns a wrapper that declares `policy` for every route
// registered through it (unless overridden via With).
func (g *rbacGuards) apiKeyGroup(grp *gin.RouterGroup, policy middleware.APIKeyRoutePolicy) *apiKeyRouteGroup {
g.ensureAPIKeyAuthorizer()
return &apiKeyRouteGroup{g: g, grp: grp, policy: policy}
}
// With returns a sibling wrapper on the same gin group but with a different
// policy, for the odd route that differs from its group default (e.g. a read
// search inside an otherwise contributor-gated group).
func (a *apiKeyRouteGroup) With(policy middleware.APIKeyRoutePolicy) *apiKeyRouteGroup {
return &apiKeyRouteGroup{g: a.g, grp: a.grp, policy: policy}
}
func (a *apiKeyRouteGroup) handle(method, rel string, handlers ...gin.HandlerFunc) gin.IRoutes {
full := path.Join(a.grp.BasePath(), rel)
a.g.ensureAPIKeyAuthorizer().Register(method, full, a.policy)
return a.grp.Handle(method, rel, handlers...)
}
func (a *apiKeyRouteGroup) GET(rel string, h ...gin.HandlerFunc) gin.IRoutes {
return a.handle(http.MethodGet, rel, h...)
}
func (a *apiKeyRouteGroup) POST(rel string, h ...gin.HandlerFunc) gin.IRoutes {
return a.handle(http.MethodPost, rel, h...)
}
func (a *apiKeyRouteGroup) PUT(rel string, h ...gin.HandlerFunc) gin.IRoutes {
return a.handle(http.MethodPut, rel, h...)
}
func (a *apiKeyRouteGroup) DELETE(rel string, h ...gin.HandlerFunc) gin.IRoutes {
return a.handle(http.MethodDelete, rel, h...)
}
// apiKeyRoute declares a single API-key-accessible route directly on a gin
// group (for routes registered outside an apiKeyGroup, e.g. top-level r.POST).
func (g *rbacGuards) apiKeyRoute(
grp *gin.RouterGroup, method, rel string, policy middleware.APIKeyRoutePolicy, handlers ...gin.HandlerFunc,
) gin.IRoutes {
full := path.Join(grp.BasePath(), rel)
g.ensureAPIKeyAuthorizer().Register(method, full, policy)
return grp.Handle(method, rel, handlers...)
}
// assertAPIKeyPoliciesMatchRoutes verifies every declared API-key policy
// resolves to a real registered route. gin's c.FullPath() must match the
// authorizer key verbatim or the gate silently 403s the route for API keys;
// panicking here turns that latent misconfiguration into a startup failure.
func (g *rbacGuards) assertAPIKeyPoliciesMatchRoutes(engine *gin.Engine) {
registered := map[string]struct{}{}
for _, ri := range engine.Routes() {
// Authorizer keys are stored normalized (trailing slash trimmed), so
// normalize gin's reported path the same way. Otherwise a route
// registered with a "/" rel (gin path ".../evaluation/") would look
// missing against the normalized key (".../evaluation") even though
// the gate — which also normalizes c.FullPath() — matches it fine.
p := ri.Path
if len(p) > 1 {
p = strings.TrimRight(p, "/")
}
registered[ri.Method+" "+p] = struct{}{}
}
var missing []string
for method, paths := range g.apiKeyAuthorizer.RegisteredRoutes() {
for _, p := range paths {
if _, ok := registered[method+" "+p]; !ok {
missing = append(missing, method+" "+p)
}
}
}
if len(missing) > 0 {
panic("api-key policy declared for non-existent route(s): " + strings.Join(missing, ", "))
}
}
func (g *rbacGuards) SystemAdmin() gin.HandlerFunc {