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
-108
View File
@@ -1,108 +0,0 @@
package middleware
import (
"context"
stderrors "errors"
"net/http"
"strings"
"github.com/Tencent/WeKnora/internal/types"
"github.com/gin-gonic/gin"
)
var errTenantAPIKeyScopeForbidden = stderrors.New("tenant api key scope forbidden")
// isTenantAPIKeyManagementPath reports tenant API-key lifecycle endpoints that
// no scoped key may call, regardless of role.
func isTenantAPIKeyManagementPath(path string) bool {
for _, marker := range []string{"/api-keys", "/api-principal"} {
if strings.Contains(path, marker) {
return true
}
}
// Legacy reset endpoint: POST /tenants/:id/api-key (singular).
return strings.HasSuffix(path, "/api-key")
}
// rejectTenantAPIKeyManagementPath is a defense-in-depth guard in auth: API keys
// must never reach key-management routes even if a route forgets APIKeyDeny().
// Role and KB checks are enforced by per-route APIKey* guards and types helpers.
func rejectTenantAPIKeyManagementPath(ctx context.Context, path string) error {
if _, ok := types.TenantAPIKeyScopeFromContext(ctx); !ok {
return nil
}
if isTenantAPIKeyManagementPath(path) {
return errTenantAPIKeyScopeForbidden
}
return nil
}
// RequireAPIKeyDeny rejects all X-API-Key callers. JWT sessions pass through.
func RequireAPIKeyDeny() gin.HandlerFunc {
return func(c *gin.Context) {
if _, ok := types.TenantAPIKeyScopeFromContext(c.Request.Context()); ok {
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{
"error": "Forbidden: API key scope does not allow this operation",
})
return
}
c.Next()
}
}
// RequireAPIKeyMinRole enforces minRole for X-API-Key callers on every HTTP
// method. JWT sessions pass through.
func RequireAPIKeyMinRole(minRole types.TenantRole) gin.HandlerFunc {
return func(c *gin.Context) {
if err := requireTenantAPIKeyMinRole(c.Request.Context(), minRole); err != nil {
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{
"error": "Forbidden: API key scope does not allow this operation",
})
return
}
c.Next()
}
}
// RequireAPIKeyMinRoleForUnsafe enforces minRole for X-API-Key callers on
// POST/PUT/PATCH/DELETE only. Safe reads (GET/HEAD/OPTIONS) pass through so
// group-level guards can cover mixed read/write route trees.
func RequireAPIKeyMinRoleForUnsafe(minRole types.TenantRole) gin.HandlerFunc {
return func(c *gin.Context) {
if isSafeHTTPMethod(c.Request.Method) {
c.Next()
return
}
if err := requireTenantAPIKeyMinRole(c.Request.Context(), minRole); err != nil {
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{
"error": "Forbidden: API key scope does not allow this operation",
})
return
}
c.Next()
}
}
func requireTenantAPIKeyMinRole(ctx context.Context, minRole types.TenantRole) error {
scope, ok := types.TenantAPIKeyScopeFromContext(ctx)
if !ok {
return nil
}
role := scope.Role
if role == "" {
role = types.TenantRoleViewer
}
if !role.HasPermission(minRole) {
return errTenantAPIKeyScopeForbidden
}
return nil
}
func isSafeHTTPMethod(method string) bool {
switch method {
case http.MethodGet, http.MethodHead, http.MethodOptions:
return true
default:
return false
}
}
-114
View File
@@ -1,114 +0,0 @@
package middleware
import (
"context"
stderrors "errors"
"net/http"
"net/http/httptest"
"testing"
"github.com/Tencent/WeKnora/internal/types"
"github.com/gin-gonic/gin"
)
func TestRejectTenantAPIKeyManagementPath(t *testing.T) {
ctx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{
Role: types.TenantRoleAdmin,
})
for _, path := range []string{
"/api/v1/tenants/1/api-keys",
"/api/v1/tenants/1/api-key",
"/api/v1/tenants/1/api-principal-config",
"/api/v1/tenants/1/api-principal-test-token",
} {
err := rejectTenantAPIKeyManagementPath(ctx, path)
if !stderrors.Is(err, errTenantAPIKeyScopeForbidden) {
t.Fatalf("management path %s error = %v, want errTenantAPIKeyScopeForbidden", path, err)
}
}
if err := rejectTenantAPIKeyManagementPath(ctx, "/api/v1/knowledge-bases"); err != nil {
t.Fatalf("non-management path should pass: %v", err)
}
if err := rejectTenantAPIKeyManagementPath(context.Background(), "/api/v1/tenants/1/api-keys"); err != nil {
t.Fatalf("non-api-key principal should pass: %v", err)
}
}
func TestRequireAPIKeyDenyBlocksAPIKey(t *testing.T) {
gin.SetMode(gin.TestMode)
ctx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{
Role: types.TenantRoleAdmin,
})
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest(http.MethodPost, "/api/v1/knowledge-bases", nil)
c.Request = c.Request.WithContext(ctx)
RequireAPIKeyDeny()(c)
if !c.IsAborted() {
t.Fatal("expected API key request to be aborted")
}
if w.Code != http.StatusForbidden {
t.Fatalf("status = %d, want %d", w.Code, http.StatusForbidden)
}
}
func TestRequireAPIKeyDenyAllowsJWT(t *testing.T) {
gin.SetMode(gin.TestMode)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest(http.MethodPost, "/api/v1/knowledge-bases", nil)
RequireAPIKeyDeny()(c)
if c.IsAborted() {
t.Fatal("expected JWT request to pass RequireAPIKeyDeny")
}
}
func TestRequireAPIKeyMinRoleForUnsafeSkipsSafeMethods(t *testing.T) {
ctx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{
Role: types.TenantRoleViewer,
})
if err := requireTenantAPIKeyMinRole(ctx, types.TenantRoleAdmin); !stderrors.Is(err, errTenantAPIKeyScopeForbidden) {
t.Fatalf("viewer should not satisfy admin min role: %v", err)
}
gin.SetMode(gin.TestMode)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest(http.MethodGet, "/api/v1/models", nil)
c.Request = c.Request.WithContext(ctx)
RequireAPIKeyMinRoleForUnsafe(types.TenantRoleAdmin)(c)
if c.IsAborted() {
t.Fatal("safe GET should skip unsafe min-role guard")
}
}
func TestRequireAPIKeyMinRoleEnforcesOnPost(t *testing.T) {
ctx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{
Role: types.TenantRoleViewer,
})
gin.SetMode(gin.TestMode)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest(http.MethodPost, "/api/v1/knowledge-search", nil)
c.Request = c.Request.WithContext(ctx)
RequireAPIKeyMinRole(types.TenantRoleViewer)(c)
if c.IsAborted() {
t.Fatal("viewer key should pass viewer min role on POST")
}
}
func TestRequireAPIKeyMinRoleForUnsafeAllowsContributorKnowledgeWrite(t *testing.T) {
ctx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{
Role: types.TenantRoleContributor,
KnowledgeBaseIDs: types.StringArray{"kb-1"},
})
if err := requireTenantAPIKeyMinRole(ctx, types.TenantRoleContributor); err != nil {
t.Fatalf("scoped knowledge write should pass route guard: %v", err)
}
}
+160
View File
@@ -0,0 +1,160 @@
package middleware
import (
stderrors "errors"
"net/http"
"strings"
"github.com/Tencent/WeKnora/internal/types"
"github.com/gin-gonic/gin"
)
var errTenantAPIKeyScopeForbidden = stderrors.New("tenant api key scope forbidden")
// APIKeyRoutePolicy declares how an X-API-Key caller may use a single route.
//
// Design: API-key authorization is a SEPARATE authority from the JWT
// role/ownership guards. Ownership ("creator OR Admin+") is a human concept
// and never applies to a machine principal; instead every API-key-accessible
// route declares one policy here, and the APIKeyGate is the single place that
// enforces it. Routes that declare no policy are denied for API keys by
// default (fail-closed), which removes the old "remember to add APIKeyDeny"
// footgun.
type APIKeyRoutePolicy struct {
// MinRole is the minimum tenant role an API key needs for this route.
//
// Data-plane routes (knowledge bases and their content) use Viewer /
// Contributor / Admin; for those, safe reads (GET/HEAD/OPTIONS) only
// require Viewer while writes require the declared role. Tenant-level
// infrastructure routes (models, vector stores, MCP, data sources,
// channels, tenant KV, ...) use Owner, which is required for EVERY
// method — reading tenant configuration is itself a privileged action.
//
// KB scoping is NOT enforced here: a key's knowledge_base_ids allow-list
// is a pure data filter applied by the KBAccess guards and the handler
// scope checks on data-plane routes. Tenant-level routes are simply
// gated behind the Owner role instead of being reachable by a narrow key.
MinRole types.TenantRole
}
// APIKeyRouteAuthorizer is the registry of per-route API-key policies. It is
// populated at router-construction time (single-threaded) and only read at
// request time, so it needs no locking.
type APIKeyRouteAuthorizer struct {
// policies is keyed by HTTP method, then by the gin full-path
// template (e.g. "/api/v1/knowledge-bases/:id/knowledge/file").
policies map[string]map[string]APIKeyRoutePolicy
}
// NewAPIKeyRouteAuthorizer returns an empty authorizer.
func NewAPIKeyRouteAuthorizer() *APIKeyRouteAuthorizer {
return &APIKeyRouteAuthorizer{policies: map[string]map[string]APIKeyRoutePolicy{}}
}
// Register records the API-key policy for (method, fullPath). fullPath MUST be
// the same string gin reports via c.FullPath() for the route, otherwise the
// gate lookup will miss and the route will be denied for API keys. Router-side
// helpers build fullPath from the group's BasePath so the two stay in sync.
func (a *APIKeyRouteAuthorizer) Register(method, fullPath string, policy APIKeyRoutePolicy) {
method = strings.ToUpper(strings.TrimSpace(method))
fullPath = normalizeRoutePath(fullPath)
if a.policies[method] == nil {
a.policies[method] = map[string]APIKeyRoutePolicy{}
}
a.policies[method][fullPath] = policy
}
// Lookup returns the policy for (method, fullPath) if one was declared.
func (a *APIKeyRouteAuthorizer) Lookup(method, fullPath string) (APIKeyRoutePolicy, bool) {
byPath, ok := a.policies[strings.ToUpper(method)]
if !ok {
return APIKeyRoutePolicy{}, false
}
policy, ok := byPath[normalizeRoutePath(fullPath)]
return policy, ok
}
// RegisteredRoutes returns every (method, fullPath) pair the authorizer knows
// about. Used by the router startup self-check to detect stale path templates.
func (a *APIKeyRouteAuthorizer) RegisteredRoutes() map[string][]string {
out := make(map[string][]string, len(a.policies))
for method, byPath := range a.policies {
paths := make([]string, 0, len(byPath))
for path := range byPath {
paths = append(paths, path)
}
out[method] = paths
}
return out
}
// Middleware returns the gate middleware. It runs as the first handler on the
// authenticated API group, after routing (so c.FullPath() is populated). JWT
// principals pass straight through; API-key principals are authorized purely
// from the declared policy table.
func (a *APIKeyRouteAuthorizer) Middleware() gin.HandlerFunc {
return func(c *gin.Context) {
scope, ok := types.TenantAPIKeyScopeFromContext(c.Request.Context())
if !ok {
c.Next()
return
}
if err := a.authorize(scope, c.Request.Method, c.FullPath()); err != nil {
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{
"error": "Forbidden: API key scope does not allow this operation",
})
return
}
c.Next()
}
}
// authorize applies the declared policy to an API-key scope. Absent policy =>
// default deny.
func (a *APIKeyRouteAuthorizer) authorize(scope types.TenantAPIKeyScope, method, fullPath string) error {
policy, ok := a.Lookup(method, fullPath)
if !ok {
return errTenantAPIKeyScopeForbidden
}
role := scope.Role
if role == "" {
role = types.TenantRoleViewer
}
required := policy.MinRole
if required == "" {
required = types.TenantRoleViewer
}
// Data-plane safe reads only need a Viewer floor. Tenant-level (Owner)
// routes require the full role even for reads, so they are never lowered.
if isSafeHTTPMethod(method) && required != types.TenantRoleOwner {
required = types.TenantRoleViewer
}
if !role.HasPermission(required) {
return errTenantAPIKeyScopeForbidden
}
return nil
}
func isSafeHTTPMethod(method string) bool {
switch method {
case http.MethodGet, http.MethodHead, http.MethodOptions:
return true
default:
return false
}
}
// normalizeRoutePath collapses duplicate slashes and trims a trailing slash so
// helper-built paths (BasePath()+rel) match gin's c.FullPath() exactly.
func normalizeRoutePath(p string) string {
if p == "" {
return ""
}
for strings.Contains(p, "//") {
p = strings.ReplaceAll(p, "//", "/")
}
if len(p) > 1 {
p = strings.TrimSuffix(p, "/")
}
return p
}
+166
View File
@@ -0,0 +1,166 @@
package middleware
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/Tencent/WeKnora/internal/types"
"github.com/gin-gonic/gin"
)
func newTestAuthorizer() *APIKeyRouteAuthorizer {
a := NewAPIKeyRouteAuthorizer()
// Data-plane routes (Viewer read, Contributor write, Admin destructive)
// plus one tenant-level Owner route.
a.Register(http.MethodGet, "/api/v1/knowledge-bases/:id", policyMinRole(types.TenantRoleViewer))
a.Register(http.MethodPost, "/api/v1/knowledge-bases/:id/knowledge/file", policyMinRole(types.TenantRoleContributor))
a.Register(http.MethodDelete, "/api/v1/knowledge-bases/:id/knowledge", policyMinRole(types.TenantRoleAdmin))
a.Register(http.MethodGet, "/api/v1/models", policyMinRole(types.TenantRoleOwner))
a.Register(http.MethodPut, "/api/v1/tenants/kv/:key", policyMinRole(types.TenantRoleOwner))
return a
}
func policyMinRole(r types.TenantRole) APIKeyRoutePolicy {
return APIKeyRoutePolicy{MinRole: r}
}
// runGate exercises the gate middleware with a given scope, method and route
// full-path, returning whether the request was allowed to proceed.
func runGate(t *testing.T, a *APIKeyRouteAuthorizer, scope *types.TenantAPIKeyScope, method, fullPath string) bool {
t.Helper()
gin.SetMode(gin.TestMode)
engine := gin.New()
engine.Use(func(c *gin.Context) {
if scope != nil {
c.Request = c.Request.WithContext(types.WithTenantAPIKeyScope(c.Request.Context(), *scope))
}
c.Next()
})
engine.Use(a.Middleware())
allowed := false
engine.Handle(method, fullPath, func(c *gin.Context) {
allowed = true
c.Status(http.StatusOK)
})
w := httptest.NewRecorder()
engine.ServeHTTP(w, httptest.NewRequest(method, concretePath(fullPath), nil))
return allowed && w.Code == http.StatusOK
}
// concretePath substitutes gin :params with literals so httptest can hit it.
func concretePath(tmpl string) string {
switch tmpl {
case "/api/v1/knowledge-bases/:id":
return "/api/v1/knowledge-bases/kb-1"
case "/api/v1/knowledge-bases/:id/knowledge/file":
return "/api/v1/knowledge-bases/kb-1/knowledge/file"
case "/api/v1/knowledge-bases/:id/knowledge":
return "/api/v1/knowledge-bases/kb-1/knowledge"
case "/api/v1/tenants/kv/:key":
return "/api/v1/tenants/kv/some-key"
default:
return tmpl
}
}
func TestGateJWTPassesThrough(t *testing.T) {
a := newTestAuthorizer()
// No scope => JWT principal => always allowed, even on an Owner route.
if !runGate(t, a, nil, http.MethodGet, "/api/v1/models") {
t.Fatal("JWT principal must pass the gate")
}
}
func TestGateDefaultDeny(t *testing.T) {
a := newTestAuthorizer()
owner := &types.TenantAPIKeyScope{Role: types.TenantRoleOwner}
gin.SetMode(gin.TestMode)
engine := gin.New()
engine.Use(func(c *gin.Context) {
c.Request = c.Request.WithContext(types.WithTenantAPIKeyScope(c.Request.Context(), *owner))
c.Next()
})
engine.Use(a.Middleware())
engine.POST("/api/v1/agents", func(c *gin.Context) { c.Status(http.StatusOK) })
w := httptest.NewRecorder()
engine.ServeHTTP(w, httptest.NewRequest(http.MethodPost, "/api/v1/agents", nil))
if w.Code != http.StatusForbidden {
t.Fatalf("undeclared route should default-deny even an Owner key: status=%d", w.Code)
}
}
func TestGateDataPlaneRoleLadder(t *testing.T) {
a := newTestAuthorizer()
viewer := &types.TenantAPIKeyScope{Role: types.TenantRoleViewer}
contributor := &types.TenantAPIKeyScope{Role: types.TenantRoleContributor}
admin := &types.TenantAPIKeyScope{Role: types.TenantRoleAdmin}
// Safe read: any data-plane key (Viewer) passes.
if !runGate(t, a, viewer, http.MethodGet, "/api/v1/knowledge-bases/:id") {
t.Fatal("viewer key should read a declared KB route")
}
// Contributor write.
if runGate(t, a, viewer, http.MethodPost, "/api/v1/knowledge-bases/:id/knowledge/file") {
t.Fatal("viewer key must not perform a contributor write")
}
if !runGate(t, a, contributor, http.MethodPost, "/api/v1/knowledge-bases/:id/knowledge/file") {
t.Fatal("contributor key should perform a contributor write")
}
// Admin destructive.
if runGate(t, a, contributor, http.MethodDelete, "/api/v1/knowledge-bases/:id/knowledge") {
t.Fatal("contributor key must not perform an admin destructive op")
}
if !runGate(t, a, admin, http.MethodDelete, "/api/v1/knowledge-bases/:id/knowledge") {
t.Fatal("admin key should perform an admin destructive op")
}
}
func TestGateTenantRoutesRequireOwner(t *testing.T) {
a := newTestAuthorizer()
admin := &types.TenantAPIKeyScope{Role: types.TenantRoleAdmin}
owner := &types.TenantAPIKeyScope{Role: types.TenantRoleOwner}
// Even a safe GET on a tenant-level route requires Owner (no Viewer floor).
if runGate(t, a, admin, http.MethodGet, "/api/v1/models") {
t.Fatal("admin key must NOT read a tenant-level route")
}
if !runGate(t, a, owner, http.MethodGet, "/api/v1/models") {
t.Fatal("owner key should read a tenant-level route")
}
// Unsafe tenant write also requires Owner.
if runGate(t, a, admin, http.MethodPut, "/api/v1/tenants/kv/:key") {
t.Fatal("admin key must NOT write a tenant-level route")
}
if !runGate(t, a, owner, http.MethodPut, "/api/v1/tenants/kv/:key") {
t.Fatal("owner key should write a tenant-level route")
}
}
func TestGateKBScopeDoesNotBlockDataPlane(t *testing.T) {
a := newTestAuthorizer()
// A KB-restricted key is NOT blocked by the gate on data-plane routes;
// its KB allow-list is enforced downstream by KBAccess/handler checks.
restricted := &types.TenantAPIKeyScope{
Role: types.TenantRoleContributor,
KnowledgeBaseIDs: types.StringArray{"kb-1"},
}
if !runGate(t, a, restricted, http.MethodPost, "/api/v1/knowledge-bases/:id/knowledge/file") {
t.Fatal("KB-restricted contributor key should pass the gate on a data-plane write")
}
}
func TestNormalizeRoutePath(t *testing.T) {
cases := map[string]string{
"/api/v1//models": "/api/v1/models",
"/api/v1/models/": "/api/v1/models",
"/": "/",
"/api/v1/agents": "/api/v1/agents",
}
for in, want := range cases {
if got := normalizeRoutePath(in); got != want {
t.Fatalf("normalizeRoutePath(%q)=%q want %q", in, got, want)
}
}
}
@@ -1,83 +0,0 @@
package middleware
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"github.com/Tencent/WeKnora/internal/types"
"github.com/gin-gonic/gin"
)
func TestTenantAPIKeyRouteScopeManifest(t *testing.T) {
readCtx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{
Role: types.TenantRoleViewer,
})
writeCtx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{
Role: types.TenantRoleContributor,
})
adminCtx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{
Role: types.TenantRoleAdmin,
})
baselineCases := []struct {
name string
ctx context.Context
path string
allowed bool
}{
{name: "read get kb list", ctx: readCtx, path: "/api/v1/knowledge-bases", allowed: true},
{name: "read get wiki page", ctx: readCtx, path: "/api/v1/knowledgebase/kb-1/wiki/pages", allowed: true},
{name: "admin reset api key blocked", ctx: adminCtx, path: "/api/v1/tenants/1/api-key", allowed: false},
{name: "admin api principal blocked", ctx: adminCtx, path: "/api/v1/tenants/1/api-principal-config", allowed: false},
}
for _, tc := range baselineCases {
t.Run("baseline/"+tc.name, func(t *testing.T) {
err := rejectTenantAPIKeyManagementPath(tc.ctx, tc.path)
got := err == nil
if got != tc.allowed {
t.Fatalf("rejectTenantAPIKeyManagementPath(%s) allowed=%v, want %v (err=%v)",
tc.path, got, tc.allowed, err)
}
})
}
guardCases := []struct {
name string
ctx context.Context
method string
guard gin.HandlerFunc
allowed bool
}{
{name: "read delete kb", ctx: readCtx, method: http.MethodDelete, guard: RequireAPIKeyMinRoleForUnsafe(types.TenantRoleContributor), allowed: false},
{name: "write put kb", ctx: writeCtx, method: http.MethodPut, guard: RequireAPIKeyMinRoleForUnsafe(types.TenantRoleContributor), allowed: true},
{name: "write create kb", ctx: writeCtx, method: http.MethodPost, guard: RequireAPIKeyDeny(), allowed: false},
{name: "write batch delete", ctx: writeCtx, method: http.MethodPost, guard: RequireAPIKeyDeny(), allowed: false},
{name: "write faq upsert", ctx: writeCtx, method: http.MethodPost, guard: RequireAPIKeyMinRoleForUnsafe(types.TenantRoleContributor), allowed: true},
{name: "write semantic search post", ctx: writeCtx, method: http.MethodPost, guard: RequireAPIKeyMinRole(types.TenantRoleViewer), allowed: true},
{name: "read semantic search post", ctx: readCtx, method: http.MethodPost, guard: RequireAPIKeyMinRole(types.TenantRoleViewer), allowed: true},
{name: "read knowledge chat post", ctx: readCtx, method: http.MethodPost, guard: RequireAPIKeyMinRole(types.TenantRoleViewer), allowed: true},
{name: "admin tenant kv", ctx: adminCtx, method: http.MethodPut, guard: RequireAPIKeyMinRoleForUnsafe(types.TenantRoleAdmin), allowed: true},
{name: "contributor tenant kv", ctx: writeCtx, method: http.MethodPut, guard: RequireAPIKeyMinRoleForUnsafe(types.TenantRoleAdmin), allowed: false},
}
for _, tc := range guardCases {
t.Run("guard/"+tc.name, func(t *testing.T) {
got := runAPIKeyGuard(t, tc.ctx, tc.method, tc.guard)
if got != tc.allowed {
t.Fatalf("guard allowed=%v, want %v", got, tc.allowed)
}
})
}
}
func runAPIKeyGuard(t *testing.T, ctx context.Context, method string, guard gin.HandlerFunc) bool {
t.Helper()
gin.SetMode(gin.TestMode)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest(method, "/api/v1/test", nil)
c.Request = c.Request.WithContext(ctx)
guard(c)
return !c.IsAborted() && w.Code != http.StatusForbidden
}
+3 -5
View File
@@ -260,11 +260,9 @@ func authenticateAPIKeyRequest(
if c.IsAborted() {
return false
}
if err := rejectTenantAPIKeyManagementPath(c.Request.Context(), c.Request.URL.Path); err != nil {
c.JSON(http.StatusForbidden, gin.H{"error": "Forbidden: API key scope does not allow this operation"})
c.Abort()
return false
}
// Per-route API-key authorization (role + KB scope + default-deny) is
// enforced by middleware.APIKeyRouteAuthorizer on the /api/v1 group.
// Key-management and any other undeclared route is denied there.
return true
}
@@ -1,36 +0,0 @@
package middleware
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/Tencent/WeKnora/internal/types"
"github.com/gin-gonic/gin"
)
// TestAuthenticateAPIKeyScopeUsesRequestContextAfterAttach verifies the
// rejectTenantAPIKeyManagementPath call in authenticateAPIKeyRequest reads
// scope from c.Request.Context() after attachAPIKeyAuthContext.
func TestAuthenticateAPIKeyScopeUsesRequestContextAfterAttach(t *testing.T) {
gin.SetMode(gin.TestMode)
c, _ := gin.CreateTestContext(httptest.NewRecorder())
c.Request = httptest.NewRequest(http.MethodDelete, "/api/v1/knowledge-bases/kb-1", nil)
preAttach := c.Request.Context()
c.Request = c.Request.WithContext(types.WithTenantAPIKeyScope(preAttach, types.TenantAPIKeyScope{
KeyID: 1,
Role: types.TenantRoleViewer,
}))
if err := rejectTenantAPIKeyManagementPath(preAttach, c.Request.URL.Path); err != nil {
t.Fatalf("pre-attach ctx should not carry scope and must not block: %v", err)
}
if err := rejectTenantAPIKeyManagementPath(c.Request.Context(), c.Request.URL.Path); err != nil {
t.Fatalf("non-management path should pass auth baseline: %v", err)
}
if err := requireTenantAPIKeyMinRole(c.Request.Context(), types.TenantRoleContributor); err == nil {
t.Fatal("viewer key must not satisfy contributor route guard on DELETE")
}
}
+25
View File
@@ -68,6 +68,13 @@ func RequireRole(min types.TenantRole, cfg *config.Config) gin.HandlerFunc {
warnOnNilConfig(cfg)
return func(c *gin.Context) {
ctx := c.Request.Context()
// API-key principals are authorized solely by the APIKeyGate
// (role + KB scope + default-deny). The JWT role ladder does not
// apply to a machine principal, so short-circuit here.
if _, ok := types.TenantAPIKeyScopeFromContext(ctx); ok {
c.Next()
return
}
role := types.TenantRoleFromContext(ctx)
if role.HasPermission(min) {
c.Next()
@@ -121,6 +128,15 @@ func RequireSystemAdmin(cfg *config.Config) gin.HandlerFunc {
warnOnNilConfig(cfg)
return func(c *gin.Context) {
ctx := c.Request.Context()
// API-key principals never gain system-admin authority, but the
// APIKeyGate is the single place that decides which routes they may
// reach. System routes are simply not declared there, so an API key
// is already rejected by default-deny before this guard runs. Short-
// circuit to avoid a misleading "system administrator required" 403.
if _, ok := types.TenantAPIKeyScopeFromContext(ctx); ok {
c.Next()
return
}
if types.IsSystemAdminFromContext(ctx) {
c.Next()
return
@@ -169,6 +185,15 @@ func RequireOwnershipOrRole(min types.TenantRole, lookup CreatorLookup, cfg *con
warnOnNilConfig(cfg)
return func(c *gin.Context) {
ctx := c.Request.Context()
// API-key principals are authorized solely by the APIKeyGate.
// Ownership ("creator OR Admin+") is a human concept that cannot
// apply to a machine principal (its synthetic system-user never
// matches creator_id), so short-circuit here. KB-scope for API
// keys is still enforced by the KBAccess guards + handler checks.
if _, ok := types.TenantAPIKeyScopeFromContext(ctx); ok {
c.Next()
return
}
role := types.TenantRoleFromContext(ctx)
// 1. Fast path: role meets the bar.
@@ -0,0 +1,101 @@
package middleware
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"github.com/Tencent/WeKnora/internal/config"
"github.com/Tencent/WeKnora/internal/types"
"github.com/gin-gonic/gin"
)
// apiKeyRBACHarness seeds an API-key scope (as attachAPIKeyAuthContext would)
// plus a deliberately-insufficient TenantRole, then runs the guard. It
// asserts the JWT guard short-circuits for API-key principals so that
// per-route API-key authorization is left entirely to the APIKeyGate.
func apiKeyRBACHarness(scope types.TenantAPIKeyScope, role types.TenantRole, mw gin.HandlerFunc) *httptest.ResponseRecorder {
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(func(c *gin.Context) {
ctx := context.WithValue(c.Request.Context(), types.TenantRoleContextKey, role)
ctx = types.WithTenantAPIKeyScope(ctx, scope)
c.Request = c.Request.WithContext(ctx)
c.Next()
})
r.GET("/protected", mw, func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"ok": true}) })
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/protected", nil))
return w
}
func TestRequireRole_ShortCircuitsAPIKey(t *testing.T) {
// Viewer-role API key against an Admin gate would 403 under the JWT
// ladder; the short-circuit lets it through (the gate handles it).
w := apiKeyRBACHarness(
types.TenantAPIKeyScope{Role: types.TenantRoleViewer},
types.TenantRoleViewer,
RequireRole(types.TenantRoleAdmin, cfgRBAC(true)),
)
if w.Code != http.StatusOK {
t.Fatalf("API-key principal should short-circuit RequireRole, got %d", w.Code)
}
}
func TestRequireSystemAdmin_ShortCircuitsAPIKey(t *testing.T) {
w := apiKeyRBACHarness(
types.TenantAPIKeyScope{Role: types.TenantRoleAdmin},
types.TenantRoleAdmin,
RequireSystemAdmin(cfgRBAC(true)),
)
if w.Code != http.StatusOK {
t.Fatalf("API-key principal should short-circuit RequireSystemAdmin, got %d", w.Code)
}
}
// TestRequireOwnershipOrRole_ShortCircuitsAPIKeyContributor is the core
// regression for review #1: a Contributor API key writing to a KB it does not
// "own" (synthetic system user never matches creator_id) must not be 403'd by
// the OwnedKBOrAdmin guard when EnableRBAC=true. The lookup deliberately
// returns a foreign creator to prove the guard never runs it.
func TestRequireOwnershipOrRole_ShortCircuitsAPIKeyContributor(t *testing.T) {
lookupCalled := false
lookup := func(_ *gin.Context) (string, error) {
lookupCalled = true
return "some-other-human-user", nil
}
w := apiKeyRBACHarness(
types.TenantAPIKeyScope{Role: types.TenantRoleContributor, KnowledgeBaseIDs: types.StringArray{"kb-1"}},
types.TenantRoleContributor,
RequireOwnershipOrRole(types.TenantRoleAdmin, lookup, cfgRBAC(true)),
)
if w.Code != http.StatusOK {
t.Fatalf("Contributor API-key write should short-circuit OwnedKBOrAdmin, got %d", w.Code)
}
if lookupCalled {
t.Fatal("ownership lookup must not run for API-key principals")
}
}
// Sanity: a real JWT Viewer is still rejected by the Admin gate — the
// short-circuit must be scoped to API-key principals only.
func TestRequireRole_JWTViewerStillDenied(t *testing.T) {
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(func(c *gin.Context) {
ctx := context.WithValue(c.Request.Context(), types.TenantRoleContextKey, types.TenantRoleViewer)
c.Request = c.Request.WithContext(ctx)
c.Next()
})
r.GET("/p", RequireRole(types.TenantRoleAdmin, &config.Config{Tenant: &config.TenantConfig{EnableRBAC: boolPtr(true)}}),
func(c *gin.Context) { c.Status(http.StatusOK) })
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/p", nil))
if w.Code != http.StatusForbidden {
t.Fatalf("JWT Viewer must still be denied by Admin gate, got %d", w.Code)
}
}
func boolPtr(b bool) *bool { return &b }