Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
test(rbac): cover review gaps from PR 2 self-review
wizardchen0f0f7e433964
diff --git a/internal/handler/rbac_lookups_test.go b/internal/handler/rbac_lookups_test.goindex 37a57ed32..c5be81137 100644--- a/internal/handler/rbac_lookups_test.go+++ b/internal/handler/rbac_lookups_test.go@@ -148,3 +148,24 @@ func TestAgentCreatorLookup_AgentNotFoundMapsToSentinel(t *testing.T) {t.Fatalf("expected ErrResourceNotFound, got %v", err)}}++func TestAgentCreatorLookup_CrossTenantIsHiddenAsNotFound(t *testing.T) {+ // Defensive: service.GetAgentByID already scopes by tenant, but+ // AgentCreatorLookup re-checks the row's TenantID anyway. If a+ // future refactor loosens the service-layer scope (or adds a+ // cross-tenant variant that gets wired here by mistake), a+ // foreign-tenant row must NEVER leak through the ownership+ // shortcut. Pinning the contract here so the defensive branch+ // survives refactors.+ h := &CustomAgentHandler{service: &stubAgentService{+ get: func(_ context.Context, _ string) (*types.CustomAgent, error) {+ return &types.CustomAgent{+ ID: "agent-1", TenantID: 999, CreatedBy: "u1",+ }, nil+ },+ }}+ _, err := h.AgentCreatorLookup(newKBLookupCtx(t, 1, "agent-1"))+ if !errors.Is(err, middleware.ErrResourceNotFound) {+ t.Fatalf("cross-tenant agent must surface as not-found, got %v", err)+ }+}diff --git a/internal/middleware/auth.go b/internal/middleware/auth.goindex 055a4050f..5a2c5e071 100644--- a/internal/middleware/auth.go+++ b/internal/middleware/auth.go@@ -220,6 +220,12 @@ func Auth(// 确保所有依赖 UserContextKey 的下游 handler 正常工作。user, err := userService.GetUserByTenantID(c.Request.Context(), tenantID)if err != nil || user == nil {+ // Synthetic user. The "system-<tenantID>" shape is recognised+ // by types.IsSyntheticUserID, which RBAC service-layer code+ // uses to skip recording these IDs as a resource creator.+ // Do NOT change the prefix or numeric suffix without+ // updating that helper, otherwise KB/Agent CreatorID will+ // silently start pointing at the synthetic user again.user = &types.User{ID: fmt.Sprintf("system-%d", tenantID),Username: fmt.Sprintf("system-%d", tenantID),diff --git a/internal/middleware/rbac.go b/internal/middleware/rbac.goindex c42f18645..cb6be6b9f 100644--- a/internal/middleware/rbac.go+++ b/internal/middleware/rbac.go@@ -116,8 +116,9 @@ func RequireRole(min types.TenantRole, cfg *config.Config) gin.HandlerFunc {// 5. lookup returns other error -> 503 (transient/unexpected fault).// Preserves observability instead of disguising server errors as 403.// 6. lookup returns the caller's user ID -> allow (ownership match).-// 7. lookup returns "" -> tenant-owned, role check already failed: 403.-// 8. lookup returns a different non-empty user ID -> 403.+// 7. lookup returns "" (tenant-owned, no human creator) -> 403 (we+// already know role < min from step 1).+// 8. lookup returns a non-empty creator that is not the caller -> 403.func RequireOwnershipOrRole(min types.TenantRole, lookup CreatorLookup, cfg *config.Config) gin.HandlerFunc {warnOnNilConfig(cfg)return func(c *gin.Context) {diff --git a/internal/middleware/rbac_test.go b/internal/middleware/rbac_test.goindex 499b96135..e014b34c9 100644--- a/internal/middleware/rbac_test.go+++ b/internal/middleware/rbac_test.go@@ -89,6 +89,39 @@ func TestRequireRole_NilConfigFailsOpen(t *testing.T) {}}+func TestRequireRole_CrossTenantSuperuserBypass(t *testing.T) {+ // Org-level superusers (User.CanAccessAllTenants) bypass tenant role+ // gates — see auth.go's resolveTenantRole, which gives them a+ // transient Admin in foreign tenants. RequireRole has to honour the+ // same bypass for Owner-only gates, otherwise a superuser would be+ // locked out of DELETE /tenants/:id once enforcement turns on.+ //+ // Pinned as a regression test: if anyone reorders the fast paths so+ // the superuser check ends up after the enforcement branch, this+ // test fails before the change ships.+ router := gin.New()+ router.Use(func(c *gin.Context) {+ ctx := c.Request.Context()+ ctx = context.WithValue(ctx, types.TenantRoleContextKey, types.TenantRoleViewer)+ 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",+ RequireRole(types.TenantRoleOwner, 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 role gate, got %d", w.Code)+ }+}+// ---------- RequireOwnershipOrRole ----------func TestRequireOwnershipOrRole_AdminBypassesLookup(t *testing.T) {