fix(rbac): address PR 2 review feedback

Middleware
- RequireOwnershipOrRole now skips the creator lookup entirely when
  EnableRBAC is off, eliminating a hidden per-request DB roundtrip in
  the rollout window.
- New ErrResourceNotFound sentinel lets lookups signal "not visible to
  this tenant"; the middleware passes the request through so handlers
  can return a real 404 instead of a misleading 403.
- Transient lookup failures now surface as 503 (was 403) so monitoring
  can tell denied-by-policy from cannot-verify-right-now.
- Cross-tenant superusers (CanAccessAllTenants) bypass tenant role gates,
  restoring DELETE /tenants/:id and ResetAPIKey for org operators that
  resolve to Admin in foreign tenants.
- Construction-time warning fires once when cfg is nil/incomplete, so a
  wiring bug that disables enforcement globally is visible at boot.

Route coverage
- Add role guards to FAQ, KnowledgeTag, WikiPage, Skill, WebSearch,
  WebSearchProvider, WeKnoraCloud, Session, Chat, and Message route
  groups so the matrix actually matches the PR description.

Service layer
- KB and agent creators are no longer recorded as the synthetic
  system-<tenantID> user used by the X-API-Key path; resources stay
  tenant-owned. New types.IsSyntheticUserID helper centralises the
  prefix check.
- KBCreatorLookup and AgentCreatorLookup re-check tenant scope so a
  same-ID resource in another tenant cannot piggyback through the
  ownership shortcut.

Docs
- CustomAgent.RunnableByViewer comment now matches enforcement: it only
  blocks Viewer-driven agent-mode runs, not plain RAG/Wiki QA.

Tests
- New cases for the 503/404 paths, lookup-skip behaviour, cross-tenant
  superuser bypass, the lookup helpers (not-found, cross-tenant,
  built-in agent, missing tenant context), and IsSyntheticUserID.
This commit is contained in:
wizardchen
2026-05-13 21:37:47 +08:00
committed by lyingbug
parent 9e3c92ca95
commit 8b71def60b
10 changed files with 621 additions and 162 deletions
+53 -15
View File
@@ -4,37 +4,59 @@ import (
"errors"
apprepo "github.com/Tencent/WeKnora/internal/application/repository"
"github.com/Tencent/WeKnora/internal/application/service"
"github.com/Tencent/WeKnora/internal/middleware"
"github.com/Tencent/WeKnora/internal/types"
"github.com/gin-gonic/gin"
)
// Per-resource creator-id resolvers used by middleware.RequireOwnershipOrRole.
// The route registration wires these as closures so they capture the handler's
// service dependencies; the middleware just calls them with the gin.Context
// and gets back ("", nil) for legacy tenant-owned rows or (creatorID, nil)
// for resources we know how to attribute.
// and gets back one of:
//
// Lookup contract (mirrors middleware.CreatorLookup):
// - URL param missing -> error (the middleware will 403; better than
// letting an unauthenticated mutation through on a malformed route).
// - Resource not found -> error (downstream handler would 404 anyway,
// and middleware-level 403 is a fine signal to clients).
// - Resource found but creator_id == "" -> ("", nil); the middleware
// treats that as tenant-owned and falls back to pure role check.
// - (creatorID, nil) : ownership match check decides
// - ("", nil) : tenant-owned (legacy or built-in)
// - ("", ErrResourceNotFound) : :id doesn't resolve in this tenant;
// middleware passes through so the
// handler can issue a real 404
// - ("", <other err>) : transient/unexpected failure;
// middleware will 503 the request
//
// Tenant scoping is enforced INSIDE the lookup: even if the underlying
// `Get*ByID` repo call is unscoped, the lookup re-checks `tenant_id`
// against the caller's context. This stops a creator-match shortcut
// from leaking access to a same-ID resource in a different tenant.
// KBCreatorLookup resolves :id -> KnowledgeBase.CreatorID. Used by all
// per-KB mutating routes.
// KBCreatorLookup resolves :id -> KnowledgeBase.CreatorID, scoped to
// the caller's tenant. Used by all per-KB mutating routes.
func (h *KnowledgeBaseHandler) KBCreatorLookup(c *gin.Context) (string, error) {
id := c.Param("id")
if id == "" {
return "", errors.New("missing :id param for KB creator lookup")
}
kb, err := h.service.GetKnowledgeBaseByID(c.Request.Context(), id)
ctx := c.Request.Context()
tenantID, ok := types.TenantIDFromContext(ctx)
if !ok {
// 没有租户上下文意味着 auth 中间件未完成;当作 lookup 失败让上层 503,
// 而不是 silently 走 fail-open 给一个不该有的访问。
return "", errors.New("tenant context missing")
}
kb, err := h.service.GetKnowledgeBaseByID(ctx, id)
if err != nil {
if errors.Is(err, apprepo.ErrKnowledgeBaseNotFound) {
return "", middleware.ErrResourceNotFound
}
return "", err
}
if kb == nil {
return "", apprepo.ErrKnowledgeBaseNotFound
return "", middleware.ErrResourceNotFound
}
// 显式重校验租户:repo.GetKnowledgeBaseByID 不带 tenant 过滤,
// 万一未来 :id 被攻击者从他人租户 UUID 试探到,也不会借由
// "ownership match" 通过中间件。
if kb.TenantID != tenantID {
return "", middleware.ErrResourceNotFound
}
return kb.CreatorID, nil
}
@@ -44,17 +66,33 @@ func (h *KnowledgeBaseHandler) KBCreatorLookup(c *gin.Context) (string, error) {
// belong to the tenant rather than to any one user, so we return
// ("", nil) and let the role check decide. The same holds for legacy
// rows whose CreatedBy was never populated.
//
// The underlying GetAgentByID already scopes to the caller's tenant,
// but we keep an explicit defence-in-depth check here in case future
// refactors loosen the service-layer scope.
func (h *CustomAgentHandler) AgentCreatorLookup(c *gin.Context) (string, error) {
id := c.Param("id")
if id == "" {
return "", errors.New("missing :id param for agent creator lookup")
}
agent, err := h.service.GetAgentByID(c.Request.Context(), id)
ctx := c.Request.Context()
tenantID, ok := types.TenantIDFromContext(ctx)
if !ok {
return "", errors.New("tenant context missing")
}
agent, err := h.service.GetAgentByID(ctx, id)
if err != nil {
if errors.Is(err, service.ErrAgentNotFound) ||
errors.Is(err, apprepo.ErrCustomAgentNotFound) {
return "", middleware.ErrResourceNotFound
}
return "", err
}
if agent == nil {
return "", errors.New("agent not found")
return "", middleware.ErrResourceNotFound
}
if agent.TenantID != tenantID {
return "", middleware.ErrResourceNotFound
}
if agent.IsBuiltin {
return "", nil
+150
View File
@@ -0,0 +1,150 @@
package handler
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"testing"
apprepo "github.com/Tencent/WeKnora/internal/application/repository"
"github.com/Tencent/WeKnora/internal/application/service"
"github.com/Tencent/WeKnora/internal/middleware"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/gin-gonic/gin"
)
// The lookup helpers translate handler/service errors into the
// middleware sentinel set; that translation is where bugs hide (404
// becoming 403, cross-tenant leaks, etc.), so we test those edges
// directly rather than via end-to-end HTTP.
// stubKBService implements just enough of interfaces.KnowledgeBaseService
// to drive KBCreatorLookup. Any other method panics so the test fails
// loudly if a future lookup refactor reaches outside the contract.
type stubKBService struct {
interfaces.KnowledgeBaseService
get func(ctx context.Context, id string) (*types.KnowledgeBase, error)
}
func (s *stubKBService) GetKnowledgeBaseByID(ctx context.Context, id string) (*types.KnowledgeBase, error) {
return s.get(ctx, id)
}
func newKBLookupCtx(t *testing.T, tenantID uint64, paramID string) *gin.Context {
t.Helper()
gin.SetMode(gin.TestMode)
c, _ := gin.CreateTestContext(httptest.NewRecorder())
c.Request = httptest.NewRequest(http.MethodGet, "/x", nil)
ctx := context.WithValue(c.Request.Context(), types.TenantIDContextKey, tenantID)
c.Request = c.Request.WithContext(ctx)
c.Params = gin.Params{{Key: "id", Value: paramID}}
return c
}
func TestKBCreatorLookup_NotFoundMapsToSentinel(t *testing.T) {
h := &KnowledgeBaseHandler{service: &stubKBService{
get: func(_ context.Context, _ string) (*types.KnowledgeBase, error) {
return nil, apprepo.ErrKnowledgeBaseNotFound
},
}}
_, err := h.KBCreatorLookup(newKBLookupCtx(t, 1, "kb-1"))
if !errors.Is(err, middleware.ErrResourceNotFound) {
t.Fatalf("expected ErrResourceNotFound, got %v", err)
}
}
func TestKBCreatorLookup_CrossTenantIsHiddenAsNotFound(t *testing.T) {
// A foreign-tenant KB must NEVER leak via the ownership shortcut.
// Returning the row's CreatorID would let a user-id collision pass
// the middleware's "creator == uid" branch; hiding it as not-found
// keeps the lookup strictly tenant-scoped.
h := &KnowledgeBaseHandler{service: &stubKBService{
get: func(_ context.Context, _ string) (*types.KnowledgeBase, error) {
return &types.KnowledgeBase{ID: "kb-1", TenantID: 999, CreatorID: "u1"}, nil
},
}}
_, err := h.KBCreatorLookup(newKBLookupCtx(t, 1, "kb-1"))
if !errors.Is(err, middleware.ErrResourceNotFound) {
t.Fatalf("cross-tenant KB must surface as not-found, got %v", err)
}
}
func TestKBCreatorLookup_OwnerMatchReturnsCreatorID(t *testing.T) {
h := &KnowledgeBaseHandler{service: &stubKBService{
get: func(_ context.Context, _ string) (*types.KnowledgeBase, error) {
return &types.KnowledgeBase{ID: "kb-1", TenantID: 1, CreatorID: "u-creator"}, nil
},
}}
creator, err := h.KBCreatorLookup(newKBLookupCtx(t, 1, "kb-1"))
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if creator != "u-creator" {
t.Fatalf("expected creator=u-creator, got %q", creator)
}
}
func TestKBCreatorLookup_MissingTenantContext(t *testing.T) {
// Without tenant context, the lookup can't decide scope. Surfacing
// a real error (which middleware turns into 503) is safer than
// silently returning ErrResourceNotFound: the request shouldn't be
// happening at all.
gin.SetMode(gin.TestMode)
c, _ := gin.CreateTestContext(httptest.NewRecorder())
c.Request = httptest.NewRequest(http.MethodGet, "/x", nil)
c.Params = gin.Params{{Key: "id", Value: "kb-1"}}
h := &KnowledgeBaseHandler{service: &stubKBService{
get: func(_ context.Context, _ string) (*types.KnowledgeBase, error) {
t.Fatalf("service must not be called without tenant context")
return nil, nil
},
}}
_, err := h.KBCreatorLookup(c)
if err == nil {
t.Fatalf("expected error when tenant context missing")
}
if errors.Is(err, middleware.ErrResourceNotFound) {
t.Fatalf("missing tenant must not be reported as not-found: %v", err)
}
}
// stubAgentService mirrors stubKBService for the agent lookup tests.
type stubAgentService struct {
interfaces.CustomAgentService
get func(ctx context.Context, id string) (*types.CustomAgent, error)
}
func (s *stubAgentService) GetAgentByID(ctx context.Context, id string) (*types.CustomAgent, error) {
return s.get(ctx, id)
}
func TestAgentCreatorLookup_BuiltinIsTenantOwned(t *testing.T) {
h := &CustomAgentHandler{service: &stubAgentService{
get: func(_ context.Context, _ string) (*types.CustomAgent, error) {
return &types.CustomAgent{
ID: "smart-reasoning", TenantID: 1, IsBuiltin: true, CreatedBy: "ignored",
}, nil
},
}}
creator, err := h.AgentCreatorLookup(newKBLookupCtx(t, 1, "smart-reasoning"))
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if creator != "" {
t.Fatalf("built-in agent must surface as tenant-owned (empty creator), got %q", creator)
}
}
func TestAgentCreatorLookup_AgentNotFoundMapsToSentinel(t *testing.T) {
h := &CustomAgentHandler{service: &stubAgentService{
get: func(_ context.Context, _ string) (*types.CustomAgent, error) {
return nil, service.ErrAgentNotFound
},
}}
_, err := h.AgentCreatorLookup(newKBLookupCtx(t, 1, "missing-agent"))
if !errors.Is(err, middleware.ErrResourceNotFound) {
t.Fatalf("expected ErrResourceNotFound, got %v", err)
}
}