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
+96 -4
View File
@@ -142,14 +142,106 @@ func TestRequireOwnershipOrRole_LegacyEmptyCreatorTreatedAsTenantOwned(t *testin
}
}
func TestRequireOwnershipOrRole_LookupErrorRejects(t *testing.T) {
// A failing lookup is treated as deny — failing open here would mean
func TestRequireOwnershipOrRole_LookupErrorReturns503(t *testing.T) {
// A transient lookup error surfaces as 503 (not 403) so monitoring
// and clients can tell "your permission was denied" from "the server
// briefly couldn't verify ownership". Failing open here would mean
// any DB hiccup on the creator query becomes a free pass.
lookup := func(c *gin.Context) (string, error) { return "", errors.New("boom") }
w := rbacTestHarness(types.TenantRoleContributor, "u1",
RequireOwnershipOrRole(types.TenantRoleAdmin, lookup, cfgRBAC(true)))
if w.Code != http.StatusForbidden {
t.Fatalf("lookup error must reject, got %d", w.Code)
if w.Code != http.StatusServiceUnavailable {
t.Fatalf("lookup error must surface as 503, got %d", w.Code)
}
}
func TestRequireOwnershipOrRole_NotFoundPassesThroughTo404(t *testing.T) {
// When the lookup signals "no such resource visible to this tenant",
// the middleware MUST NOT mask it as 403. The handler downstream
// gets to decide the right status (usually 404), which keeps client
// error handling honest and avoids hiding "wrong URL" behind a
// permissions error.
called := false
lookup := func(c *gin.Context) (string, error) {
return "", ErrResourceNotFound
}
router := gin.New()
router.Use(func(c *gin.Context) {
ctx := c.Request.Context()
ctx = context.WithValue(ctx, types.TenantRoleContextKey, types.TenantRoleContributor)
ctx = context.WithValue(ctx, types.UserIDContextKey, "u1")
c.Request = c.Request.WithContext(ctx)
c.Next()
})
router.GET("/protected",
RequireOwnershipOrRole(types.TenantRoleAdmin, lookup, cfgRBAC(true)),
func(c *gin.Context) {
called = true
c.JSON(http.StatusNotFound, gin.H{"error": "kb not found"})
},
)
req := httptest.NewRequest(http.MethodGet, "/protected", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if !called {
t.Fatalf("handler should have been invoked so it can produce 404")
}
if w.Code != http.StatusNotFound {
t.Fatalf("expected handler 404 to win, got %d", w.Code)
}
}
func TestRequireOwnershipOrRole_SkipsLookupWhenRBACDisabled(t *testing.T) {
// H1 regression: when enforcement is off, the lookup must not run at
// all. Hooking up RBAC pre-rollout used to add a hidden DB roundtrip
// to every mutating request even though the result was thrown away.
calls := 0
lookup := func(c *gin.Context) (string, error) {
calls++
return "someone-else", nil
}
w := rbacTestHarness(types.TenantRoleViewer, "u1",
RequireOwnershipOrRole(types.TenantRoleAdmin, lookup, cfgRBAC(false)))
if w.Code != http.StatusOK {
t.Fatalf("fail-open should let the request through, got %d", w.Code)
}
if calls != 0 {
t.Fatalf("lookup must not run when EnableRBAC=false (got %d calls)", calls)
}
}
func TestRequireOwnershipOrRole_CrossTenantSuperuserBypass(t *testing.T) {
// Cross-tenant superusers resolve to Admin in foreign tenants (see
// resolveTenantRole). For Owner-only gates we additionally let them
// through to preserve the pre-RBAC ability to administer any tenant.
calls := 0
lookup := func(c *gin.Context) (string, error) {
calls++
return "", nil
}
router := gin.New()
router.Use(func(c *gin.Context) {
ctx := c.Request.Context()
ctx = context.WithValue(ctx, types.TenantRoleContextKey, types.TenantRoleAdmin)
ctx = context.WithValue(ctx, types.UserIDContextKey, "su1")
ctx = context.WithValue(ctx, types.UserContextKey, &types.User{
ID: "su1", CanAccessAllTenants: true,
})
c.Request = c.Request.WithContext(ctx)
c.Next()
})
router.GET("/protected",
RequireOwnershipOrRole(types.TenantRoleOwner, lookup, cfgRBAC(true)),
func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{}) },
)
req := httptest.NewRequest(http.MethodGet, "/protected", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("superuser must bypass Owner gate, got %d", w.Code)
}
if calls != 0 {
t.Fatalf("superuser bypass must skip lookup, got %d", calls)
}
}