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.
This commit is contained in:
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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) {
|
||||
|
||||
Reference in New Issue
Block a user