From 0f0f7e433964d7dbcd69a7dd3b554a9198cfb953 Mon Sep 17 00:00:00 2001 From: wizardchen Date: Wed, 13 May 2026 21:49:40 +0800 Subject: [PATCH] test(rbac): cover review gaps from PR 2 self-review - Add TestRequireRole_CrossTenantSuperuserBypass: pin the CanAccessAllTenants -> Owner-gate bypass behaviour for RequireRole, matching the existing coverage on RequireOwnershipOrRole. Catches reorderings of the fast paths that would re-lock org-level superusers out of foreign-tenant Owner-only routes. - Add TestAgentCreatorLookup_CrossTenantIsHiddenAsNotFound: lock down the defence-in-depth tenant re-check inside AgentCreatorLookup so a future refactor that loosens the service-layer scope (or wires a cross-tenant variant by mistake) cannot leak access via the ownership shortcut. - Reword RequireOwnershipOrRole step 7-8 doc comment so "role check already failed" is unambiguous (it refers to step 1 above). - Annotate the synthetic-system-user construction in middleware/auth.go with a back-pointer to types.IsSyntheticUserID so anyone changing the prefix or numeric suffix knows to update the helper too. --- internal/handler/rbac_lookups_test.go | 21 +++++++++++++++++ internal/middleware/auth.go | 6 +++++ internal/middleware/rbac.go | 5 ++-- internal/middleware/rbac_test.go | 33 +++++++++++++++++++++++++++ 4 files changed, 63 insertions(+), 2 deletions(-) diff --git a/internal/handler/rbac_lookups_test.go b/internal/handler/rbac_lookups_test.go index 37a57ed3..c5be8113 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.go index 055a4050..5a2c5e07 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-" 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.go index c42f1864..cb6be6b9 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.go index 499b9613..e014b34c 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) {